diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 78b40368a..8230903cd 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -118,7 +118,7 @@ jobs: strategy: matrix: - boards: [arm-01, arm-02, arm-03, arm-04, arm-05, arm-06, arm-07, arm-08, arm-09, arm-10, arm-11, arm-12, arm-13, other, risc-v, sim-01, sim-02, xtensa, codechecker] + boards: [arm-01, arm-02, arm-03, arm-04, arm-05, arm-06, arm-07, arm-08, arm-09, arm-10, arm-11, arm-12, arm-13, other, risc-v, sim-01, sim-02, xtensa] steps: - name: Download Source Artifact @@ -187,19 +187,19 @@ jobs: - name: Restore Tools Cache id: cache-tools - uses: actions/cache@v3 + uses: actions/cache@v4 env: cache-name: ${{ runner.os }}-cache-tools with: path: ./sources/tools - key: ${{ runner.os }}-tools-${{ hashFiles('./sources/nuttx/tools/ci/cibuild.sh') }} + key: ${{ runner.os }}-tools-${{ hashFiles('./sources/nuttx/tools/ci/platforms/darwin.sh') }} - name: Export NuttX Repo SHA run: echo "nuttx_sha=`git -C sources/nuttx rev-parse HEAD`" >> $GITHUB_ENV # Released version of Cython has issues with Python 11. Set runner to use Python 3.10 # https://github.com/cython/cython/issues/4500 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.10' - name: Run Builds @@ -214,3 +214,71 @@ jobs: name: macos-builds path: buildartifacts/ continue-on-error: true + + msys2: + needs: Fetch-Source + runs-on: windows-latest + strategy: + fail-fast: false + matrix: + boards: [msys2] + + defaults: + run: + shell: msys2 {0} + steps: + - uses: actions/checkout@v4 + - uses: msys2/setup-msys2@v2 + with: + msystem: MSYS + update: false + install: >- + base-devel + gcc + gperf + automake + autoconf + git + python3 + ncurses-devel + unzip + zip + tio + zlib-devel + cmake + ninja + python-pip + vim + + - name: pip3 install + run: | + pip3 install --root-user-action=ignore --no-cache-dir pyelftools cxxfilt kconfiglib + + - run: git config --global core.autocrlf false + + - name: Download Source Artifact + uses: actions/download-artifact@v3 + with: + name: source-bundle + path: . + + - name: Extract sources + run: tar zxf sources.tar.gz + + - name: Export NuttX Repo SHA + run: echo "nuttx_sha=`git -C sources/nuttx rev-parse HEAD`" >> $GITHUB_ENV + + - name: Run Builds + run: | + echo "::add-matcher::sources/nuttx/.github/gcc.json" + export ARTIFACTDIR=`pwd`/buildartifacts + git config --global --add safe.directory /github/workspace/sources/nuttx + git config --global --add safe.directory /github/workspace/sources/apps + cd sources/nuttx/tools/ci + ./cibuild.sh -g -i -A -C -R testlist/${{matrix.boards}}.dat + + - uses: actions/upload-artifact@v3 + with: + name: msys2-builds + path: buildartifacts/ + continue-on-error: true diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index b7c1070be..8da61e8cf 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -22,7 +22,7 @@ jobs: fetch-depth: 0 - run: mkdir super-linter.report - name: Lint - uses: github/super-linter@v5 + uses: github/super-linter@v6 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} VALIDATE_ALL_CODEBASE: false diff --git a/.gitignore b/.gitignore index ad4843518..578b989f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,6 @@ *.a -*.dbo -*.dba *.adb *.asm -*.d *.dSYM *.exe *.gcno @@ -25,7 +22,7 @@ .context .depend .kconfig -/*.lock +*.lock /bin /boot_romfsimg.h /external @@ -41,3 +38,6 @@ Make.dep .dirlinks .vscode .DS_Store +build +.ccls-cache +compile_commands.json diff --git a/Application.mk b/Application.mk index bb0b58bc5..c12903d59 100644 --- a/Application.mk +++ b/Application.mk @@ -23,18 +23,12 @@ # has the value "m" ifneq ($(MAINSRC),) - ifeq ($(DYNLIB),y) + ifeq ($(MODULE),m) + BUILD_MODULE = y + endif + + ifeq ($(CONFIG_BUILD_KERNEL),y) BUILD_MODULE = y - MODAELFFLAGS = $(CMODULELFFLAGS) - MODCFLAGS = $(CMODULEFLAGS) - MODCXXFLAGS = $(CXXMODULEFLAGS) - MODLDFLAGS = $(LDMODULEFLAGS) - else ifneq ($(or $(filter y,$(CONFIG_BUILD_KERNEL)), $(filter m,$(MODULE))),) - BUILD_MODULE = y - MODAELFFLAGS = $(AELFFLAGS) - MODCFLAGS = $(CELFFLAGS) - MODCXXFLAGS = $(CXXELFFLAGS) - MODLDFLAGS = $(LDELFFLAGS) endif endif @@ -48,10 +42,6 @@ else CWD = $(CURDIR) endif -SUFFIX ?= $(subst $(DELIM),.,$(CWD)) - -PROGNAME := $(subst ",,$(PROGNAME)) - # Add the static application library to the linked libraries. LDLIBS += $(call CONVERT_PATH,$(BIN)) @@ -71,6 +61,10 @@ ifeq ($(BUILD_MODULE),y) LDLIBS += $(COMPILER_RT_LIB) endif +SUFFIX ?= $(subst $(DELIM),.,$(CWD)) + +PROGNAME := $(subst ",,$(PROGNAME)) + # Object files RASRCS = $(filter %.s,$(ASRCS)) @@ -82,26 +76,28 @@ COBJS = $(CSRCS:=$(SUFFIX)$(OBJEXT)) CXXOBJS = $(CXXSRCS:=$(SUFFIX)$(OBJEXT)) RUSTOBJS = $(RUSTSRCS:=$(SUFFIX)$(OBJEXT)) ZIGOBJS = $(ZIGSRCS:=$(SUFFIX)$(OBJEXT)) -AIDLOBJS = $(patsubst %$(AIDLEXT),%$(CXXEXT),$(AIDLSRCS)) +DOBJS = $(DSRCS:=$(SUFFIX)$(OBJEXT)) MAINCXXSRCS = $(filter %$(CXXEXT),$(MAINSRC)) MAINCSRCS = $(filter %.c,$(MAINSRC)) MAINRUSTSRCS = $(filter %$(RUSTEXT),$(MAINSRC)) MAINZIGSRCS = $(filter %$(ZIGEXT),$(MAINSRC)) +MAINDSRCS = $(filter %$(DEXT),$(MAINSRC)) MAINCXXOBJ = $(MAINCXXSRCS:=$(SUFFIX)$(OBJEXT)) MAINCOBJ = $(MAINCSRCS:=$(SUFFIX)$(OBJEXT)) MAINRUSTOBJ = $(MAINRUSTSRCS:=$(SUFFIX)$(OBJEXT)) MAINZIGOBJ = $(MAINZIGSRCS:=$(SUFFIX)$(OBJEXT)) +MAINDOBJ = $(MAINDSRCS:=$(SUFFIX)$(OBJEXT)) SRCS = $(ASRCS) $(CSRCS) $(CXXSRCS) $(MAINSRC) -OBJS = $(RAOBJS) $(CAOBJS) $(COBJS) $(CXXOBJS) $(RUSTOBJS) $(ZIGOBJS) $(EXTOBJS) +OBJS = $(RAOBJS) $(CAOBJS) $(COBJS) $(CXXOBJS) $(RUSTOBJS) $(ZIGOBJS) $(DOBJS) $(EXTOBJS) ifneq ($(BUILD_MODULE),y) - OBJS += $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) + OBJS += $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ) endif ifneq ($(strip $(PROGNAME)),) - PROGOBJ := $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) + PROGOBJ := $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ) PROGLIST := $(addprefix $(BINDIR)$(DELIM),$(PROGNAME)) REGLIST := $(addprefix $(BUILTIN_REGISTRY)$(DELIM),$(addsuffix .bdat,$(PROGNAME))) @@ -134,14 +130,14 @@ ifeq ($(WASM_BUILD),y) DO_REGISTRATION = n endif -ifeq ($(DYNLIB),y) - DO_REGISTRATION = n -endif - # Compile flags, notice the default flags only suitable for flat build ZIGELFFLAGS ?= $(ZIGFLAGS) RUSTELFFLAGS ?= $(RUSTFLAGS) +DELFFLAGS ?= $(DFLAGS) + +DEPPATH += --dep-path . +DEPPATH += --obj-path . VPATH += :. @@ -154,19 +150,19 @@ all:: .built define ELFASSEMBLE $(ECHO_BEGIN)"AS: $1 " - $(Q) $(CC) -c $(MODAELFFLAGS) $($(strip $1)_AELFFLAGS) $1 -o $2 + $(Q) $(CC) -c $(AELFFLAGS) $($(strip $1)_AELFFLAGS) $1 -o $2 $(ECHO_END) endef define ELFCOMPILE $(ECHO_BEGIN)"CC: $1 " - $(Q) $(CC) -c $(MODCFLAGS) $($(strip $1)_CELFFLAGS) $1 -o $2 + $(Q) $(CC) -c $(CELFFLAGS) $($(strip $1)_CELFFLAGS) $1 -o $2 $(ECHO_END) endef define ELFCOMPILEXX $(ECHO_BEGIN)"CXX: $1 " - $(Q) $(CXX) -c $(MODCXXFLAGS) $($(strip $1)_CXXELFFLAGS) $1 -o $2 + $(Q) $(CXX) -c $(CXXELFFLAGS) $($(strip $1)_CXXELFFLAGS) $1 -o $2 $(ECHO_END) endef @@ -176,57 +172,59 @@ define ELFCOMPILERUST $(ECHO_END) endef +# Remove target suffix here since zig compiler add .o automatically define ELFCOMPILEZIG $(ECHO_BEGIN)"ZIG: $1 " - # Remove target suffix here since zig compiler add .o automatically $(Q) $(ZIG) build-obj $(ZIGELFFLAGS) $($(strip $1)_ZIGELFFLAGS) --name $(basename $2) $1 $(ECHO_END) endef +define ELFCOMPILED + $(ECHO_BEGIN)"DC: $1 " + $(Q) $(DC) -c $(DELFFLAGS) $($(strip $1)_DELFFLAGS) $1 -of $2 + $(ECHO_END) +endef + define ELFLD $(ECHO_BEGIN)"LD: $2 " - $(Q) $(LD) $(MODLDFLAGS) $(LDMAP) $(LDLIBPATH) $(ARCHCRT0OBJ) $1 $(LDSTARTGROUP) $(LDLIBS) $(LDENDGROUP) -o $2 + $(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) $(ARCHCRT0OBJ) $1 $(LDSTARTGROUP) $(LDLIBS) $(LDENDGROUP) -o $2 $(ECHO_END) endef -define COMPILEAIDL - $(ECHO_BEGIN)"AIDL: $1 " - $(Q) $(AIDL) $(AIDLFLAGS) $($(strip $1)_AIDLFLAGS) $1 - $(ECHO_END) -endef - -define DELAIDLOUT - $(ECHO_BEGIN)"DELAIDLOUT: $1 " - $(Q) $(AIDL) $(AIDLFLAGS) $($(strip $1)_AIDLFLAGS) $1 --delete +# rename "main()" in $1 to "xxx_main()" and save to $2 +define RENAMEMAIN + $(ECHO_BEGIN)"Rename main() in $1 and save to $2" + $(Q) ${shell cat $1 | sed -e "s/fn[ ]\+main/fn $(addsuffix _main,$(PROGNAME_$@))/" > $2} $(ECHO_END) endef $(RAOBJS): %.s$(SUFFIX)$(OBJEXT): %.s - $(if $(and $(CONFIG_MODULES),$(MODAELFFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(AELFFLAGS)), \ $(call ELFASSEMBLE, $<, $@), $(call ASSEMBLE, $<, $@)) $(CAOBJS): %.S$(SUFFIX)$(OBJEXT): %.S - $(if $(and $(CONFIG_MODULES),$(MODAELFFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(AELFFLAGS)), \ $(call ELFASSEMBLE, $<, $@), $(call ASSEMBLE, $<, $@)) $(COBJS): %.c$(SUFFIX)$(OBJEXT): %.c - $(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ $(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@)) $(CXXOBJS): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT) - $(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \ $(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@)) $(RUSTOBJS): %$(RUSTEXT)$(SUFFIX)$(OBJEXT): %$(RUSTEXT) - $(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ $(call ELFCOMPILERUST, $<, $@), $(call COMPILERUST, $<, $@)) $(ZIGOBJS): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT) - $(if $(and $(CONFIG_MODULES), $(CELFFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE), $(CELFFLAGS)), \ $(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@)) -$(AIDLOBJS): %$(CXXEXT): %$(AIDLEXT) - $(call COMPILEAIDL, $<) +$(DOBJS): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT) + $(if $(and $(CONFIG_BUILD_LOADABLE), $(CELFFLAGS)), \ + $(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@)) AROBJS := ifneq ($(OBJS),) @@ -251,20 +249,24 @@ endif ifeq ($(BUILD_MODULE),y) $(MAINCXXOBJ): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT) - $(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \ $(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@)) $(MAINCOBJ): %.c$(SUFFIX)$(OBJEXT): %.c - $(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ $(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@)) -$(PROGLIST): $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) +$(MAINZIGOBJ): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT) + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ + $(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@)) + +$(MAINDOBJ): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT) + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ + $(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@)) + +$(PROGLIST): $(MAINCOBJ) $(MAINCXXOBJ) $(MAINRUSTOBJ) $(MAINZIGOBJ) $(MAINDOBJ) $(Q) mkdir -p $(BINDIR) -ifneq ($(CONFIG_DEBUG_LINK_MAP),) - $(eval PROGNAME_$@ := $(basename $(notdir $@))) - $(eval LDMAP := --cref -Map $(PROGNAME_$@).map) -endif - $(call ELFLD,$(PROGOBJ_$@),$(call CONVERT_PATH,$@)) + $(call ELFLD, $(PROGOBJ_$@), $(call CONVERT_PATH,$@)) $(Q) chmod +x $@ ifneq ($(CONFIG_DEBUG_SYMBOLS),y) $(Q) $(STRIP) $@ @@ -278,32 +280,35 @@ else $(MAINCXXOBJ): %$(CXXEXT)$(SUFFIX)$(OBJEXT): %$(CXXEXT) $(eval $<_CXXFLAGS += ${shell $(DEFINE) "$(CXX)" main=$(addsuffix _main,$(PROGNAME_$@))}) $(eval $<_CXXELFFLAGS += ${shell $(DEFINE) "$(CXX)" main=$(addsuffix _main,$(PROGNAME_$@))}) - $(if $(and $(CONFIG_MODULES),$(MODCXXFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CXXELFFLAGS)), \ $(call ELFCOMPILEXX, $<, $@), $(call COMPILEXX, $<, $@)) $(MAINCOBJ): %.c$(SUFFIX)$(OBJEXT): %.c $(eval $<_CFLAGS += ${DEFINE_PREFIX}main=$(addsuffix _main,$(PROGNAME_$@))) $(eval $<_CELFFLAGS += ${DEFINE_PREFIX}main=$(addsuffix _main,$(PROGNAME_$@))) - $(if $(and $(CONFIG_MODULES),$(MODCFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ $(call ELFCOMPILE, $<, $@), $(call COMPILE, $<, $@)) $(MAINRUSTOBJ): %$(RUSTEXT)$(SUFFIX)$(OBJEXT): %$(RUSTEXT) - $(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \ + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ $(call ELFCOMPILERUST, $<, $@), $(call COMPILERUST, $<, $@)) $(MAINZIGOBJ): %$(ZIGEXT)$(SUFFIX)$(OBJEXT): %$(ZIGEXT) - $(if $(and $(CONFIG_MODULES),$(CELFFLAGS)), \ - $(call ELFCOMPILEZIG, $<, $@), $(call COMPILEZIG, $<, $@)) + $(Q) $(call RENAMEMAIN, $<, $(basename $<)_tmp.zig) + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ + $(call ELFCOMPILEZIG, $(basename $<)_tmp.zig, $@), $(call COMPILEZIG, $(basename $<)_tmp.zig, $@)) + $(Q) rm -f $(basename $<)_tmp.zig + +$(MAINDOBJ): %$(DEXT)$(SUFFIX)$(OBJEXT): %$(DEXT) + $(if $(and $(CONFIG_BUILD_LOADABLE),$(CELFFLAGS)), \ + $(call ELFCOMPILED, $<, $@), $(call COMPILED, $<, $@)) install:: @: endif # BUILD_MODULE -postinstall:: - @: - -context:: $(AIDLOBJS) +context:: @: ifeq ($(DO_REGISTRATION),y) @@ -326,7 +331,7 @@ endif .depend: Makefile $(wildcard $(foreach SRC, $(SRCS), $(addsuffix /$(SRC), $(subst :, ,$(VPATH))))) $(DEPCONFIG) $(call SPLITVARIABLE,ALL_DEP_OBJS,$^,100) $(foreach BATCH, $(ALL_DEP_OBJS_TOTAL), \ - $(shell $(MKDEP) $(DEPPATH) --obj-suffix .c$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.c,$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \ + $(shell $(MKDEP) $(DEPPATH) --obj-suffix .c$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.c,$(ALL_DEP_OBJS_$(BATCH))) >Make.dep) \ $(shell $(MKDEP) $(DEPPATH) --obj-suffix .S$(SUFFIX)$(OBJEXT) "$(CC)" -- $(CFLAGS) -- $(filter %.S,$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \ $(shell $(MKDEP) $(DEPPATH) --obj-suffix $(CXXEXT)$(SUFFIX)$(OBJEXT) "$(CXX)" -- $(CXXFLAGS) -- $(filter %$(CXXEXT),$(ALL_DEP_OBJS_$(BATCH))) >>Make.dep) \ ) @@ -342,7 +347,6 @@ clean:: distclean:: clean $(call DELFILE, Make.dep) $(call DELFILE, .depend) - $(foreach AIDLSRC,$(AIDLSRCS),$(call DELAIDLOUT,$(AIDLSRC))) -include Make.dep diff --git a/CMakeLists.txt b/CMakeLists.txt index c2f1f4b4b..5b2fd150f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,7 +27,6 @@ # ~~~ if(CONFIG_APPS_DIR) - include(nuttx_add_aidl) nuttx_add_library(apps) if(NOT EXISTS {NUTTX_APPS_BINDIR}/dummy.c) file(TOUCH ${NUTTX_APPS_BINDIR}/dummy.c) @@ -60,22 +59,15 @@ add_subdirectory(platform) add_subdirectory(sdr) add_subdirectory(system) add_subdirectory(testing) +add_subdirectory(tools) add_subdirectory(wireless) # add examples and external at the end to allow library dependencies add_subdirectory(examples) -if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt) +if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/external) add_subdirectory(external) endif() -if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/frameworks/CMakeLists.txt) - add_subdirectory(frameworks) -endif() - -if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/vendor/CMakeLists.txt) - add_subdirectory(vendor) -endif() - add_subdirectory(builtin) # must be last nuttx_generate_kconfig() diff --git a/LICENSE b/LICENSE index 93ed520f1..61fb28ab4 100644 --- a/LICENSE +++ b/LICENSE @@ -1873,3 +1873,378 @@ apps/crypto/libsodium WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +apps/crypto/wolfssl +=================== + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. + +apps/testing/sd_stress +apps/testing/sd_bench +=================== + +Copyright (c) 2016-2021 PX4 Development Team. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. +3. Neither the name PX4 nor the names of its contributors may be + used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/Make.defs b/Make.defs index 1b3e2e17e..4f97aa804 100644 --- a/Make.defs +++ b/Make.defs @@ -54,11 +54,7 @@ $(foreach BDIR, $(BUILDIRS), $(eval $(call Add_Application,$(BDIR)))) CXXEXT ?= .cxx RUSTEXT ?= .rs ZIGEXT ?= .zig -AIDLEXT ?= .aidl - -# Tools - -AIDL ?= aidl +DEXT ?= .d # Library path @@ -166,7 +162,7 @@ endef define AROBJSRULES $(1) : $(2) - @ cp $(2) $(1) + cp $(2) $(1) endef # CLEANAROBJS - del AR target files exclusively @@ -174,9 +170,17 @@ endef ifeq ($(CONFIG_WINDOWS_NATIVE),y) define CLEANAROBJS $(call DELFILE,$(subst /,\,$(AROBJS))) + $(call DELFILE,$(subst /,\,$(OBJS))) + $(eval OBJS :=) endef else define CLEANAROBJS - $(foreach AROBJ, $(AROBJS), $(shell rm -f $(AROBJ))) + $(call SPLITVARIABLE,CLEAN_AROBJS,${AROBJS},100) + $(foreach BATCH, $(CLEAN_AROBJS_TOTAL), \ + $(shell rm -rf $(CLEAN_AROBJS_$(BATCH)))) + $(call SPLITVARIABLE,CLEAN_OBJS,${OBJS},100) + $(foreach BATCH, $(CLEAN_OBJS_TOTAL), \ + $(shell rm -rf $(CLEAN_OBJS_$(BATCH)))) + $(eval OBJS :=) endef endif \ No newline at end of file diff --git a/Makefile b/Makefile index 1befcc3c7..4da8a1528 100644 --- a/Makefile +++ b/Makefile @@ -45,12 +45,11 @@ SYMTABOBJ = $(SYMTABSRC:.c=$(OBJEXT)) all: $(BIN) .PHONY: import install dirlinks export .depdirs preconfig depend clean distclean -.PHONY: context postinstall clean_context context_all postinstall_all register register_all +.PHONY: context clean_context context_all register register_all .PRECIOUS: $(BIN) $(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),all))) $(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),install))) -$(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),postinstall))) $(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),context))) $(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),register))) $(foreach SDIR, $(CONFIGURED_APPS), $(eval $(call SDIR_template,$(SDIR),depend))) @@ -65,6 +64,25 @@ $(INCDIR): $(TOPDIR)/tools/incdir.c IMPORT_TOOLS = $(MKDEP) $(INCDIR) +ifeq ($(CONFIG_TOOLS_WASM_BUILD),y) + +configure_wasm: + $(Q) cmake -B$(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build \ + $(APPDIR)$(DELIM)tools$(DELIM)Wasm \ + -DAPPDIR=$(APPDIR) -DTOPDIR=$(TOPDIR) \ + -DWASI_SDK_PATH=$(WASI_SDK_PATH) \ + -DKCONFIG_FILE_PATH=$(TOPDIR)$(DELIM).config + +context_wasm: configure_wasm + $(Q) cmake --build $(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build + +else + +context_wasm: + +endif + + # In the KERNEL build, we must build and install all of the modules. No # symbol table is needed @@ -77,7 +95,6 @@ $(BIN): $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_all) .import: $(BIN) $(Q) install libapps.a $(APPDIR)$(DELIM)import$(DELIM)libs $(Q) $(MAKE) install - $(Q) $(MAKE) postinstall import: $(IMPORT_TOOLS) $(Q) $(MAKE) context TOPDIR="$(APPDIR)$(DELIM)import" @@ -90,7 +107,7 @@ else # In FLAT and protected modes, the modules have already been created. A # symbol table is required. -ifeq ($(CONFIG_MODULES),) +ifeq ($(CONFIG_BUILD_LOADABLE),) ifeq ($(CONFIG_WINDOWS_NATIVE),y) $(BIN): $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_all) else @@ -112,10 +129,9 @@ $(BIN): $(SYMTABOBJ) $(call ARLOCK, $(call CONVERT_PATH,$(BIN)), $^) $(call LINK_WASM) -endif # !CONFIG_MODULES +endif # !CONFIG_BUILD_LOADABLE install: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_install) - $(Q) $(MAKE) postinstall_all # Link nuttx @@ -151,7 +167,6 @@ dirlinks: context_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_context) register_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_register) -postinstall_all: $(foreach SDIR, $(CONFIGURED_APPS), $(SDIR)_postinstall) staging: $(Q) mkdir -p $@ @@ -159,6 +174,7 @@ staging: context: | staging $(Q) $(MAKE) context_all $(Q) $(MAKE) register_all + $(Q) $(MAKE) context_wasm Kconfig: $(foreach SDIR, $(CONFIGDIRS), $(call MAKE_template,$(SDIR),preconfig)) @@ -209,4 +225,5 @@ distclean: $(foreach SDIR, $(CLEANDIRS), $(SDIR)_distclean) $(call DELDIR, $(BINDIR)) $(call DELDIR, staging) $(call DELDIR, wasm) + $(call DELDIR, $(APPDIR)$(DELIM)tools$(DELIM)Wasm$(DELIM)build) $(call CLEAN) diff --git a/audioutils/fmsynth/test/Makefile b/audioutils/fmsynth/test/Makefile index 7031c15e0..65bdf923d 100644 --- a/audioutils/fmsynth/test/Makefile +++ b/audioutils/fmsynth/test/Makefile @@ -1,3 +1,23 @@ +############################################################################ +# apps/audioutils/fmsynth/test/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + SRCS = ../fmsynth_eg.c ../fmsynth_op.c ../fmsynth.c CFLAGS = -DFAR= -DCODE= -DOK=0 -DERROR=-1 -I .. -I ../../../include -g diff --git a/audioutils/mml_parser/README.md b/audioutils/mml_parser/README.md deleted file mode 100644 index 95dde0126..000000000 --- a/audioutils/mml_parser/README.md +++ /dev/null @@ -1,211 +0,0 @@ -# Music Macro Language (MML) Parser library - -MML has often been used as a language for describing music in strings, for example, -in the BASIC language. The mml_parser is a minimalistic Music Macro Language parser -library written in pure C intended for resource-constrained platforms, especially -microcontrollers and other embedded systems. - -## Supported Syntax on this library - -### Notes - -* **C** (Do) -* **D** (Re) -* **E** (Mi) -* **F** (Fa) -* **G** (Sol) -* **A** (La) -* **B** (Ti) - -### Sharp and Flat - -Add "#" or "+" after the note indicates Sharp. ex: ``"C#"`` ``"C+."`` -Add "-" after the note indicates Flat. ex: ``"C-"`` - -### Length - -Length of the tone can be specified in two ways. -One is to specify a length for each note. Add a number after the note in 1, 2, 4, 8, 16, 32 or 64. -ex: ``"C8 C16 C#4."`` - -The other is to use ``L`` . The ``L`` sets default length. If the note without length, the number which is -indicated by the "L" is used. The number followed after the "L" can be in 1, 2, 4, 8, 16, 32 or 64. -ex: ``"L4 A"`` means "A" with length 4. - -In addition, dot is supported. For example, length of "C4." is 4 + 8. Length of "C16.." is 4 + 8 + 16. - -### Rest - -Rest is represented by "R". -Length of the rest is following after the "R" as the same as the note length. If no length is -specified, the length specified by the ”L" is used. - -### Chord - -Chord is supported. If some notes are enclosed in parentheses by ``[`` and ``]``, they are interpreted as -a chord. ex: ``"[CEG]"`` is a chord of Do, Mi and Sol. -Chord's length can be put after ``]`` . ex: ``"[CEG]4"`` is a chord with 4 length. - -Note: Max notes in a chord is defined as MAX_CHORD_NOTES in ``mml_parser.h``. - -### Tuplet - -Tuplet is supported. If some notes and Chord are enclosed in parentheses by ``{`` and ``}``, they are -interpreted as a tuplet. ex: ``"{C E G [CEG]}"`` is a tuplet with C, E, G and chord of CEG. -Tuplet's length can be put after "}", and the length is divided equally among each note. -ex: in ``"{C E G [CEG]}4"`` case, C, E, G and chord CEG has each a quarter of the L4 length. - -### Octave - -Octarve is controlled by "O", ">" or "<". -When "O" is used, the O is followed by a number indicating the octave. -When ">" is used, the value of the new octave is the current octave plus one. -When "<" is used, the value of the new octave is the current octave minus one. -ex: ``"CDEFGAB > C R C < BAGFEDC"``, ``"O4 CDEFGAB O5 C R C O4 BAGFEDC"`` - -### Tempo - -Tempo is indicated as "T" and numter following after the "T". -Tempo number decide a speed of the score. This value is used for culculating sample number for -the note (or rest). -ex: ``"T120"`` - -### Volume - -Volume can be controlled by "V". And numter following after the "V". -ex: ``"V4"`` - -## Example of a score - -### The beginning of the Do Re Mi Song. - -Tempo 120, Voulume 10, Octave 4, Default length is 4. - -``"T120 V10 O4 L4 C. D8 E. C8 E C E2 D. E8 {FF} {ED} F2"`` - -## Provided C Functions - -mml_parser is providing just 2 functions. - -### init_mml() - -Initialize an instance of mml parser. - -#### Synopsis - -```c -#include - -int init_mml(FAR struct music_macro_lang_s *mml, - int fs, int tempo, int octave, int length); -``` - -#### Description - -The function initializes `struct music_macro_lang_s` instance provided as 1st argument. -The argument `fs` is a sampling frequency of target audio output system, and this value is used for -calculating sample number in case of a tempo and length of note. -`tempo`, `octave` and `length` specify initial values for tempo, octave, and length, respectively. - -#### Return value - -On success, init_mml() returns 0. On error, it returns an negative value. - -#### Errors - -Currently no error is happened. - -### parse_mml() - -Parse MML from given string. - -#### Synopsis - -```c -#include - -int parse_mml(FAR struct music_macro_lang_s *mml, - FAR char **score, FAR struct mml_result_s *result); -``` - -#### Description - -parse_mml() parses the first MML of the string given by the argument ``score`` and gives -the result in the return value and the argument ``result``. -The ``result`` is an instance of mml_result_s, which contains note_idx, length, and -chord_notes as members. The meaning of the value of each member depends on the return value. - -#### Return value - -On error, a nevative value is returned. -On success, following values can be returned. And those values are defined in ``mml_parser.h``. - -| Return values | Description | -| -------------------- | ----------- | -| MML_TYPE_EOF | This means that it have reached the end of the string. The content of the ``result`` has no meaning. | -| MML_TYPE_NOTE | This indicates that some note has been parsed. The scale of the note is stored in ``note_idx[0]``. The length of the note is given by the ``length`` member as the number of samples. In the case of tuplet, this return value is returned at the time each note is parsed. In other words, a tuplet is parsed as a single note. | -| MML_TYPE_REST | This indicates the ``rest`` has been parsed. The length of it is given by the ``length`` member as the number of samples. | -| MML_TYPE_TEMPO | This indicates ``"T"`` is parsed. ``length`` member in ``result`` has the value of the tempo. But tempo value is kept in mml instance for calculating sample number for each notes. So basically, no need to handle this return value in your code. | -| MML_TYPE_LENGTH | This indicates ``"L"`` is parsed. ``length`` member in ``result`` has the value of the parsed length. But current length value is kept in mml instance. So basically, no need to handle this return value in your code. | -| MML_TYPE_OCTAVE | This indicates ``"O"``, ``">"``, or ``"<"`` is parsed. ``length`` member in ``result`` has the value of the octave. But the octave is encoded in ``note_idx`` in ``MML_TYPE_NOTE`` case. So basically, no need to handle this return value in your code. | -| MML_TYPE_TUPLETSTART | This indicates tuplet is just started. And total length of the tuplet is stored in ``length`` of ``result`` members. | -| MML_TYPE_TUPLETDONE | This indicates the tuplet is just finished. | -| MML_TYPE_VOLUME | This indicates ``"V"`` is parsed. ``length`` member in ``result`` has the value of the parsed volume. | -| MML_TYPE_TONE | T.B.D. | -| MML_TYPE_CHORD | This indicates a chord is parsed. Chord has some notes, and how many notes is stored in ``chord_notes`` member of ``result``. And each notes are stored in ``note_idx[]``. Length of the chord is stored in ``length`` member of ``result``. | - -The value of ``note_idx[]`` is encoding octave, like - -| Octave | Note | node_idx value | -| ------ | ---- |:--------------:| -| O0 | C | 0 | -| O0 | C# | 1 | -| O0 | D | 2 | -| O0 | D# | 3 | -| O0 | E | 4 | -| O0 | F | 5 | -| O0 | F# | 6 | -| O0 | G | 7 | -| O0 | G# | 8 | -| O0 | A | 9 | -| O0 | A# | 10 | -| O0 | B | 11 | -| O1 | C | 12 | - -And so on. - -So for example, G# at Octave 4 is encoded as 56. - -#### Errors - -Following error code can be received as return value. - -| Error code | Description | -| ------------------------------ | -------------- | -| MML_TYPE_NOTE_ERROR | | -| MML_TYPE_REST_ERROR | | -| MML_TYPE_TEMPO_ERROR | | -| MML_TYPE_LENGTH_ERROR | | -| MML_TYPE_OCTAVE_ERROR | | -| MML_TYPE_VOLUME_ERROR | | -| MML_TYPE_TUPLET_ERROR | | -| MML_TYPE_TONE_ERROR | | -| MML_TYPE_CHORD_ERROR | | -| MML_TYPE_ILLIGAL_COMPOSITION | | -| MML_TYPE_ILLIGAL_TOOMANY_NOTES | | -| MML_TYPE_ILLIGAL_TOOFEW_NOTES | | -| MML_TYPE_ILLIGAL_DOUBLE_TUPLET | | - - -## Running unit tests - -Please see examples/mml_parser - -## Bugs - -There are plenty. Report them on GitHub, or - even better - open a pull request. -Please write unit tests for any new functions you add - it's fun! - -## Author - -mml_parser was written by Takayoshi Koizumi <takayoshi.koizumi@gmail.com> diff --git a/audioutils/nxaudio/nxaudio.c b/audioutils/nxaudio/nxaudio.c index 68d709a0b..1ac3d0979 100644 --- a/audioutils/nxaudio/nxaudio.c +++ b/audioutils/nxaudio/nxaudio.c @@ -68,7 +68,7 @@ static int configure_audio(int fd, int ch, int fs, int bps, int chmap) * name: create_audiomq ****************************************************************************/ -static mqd_t create_audiomq(int fd, int buf_num) +static mqd_t create_audiomq(const char *mqname, int fd, int buf_num) { mqd_t ret; struct mq_attr attr; @@ -78,8 +78,7 @@ static mqd_t create_audiomq(int fd, int buf_num) attr.mq_curmsgs = 0; attr.mq_flags = 0; - ret = mq_open(CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME, - O_RDWR | O_CREAT, 0644, &attr); + ret = mq_open(mqname, O_RDWR | O_CREAT, 0644, &attr); if (ret >= (mqd_t)0) { int rr; @@ -147,14 +146,13 @@ static void free_audio_buffers(FAR struct nxaudio_s *nxaudio) void fin_nxaudio(FAR struct nxaudio_s *nxaudio) { - free_audio_buffers(nxaudio); - ioctl(nxaudio->fd, AUDIOIOC_STOP, 0); + ioctl(nxaudio->fd, AUDIOIOC_SHUTDOWN, 0); ioctl(nxaudio->fd, AUDIOIOC_UNREGISTERMQ, (unsigned long)nxaudio->mq); ioctl(nxaudio->fd, AUDIOIOC_RELEASE, 0); - ioctl(nxaudio->fd, AUDIOIOC_SHUTDOWN, 0); + free_audio_buffers(nxaudio); + close(nxaudio->fd); mq_close(nxaudio->mq); mq_unlink(CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME); - close(nxaudio->fd); } /**************************************************************************** @@ -163,10 +161,23 @@ void fin_nxaudio(FAR struct nxaudio_s *nxaudio) int init_nxaudio(FAR struct nxaudio_s *nxaudio, int fs, int bps, int chnum) +{ + return init_nxaudio_devname(nxaudio, fs, bps, chnum, + CONFIG_AUDIOUTILS_NXAUDIO_DEVPATH, + CONFIG_AUDIOUTILS_NXAUDIO_MSGQNAME); +} + +/**************************************************************************** + * name: init_nxaudio_devname + ****************************************************************************/ + +int init_nxaudio_devname(FAR struct nxaudio_s *nxaudio, + int fs, int bps, int chnum, + const char *devname, const char *mqname) { struct ap_buffer_info_s buf_info; - nxaudio->fd = open(CONFIG_AUDIOUTILS_NXAUDIO_DEVPATH, O_RDWR | O_CLOEXEC); + nxaudio->fd = open(devname, O_RDWR | O_CLOEXEC); if (nxaudio->fd >= 0) { if (ioctl(nxaudio->fd, AUDIOIOC_RESERVE, 0) < 0) @@ -186,7 +197,8 @@ int init_nxaudio(FAR struct nxaudio_s *nxaudio, /* Create message queue to communicate with audio driver */ - nxaudio->mq = create_audiomq(nxaudio->fd, buf_info.nbuffers + 8); + nxaudio->mq = create_audiomq(mqname, nxaudio->fd, + buf_info.nbuffers + 8); /* Create audio buffers to inject audio sample */ @@ -218,6 +230,24 @@ int nxaudio_enqbuffer(FAR struct nxaudio_s *nxaudio, (unsigned long)(uintptr_t)&desc); } +/**************************************************************************** + * name: nxaudio_pause + ****************************************************************************/ + +int nxaudio_pause(FAR struct nxaudio_s *nxaudio) +{ + return ioctl(nxaudio->fd, AUDIOIOC_PAUSE, 0); +} + +/**************************************************************************** + * name: nxaudio_resume + ****************************************************************************/ + +int nxaudio_resume(FAR struct nxaudio_s *nxaudio) +{ + return ioctl(nxaudio->fd, AUDIOIOC_RESUME, 0); +} + /**************************************************************************** * name: nxaudio_setvolume ****************************************************************************/ @@ -252,6 +282,8 @@ int nxaudio_stop(FAR struct nxaudio_s *nxaudio) { struct audio_msg_s term_msg; + ioctl(nxaudio->fd, AUDIOIOC_STOP, 0); + term_msg.msg_id = AUDIO_MSG_STOP; term_msg.u.data = 0; mq_send(nxaudio->mq, (FAR const char *)&term_msg, sizeof(term_msg), 0); diff --git a/testing/events/CMakeLists.txt b/benchmarks/cachespeed/CMakeLists.txt similarity index 81% rename from testing/events/CMakeLists.txt rename to benchmarks/cachespeed/CMakeLists.txt index 63e6a275e..f41b75a2f 100644 --- a/testing/events/CMakeLists.txt +++ b/benchmarks/cachespeed/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/testing/events/CMakeLists.txt +# apps/benchmarks/cachespeed/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,16 +18,14 @@ # # ############################################################################## -if(CONFIG_TESTING_PERF) +if(CONFIG_BENCHMARK_CACHESPEED) nuttx_add_application( NAME - perf_test - PRIORITY - ${CONFIG_TESTING_PERF_PRIORITY} - STACKSIZE - ${CONFIG_TESTING_PERF_STACKSIZE} - MODULE - ${CONFIG_TESTING_PERF} + ${CONFIG_BENCHMARK_CACHESPEED_PROGNAME} SRCS - perf_test.c) + cachespeed_main.c + STACKSIZE + ${CONFIG_BENCHMARK_CACHESPEED_STACKSIZE} + PRIORITY + ${CONFIG_BENCHMARK_CACHESPEED_PRIORITY}) endif() diff --git a/benchmarks/cachespeed/cachespeed_main.c b/benchmarks/cachespeed/cachespeed_main.c index 30bd06eef..c8934e437 100644 --- a/benchmarks/cachespeed/cachespeed_main.c +++ b/benchmarks/cachespeed/cachespeed_main.c @@ -141,7 +141,7 @@ static void report_line(size_t bytes, TIME cost) if (cost == 0) { - printf(CACHESPEED_PREFIX "%zu bytes cost time too small!\n", bytes); + printf(CACHESPEED_PREFIX "%d bytes cost time too small!\n", bytes); return; } @@ -149,7 +149,7 @@ static void report_line(size_t bytes, TIME cost) rate = 1.00 * bytes * REPEAT_NUM / cost; - printf("%zu Bytes: %4lf, %4" PRIu64", %4" PRIu64"\n\r", + printf("%d Bytes: %4lf, %4llu, %4llu\n\r", bytes, rate, cost / REPEAT_NUM, cost); } diff --git a/benchmarks/coremark-pro/.gitignore b/benchmarks/coremark-pro/.gitignore deleted file mode 100644 index 617cd88b8..000000000 --- a/benchmarks/coremark-pro/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/coremark-pro diff --git a/benchmarks/coremark-pro/CMakeLists.txt b/benchmarks/coremark-pro/CMakeLists.txt deleted file mode 100644 index 119fec2a0..000000000 --- a/benchmarks/coremark-pro/CMakeLists.txt +++ /dev/null @@ -1,314 +0,0 @@ -# ############################################################################## -# apps/benchmarks/coremark-pro/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_BENCHMARK_COREMARK_PRO) - - nuttx_add_library(coremark_pro STATIC) - - set(CSRCS - coremark-pro/mith/src/md5.c - coremark-pro/mith/src/mith_lib.c - coremark-pro/mith/src/mith_workload.c - coremark-pro/mith/src/th_bignum.c - coremark-pro/mith/src/th_encode.c - coremark-pro/mith/src/th_lib.c - coremark-pro/mith/src/th_math.c - coremark-pro/mith/src/th_rand.c) - - file(GLOB MITH_AL_SRCS coremark-pro/mith/al/src/*.c) - - list(APPEND CSRCS ${MITH_AL_SRCS}) - - set(CFLAGS - -Wno-undef - -Wno-strict-prototypes - -Wno-unused-variable - -Wno-pointer-sign - -Wno-unused-but-set-variable - -Wno-shadow - -DNDEBUG - -DHOST_EXAMPLE_CODE=1 - -DHAVE_SYS_STAT_H=1 - -DGCC_INLINE_MACRO=1 - -DMAX_CONTEXTS=100 - -DEE_SIZEOF_INT=4 - -DUSE_FP128=0) - - set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/coremark-pro/mith/include - ${CMAKE_CURRENT_LIST_DIR}/coremark-pro/mith/al/include) - - if(CONFIG_BENCHMARK_COREMARK_PRO_USE_SINGLE_CONTEXT) - list(APPEND CFLAGS -DUSE_SINGLE_CONTEXT=1 -DHAVE_PTHREAD=0 - -DUSE_NATIVE_PTHREAD=0) - else() - list(APPEND CFLAGS -DUSE_SINGLE_CONTEXT=0 -DHAVE_PTHREAD=1 - -DUSE_NATIVE_PTHREAD=1) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_SMP) - list(APPEND CFLAGS -DHAVE_PTHREAD_SETAFFINITY_NP=1 -DHAVE_PTHREAD_SELF=1) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_64BIT) - list(APPEND CFLAGS -DEE_SIZEOF_PTR=8 -DEE_PTR_ALIGN=8 -DEE_SIZEOF_LONG=8) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64) - - list(APPEND CFLAGS -DUSE_FP64=1 -DUSE_FP32=0) - list(APPEND CSRCS coremark-pro/benchmarks/fp/linpack/ref/inputs_f64.c) - - else() - list(APPEND CFLAGS -DUSE_FP32=1 -DUSE_FP64=0) - list(APPEND CSRCS coremark-pro/benchmarks/fp/linpack/ref/inputs_f32.c) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_CORE_TEST) - file(GLOB CORE_TEST_SRCS coremark-pro/benchmarks/core/*.c) - set(CORE_TEST_CSRCS coremark-pro/workloads/core/core.c ${CORE_TEST_SRCS}) - nuttx_add_application( - NAME - core - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${CORE_TEST_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_CJPEG_TEST) - file(GLOB CJPEG_SRCS coremark-pro/benchmarks/consumer_v2/cjpeg/*.c) - set(CJPEG_CSRCS - coremark-pro/workloads/cjpeg-rose7-preset/cjpeg-rose7-preset.c - coremark-pro/benchmarks/consumer_v2/cjpeg/data/Rose256_bmp.c - ${CJPEG_SRCS}) - nuttx_add_application( - NAME - cjpeg_rose7_preset - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${CJPEG_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_SHA_TEST) - file(GLOB SHA_TEST_SRCS coremark-pro/benchmarks/darkmark/sha/*.c) - set(SHA_TEST_CSRCS coremark-pro/workloads/sha-test/sha-test.c - ${SHA_TEST_SRCS}) - nuttx_add_application( - NAME - sha_test - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${SHA_TEST_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_ZIP_TEST) - set(ZIP_TEST_CSRCS coremark-pro/workloads/zip-test/zip-test.c - coremark-pro/benchmarks/darkmark/zip/zip_darkmark.c) - set(ZIP_TEST_FLAGS ${CFLAGS} -Dgzclose_r=coremark_zip_gzclose_r - -Dgzclose_w=coremark_zip_gzclose_w) - set(ZIP_TEST_INCDIR ${INCDIR} ${NUTTX_APPS_DIR}/system/zlib/zlib) - nuttx_add_application( - NAME - zip_test - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${ZIP_TEST_FLAGS} - SRCS - ${ZIP_TEST_CSRCS} - INCLUDE_DIRECTORIES - ${ZIP_TEST_INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_LINEAR_ALG_MID_TEST) - set(ALG_MID_CSRCS - coremark-pro/workloads/linear_alg-mid-100x100-sp/linear_alg-mid-100x100-sp.c - coremark-pro/benchmarks/fp/linpack/linpack.c) - nuttx_add_application( - NAME - linear_alg_mid_100x100_sp - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${ALG_MID_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_RADIX_TEST) - if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64) - file(GLOB RADIX_SRCS coremark-pro/benchmarks/fp/fft_radix2/ref/*.c) - else() - file(GLOB RADIX_SRCS coremark-pro/benchmarks/fp/fft_radix2/ref-sp/*.c) - endif() - - set(RADIX_CSRCS - coremark-pro/workloads/radix2-big-64k/radix2-big-64k.c - coremark-pro/benchmarks/fp/fft_radix2/fft_radix2.c ${RADIX_SRCS}) - nuttx_add_application( - NAME - radix2_big_64k - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${RADIX_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_LOOPS_ALL_MID_TEST) - if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64) - file(GLOB MID_SRCS coremark-pro/benchmarks/fp/loops/ref/*.c) - else() - file(GLOB MID_SRCS coremark-pro/benchmarks/fp/loops/ref-sp/*.c) - endif() - - set(MID_CSRCS - coremark-pro/workloads/loops-all-mid-10k-sp/loops-all-mid-10k-sp.c - coremark-pro/benchmarks/fp/loops/loops.c ${MID_SRCS}) - nuttx_add_application( - NAME - loops_all_mid_10k_sp - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${MID_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_NNET_TEST) - if(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64) - file(GLOB NNET_SRCS coremark-pro/benchmarks/fp/nnet/ref/*.c) - else() - file(GLOB NNET_SRCS coremark-pro/benchmarks/fp/nnet/ref-sp/*.c) - endif() - file(GLOB FP_NNET_SRCS coremark-pro/benchmarks/fp/nnet/*.c) - set(NNET_CSRCS coremark-pro/workloads/nnet_test/nnet_test.c ${FP_NNET_SRCS} - ${NNET_SRCS}) - nuttx_add_application( - NAME - nnet_test - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${NNET_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - if(CONFIG_BENCHMARK_COREMARK_PRO_PARSER_125K) - file(GLOB PARSER_SRCS coremark-pro/benchmarks/darkmark/parser/*.c) - set(PARSER_CSRCS coremark-pro/workloads/parser-125k/parser-125k.c - ${PARSER_SRCS}) - nuttx_add_application( - NAME - parser_125k - PRIORITY - ${CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_COREMARK_PRO} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${PARSER_CSRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - DEPENDS - coremark_pro) - endif() - - target_sources(coremark_pro PRIVATE ${CSRCS}) - target_include_directories(coremark_pro PRIVATE ${INCDIR}) - target_compile_options(coremark_pro PRIVATE ${CFLAGS}) - -endif() diff --git a/benchmarks/coremark-pro/Makefile b/benchmarks/coremark-pro/Makefile index 0fa3a0986..c0ee5a2a3 100644 --- a/benchmarks/coremark-pro/Makefile +++ b/benchmarks/coremark-pro/Makefile @@ -24,13 +24,10 @@ PRIORITY = $(CONFIG_BENCHMARK_COREMARK_PRO_PRIORITY) STACKSIZE = $(CONFIG_BENCHMARK_COREMARK_PRO_STACKSIZE) MODULE = $(CONFIG_BENCHMARK_COREMARK_PRO) -CFLAGS += -Wno-undef -Wno-strict-prototypes -Wno-unused-variable \ - -Wno-pointer-sign -Wno-unused-but-set-variable -Wno-shadow CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/benchmarks/coremark-pro/coremark-pro/mith/include CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/benchmarks/coremark-pro/coremark-pro/mith/al/include CFLAGS += -DNDEBUG -DHOST_EXAMPLE_CODE=1 -DHAVE_SYS_STAT_H=1 \ -DGCC_INLINE_MACRO=1 -DMAX_CONTEXTS=100 -DEE_SIZEOF_INT=4 \ - -DUSE_FP128=0 ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_USE_SINGLE_CONTEXT),) CFLAGS += -DUSE_SINGLE_CONTEXT=1 -DHAVE_PTHREAD=0 -DUSE_NATIVE_PTHREAD=0 @@ -47,10 +44,10 @@ ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_64BIT),) endif ifneq ($(CONFIG_BENCHMARK_COREMARK_PRO_USE_FP64),) - CFLAGS += -DUSE_FP64=1 -DUSE_FP32=0 + CFLAGS += -DUSE_FP64=1 CSRCS += coremark-pro/benchmarks/fp/linpack/ref/inputs_f64.c else - CFLAGS += -DUSE_FP32=1 -DUSE_FP64=0 + CFLAGS += -DUSE_FP32=1 CSRCS += coremark-pro/benchmarks/fp/linpack/ref/inputs_f32.c endif diff --git a/benchmarks/coremark/CMakeLists.txt b/benchmarks/coremark/CMakeLists.txt index aa6bfa362..c24915eaf 100644 --- a/benchmarks/coremark/CMakeLists.txt +++ b/benchmarks/coremark/CMakeLists.txt @@ -61,56 +61,15 @@ if(CONFIG_BENCHMARK_COREMARK) # Flags # ############################################################################ - if(CONFIG_COREMARK_MULTITHREAD_OVERRIDE) - set(COREMARK_NTHREADS ${CONFIG_COREMARK_MULTITHREAD_COUNT}) - else() - if(CONFIG_SMP_NCPUS) - set(COREMARK_NTHREADS ${CONFIG_SMP_NCPUS}) - else() - set(COREMARK_NTHREADS 1) - endif() - endif() - - if(CONFIG_COREMARK_PRINT_ARGS) - set(COREMARK_PRINT_ARGS 1) - else() - set(COREMARK_PRINT_ARGS 0) - endif() - get_target_property(FLAGS_STR_LIST nuttx COMPILE_OPTIONS) list(JOIN FLAGS_STR_LIST " " FLAGS_STR) - - set(CFLAGS -Dcrc16=coremark_crc16 -Wno-strict-prototypes -Wno-undef) - - if("${CONFIG_COREMARK_MEM_METHOD}" STREQUAL "1") - list(APPEND CFLAGS -DMEM_LOCATION=\"HEAP\") - elseif("${CONFIG_COREMARK_MEM_METHOD}" STREQUAL "2") - list(APPEND CFLAGS -DMEM_LOCATION=\"STACK\") - else() - list(APPEND CFLAGS -DMEM_LOCATION=\"GLOBAL\") - endif() - - list( - APPEND - CFLAGS - -DCALLGRIND_RUN=0 - -DCOMPILER_REQUIRES_SORT_RETURN=0 - -DCORE_DEBUG=${CONFIG_COREMARK_DEBUG} - -DFLAGS_STR="${FLAGS_STR}" - -DMEM_METHOD=${CONFIG_COREMARK_MEM_METHOD} - -DMICA=0 - -DMULTITHREAD=${COREMARK_NTHREADS} - -DPERFORMANCE_RUN=1 - -DPRINT_ARGS=${COREMARK_PRINT_ARGS} - -DSEED_METHOD=${CONFIG_COREMARK_SEED_METHOD} - -DUSE_CLOCK=1 - -DUSE_PTHREAD) + set(CFLAGS + -Wno-undef -DUSE_PTHREAD -DPERFORMANCE_RUN=1 + -DMULTITHREAD=${COREMARK_NTHREADS} -DFLAGS_STR="${FLAGS_STR}" + -DMEM_LOCATION="Stack") if(CONFIG_COREMARK_ITERATIONS_OVERRIDE) list(APPEND CFLAGS -DITERATIONS=${CONFIG_COREMARK_ITERATIONS_COUNT}) - else() - list(APPEND CFLAGS -DITERATIONS=0) - endif() # ############################################################################ @@ -134,7 +93,7 @@ if(CONFIG_BENCHMARK_COREMARK) nuttx_add_application( NAME - ${CONFIG_COREMARK_PROGNAME} + coremark PRIORITY ${CONFIG_COREMARK_PRIORITY} STACKSIZE diff --git a/benchmarks/coremark/Makefile b/benchmarks/coremark/Makefile index 5965e1bf3..2274d0373 100644 --- a/benchmarks/coremark/Makefile +++ b/benchmarks/coremark/Makefile @@ -39,7 +39,6 @@ VPATH += $(COREMARK_UNPACKNAME)$(DELIM)posix DEPPATH += --dep-path $(COREMARK_UNPACKNAME) DEPPATH += --dep-path $(COREMARK_UNPACKNAME)$(DELIM)posix -CFLAGS += -Dcrc16=coremark_crc16 CFLAGS += -Wno-strict-prototypes -Wno-undef ifeq ($(CONFIG_COREMARK_MULTITHREAD_OVERRIDE),y) diff --git a/benchmarks/dhrystone/.gitignore b/benchmarks/dhrystone/.gitignore deleted file mode 100644 index f754bdd4f..000000000 --- a/benchmarks/dhrystone/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/dhrystone diff --git a/benchmarks/dhrystone/Makefile b/benchmarks/dhrystone/Makefile index 17f0912d4..64b90cdec 100644 --- a/benchmarks/dhrystone/Makefile +++ b/benchmarks/dhrystone/Makefile @@ -27,11 +27,10 @@ PRIORITY = $(CONFIG_BENCHMARK_DHRYSTONE_PRIORITY) STACKSIZE = $(CONFIG_BENCHMARK_DHRYSTONE_STACKSIZE) MODULE = $(CONFIG_BENCHMARK_DHRYSTONE) -CFLAGS += -DMSC_CLOCK -Wno-implicit-int -Wno-strict-prototypes -CFLAGS += -Wno-implicit-function-declaration -Wno-return-type -CFLAGS += -Wno-maybe-uninitialized +CFLAGS += -DMSC_CLOCK CSRCS += dhrystone/v2.1/dhry_2.c + MAINSRC = dhrystone/v2.2/dry.c ifeq ($(wildcard dhrystone/.git),) diff --git a/benchmarks/fio/.gitignore b/benchmarks/fio/.gitignore deleted file mode 100644 index 97c3b30d0..000000000 --- a/benchmarks/fio/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/fio diff --git a/benchmarks/fio/CMakeLists.txt b/benchmarks/fio/CMakeLists.txt deleted file mode 100644 index f279bcadc..000000000 --- a/benchmarks/fio/CMakeLists.txt +++ /dev/null @@ -1,169 +0,0 @@ -# ############################################################################## -# apps/benchmarks/fio/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_BENCHMARK_FIO) - - set(FIOAPP_DIR ${CMAKE_CURRENT_LIST_DIR}/fio) - - if(NOT EXISTS ${FIOAPP_DIR}) - FetchContent_Declare( - fio_fetch - URL https://github.com/ldorau/fio/archive/refs/heads/master.zip SOURCE_DIR - ${CMAKE_CURRENT_LIST_DIR}/fio BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/benchmarks/fio/fio - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30 - PATCH_COMMAND - patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0001-external-fio-fix-compile-warning.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0002-external-fio-add-os-nuttx-support.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0003-external-fio-modify-smaller-size-for-nuttx.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0004-external-fio-fix-runtime-error-by-asan.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0005-external-fio-fix-compile-warning.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0006-external-fio-reinit-global-var-issue-when-run-multip.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0007-external-fio-add-engine-init.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0008-fio-fix-memory-leak-run-cpuio.fio.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0009-fio-fix-memory-leak-ioengine-filecreate.patch - COMMAND patch -p1 -d ${CMAKE_CURRENT_LIST_DIR}/fio < - ${CMAKE_CURRENT_LIST_DIR}/0010-fio-fix-memory-leak-ioengine-exec.patch) - - FetchContent_GetProperties(fio_fetch) - if(NOT fio_fetch_POPULATED) - FetchContent_Populate(fio_fetch) - endif() - endif() - - file(GLOB LIB_SRCS ${FIOAPP_DIR}/lib/*.c) - file(GLOB CRC_SRCS ${FIOAPP_DIR}/crc/*.c) - - set(CSRCS - ${LIB_SRCS} - ${CRC_SRCS} - ${FIOAPP_DIR}/gettime.c - ${FIOAPP_DIR}/ioengines.c - ${FIOAPP_DIR}/init.c - ${FIOAPP_DIR}/stat.c - ${FIOAPP_DIR}/log.c - ${FIOAPP_DIR}/time.c - ${FIOAPP_DIR}/filesetup.c - ${FIOAPP_DIR}/eta.c - ${FIOAPP_DIR}/verify.c - ${FIOAPP_DIR}/memory.c - ${FIOAPP_DIR}/io_u.c - ${FIOAPP_DIR}/parse.c - ${FIOAPP_DIR}/fio_sem.c - ${FIOAPP_DIR}/rwlock.c - ${FIOAPP_DIR}/pshared.c - ${FIOAPP_DIR}/options.c - ${FIOAPP_DIR}/smalloc.c - ${FIOAPP_DIR}/filehash.c - ${FIOAPP_DIR}/profile.c - ${FIOAPP_DIR}/debug.c - ${FIOAPP_DIR}/server.c - ${FIOAPP_DIR}/client.c - ${FIOAPP_DIR}/iolog.c - ${FIOAPP_DIR}/backend.c - ${FIOAPP_DIR}/libfio.c - ${FIOAPP_DIR}/flow.c - ${FIOAPP_DIR}/cconv.c - ${FIOAPP_DIR}/gettime-thread.c - ${FIOAPP_DIR}/helpers.c - ${FIOAPP_DIR}/json.c - ${FIOAPP_DIR}/idletime.c - ${FIOAPP_DIR}/td_error.c - ${FIOAPP_DIR}/zbd.c - ${FIOAPP_DIR}/profiles/tiobench.c - ${FIOAPP_DIR}/profiles/act.c - ${FIOAPP_DIR}/io_u_queue.c - ${FIOAPP_DIR}/filelock.c - ${FIOAPP_DIR}/steadystate.c - ${FIOAPP_DIR}/workqueue.c - ${FIOAPP_DIR}/rate-submit.c - ${FIOAPP_DIR}/optgroup.c - ${FIOAPP_DIR}/helper_thread.c - ${FIOAPP_DIR}/zone-dist.c - ${FIOAPP_DIR}/dedupe.c - ${FIOAPP_DIR}/engines/exec.c - ${FIOAPP_DIR}/engines/cpu.c - ${FIOAPP_DIR}/engines/sync.c - ${FIOAPP_DIR}/engines/ftruncate.c - ${FIOAPP_DIR}/engines/falloc.c - ${FIOAPP_DIR}/engines/fileoperations.c - ${FIOAPP_DIR}/engines/mmap.c - ${FIOAPP_DIR}/engines/null.c - ${FIOAPP_DIR}/engines/net.c) - - set(CFLAGS - -DCONFIG_GETTIMEOFDAY - -DCONFIG_CLOCK_GETTIME - -DCONFIG_HAVE_GETTID - -DCONFIG_STATIC_ASSERT - -DCONFIG_LITTLE_ENDIAN - -DCONFIG_POSIX_FALLOCATE - -DCONFIG_HAVE_BOOL - -DFIO_INTERNAL - -DCONFIG_NO_SHM - -DFIO_VERSION=\"1.2.0\" - -DFIO_USE_GENERIC_SWAP - -DFIO_USE_GENERIC_INIT_RANDOM_STATE - -DFIO_USE_GENERIC_BDEV_SIZE - -DBLOOM_SIZE=1024*1024 - -DBUF_SIZE=512*1024 - -DMAX_POOLS=4 - -DINITIAL_POOLS=2 - -DINITIAL_SIZE=512*1024 - -DCONFIG_SEED_BUCKETS=8 - -DBITS_PER_LONG=32 - -DXXH32_digest=fio_XXH32_digest - -DXXH32_update=fio_XXH32_update - -DXXH32=fio_XXH32 - -Dparse_options=fio_parse_options - -Dparse_option=fio_parse_option) - - set(INCDIR ${FIOAPP_DIR} ${FIOAPP_DIR}/arch ${FIOAPP_DIR}/crc - ${FIOAPP_DIR}/os) - include_directories(${INCDIR}) - - if(CONFIG_ARCH_ARM) - list(APPEND CFLAGS -D__ARM_ARCH_6__) - endif() - - set(SRCS ${FIOAPP_DIR}/fio.c ${CSRCS}) - nuttx_add_application( - NAME - fio - PRIORITY - ${CONFIG_BENCHMARK_FIO_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_FIO_STACKSIZE} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${SRCS}) - -endif() diff --git a/benchmarks/iozone/CMakeLists.txt b/benchmarks/iozone/CMakeLists.txt deleted file mode 100644 index 843fa53ac..000000000 --- a/benchmarks/iozone/CMakeLists.txt +++ /dev/null @@ -1,87 +0,0 @@ -# ############################################################################## -# apps/benchmarks/iozone/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_BENCHMARK_IOZONE) - - # Define the directory and file paths - set(IOZONE_VERSION "${CONFIG_BENCHMARK_IOZONE_VERSION}") # Adjust this as - # needed - set(IOZONE_DIR ${CMAKE_CURRENT_LIST_DIR}/iozone) - set(IOZONE_ZIP ${IOZONE_DIR}.tgz) - set(IOZONE_URL - "https://www.iozone.org/src/current/iozone${IOZONE_VERSION}.tgz") - - # Download and unpack iozone if not already present - if(NOT EXISTS ${IOZONE_DIR}) - FetchContent_Declare( - iozone_fetch - URL ${IOZONE_URL} SOURCE_DIR ${IOZONE_DIR} - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30 - PATCH_COMMAND patch -p1 -d ${IOZONE_DIR} < - ${CMAKE_CURRENT_LIST_DIR}/iozone.patch) - - FetchContent_GetProperties(iozone_fetch) - if(NOT iozone_fetch_POPULATED) - FetchContent_Populate(iozone_fetch) - endif() - endif() - - # Define source files - set(CSRCS ${IOZONE_DIR}/src/current/libbif.c) - set(MAINSRC ${IOZONE_DIR}/src/current/iozone.c) - - # Define compile flags - set(CFLAGS - -Dunix - -DHAVE_ANSIC_C - -DHAVE_PREAD - -DNAME=\"nuttx\" - -DNO_MADVISE - -DNO_FORK - -D__FreeBSD__ - -DNO_THREADS - -Wno-unused-parameter - -Wno-unused-function - -Wno-shadow - -Wno-unused-but-set-variable - -Wno-strict-prototypes - -Wno-misleading-indentation - -Wno-maybe-uninitialized - -DMAXBUFFERSIZE=32*1024 - -DMAXSTREAMS=8 - -DMAXNAMESIZE=NAME_MAX - -DRECLEN_START=1024) - - # Add application to the build - set(SRCS ${IOZONE_DIR}/src/current/iozone.c ${CSRCS}) - nuttx_add_application( - NAME - iozone - PRIORITY - ${CONFIG_BENCHMARK_IOZONE_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_IOZONE_STACKSIZE} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${SRCS}) - -endif() diff --git a/benchmarks/iozone/Makefile b/benchmarks/iozone/Makefile index a593dd269..3f11b2ccc 100644 --- a/benchmarks/iozone/Makefile +++ b/benchmarks/iozone/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/benchmarks/iozone/Make.defs +# apps/benchmarks/iozone/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/benchmarks/osperf/osperf.c b/benchmarks/osperf/osperf.c index 66d24ac3f..e4b69827c 100644 --- a/benchmarks/osperf/osperf.c +++ b/benchmarks/osperf/osperf.c @@ -131,7 +131,7 @@ static size_t performance_gettime(FAR struct performance_time_s *result) static FAR void *pthread_switch_task(FAR void *arg) { FAR struct performance_thread_s *perf = arg; - irqstate_t flags = enter_critical_section(); + irq_t flags = enter_critical_section(); sem_wait(&perf->sem); performance_end(&perf->time); leave_critical_section(flags); @@ -281,9 +281,9 @@ static size_t poll_performance(void) poll(&fds, 1, -1); performance_end(&result); - pthread_join(ret, NULL); close(pipefd[0]); close(pipefd[1]); + pthread_join(ret, NULL); return performance_gettime(&result); } @@ -353,7 +353,7 @@ static void performance_run(const FAR struct performance_entry_s *item, for (i = 0; i < count; i++) { - irqstate_t flags = enter_critical_section(); + irq_t flags = enter_critical_section(); size_t time = item->entry(); leave_critical_section(flags); diff --git a/benchmarks/ramspeed/Kconfig b/benchmarks/ramspeed/Kconfig index 19c5b47c7..86e890e42 100644 --- a/benchmarks/ramspeed/Kconfig +++ b/benchmarks/ramspeed/Kconfig @@ -6,7 +6,6 @@ config BENCHMARK_RAMSPEED tristate "RAM Speed Test" default n - depends on LIBC_FLOATINGPOINT ---help--- Enable a simple RAM speed test. diff --git a/benchmarks/ramspeed/ramspeed_main.c b/benchmarks/ramspeed/ramspeed_main.c index 7587606b2..24706e11b 100644 --- a/benchmarks/ramspeed/ramspeed_main.c +++ b/benchmarks/ramspeed/ramspeed_main.c @@ -64,6 +64,17 @@ } \ } while (0) + #define HAS_IRQ_CONTROL !defined(CONFIG_BUILD_KERNEL) && \ + !defined(CONFIG_BUILD_PROTECTED) + + #if HAS_IRQ_CONTROL + # define ENABLE_IRQ(flags) leave_critical_section(flags); + # define DISABLE_IRQ(flags) flags=enter_critical_section(); + #else + # define ENABLE_IRQ(flags) (void)flags; + # define DISABLE_IRQ(flags) (void)flags; + #endif + /**************************************************************************** * Private Types ****************************************************************************/ @@ -76,7 +87,6 @@ struct ramspeed_s uint8_t value; uint32_t repeat_num; bool irq_disable; - bool allocate_rw_address; }; /**************************************************************************** @@ -105,8 +115,10 @@ static void show_usage(FAR const char *progname, int exitcode) " [default value: 0x00].\n"); printf(" -n number of repetitions" " [default value: 100].\n"); + #if HAS_IRQ_CONTROL printf(" -i turn off interrupts while testing" " [default value: false].\n"); + #endif exit(exitcode); } @@ -118,6 +130,7 @@ static void parse_commandline(int argc, FAR char **argv, FAR struct ramspeed_s *info) { int ch; + bool allocate_rw_address = false; memset(info, 0, sizeof(struct ramspeed_s)); info->repeat_num = 100; @@ -133,7 +146,7 @@ static void parse_commandline(int argc, FAR char **argv, switch (ch) { case 'a': - info->allocate_rw_address = true; + allocate_rw_address = true; break; case 'r': OPTARG_TO_VALUE(info->src, const void *, 16); @@ -162,9 +175,11 @@ static void parse_commandline(int argc, FAR char **argv, } break; + #if HAS_IRQ_CONTROL case 'i': info->irq_disable = true; break; + #endif case '?': printf(RAMSPEED_PREFIX "Unknown option: %c\n", (char)optopt); show_usage(argv[0], EXIT_FAILURE); @@ -172,45 +187,17 @@ static void parse_commandline(int argc, FAR char **argv, } } - if ((info->dest == NULL && !info->allocate_rw_address) || info->size == 0) + if (allocate_rw_address) + { + info->dest = malloc(info->size); + info->src = malloc(info->size); + } + + if (info->dest == NULL || info->src == NULL || info->size == 0) { printf(RAMSPEED_PREFIX "Missing required arguments\n"); - goto out; + show_usage(argv[0], EXIT_FAILURE); } - else - { - /* We need to automatically apply for memory */ - - printf(RAMSPEED_PREFIX "Allocate RW buffers on heap\n"); - info->dest = malloc(info->size); - if (info->dest == NULL) - { - printf(RAMSPEED_PREFIX "Dest Alloc Memory Failed!\n"); - goto out; - } - - info->src = malloc(info->size); - if (info->src == NULL) - { - printf(RAMSPEED_PREFIX "Src Alloc Memory Failed!\n"); - goto out; - } - } - - /* Print info */ - - printf(RAMSPEED_PREFIX "Write address: %p\n", info->dest); - printf(RAMSPEED_PREFIX "Read address: %p\n", info->src); - printf(RAMSPEED_PREFIX "Size: %zu bytes\n", info->size); - printf(RAMSPEED_PREFIX "Value: 0x%02x\n", info->value); - printf(RAMSPEED_PREFIX "Repeat number: %" PRIu32 "\n", info->repeat_num); - printf(RAMSPEED_PREFIX "Interrupts disabled: %s\n", - info->irq_disable ? "true" : "false"); - - return; - -out: - show_usage(argv[0], EXIT_FAILURE); } /**************************************************************************** @@ -220,10 +207,10 @@ out: static uint32_t get_timestamp(void) { struct timespec ts; - uint32_t us; + uint32_t ms; clock_gettime(CLOCK_MONOTONIC, &ts); - us = ts.tv_sec * 1000000 + ts.tv_nsec / 1000; - return us; + ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000; + return ms; } /**************************************************************************** @@ -379,7 +366,7 @@ static void internal_memset(FAR void *dst, uint8_t v, size_t len) static void print_rate(FAR const char *name, uint64_t bytes, uint32_t cost_time) { - double rate; + uint32_t rate; if (cost_time == 0) { printf(RAMSPEED_PREFIX @@ -388,10 +375,10 @@ static void print_rate(FAR const char *name, uint64_t bytes, return; } - rate = (double)bytes / 1024 / (cost_time / 1000000.0); + rate = bytes * 1000 / cost_time / 1024; printf(RAMSPEED_PREFIX - "%s Rate = %.3f KB/s\t[cost: %.3f ms]\n", - name, rate, cost_time / 1000.0f); + "%s Rate = %" PRIu32 " KB/s\t[cost: %" PRIu32 "ms]\n", + name, rate, cost_time); } /**************************************************************************** @@ -428,7 +415,7 @@ static void memcpy_speed_test(FAR void *dest, FAR const void *src, if (irq_disable) { - flags = enter_critical_section(); + DISABLE_IRQ(flags); } start_time = get_timestamp(); @@ -451,7 +438,7 @@ static void memcpy_speed_test(FAR void *dest, FAR const void *src, if (irq_disable) { - leave_critical_section(flags); + ENABLE_IRQ(flags); } print_rate("system memcpy():\t", total_size, cost_time_system); @@ -493,7 +480,7 @@ static void memset_speed_test(FAR void *dest, uint8_t value, if (irq_disable) { - flags = enter_critical_section(); + DISABLE_IRQ(flags); } start_time = get_timestamp(); @@ -516,7 +503,7 @@ static void memset_speed_test(FAR void *dest, uint8_t value, if (irq_disable) { - leave_critical_section(flags); + ENABLE_IRQ(flags); } print_rate("system memset():\t", total_size, cost_time_system); @@ -538,24 +525,13 @@ int main(int argc, FAR char *argv[]) parse_commandline(argc, argv, &ramspeed); - if (ramspeed.src != NULL) - { - memcpy_speed_test(ramspeed.dest, ramspeed.src, - ramspeed.size, ramspeed.repeat_num, - ramspeed.irq_disable); - } + memcpy_speed_test(ramspeed.dest, ramspeed.src, + ramspeed.size, ramspeed.repeat_num, + ramspeed.irq_disable); memset_speed_test(ramspeed.dest, ramspeed.value, ramspeed.size, ramspeed.repeat_num, ramspeed.irq_disable); - /* Check if alloc from heap? */ - - if (ramspeed.allocate_rw_address) - { - free(ramspeed.dest); - free((void *)ramspeed.src); - } - return EXIT_SUCCESS; } diff --git a/benchmarks/rt-tests/.gitignore b/benchmarks/rt-tests/.gitignore deleted file mode 100644 index baa0c8710..000000000 --- a/benchmarks/rt-tests/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/rt-tests -/*.zip diff --git a/benchmarks/rt-tests/CMakeLists.txt b/benchmarks/rt-tests/CMakeLists.txt deleted file mode 100644 index abf711354..000000000 --- a/benchmarks/rt-tests/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# - -if(CONFIG_BENCHMARK_RTTESTS) - - list( - APPEND - CFLAGS - -Wno-maybe-uninitialized - -Wno-unused-variable - -Wno-unused-function - -Wno-unused-but-set-variable - -Wno-shadow - -Wno-stringop-truncation - -Wno-strict-prototypes) - - nuttx_add_application( - NAME - cyclictest - PRIORITY - ${CONFIG_BENCHMARK_RTTESTS_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_RTTESTS_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_RTTESTS} - COMPILE_FLAGS - ${CFLAGS} - SRCS - rttests/src/cyclictest/cyclictest.c) -endif() diff --git a/benchmarks/rt-tests/Kconfig b/benchmarks/rt-tests/Kconfig deleted file mode 100644 index 2523aceee..000000000 --- a/benchmarks/rt-tests/Kconfig +++ /dev/null @@ -1,32 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -config BENCHMARK_RTTESTS - tristate "RT-Tests" - default n - ---help--- - Measure the timer jitter - -if BENCHMARK_RTTESTS - -config BENCHMARK_RTTESTS_PRIORITY - int "OS profiling task priority" - default 100 - -config BENCHMARK_RTTESTS_STACKSIZE - int "OS profiling stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/benchmarks/rt-tests/Make.defs b/benchmarks/rt-tests/Make.defs deleted file mode 100644 index 20e4fff58..000000000 --- a/benchmarks/rt-tests/Make.defs +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -ifneq ($(CONFIG_BENCHMARK_RTTESTS),) -CONFIGURED_APPS += $(APPDIR)/benchmarks/rttests -endif diff --git a/benchmarks/rt-tests/Makefile b/benchmarks/rt-tests/Makefile deleted file mode 100644 index 607d12730..000000000 --- a/benchmarks/rt-tests/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -############################################################################ -# Targets -############################################################################ - - -include $(APPDIR)/Make.defs - -PROGNAME = cyclictest -PRIORITY = $(CONFIG_BENCHMARK_RTTESTS_PRIORITY) -STACKSIZE = $(CONFIG_BENCHMARK_RTTESTS_STACKSIZE) -MODULE = $(CONFIG_BENCHMARK_RTTESTS) - -MAINSRC = rttests/src/cyclictest/cyclictest.c - -CFLAGS += -Wno-maybe-uninitialized -Wno-unused-variable -Wno-unused-function -CFLAGS += -Wno-unused-but-set-variable -Wno-shadow -Wno-stringop-truncation -CFLAGS += -Wno-strict-prototypes - -include $(APPDIR)/Application.mk diff --git a/math/ruy/CMakeLists.txt b/benchmarks/spinlock_bench/CMakeLists.txt similarity index 65% rename from math/ruy/CMakeLists.txt rename to benchmarks/spinlock_bench/CMakeLists.txt index 94dbcf730..2707c223a 100644 --- a/math/ruy/CMakeLists.txt +++ b/benchmarks/spinlock_bench/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/math/ruy/CMakeLists.txt +# apps/benchmarks/spinlock_bench/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,43 +18,38 @@ # # ############################################################################## -if(CONFIG_MATH_RUY) +if(CONFIG_BENCHMARK_SPINLOCK) # ############################################################################ - # Config and Fetch ruy lib + # Config and Fetch Coremark application # ############################################################################ - set(RUY_DIR ${CMAKE_CURRENT_LIST_DIR}/ruy) - - if(NOT EXISTS ${RUY_DIR}) - set(RUY_URL - https://github.com/google/ruy/archive/d37128311b445e758136b8602d1bbd2a755e115d.zip - ) - FetchContent_Declare( - ruy_fetch - URL ${RUY_URL} SOURCE_DIR ${RUY_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/math/ruy/ruy - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(ruy_fetch) - - if(NOT ruy_fetch_POPULATED) - FetchContent_Populate(ruy_fetch) - endif() - endif() + set(SPINLOCKAPP_DIR ${CMAKE_CURRENT_LIST_DIR}) # ############################################################################ - # Include Directory + # Sources # ############################################################################ - set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/ruy) + set(CSRCS ${SPINLOCKAPP_DIR}/spinlock_bench.c) # ############################################################################ - # Library Configuration + # Applications Configuration # ############################################################################ - nuttx_add_library(ruy STATIC) - target_include_directories(ruy PUBLIC ${INCDIR}) + nuttx_add_application( + NAME + spinlock_bench + PRIORITY + ${CONFIG_SPINLOCK_PRIORITY} + STACKSIZE + ${CONFIG_SPINLOCK_STACKSIZE} + MODULE + ${CONFIG_BENCHMARK_SPINLOCK} + COMPILE_FLAGS + ${CFLAGS} + SRCS + ${CSRCS} + INCLUDE_DIRECTORIES + ${INCDIR}) endif() diff --git a/benchmarks/spinlock_bench/Kconfig b/benchmarks/spinlock_bench/Kconfig new file mode 100644 index 000000000..b872f5e84 --- /dev/null +++ b/benchmarks/spinlock_bench/Kconfig @@ -0,0 +1,45 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +menuconfig BENCHMARK_SPINLOCK + bool "Spinlock Benchmark" + depends on BUILD_FLAT + default n + ---help--- + Enable the Spinlock benchmark application. + +if BENCHMARK_SPINLOCK + +config SPINLOCK_PROGNAME + string "spinlock benchmark" + default "spinlock_bench" + ---help--- + This is the name of the program that will be used when the NSH ELF + program is installed. + +config SPINLOCK_PRIORITY + int "Spinlock task priority" + default 100 + +config SPINLOCK_STACKSIZE + int "Spinlock task stack size" + default 4096 + + +config SPINLOCK_MULTITHREAD + int "Number of threads" + default 40 + ---help--- + Override the default number of threads to be executed. + The default value is 40. + +config SPINLOCK_ITERATIONS + int "Number of iterations" + default 100 + ---help--- + Default number of iterations for the benchmark on each thread. + The default value is 100. + +endif # BENCHMARK_SPINLOCK diff --git a/examples/module/main/Make.defs b/benchmarks/spinlock_bench/Make.defs similarity index 87% rename from examples/module/main/Make.defs rename to benchmarks/spinlock_bench/Make.defs index f4f4ea83c..e82177760 100644 --- a/examples/module/main/Make.defs +++ b/benchmarks/spinlock_bench/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/module/main/Make.defs +# apps/benchmarks/spinlock_bench/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,6 @@ # ############################################################################ -ifneq ($(CONFIG_EXAMPLES_MODULE),) -CONFIGURED_APPS += $(APPDIR)/examples/module/main +ifneq ($(CONFIG_BENCHMARK_SPINLOCK),) +CONFIGURED_APPS += $(APPDIR)/benchmarks/spinlock_bench endif diff --git a/math/gemmlowp/Makefile b/benchmarks/spinlock_bench/Makefile similarity index 66% rename from math/gemmlowp/Makefile rename to benchmarks/spinlock_bench/Makefile index 3f5b76456..fada2fb61 100644 --- a/math/gemmlowp/Makefile +++ b/benchmarks/spinlock_bench/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/gemmlowp/Makefile +# apps/benchmarks/spinlock_bench/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,22 +20,20 @@ include $(APPDIR)/Make.defs -MODULE = $(CONFIG_MATH_GEMMLOWP) +# spinlock_bench application -GEMMLOWP_VER = 719139ce755a0f31cbf1c37f7f98adcc7fc9f425 +############################################################################ +# Applications Configuration +############################################################################ -gemmlowp.zip: - $(Q) curl -L https://github.com/google/gemmlowp/archive/$(GEMMLOWP_VER).zip -o gemmlowp.zip - $(Q) unzip -o gemmlowp.zip - $(Q) mv gemmlowp-$(GEMMLOWP_VER) gemmlowp +MODULE = $(CONFIG_BENCHMARK_SPINLOCK) -# Download and unpack tarball if no git repo found -ifeq ($(wildcard gemmlowp/.git),) -context:: gemmlowp.zip +PROGNAME += $(CONFIG_SPINLOCK_PROGNAME) +PRIORITY += $(CONFIG_SPINLOCK_PRIORITY) +STACKSIZE += $(CONFIG_SPINLOCK_STACKSIZE) -distclean:: - $(call DELDIR, gemmlowp) - $(call DELFILE, gemmlowp.zip) -endif +MAINSRC += spinlock_bench.c + +# Build with WebAssembly when CONFIG_INTERPRETERS_WAMR is enabled include $(APPDIR)/Application.mk diff --git a/benchmarks/spinlock_bench/spinlock_bench.c b/benchmarks/spinlock_bench/spinlock_bench.c new file mode 100644 index 000000000..a6014ca9a --- /dev/null +++ b/benchmarks/spinlock_bench/spinlock_bench.c @@ -0,0 +1,110 @@ +/**************************************************************************** + * apps/benchmarks/spinlock_bench/spinlock_bench.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define TEST_NUM CONFIG_SPINLOCK_MULTITHREAD +#define THREAD_NUM CONFIG_SPINLOCK_MULTITHREAD + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct thread_parmeter_s +{ + FAR int *result; + FAR spinlock_t *lock; +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static FAR void *thread_spinlock(FAR void *parameter) +{ + FAR int *result = ((FAR struct thread_parmeter_s *)parameter)->result; + FAR spinlock_t *lock = ((FAR struct thread_parmeter_s *)parameter)->lock; + + int i; + + for (i = 0; i < TEST_NUM; i++) + { + spin_lock(lock); + (*result)++; + spin_unlock(lock); + } + + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void main(void) +{ + spinlock_t lock = SP_UNLOCKED; + int result = 0; + pthread_t thread[THREAD_NUM]; + struct thread_parmeter_s para; + clock_t start; + clock_t end; + + int status; + int i; + + para.result = &result; + para.lock = &lock; + + start = perf_gettime(); + for (i = 0; i < THREAD_NUM; ++i) + { + status = pthread_create(&thread[i], NULL, + thread_spinlock, ¶); + if (status != 0) + { + printf("spinlock_test: ERROR pthread_create failed, status=%d\n", + status); + ASSERT(false); + } + } + + for (i = 0; i < THREAD_NUM; ++i) + { + pthread_join(thread[i], NULL); + } + + end = perf_gettime(); + assert(result == THREAD_NUM * TEST_NUM); + + printf("total_time: %lu\n", end - start); +} diff --git a/benchmarks/superpi/CMakeLists.txt b/benchmarks/superpi/CMakeLists.txt deleted file mode 100644 index aec5016d8..000000000 --- a/benchmarks/superpi/CMakeLists.txt +++ /dev/null @@ -1,54 +0,0 @@ -# ############################################################################## -# apps/benchmarks/superpi/CMakeList.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_BENCHMARK_SUPERPI) - - set(SUPERPI_UNPACK ${CMAKE_CURRENT_LIST_DIR}/superpi) - set(SUPERPI_URL https://github.com/Fibonacci43/SuperPI/archive) - set(SUPERPI_ZIP main.zip) - - if(NOT EXISTS ${SUPERPI_UNPACK}) - - FetchContent_Declare( - superpi_fetch - URL ${SUPERPI_URL}/${SUPERPI_ZIP} SOURCE_DIR ${SUPERPI_UNPACK} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/benchmarks/superpi/superpi - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(superpi_fetch) - if(NOT superpi_fetch_POPULATED) - FetchContent_Populate(superpi_fetch) - endif() - - endif() - - nuttx_add_application( - NAME - ${CONFIG_BENCHMARK_SUPERPI_PROGNAME} - STACKSIZE - ${CONFIG_BENCHMARK_SUPERPI_STACKSIZE} - PRIORITY - ${CONFIG_BENCHMARK_SUPERPI_PRIORITY} - SRCS - ${SUPERPI_UNPACK}/pi_fftcs.c - ${SUPERPI_UNPACK}/fftsg_h.c) - -endif() diff --git a/benchmarks/tacle-bench/.gitignore b/benchmarks/tacle-bench/.gitignore deleted file mode 100644 index 649ff84b9..000000000 --- a/benchmarks/tacle-bench/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/tacle-bench -/*.zip diff --git a/benchmarks/test-tlb/.gitignore b/benchmarks/test-tlb/.gitignore deleted file mode 100644 index 3c99f56ef..000000000 --- a/benchmarks/test-tlb/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/test-tlb -/*.zip diff --git a/benchmarks/test-tlb/CMakeLists.txt b/benchmarks/test-tlb/CMakeLists.txt deleted file mode 100644 index 501e21f63..000000000 --- a/benchmarks/test-tlb/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# - -if(CONFIG_BENCHMARK_TESTTLB) - - set(SRCS testtlb/test-tlb.c) - - nuttx_add_application( - NAME - testtlb - PRIORITY - ${CONFIG_BENCHMARK_TESTTLB_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_TESTTLB_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_TESTTLB} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${SRCS}) -endif() diff --git a/benchmarks/test-tlb/Kconfig b/benchmarks/test-tlb/Kconfig deleted file mode 100644 index 0e12d5ba6..000000000 --- a/benchmarks/test-tlb/Kconfig +++ /dev/null @@ -1,33 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -config BENCHMARK_TESTTLB - tristate "Memory Latency profiling" - default n - ---help--- - Measure the memory latency - -if BENCHMARK_TESTTLB - -config BENCHMARK_TESTTLB_PRIORITY - int "TestTLB task priority" - default 100 - -config BENCHMARK_TESTTLB_STACKSIZE - int "TestTLB stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/benchmarks/test-tlb/Make.defs b/benchmarks/test-tlb/Make.defs deleted file mode 100644 index 6d4565f44..000000000 --- a/benchmarks/test-tlb/Make.defs +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -ifneq ($(CONFIG_BENCHMARK_TESTTLB),) -CONFIGURED_APPS += $(APPDIR)/benchmarks/testtlb -endif diff --git a/benchmarks/test-tlb/Makefile b/benchmarks/test-tlb/Makefile deleted file mode 100644 index c1d741474..000000000 --- a/benchmarks/test-tlb/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -include $(APPDIR)/Make.defs - -PROGNAME = testtlb -PRIORITY = $(CONFIG_BENCHMARK_TESTTLB_PRIORITY) -STACKSIZE = $(CONFIG_BENCHMARK_TESTTLB_STACKSIZE) -MODULE = $(CONFIG_BENCHMARK_TESTTLB) - -MAINSRC = testtlb/test-tlb.c - -include $(APPDIR)/Application.mk diff --git a/benchmarks/tinymembench/.gitignore b/benchmarks/tinymembench/.gitignore deleted file mode 100644 index 0a80bd78b..000000000 --- a/benchmarks/tinymembench/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/tinymembench -/*.zip diff --git a/benchmarks/tinymembench/CMakeLists.txt b/benchmarks/tinymembench/CMakeLists.txt deleted file mode 100644 index 0dc67411b..000000000 --- a/benchmarks/tinymembench/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# - -if(CONFIG_BENCHMARK_TINY_MEMBENCH) - - list(APPEND CFLAGS -Wno-unused-but-set-variable -Wno-unused-variable - -Wno-strict-prototypes) - - set(SRCS tinymembench/main.c) - - list( - APPEND - SRCS - tinymembench/aarch64-asm.S - tinymembench/arm-neon.S - tinymembench/x86-sse2.S - tinymembench/mips-32.S - tinymembench/asm-opt.c - tinymembench/util.c) - - nuttx_add_application( - NAME - tinymembench - PRIORITY - ${CONFIG_BENCHMARK_TINY_MEMBENCH_PRIORITY} - STACKSIZE - ${CONFIG_BENCHMARK_TINY_MEMBENCH_STACKSIZE} - MODULE - ${CONFIG_BENCHMARK_TINY_MEMBENCH} - COMPILE_FLAGS - ${CFLAGS} - SRCS - ${SRCS}) -endif() diff --git a/benchmarks/tinymembench/Kconfig b/benchmarks/tinymembench/Kconfig deleted file mode 100644 index 5a0805982..000000000 --- a/benchmarks/tinymembench/Kconfig +++ /dev/null @@ -1,33 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -config BENCHMARK_TINY_MEMBENCH - tristate "TinyMemBench" - default n - ---help--- - Measure the memory bandwidth and latency - -if BENCHMARK_TINY_MEMBENCH - -config BENCHMARK_TINY_MEMBENCH_PRIORITY - int "TinyMemBench task priority" - default 100 - -config BENCHMARK_TINY_MEMBENCH_STACKSIZE - int "TinyMemBench stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/benchmarks/tinymembench/Make.defs b/benchmarks/tinymembench/Make.defs deleted file mode 100644 index 456ce2a78..000000000 --- a/benchmarks/tinymembench/Make.defs +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -ifneq ($(CONFIG_BENCHMARK_TINY_MEMBENCH),) -CONFIGURED_APPS += $(APPDIR)/benchmarks/tinymembench -endif diff --git a/benchmarks/tinymembench/Makefile b/benchmarks/tinymembench/Makefile deleted file mode 100644 index 5e09c88be..000000000 --- a/benchmarks/tinymembench/Makefile +++ /dev/null @@ -1,37 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -include $(APPDIR)/Make.defs - -PROGNAME = tinymembench -PRIORITY = $(CONFIG_BENCHMARK_TINY_MEMBENCH_PRIORITY) -STACKSIZE = $(CONFIG_BENCHMARK_TINY_MEMBENCH_STACKSIZE) -MODULE = $(CONFIG_BENCHMARK_TINY_MEMBENCH) - -ASRCS += tinymembench/aarch64-asm.S -ASRCS += tinymembench/arm-neon.S -ASRCS += tinymembench/x86-sse2.S -ASRCS += tinymembench/mips-32.S - -CSRCS += tinymembench/asm-opt.c -CSRCS += tinymembench/util.c - -MAINSRC = tinymembench/main.c - -CFLAGS += -Wno-unused-but-set-variable -Wno-unused-variable -CFLAGS += -Wno-strict-prototypes - -include $(APPDIR)/Application.mk diff --git a/boot/mcuboot/Kconfig b/boot/mcuboot/Kconfig index c09133149..f5c904a7a 100644 --- a/boot/mcuboot/Kconfig +++ b/boot/mcuboot/Kconfig @@ -12,9 +12,21 @@ menuconfig BOOT_MCUBOOT if BOOT_MCUBOOT +config MCUBOOT_REPOSITORY + string "MCUboot GIT repository" + default "github.com/mcu-tools/mcuboot" + ---help--- + Specifies the location of MCUboot GIT repository . This + is by default MCUboot main GIT repository, but it can be changed + to user's fork if required. + config MCUBOOT_VERSION string "MCUboot version" default "fefc398cc13ebbc527e297fe9df78cd98a359d75" + ---help--- + Defines MCUboot version to be downloaded. Either release tag + or commit hash should be specified. Using newer MCUboot version + may cause compatability issues. config MCUBOOT_ENABLE_LOGGING bool "Enable MCUboot logging" diff --git a/boot/mcuboot/Makefile b/boot/mcuboot/Makefile index 3fbd6c62a..64157bf09 100644 --- a/boot/mcuboot/Makefile +++ b/boot/mcuboot/Makefile @@ -20,10 +20,11 @@ include $(APPDIR)/Make.defs -MCUBOOT_VERSION := $(patsubst "%",%,$(CONFIG_MCUBOOT_VERSION)) -MCUBOOT_TARBALL = $(MCUBOOT_VERSION).tar.gz -MCUBOOT_UNPACK = mcuboot -MCUBOOT_SRCDIR = $(MCUBOOT_UNPACK)$(DELIM)boot$(DELIM)bootutil$(DELIM)src +MCUBOOT_VERSION := $(patsubst "%",%,$(CONFIG_MCUBOOT_VERSION)) +MCUBOOT_REPOSITORY := $(patsubst "%",%,$(CONFIG_MCUBOOT_REPOSITORY)) +MCUBOOT_TARBALL = $(MCUBOOT_VERSION).tar.gz +MCUBOOT_UNPACK = mcuboot +MCUBOOT_SRCDIR = $(MCUBOOT_UNPACK)$(DELIM)boot$(DELIM)bootutil$(DELIM)src DEPPATH += --dep-path $(MCUBOOT_UNPACK)$(DELIM)src DEPPATH += --dep-path $(MCUBOOT_SRCDIR) @@ -38,7 +39,7 @@ PRIORITY += SCHED_PRIORITY_DEFAULT STACKSIZE += $(CONFIG_DEFAULT_TASK_STACKSIZE) endif -CFLAGS += -Wno-undef +CFLAGS += -Wno-undef -Wno-unused-but-set-variable CSRCS := $(MCUBOOT_UNPACK)/boot/bootutil/src/boot_record.c \ $(MCUBOOT_UNPACK)/boot/bootutil/src/bootutil_misc.c \ @@ -75,8 +76,8 @@ CXXFLAGS += ${INCDIR_PREFIX}mcuboot/ext/tinycrypt/lib/include endif $(MCUBOOT_TARBALL): - $(Q) echo "Downloading MCUboot-$(MCUBOOT_VERSION)" - $(Q) curl -O -L https://github.com/mcu-tools/mcuboot/archive/$(MCUBOOT_TARBALL) + $(Q) echo "Downloading MCUboot-$(MCUBOOT_VERSION) from $(MCUBOOT_REPOSITORY)" + $(Q) curl -O -L --proto-default https $(MCUBOOT_REPOSITORY)/archive/$(MCUBOOT_TARBALL) $(MCUBOOT_UNPACK): $(MCUBOOT_TARBALL) $(Q) echo "Unpacking: $(MCUBOOT_TARBALL) -> $(MCUBOOT_UNPACK)" diff --git a/boot/mcuboot/README.md b/boot/mcuboot/README.md deleted file mode 100644 index 439c2e720..000000000 --- a/boot/mcuboot/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# Boot / `mcuboot` MCUboot - -## Description - -The NuttX port of MCUboot secure boot library expects that the platform provides a Flash storage with the following partitions: -- `CONFIG_MCUBOOT_PRIMARY_SLOT_PATH`: MTD partition for the application firmware image PRIMARY slot; -- `CONFIG_MCUBOOT_SECONDARY_SLOT_PATH`: MTD partition for the application firmware image SECONDARY slot; -- `CONFIG_MCUBOOT_SCRATCH_PATH`: MTD partition for the Scratch area; - -Also, these are optional features that may be enabled: - -- `CONFIG_MCUBOOT_WATCHDOG`: If `CONFIG_WATCHDOG` is enabled, MCUboot shall reset the watchdog timer indicated by `CONFIG_MCUBOOT_WATCHDOG_DEVPATH` to the current timeout value, preventing any imminent watchdog timeouts. - -The porting layer of MCUboot library consists of the following interfaces: -- ``, for enabling MCUboot to manage the application firmware image slots in the device storage. -- ``, for configuration of MCUboot's features. -- ``, for providing logging capabilities. -- ``, for providing MCUboot access to the OS memory management interfaces. -- ``, for configuration of the system's flash area organization. - -The NuttX port of MCUboot is implemented at application-level and requires minimal knowledge about characteristics of the underlying storage device. This is achieved by means of the `BCH` and `FTL` subsystems, which enable MCUboot to manage MTD partitions via character device drivers using standard POSIX filesystem operations (e.g. `open()` / `close()` / `read()` / `write()`). - -## Creating MCUboot-compatible application firmware images - -One common use case for MCUboot is to integrate it to a firmware update agent, which is an important component of a secure firmware update subsystem. Through MCUboot APIs an application is able to install a newly received application firmware image and, once this application firmware image is assured to be valid, the application may confirm it as a stable image. In case that application firmware image is deemed bogus, MCUboot provides an API for invalidating that update, which will induce a rollback procedure to the most recent stable application firmware image. - -The `CONFIG_EXAMPLES_MCUBOOT_UPDATE_AGENT` example demonstrates this workflow by downloading an application firmware image from a webserver, installing it and triggering the firmware update process for the next boot after a system reset. There is also the `CONFIG_EXAMPLES_MCUBOOT_SLOT_CONFIRM`, which is a fairly simple example that just calls an MCUboot API for confirming the executing application firmware image as stable. - -For more information about all MCUboot examples, see `examples/mcuboot` directory. - -## Using MCUboot on NuttX as a secure boot solution - -NuttX port for MCUboot also enables the creation of a secure bootloader application requiring minimal platform-specific implementation. The logical implementation for the secure boot is performed at application-level by the MCUboot library. Once MCUboot validates the application firmware image, it delegates the loading and execution of the application firmware image to a platform-specific routine, which is accessed via `boardctl(BOARDIOC_BOOT_IMAGE)` call. Each platform must then provide an implementation for the `board_boot_image()` for executing the required actions in order to boot a new application firmware image (e.g. deinitialize peripherals, load the Program Counter register with the application firmware image entry point address). - -The MCUboot bootloader application may be enabled by selecting the `CONFIG_MCUBOOT_BOOTLOADER` option. - -## Assumptions - -### IOCTL MTD commands - -The implementation of `` expects that the MTD driver for a given image partition handles the following `ioctl` commands: -- `MTDIOC_GEOMETRY`, for retrieving information about the geometry of the MTD, required for the configuration of the size of each flash area. -- `MTDIOC_ERASESTATE`, for retrieving the byte value of an erased cell of the MTD, required for the implementation of `flash_area_erased_val()` interface. - -### Write access alignment - -Through `flash_area_align()` interface MCUboot expects that the implementation provides the shortest data length that may be written via `flash_area_write()` interface. The NuttX implementation passes through the `BCH` and `FTL` layers, which appropriately handle the write alignment restrictions of the underlying MTD. So The NuttX implementation of `flash_area_align()` is able to return a fixed value of 1 byte, even if the MTD does not support byte operations. - -## Limitations - -### `` functions are not multitasking-safe - -MCUboot's documentation imposes no restrictions regarding the usage of its public interfaces, which doesn't mean they are thread-safe. -But, regarding NuttX implementation of the ``, it is safe to state that they are **not** multitasking-safe. NuttX implementation manages the MTD partitions via character device drivers. As file-descriptors cannot be shared between different tasks, if one task calls `flash_area_open` and another task calls `flash_area_` passing the same `struct flash_area` instance, it will result in failure. diff --git a/builtin/exec_builtin.c b/builtin/exec_builtin.c index f31d358b6..3f4c9b38b 100644 --- a/builtin/exec_builtin.c +++ b/builtin/exec_builtin.c @@ -24,11 +24,11 @@ #include +#include #include #include #include -#include "nshlib/nshlib.h" #include "builtin/builtin.h" /**************************************************************************** @@ -62,15 +62,20 @@ int exec_builtin(FAR const char *appname, FAR char * const *argv, FAR const char *redirfile, int oflags) { FAR const struct builtin_s *builtin; + posix_spawnattr_t attr; + posix_spawn_file_actions_t file_actions; + struct sched_param param; + pid_t pid; int index; + int ret; /* Verify that an application with this name exists */ index = builtin_isavail(appname); if (index < 0) { - errno = ENOENT; - return ERROR; + ret = ENOENT; + goto errout_with_errno; } /* Get information about the builtin */ @@ -78,10 +83,122 @@ int exec_builtin(FAR const char *appname, FAR char * const *argv, builtin = builtin_for_index(index); if (builtin == NULL) { - errno = ENOENT; - return ERROR; + ret = ENOENT; + goto errout_with_errno; } - return nsh_spawn(builtin->name, builtin->main, argv, builtin->priority, - builtin->stacksize, redirfile, oflags, false); + /* Initialize attributes for task_spawn(). */ + + ret = posix_spawnattr_init(&attr); + if (ret != 0) + { + goto errout_with_errno; + } + + ret = posix_spawn_file_actions_init(&file_actions); + if (ret != 0) + { + goto errout_with_attrs; + } + + /* Set the correct task size and priority */ + + param.sched_priority = builtin->priority; + ret = posix_spawnattr_setschedparam(&attr, ¶m); + if (ret != 0) + { + goto errout_with_actions; + } + + ret = posix_spawnattr_setstacksize(&attr, builtin->stacksize); + if (ret != 0) + { + goto errout_with_actions; + } + + /* If robin robin scheduling is enabled, then set the scheduling policy + * of the new task to SCHED_RR before it has a chance to run. + */ + +#if CONFIG_RR_INTERVAL > 0 + ret = posix_spawnattr_setschedpolicy(&attr, SCHED_RR); + if (ret != 0) + { + goto errout_with_actions; + } + + ret = posix_spawnattr_setflags(&attr, + POSIX_SPAWN_SETSCHEDPARAM | + POSIX_SPAWN_SETSCHEDULER); + if (ret != 0) + { + goto errout_with_actions; + } + +#else + ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSCHEDPARAM); + if (ret != 0) + { + goto errout_with_actions; + } + +#endif + + /* Is output being redirected? */ + + if (redirfile) + { + /* Set up to close open redirfile and set to stdout (1) */ + + ret = posix_spawn_file_actions_addopen(&file_actions, 1, + redirfile, oflags, 0644); + if (ret != 0) + { + serr("ERROR: posix_spawn_file_actions_addopen failed: %d\n", ret); + goto errout_with_actions; + } + } + +#ifdef CONFIG_LIBC_EXECFUNCS + /* Load and execute the application. */ + + ret = posix_spawn(&pid, builtin->name, &file_actions, &attr, argv, NULL); + if (ret != 0 && builtin->main != NULL) +#endif + { + /* Start the built-in */ + + pid = task_spawn(builtin->name, builtin->main, &file_actions, + &attr, argv ? &argv[1] : NULL, NULL); + ret = pid < 0 ? -pid : 0; + } + + if (ret != 0) + { + serr("ERROR: task_spawn failed: %d\n", ret); + goto errout_with_actions; + } + + /* Free attributes and file actions. Ignoring return values in the case + * of an error. + */ + + /* Return the task ID of the new task if the task was successfully + * started. Otherwise, ret will be ERROR (and the errno value will + * be set appropriately). + */ + + posix_spawn_file_actions_destroy(&file_actions); + posix_spawnattr_destroy(&attr); + return pid; + +errout_with_actions: + posix_spawn_file_actions_destroy(&file_actions); + +errout_with_attrs: + posix_spawnattr_destroy(&attr); + +errout_with_errno: + errno = ret; + return ERROR; } diff --git a/canutils/lely-canopen/Makefile b/canutils/lely-canopen/Makefile index 8bb3f04e4..c85733013 100644 --- a/canutils/lely-canopen/Makefile +++ b/canutils/lely-canopen/Makefile @@ -176,6 +176,8 @@ $(LELYCANOPEN_TARBALL): $(LELYCANOPEN_SRCNAME): $(LELYCANOPEN_TARBALL) @echo "Unpacking: $(LELYCANOPEN_TARBALL) -> $(LELYCANOPEN_UNPACKNAME)" $(Q) $(UNPACK) $(LELYCANOPEN_TARBALL) + # Get the name of the directory created by the tar command + $(eval LELYCANOPEN_UNPACKNAME := $(shell ls -d lely-core-master*)) $(Q) mv $(LELYCANOPEN_UNPACKNAME) $(LELYCANOPEN_SRCNAME) $(Q) cat 0001-NuttX-port.patch | patch -s -N -d $(LELYCANOPEN_SRCNAME) -p1 $(Q) echo "Patching $(LELYCANOPEN_SRCNAME)" diff --git a/canutils/libcanardv0/CMakeLists.txt b/canutils/libcanardv0/CMakeLists.txt deleted file mode 100644 index f94a3fe21..000000000 --- a/canutils/libcanardv0/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -# ############################################################################## -# apps/canutils/libcanardv0/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_CANUTILS_LIBCANARDV0) - - # ############################################################################ - # Config and Fetch libcanardv0 lib - # ############################################################################ - - set(LIBCANARDV0_DIR ${CMAKE_CURRENT_LIST_DIR}/libcanardv0) - if(NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/libcanardv0) - FetchContent_Declare( - libcanardv0 - URL ${CONFIG_LIBCANARDV0_URL}/${CONFIG_LIBCANARDV0_VERSION}.zip) - FetchContent_MakeAvailable(libcanardv0) - set(LIBCANARDV0_DIR ${libcanardv0_SOURCE_DIR}) - endif() - - # ############################################################################ - # Library Configuration - # ############################################################################ - - nuttx_add_user_library(libcanardv0) - - target_sources( - libcanardv0 PRIVATE ${LIBCANARDV0_DIR}/canard.c - ${LIBCANARDV0_DIR}/drivers/nuttx/canard_nuttx.c) - target_compile_options(libcanardv0 PRIVATE -std=c99 - -DCANARD_ASSERT=DEBUGASSERT) - target_include_directories( - libcanardv0 PRIVATE ${LIBCANARDV0_DIR} ${LIBCANARDV0_DIR}/drivers/nuttx) - -endif() diff --git a/canutils/libdronecan/Kconfig b/canutils/libdronecan/Kconfig index 6419d198d..11578b939 100644 --- a/canutils/libdronecan/Kconfig +++ b/canutils/libdronecan/Kconfig @@ -23,7 +23,7 @@ config LIBDRONECAN_VERSION default "21f2a73df86886101e254d02cfc2277cd2a15717" ---help--- libcanard version. - + config LIBDRONECAN_CANFD bool "(Experimental) libcanard CAN FD Support" default n @@ -34,4 +34,4 @@ config LIBDRONECAN_CANFD since libcanard doesn't support runtime switching between CAN2.0B and CAN FD that well -endif +endif # CANUTILS_LIBDRONECAN diff --git a/config.nims b/config.nims index 0d6c4c74c..1bf0ac25b 100644 --- a/config.nims +++ b/config.nims @@ -27,6 +27,7 @@ switch "mm", "orc" switch "arm.nuttx.gcc.exe", "arm-none-eabi-gcc" switch "arm64.nuttx.gcc.exe", "aarch64-none-elf-gcc" switch "riscv32.nuttx.gcc.exe", "riscv64-unknown-elf-gcc" +switch "riscv64.nuttx.gcc.exe", "riscv64-unknown-elf-gcc" switch "amd64.nuttx.gcc.exe", "x86_64-linux-gnu-gcc" switch "nimcache", ".nimcache" @@ -69,14 +70,19 @@ proc read_config(cfg: string): DotConfig = case arch of "arm", "arm64": result.arch = arch - of "riscv": - result.arch = "riscv32" of "sim": if defined(amd64): result.arch = "amd64" elif defined(aarch64): result.arch = "arm64" result.isSim = true + of "ARCH_FAMILY": + let arch = keyval[1].strip(chars = {'"'}) + case arch + of "rv32": + result.arch = "riscv32" + of "rv64": + result.arch = "riscv64" of "DEBUG_NOOPT": result.opt = oNone of "DEBUG_FULLOPT": @@ -121,6 +127,7 @@ proc setup_cfg(cfg: DotConfig) = switch("define", "nimMemAlignTiny") -let topdir = getEnv("TOPDIR") +const key = "TOPDIR" +let topdir = if existsEnv(key): getEnv(key) else: thisDir() & "/../nuttx" let cfg = read_config(topdir & "/.config") cfg.setup_cfg() diff --git a/testing/mm/CMakeLists.txt b/crypto/controlse/CMakeLists.txt similarity index 70% rename from testing/mm/CMakeLists.txt rename to crypto/controlse/CMakeLists.txt index 2c6f069fe..72fb36e01 100644 --- a/testing/mm/CMakeLists.txt +++ b/crypto/controlse/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/testing/mm/CMakeLists.txt +# apps/crypto/controlse/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,18 +18,28 @@ # # ############################################################################## -if(CONFIG_TESTING_MM) +if(CONFIG_CRYPTO_CONTROLSE) + + set(MBEDTLS_DIR ${CMAKE_BINARY_DIR}/apps/include/mbedtls) + nuttx_add_application( NAME - ${CONFIG_TESTING_MM_PROGNAME} - PRIORITY - ${CONFIG_TESTING_MM_PRIORITY} + ${CONFIG_CRYPTO_CONTROLSE_PROGNAME} STACKSIZE - ${CONFIG_TESTING_MM_STACKSIZE} + ${CONFIG_CRYPTO_CONTROLSE_STACKSIZE} MODULE - ${CONFIG_TESTING_MM} - INCLUDE_DIRECTORIES - ${NUTTX_DIR}/mm/mm_heap + ${CONFIG_CRYPTO_CONTROLSE} SRCS - mm_main.c) + controlse_main.cxx + chex_util.cxx + csecure_element.cxx + cstring.cxx + ccertificate.cxx + ccsr.cxx + cpublic_key.cxx + cserial_number.cxx + csan_builder.cxx + INCLUDE_DIRECTORIES + ${MBEDTLS_DIR}) + endif() diff --git a/crypto/controlse/Kconfig b/crypto/controlse/Kconfig index 550d09260..e1da37dcd 100644 --- a/crypto/controlse/Kconfig +++ b/crypto/controlse/Kconfig @@ -18,8 +18,9 @@ config CRYPTO_CONTROLSE select MBEDTLS_X509_CSR_WRITE_C select MBEDTLS_X509_CRT_WRITE_C ---help--- - Enable the controlse utility. This program is used control the - secure element device + Enable the controlse library and utility. It provides an + access library to the secure element device. The utility can + control the secure element device from the nuttx shell if CRYPTO_CONTROLSE diff --git a/crypto/controlse/Makefile b/crypto/controlse/Makefile index 6ad484059..c338507d1 100644 --- a/crypto/controlse/Makefile +++ b/crypto/controlse/Makefile @@ -18,6 +18,8 @@ # ############################################################################ +# Copyright 2023, 2024 NXP + include $(APPDIR)/Make.defs # controlse built-in application info @@ -28,7 +30,8 @@ STACKSIZE = $(CONFIG_CRYPTO_CONTROLSE_STACKSIZE) # controlse main source -MAINSRC = controlse_main.c -CSRCS = x509_utils.c mbedtls_extension.c +MAINSRC = controlse_main.cxx +CXXSRCS = chex_util.cxx csecure_element.cxx cstring.cxx ccertificate.cxx\ + ccsr.cxx cpublic_key.cxx cserial_number.cxx csan_builder.cxx include $(APPDIR)/Application.mk diff --git a/crypto/controlse/ccertificate.cxx b/crypto/controlse/ccertificate.cxx new file mode 100644 index 000000000..5731c4ddd --- /dev/null +++ b/crypto/controlse/ccertificate.cxx @@ -0,0 +1,532 @@ +//*************************************************************************** +// apps/crypto/controlse/ccertificate.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//*************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include "crypto/controlse/ccertificate.hxx" + +#include "cmbedtls_se05x_extension.hxx" +#include "crypto/controlse/chex_util.hxx" +#include "crypto/controlse/cpublic_key.hxx" +#include "crypto/controlse/cserial_number.hxx" +#include "crypto/controlse/isecure_element.hxx" +#include +#include +#include +#include +#include +#include + +namespace Controlse +{ + +//*************************************************************************** +// Private Data +//*************************************************************************** + +static constexpr int SECONDS_IN_DAY = (60 * 60 * 24); +static constexpr size_t TBS_HASH_BUFFER_SIZE = 32; + +static constexpr char certificate_header[] = "-----BEGIN CERTIFICATE-----\n"; +static constexpr char certificate_footer[] = "-----END CERTIFICATE-----\n"; +static constexpr size_t datetime_size = 15; + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CCertificate::CCertificate(const ISecureElement &se, uint32_t keystore_id) +{ + mbedtls_x509_crt_init(&crt); + is_loaded = LoadFromSecureElement(se, keystore_id); +} + +CCertificate::CCertificate(const uint8_t *crt_der_or_pem, size_t crt_size) +{ + mbedtls_x509_crt_init(&crt); + is_loaded = LoadFromDerOrPem(crt_der_or_pem, crt_size); +} + +static void GetCurrentDateTime(char datetime[datetime_size], int seconds) +{ + time_t rawtime; + struct tm tm_info; + time(&rawtime); + rawtime += seconds; + strftime(datetime, datetime_size, "%Y%m%d%H%M%S", + gmtime_r(&rawtime, &tm_info)); +} + +CCertificate::CCertificate(const ISecureElement &se, + const uint8_t *csr_der_or_pem, size_t csr_size, + uint32_t keystore_id) +{ + mbedtls_x509_crt_init(&crt); + char from_datetime[datetime_size]; + char to_datetime[datetime_size]; + GetCurrentDateTime(from_datetime, 0); + GetCurrentDateTime(to_datetime, SECONDS_IN_DAY); + is_loaded = LoadFromCsrDerOrPem(se, csr_der_or_pem, csr_size, keystore_id, + from_datetime, to_datetime); +} + +CCertificate::CCertificate(const ISecureElement &se, + const uint8_t *csr_der_or_pem, size_t csr_size, + uint32_t keystore_id, const char *from_datetime, + const char *to_datetime) +{ + mbedtls_x509_crt_init(&crt); + is_loaded = LoadFromCsrDerOrPem(se, csr_der_or_pem, csr_size, keystore_id, + from_datetime, to_datetime); +} + +CCertificate::~CCertificate() { mbedtls_x509_crt_free(&crt); } + +bool CCertificate::IsLoaded() const { return is_loaded; } + +bool CCertificate::StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const +{ + struct se05x_key_transmission_s args; + args.entry.id = keystore_id; + args.content.buffer = crt.raw.p; + args.content.buffer_size = crt.raw.len; + args.content.buffer_content_size = crt.raw.len; + return se.SetData(args); +} + +bool CCertificate::LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) +{ + size_t certificate_der_size = 1000; + uint8_t *certificate_der = new uint8_t[certificate_der_size]; + struct se05x_key_transmission_s args + = { .entry = { .id = keystore_id }, + .content = { .buffer = certificate_der, + .buffer_size = certificate_der_size } }; + bool result = se.GetData(args); + + if (result) + { + result = 0 + == mbedtls_x509_crt_parse(&crt, certificate_der, + args.content.buffer_content_size); + } + + delete[] certificate_der; + return result; +} + +bool CCertificate::LoadFromDerOrPem(const uint8_t *crt_der_or_pem, + size_t crt_size) +{ + return 0 == mbedtls_x509_crt_parse(&crt, crt_der_or_pem, crt_size); +} + +bool CCertificate::LoadFromCsrDerOrPem(const ISecureElement &se, + const uint8_t *csr_der_or_pem, + size_t csr_size, uint32_t keystore_id, + const char *from_datetime, + const char *to_datetime) +{ + mbedtls_x509_csr csr; + mbedtls_x509_csr_init(&csr); + auto result = 0 == mbedtls_x509_csr_parse(&csr, csr_der_or_pem, csr_size); + + mbedtls_x509write_cert crt_builder; + mbedtls_x509write_crt_init(&crt_builder); + char subject_name[200]; + if (result) + { + mbedtls_x509write_crt_set_version(&crt_builder, + MBEDTLS_X509_CRT_VERSION_3); + result = 0 < mbedtls_x509_dn_gets(subject_name, sizeof(subject_name), + &csr.subject); + } + + mbedtls_pk_context key; + mbedtls_pk_init(&key); + if (result) + { + result = 0 + == MbedtlsSe05xExtension::mbedtls_pk_setup_key_se05x( + key, se, keystore_id); + } + + mbedtls_pk_context public_key; + public_key.pk_ctx = csr.pk.pk_ctx; + public_key.pk_info = csr.pk.pk_info; + + // Invalidate the public key in CSR + // The public key is transferred to CRT so the CSR may not free the memory + csr.pk.pk_ctx = nullptr; + csr.pk.pk_info = nullptr; + mbedtls_x509_csr_free(&csr); + + if (result) + { + mbedtls_x509write_crt_set_subject_key(&crt_builder, &public_key); + mbedtls_x509write_crt_set_issuer_key(&crt_builder, &key); + result = 0 + == mbedtls_x509write_crt_set_subject_name(&crt_builder, + subject_name); + } + + if (result) + { + result = 0 + == mbedtls_x509write_crt_set_issuer_name(&crt_builder, + "CN=CA,O=controlse,C=NL"); + } + + mbedtls_mpi serial; + mbedtls_mpi_init(&serial); + if (result) + { + mbedtls_x509write_crt_set_md_alg(&crt_builder, MBEDTLS_MD_SHA256); + result = 0 == mbedtls_mpi_read_string(&serial, 10, "1"); + } + + if (result) + { + result = 0 == mbedtls_x509write_crt_set_serial(&crt_builder, &serial); + } + + if (result) + { + result = 0 + == mbedtls_x509write_crt_set_validity( + &crt_builder, from_datetime, to_datetime); + } + + size_t buf_size = 1000; + uint8_t *buf = nullptr; + if (result) + { + buf = new uint8_t[buf_size]; + result = buf != nullptr; + } + + size_t buf_content_size; + if (result) + { + auto der_result + = mbedtls_x509write_crt_der(&crt_builder, buf, buf_size, nullptr, 0); + buf_content_size = der_result; + result = 0 < der_result; + } + + mbedtls_x509write_crt_free(&crt_builder); + MbedtlsSe05xExtension::mbedtls_pk_free_se05x(key); + mbedtls_pk_free(&key); + mbedtls_pk_free(&public_key); + mbedtls_mpi_free(&serial); + + if (result) + { + result = LoadFromDerOrPem(buf + buf_size - buf_content_size, + buf_content_size); + } + + if (buf) + { + delete[] buf; + } + return result; +} + +bool CCertificate::VerifyAgainst(const ISecureElement &se, + uint32_t verify_against_id) const +{ + if (!is_loaded) + { + return false; + } + + uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; + bool result = 0 == mbedtls_sha256(crt.tbs.p, crt.tbs.len, tbs_buffer, 0); + + if (result) + { + struct se05x_signature_s verify_args = { + .key_id = verify_against_id, + .algorithm = SE05X_ALGORITHM_SHA256, + .tbs = { .buffer = tbs_buffer, + .buffer_size = sizeof(tbs_buffer), + .buffer_content_size = sizeof(tbs_buffer) }, + .signature = { .buffer = crt.sig.p, + .buffer_size = crt.sig.len, + .buffer_content_size = crt.sig.len }, + }; + result = se.Verify(verify_args); + } + + return result; +} + +static bool check_time(const mbedtls_x509_time *before, + const mbedtls_x509_time *after) +{ + if (before->year > after->year) + return false; + + if (before->year == after->year && before->mon > after->mon) + return false; + + if (before->year == after->year && before->mon == after->mon + && before->day > after->day) + return false; + + if (before->year == after->year && before->mon == after->mon + && before->day == after->day && before->hour > after->hour) + return false; + + if (before->year == after->year && before->mon == after->mon + && before->day == after->day && before->hour == after->hour + && before->min > after->min) + return false; + + if (before->year == after->year && before->mon == after->mon + && before->day == after->day && before->hour == after->hour + && before->min == after->min && before->sec > after->sec) + return false; + + return true; +} + +int CCertificate::TestValidTimerange(time_t now) const +{ + + auto lt = gmtime(&now); + + mbedtls_x509_time mbedtls_now; + mbedtls_now.year = lt->tm_year + 1900; + mbedtls_now.mon = lt->tm_mon + 1; + mbedtls_now.day = lt->tm_mday; + mbedtls_now.hour = lt->tm_hour; + mbedtls_now.min = lt->tm_min; + mbedtls_now.sec = lt->tm_sec; + + if (!check_time(&mbedtls_now, &crt.valid_to)) + { + return -1; + } + if (!check_time(&crt.valid_from, &mbedtls_now)) + { + return 1; + } + + return 0; +} + +CPublicKey *CCertificate::GetPublicKey() const +{ + if (!is_loaded) + { + return nullptr; + } + + size_t root_key_buf_size = 100; + uint8_t *root_key_buf = new uint8_t[root_key_buf_size]; + + bool result = false; + if (root_key_buf) + { + mbedtls_ecp_keypair *keypair + = reinterpret_cast(crt.pk.pk_ctx); + result = 0 + == mbedtls_ecp_point_write_binary( + &keypair->grp, &keypair->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, + &root_key_buf_size, root_key_buf, root_key_buf_size); + } + + CPublicKey *public_key + = result ? new CPublicKey(root_key_buf, root_key_buf_size) : nullptr; + + if (root_key_buf) + { + delete[] root_key_buf; + } + + return public_key; +} + +char *CCertificate::GetOid(const char *oid) const +{ + if (!is_loaded) + { + return nullptr; + } + auto item = mbedtls_asn1_find_named_data(&crt.subject, oid, 3); + + if (item) + { + auto data = new char[item->val.len + 1]; + memcpy(data, item->val.p, item->val.len); + data[item->val.len] = 0; + return data; + } + return nullptr; +} + +CSerialNumber *CCertificate::GetSerialNumber() const +{ + if (!is_loaded) + { + return nullptr; + } + + if (crt.serial.len == CSerialNumber::SERIAL_NUMBER_SIZE) + { + auto serial = new CSerialNumber(crt.serial.p); + return serial; + } + return nullptr; +} + +size_t CCertificate::GetNumberOfSubjectAlternativeNames() const +{ + if (!is_loaded) + { + return 0; + } + size_t size = 0; + auto current = &crt.subject_alt_names; + + do + { + if (current->buf.tag + == (MBEDTLS_ASN1_CONTEXT_SPECIFIC + | MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER)) + { + size++; + } + current = current->next; + } + while (current); + return size; +} + +char *CCertificate::GetSubjectAlternativeName(int item) const +{ + if (!is_loaded) + { + return nullptr; + } + + auto current = &crt.subject_alt_names; + + // go to first uri + while (current->buf.tag + != (MBEDTLS_ASN1_CONTEXT_SPECIFIC + | MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER)) + { + current = current->next; + if (current == nullptr) + { + return nullptr; + } + } + + // go the next uri until we get to the correct item + for (int i = 0; i < item; i++) + { + do + { + current = current->next; + if (current == nullptr) + { + return nullptr; + } + } + while (current->buf.tag + != (MBEDTLS_ASN1_CONTEXT_SPECIFIC + | MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER)); + } + + auto san = new char[current->buf.len + 1]; + if (san) + { + memcpy(san, current->buf.p, current->buf.len); + san[current->buf.len] = 0; + } + return san; +} + +size_t CCertificate::GetDer(uint8_t **der) const +{ + if (!is_loaded) + { + return 0; + } + *der = new uint8_t[crt.raw.len]; + memcpy(*der, crt.raw.p, crt.raw.len); + return crt.raw.len; +} + +char *CCertificate::GetPem() const +{ + if (!is_loaded) + { + return 0; + } + + char pem_buf[1000]; + size_t pem_content_size; + auto result = mbedtls_pem_write_buffer( + certificate_header, certificate_footer, crt.raw.p, crt.raw.len, + (uint8_t *)pem_buf, sizeof(pem_buf), &pem_content_size); + if (result != 0) + { + return nullptr; + } + + auto pem = new char[pem_content_size + 1]; + memcpy(pem, pem_buf, pem_content_size); + pem[pem_content_size] = 0; + return pem; +} + +bool CCertificate::ContainsSan(const char *name, size_t size) const +{ + auto san_amount = GetNumberOfSubjectAlternativeNames(); + for (size_t i = 0; i < san_amount; i++) + { + auto san = GetSubjectAlternativeName(i); + if (!san) + { + return false; + } + auto found = (memcmp(name, san, size) == 0); + delete[] san; + if (found) + { + return true; + } + } + return false; +} + +} // namespace Controlse diff --git a/crypto/controlse/ccsr.cxx b/crypto/controlse/ccsr.cxx new file mode 100644 index 000000000..e57f7b0d1 --- /dev/null +++ b/crypto/controlse/ccsr.cxx @@ -0,0 +1,212 @@ +//*************************************************************************** +// apps/crypto/controlse/ccsr.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include "crypto/controlse/ccsr.hxx" + +#include "cmbedtls_se05x_extension.hxx" +#include "crypto/controlse/cpublic_key.hxx" +#include "crypto/controlse/csecure_element.hxx" +#include +#include + +using Controlse::MbedtlsSe05xExtension; + +namespace Controlse +{ + +//*************************************************************************** +// Private Data +//*************************************************************************** + +static const char certificate_request_header[] + = "-----BEGIN CERTIFICATE REQUEST-----\n"; +static const char certificate_request_footer[] + = "-----END CERTIFICATE REQUEST-----\n"; + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CCsr::CCsr(const ISecureElement &se, uint32_t keystore_id) +{ + mbedtls_x509_csr_init(&csr); + is_loaded = LoadFromSecureElement(se, keystore_id); +} + +CCsr::CCsr(const uint8_t *der_or_pem, const size_t size) +{ + mbedtls_x509_csr_init(&csr); + is_loaded = 0 == mbedtls_x509_csr_parse(&csr, der_or_pem, size); +} + +CCsr::~CCsr() { mbedtls_x509_csr_free(&csr); } + +bool CCsr::IsLoaded() const { return is_loaded; } + +bool CCsr::StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const +{ + struct se05x_key_transmission_s args; + args.entry.id = keystore_id; + args.content.buffer = csr.raw.p; + args.content.buffer_size = csr.raw.len; + args.content.buffer_content_size = csr.raw.len; + return se.SetData(args); +} + +bool CCsr::LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) +{ + size_t csr_der_size = 1000; + uint8_t *csr_der = new uint8_t[csr_der_size]; + struct se05x_key_transmission_s args + = { .entry = { .id = keystore_id }, + .content = { .buffer = csr_der, .buffer_size = csr_der_size } }; + bool result = se.GetData(args); + + if (result) + { + result = 0 + == mbedtls_x509_csr_parse(&csr, csr_der, + args.content.buffer_content_size); + } + + delete[] csr_der; + return result; +} + +size_t CCsr::GetDer(uint8_t **der) const +{ + if (!IsLoaded()) + { + return 0; + } + *der = new uint8_t[csr.raw.len]; + memcpy(*der, csr.raw.p, csr.raw.len); + return csr.raw.len; +} + +char *CCsr::GetPem() const +{ + if (!IsLoaded()) + { + return nullptr; + } + + char pem_buf[1000]; + size_t pem_content_size; + auto result = mbedtls_pem_write_buffer( + certificate_request_header, certificate_request_footer, csr.raw.p, + csr.raw.len, (uint8_t *)pem_buf, sizeof(pem_buf), &pem_content_size); + if (result != 0) + { + return nullptr; + } + + auto pem = new char[pem_content_size + 1]; + memcpy(pem, pem_buf, pem_content_size); + pem[pem_content_size] = 0; + return pem; +} + +CCsr::CsrBuilder::CsrBuilder(ISecureElement &se, const char *subject, + uint32_t key_slot_id) +{ + mbedtls_x509write_csr_init(&csr_w); + mbedtls_pk_init(&key); + + ready = 0 + == MbedtlsSe05xExtension::mbedtls_pk_setup_key_se05x(key, se, + key_slot_id); + + if (ready) + { + mbedtls_x509write_csr_set_key(&csr_w, &key); + ready = 0 == mbedtls_x509write_csr_set_subject_name(&csr_w, subject); + } + + if (ready) + { + mbedtls_x509write_csr_set_md_alg(&csr_w, MBEDTLS_MD_SHA256); + ready = 0 + == mbedtls_x509write_csr_set_key_usage( + &csr_w, MBEDTLS_X509_KU_KEY_CERT_SIGN); + } +} + +CCsr::CsrBuilder *CCsr::CsrBuilder::AddExtension(const char *oid, + size_t oid_size, + const uint8_t *value, + size_t value_size) +{ + if (ready) + { + ready = 0 + == mbedtls_x509write_csr_set_extension(&csr_w, oid, oid_size, 0, + value, value_size); + } + + return this; +} + +CCsr *CCsr::CsrBuilder::Build() +{ + size_t buf_size = 1000; + uint8_t *buf = nullptr; + if (ready) + { + buf = new uint8_t[buf_size]; + ready = nullptr != buf; + } + + int write_result_size = 0; + if (ready) + { + write_result_size + = mbedtls_x509write_csr_der(&csr_w, buf, buf_size, nullptr, 0); + ready = write_result_size > 0; + } + + MbedtlsSe05xExtension::mbedtls_pk_free_se05x(key); + mbedtls_x509write_csr_free(&csr_w); + + CCsr *result_csr = nullptr; + if (ready) + { + result_csr + = new CCsr(buf + buf_size - write_result_size, write_result_size); + } + + if (buf) + { + delete[] buf; + } + + return result_csr; +} + +} // namespace Controlse diff --git a/crypto/controlse/chex_util.cxx b/crypto/controlse/chex_util.cxx new file mode 100644 index 000000000..e2aebae76 --- /dev/null +++ b/crypto/controlse/chex_util.cxx @@ -0,0 +1,100 @@ +//*************************************************************************** +// apps/crypto/controlse/chex_util.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/chex_util.hxx" +#include +#include +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +size_t CHexUtil::GetByteArraySizeFromHexString(const char *hex_buffer) +{ + auto hex_buffer_size = strcspn(hex_buffer, " \r\n"); + return GetByteArraySizeFromHexStringSize(hex_buffer_size); +} + +size_t CHexUtil::GetByteArraySizeFromHexStringSize(size_t hex_buffer_size) +{ + return hex_buffer_size / AMOUNT_OF_HEXDIGITS_PER_BYTE; +} + +size_t CHexUtil::GetHexStringSizeFromByteArraySize(size_t byte_array_size) +{ + return byte_array_size * AMOUNT_OF_HEXDIGITS_PER_BYTE; +} + +uint8_t *CHexUtil::ConvertHexStringToByteArray(const char *hex_buffer) +{ + auto hex_buffer_size = strcspn(hex_buffer, " \r\n"); + if (hex_buffer_size & 1) + { + return nullptr; + } + + return ConvertHexStringToByteArray(hex_buffer, hex_buffer_size); +} + +uint8_t *CHexUtil::ConvertHexStringToByteArray(const char *hex_buffer, + size_t hex_buffer_size) +{ + auto bin_buffer + = new uint8_t[GetByteArraySizeFromHexStringSize(hex_buffer_size)]; + if (bin_buffer) + { + size_t hex_buffer_pos; + size_t bin_buffer_pos = 0; + for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size); + hex_buffer_pos += AMOUNT_OF_HEXDIGITS_PER_BYTE) + { + sscanf(&hex_buffer[hex_buffer_pos], "%2hhx", + &bin_buffer[bin_buffer_pos]); + bin_buffer_pos++; + } + } + return bin_buffer; +} + +char *CHexUtil::ByteArrayToHexString(const uint8_t bytearray[], size_t size) +{ + auto string = new char[GetHexStringSizeFromByteArraySize(size) + 1]; + if (string) + { + char *ptr = string; + for (size_t i = 0; i < size; i++) + { + ptr += sprintf(ptr, "%02x", bytearray[i]); + } + } + return string; +} + +} // namespace Controlse diff --git a/crypto/controlse/cmbedtls_se05x_extension.hxx b/crypto/controlse/cmbedtls_se05x_extension.hxx new file mode 100644 index 000000000..9568ad667 --- /dev/null +++ b/crypto/controlse/cmbedtls_se05x_extension.hxx @@ -0,0 +1,188 @@ +//*************************************************************************** +// apps/crypto/controlse/cmbedtls_se05x_extensions.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include "crypto/controlse/cpublic_key.hxx" +#include "crypto/controlse/isecure_element.hxx" +#include <../crypto/mbedtls/mbedtls/library/pk_wrap.h> +#include +#include +#include +#include +#include + +using Controlse::ISecureElement; + +struct mbedtls_se05x_ctx +{ + const ISecureElement *se; + uint32_t private_key_slot_id; +}; + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class MbedtlsSe05xExtension +{ +public: + static int mbedtls_pk_parse_se05x_public_key(mbedtls_pk_context &key, + CPublicKey &se05x_key) + { + mbedtls_ecp_keypair *keypair; + uint8_t *key_buffer = nullptr; + size_t key_buffer_size = 0; + if (se05x_key.IsLoaded()) + { + key_buffer_size = se05x_key.GetRawSize(); + key_buffer = new uint8_t[key_buffer_size]; + keypair = (mbedtls_ecp_keypair *)key.pk_ctx; + } + + int result = -ENOMEM; + if (key_buffer) + { + se05x_key.GetRaw(key_buffer); + result + = mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1); + } + + if (result == 0) + { + result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q, + key_buffer, key_buffer_size); + } + + if (key_buffer) + { + delete[] key_buffer; + } + + return result; + } + + static int ecdsa_sign_wrap(void *ctx, mbedtls_md_type_t md_alg, + const unsigned char *hash, size_t hash_len, + unsigned char *sig, size_t sig_size, + size_t *sig_len, + int (*f_rng)(void *, unsigned char *, size_t), + void *p_rng) + { + + mbedtls_ecp_keypair *key = reinterpret_cast(ctx); + auto se05x_ctx = reinterpret_cast(key->d.p); + + struct se05x_signature_s args + = { se05x_ctx->private_key_slot_id, + SE05X_ALGORITHM_SHA256, + { const_cast(hash), hash_len, hash_len }, + { sig, sig_size, sig_size } }; + auto result = se05x_ctx->se->CreateSignature(args); + + if (result) + { + *sig_len = args.signature.buffer_content_size; + } + + return result ? 0 : -EPERM; + } + + // return value is allocated ptr to mbedtls_pk_info_t (need to be deleted) + // otherwise nulltpr + static mbedtls_pk_info_t *CreatePkInfoSe05x() + { + auto info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY); + auto se05x_ec_info = new mbedtls_pk_info_t; + if (se05x_ec_info) + { + *se05x_ec_info = *info; + se05x_ec_info->sign_func = ecdsa_sign_wrap; + } + return se05x_ec_info; + } + + static int mbedtls_pk_setup_key_se05x(mbedtls_pk_context &key, + const ISecureElement &se, + uint32_t key_slot_id) + { + auto se05x_ec_info = CreatePkInfoSe05x(); + if (se05x_ec_info) + { + key.pk_info = se05x_ec_info; + key.pk_ctx = se05x_ec_info->ctx_alloc_func(); + } + + int result = -ENOMEM; + if (key.pk_ctx) + { + auto se05x_key = CPublicKey(se, key_slot_id); + result = mbedtls_pk_parse_se05x_public_key(key, se05x_key); + } + + mbedtls_se05x_ctx *se05x_ctx = nullptr; + if (result == 0) + { + se05x_ctx = new mbedtls_se05x_ctx; + result = se05x_ctx ? 0 : -ENOMEM; + } + + if (result == 0) + { + se05x_ctx->private_key_slot_id = key_slot_id; + se05x_ctx->se = &se; + } + + ((mbedtls_ecp_keypair *)key.pk_ctx)->d.p + = reinterpret_cast(se05x_ctx); + return result; + } + + static void mbedtls_pk_free_se05x(mbedtls_pk_context &key) + { + auto key_ctx = reinterpret_cast(key.pk_ctx); + if (key_ctx) + { + auto se05x_ctx = reinterpret_cast(key_ctx->d.p); + if (se05x_ctx) + { + delete se05x_ctx; + key_ctx->d.p = nullptr; + } + } + auto pk_info = key.pk_info; + if (pk_info) + { + mbedtls_pk_free(&key); + delete pk_info; + } + } +}; +} // namespace Controlse diff --git a/crypto/controlse/controlse_main.c b/crypto/controlse/controlse_main.c deleted file mode 100644 index f2ed327b8..000000000 --- a/crypto/controlse/controlse_main.c +++ /dev/null @@ -1,737 +0,0 @@ -/**************************************************************************** - * apps/crypto/controlse/controlse_main.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/* Copyright 2023 NXP */ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#define MBEDTLS_ALLOW_PRIVATE_ACCESS -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef CONFIG_STACK_COLORATION -#include -#include -#endif - -#include "x509_utils.h" - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define EOT 0x04 - -#define DEFAULT_SETTINGS \ - { \ - .se05x_dev_filename = default_se05x_device, 0 \ - } - -#define TBS_HASH_BUFFER_SIZE 32 -#define SIGNATURE_BUFFER_SIZE 300 -#define SYMM_KEY_BUFFER_SIZE 300 -#define RAW_KEY_BUFFER_SIZE 600 -#define DEFAULT_BUFFER_SIZE 1000 - -/**************************************************************************** - * Private Types - ****************************************************************************/ - -typedef enum -{ - KEYSTORE_NO_ACTION = 0, - KEYSTORE_READ, - KEYSTORE_WRITE, - KEYSTORE_GENERATE, - KEYSTORE_DELETE, - KEYSTORE_DERIVE_SYMM_KEY, - KEYSTORE_CREATE_SIGNATURE, - KEYSTORE_VERIFY_SIGNATURE, - KEYSTORE_SIGN_CSR, - KEYSTORE_VERIFY_CERTIFICATE, - KEYSTORE_GET_INFO, - KEYSTORE_GET_UID, -} keystore_operation; - -struct settings_t -{ - FAR const char *se05x_dev_filename; - FAR char *input_filename; - FAR char *signature_filename; - bool skip_process; - keystore_operation operation; - bool raw_data_in_device; - bool interface_with_pem; - uint32_t key_id; - uint32_t private_key_id; - bool show_stack_used; -}; - -/**************************************************************************** - * Private Function Prototypes - ****************************************************************************/ - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static const char default_se05x_device[] = "/dev/se05x"; -static const char enter_key_hex[] = "enter key(hex)"; -static const char enter_data_pem[] = "enter data(pem)"; -static const char enter_data_raw[] = "enter data(raw)"; - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void print_usage(FAR FILE *f, FAR char *prg) -{ - fprintf(f, "%s - Control SE05x Secure Element\n", prg); - fprintf(f, "\nUsage: %s [options] \n", prg); - fprintf(f, "Options:\n"); - fprintf(f, " -r (read item from keystore at )\n"); - fprintf(f, " -w (set item in keystore at )\n"); - fprintf(f, " -g (generate keypair at )\n"); - fprintf(f, " -d (delete key at )\n"); - fprintf(f, " -s (create signature for data\n"); - fprintf(f, " with key at )\n"); - fprintf(f, " -S (Sign CSR with key at )\n"); - fprintf(f, " -v (verify signature for data\n"); - fprintf(f, " with key at )\n"); - fprintf(f, " -V (verify CRT with key at \n"); - fprintf(f, " -a (derive symm key\n"); - fprintf(f, " from public key \n"); - fprintf(f, " and private key)\n"); - fprintf(f, " -t (interface using raw data\n"); - fprintf(f, " use with -r, -w)\n"); - fprintf(f, " -c (interface with PEM format\n"); - fprintf(f, " internally using DER\n"); - fprintf(f, " use with -r, -w)\n"); - fprintf(f, " -p (select private key\n"); - fprintf(f, " use with -a)\n"); - fprintf(f, " -n (Read input from file)\n"); - fprintf(f, " -N (Read signature from file)\n"); - fprintf(f, " -i (show generic information)\n"); - fprintf(f, " -u (show UID)\n"); - fprintf(f, " -m (show used stack memory space)\n"); - fprintf(f, " -h (show this help)\n"); - fprintf(f, "\n"); -} - -static int set_operation(FAR struct settings_t *settings, - keystore_operation operation, FAR char *key_id_text) -{ - int result = -EPERM; - if (settings->operation == KEYSTORE_NO_ACTION) - { - settings->operation = operation; - settings->key_id = 0; - if (key_id_text != NULL) - { - settings->key_id = (uint32_t)strtoul(key_id_text, NULL, 0); - } - - result = 0; - } - - return result; -} - -static int parse_arguments(int argc, FAR char *argv[], - FAR struct settings_t *settings) -{ - int result = 0; - int opt; - FAR char *prg = basename(argv[0]); - while ( - ((opt = getopt(argc, argv, "iug:w:r:d:s:v:S:V:tca:p:n:N:mh")) != -1) && - (result == 0)) - { - switch (opt) - { - case 'i': - result = set_operation(settings, KEYSTORE_GET_INFO, optarg); - break; - case 'u': - result = set_operation(settings, KEYSTORE_GET_UID, optarg); - break; - case 'g': - result = set_operation(settings, KEYSTORE_GENERATE, optarg); - break; - case 'r': - result = set_operation(settings, KEYSTORE_READ, optarg); - break; - case 'w': - result = set_operation(settings, KEYSTORE_WRITE, optarg); - break; - case 't': - settings->raw_data_in_device = TRUE; - break; - case 'c': - settings->interface_with_pem = TRUE; - settings->raw_data_in_device = TRUE; - break; - case 'd': - result = set_operation(settings, KEYSTORE_DELETE, optarg); - break; - case 's': - result = - set_operation(settings, KEYSTORE_CREATE_SIGNATURE, optarg); - break; - case 'v': - result = - set_operation(settings, KEYSTORE_VERIFY_SIGNATURE, optarg); - break; - case 'S': - result = set_operation(settings, KEYSTORE_SIGN_CSR, optarg); - break; - case 'V': - result = - set_operation(settings, KEYSTORE_VERIFY_CERTIFICATE, optarg); - break; - case 'a': - result = set_operation(settings, KEYSTORE_DERIVE_SYMM_KEY, optarg); - break; - case 'p': - settings->private_key_id = (uint32_t)strtoul(optarg, NULL, 0); - break; - case 'n': - settings->input_filename = optarg; - break; - case 'N': - settings->signature_filename = optarg; - break; - case 'm': - settings->show_stack_used = TRUE; - break; - case 'h': - print_usage(stdout, prg); - settings->skip_process = TRUE; - break; - default: - print_usage(stderr, prg); - result = -EINVAL; - break; - } - } - - if ((result == 0) && (!settings->skip_process)) - { - if (settings->operation == KEYSTORE_NO_ACTION) - { - print_usage(stderr, prg); - result = -EINVAL; - } - - /* if device is specified as positional argument */ - - if (optind != argc) - { - settings->se05x_dev_filename = argv[optind]; - } - } - - return result; -} - -static int convert_array_hex_to_bin(FAR char *hex_buffer, - size_t hex_buffer_size, - FAR uint8_t *bin_buffer, - size_t bin_buffer_size, - FAR size_t *bin_buffer_content_size) -{ - hex_buffer_size = strcspn(hex_buffer, " \r\n"); - if (hex_buffer_size & 1) - { - return -1; - } - - *bin_buffer_content_size = 0; - size_t hex_buffer_pos; - for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size) && - (*bin_buffer_content_size < bin_buffer_size); - hex_buffer_pos += 2) - { - sscanf(&hex_buffer[hex_buffer_pos], "%2hhx", - &bin_buffer[*bin_buffer_content_size]); - (*bin_buffer_content_size)++; - } - - return hex_buffer_pos == hex_buffer_size ? 0 : -1; -} - -static int read_from_file(FAR const char *prompt, FAR char *filename, - FAR char *buffer, size_t buffer_size) -{ - FAR FILE *f = stdin; - if (filename != NULL) - { - f = fopen(filename, "r"); - } - else - { - puts(prompt); - } - - size_t buffer_content_size = 0; - if (f != NULL) - { - FAR char *c = buffer; - int result = fgetc(f); - while ((result != EOF) && (result != EOT) && - (buffer_content_size < buffer_size)) - { - *c = result & 0xff; - c++; - buffer_content_size++; - result = fgetc(f); - } - } - - if (filename != NULL) - { - fclose(f); - } - - return buffer_content_size; -} - -static int read_from_file_and_convert(FAR const char *prompt, - FAR char *filename, - FAR uint8_t *buffer, - size_t buffer_size, - FAR size_t *buffer_content_size) -{ - char file_buffer[DEFAULT_BUFFER_SIZE]; - size_t file_buffer_content_size; - int result; - - file_buffer_content_size = read_from_file( - prompt, filename, (FAR char *)file_buffer, sizeof(file_buffer)); - result = convert_array_hex_to_bin(file_buffer, file_buffer_content_size, - buffer, buffer_size, buffer_content_size - ); - - return result; -} - -static size_t add_zero_termination_character(char *data, size_t content_size, - size_t buf_size) -{ - size_t zero_termination_char_position = content_size - 1; - if ((content_size + 1) <= buf_size) - { - zero_termination_char_position = content_size; - content_size++; - } - - data[zero_termination_char_position] = 0; - return content_size; -} - -static int process(int se05x_fd, FAR struct settings_t *settings) -{ - int result = 0; - if (settings->operation == KEYSTORE_GET_INFO) - { - struct se05x_info_s info; - result = ioctl(se05x_fd, SEIOC_GET_INFO, &info); - - if (result == 0) - { - printf("OEF ID: %04x\n", info.oef_id); - } - } - - else if (settings->operation == KEYSTORE_GET_UID) - { - struct se05x_uid_s uid; - result = ioctl(se05x_fd, SEIOC_GET_UID, &uid); - - if (result == 0) - { - printf("UID: "); - for (size_t i = 0; i < SE05X_MODULE_UNIQUE_ID_LEN; i++) - { - printf("%02x", uid.uid[i]); - } - - printf("\n"); - } - } - else if (settings->operation == KEYSTORE_GENERATE) - { - struct se05x_generate_keypair_s args = { - .id = settings->key_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 - }; - - result = ioctl(se05x_fd, SEIOC_GENERATE_KEYPAIR, &args); - - if (result == 0) - { - printf("Keypair generated successfully\n"); - } - } - else if (settings->operation == KEYSTORE_WRITE) - { - char pem_buf[DEFAULT_BUFFER_SIZE]; - FAR const char *prompt = enter_key_hex; - if (settings->raw_data_in_device) - { - prompt = - settings->interface_with_pem ? enter_data_pem : enter_data_raw; - } - - size_t pem_content_size = read_from_file( - prompt, settings->input_filename, pem_buf, sizeof(pem_buf)); - - uint8_t rawkey[RAW_KEY_BUFFER_SIZE]; - size_t rawkey_size = sizeof(rawkey); - - FAR uint8_t *data = (FAR uint8_t *)pem_buf; - size_t data_size = pem_content_size; - if (!settings->raw_data_in_device) - { - result = convert_public_key_pem_to_raw(rawkey, rawkey_size, - &rawkey_size, pem_buf); - if (result == 0) - { - data = rawkey; - data_size = rawkey_size; - } - } - - if (settings->interface_with_pem) - { - pem_content_size = add_zero_termination_character( - pem_buf, pem_content_size, sizeof(pem_buf)); - result = convert_pem_certificate_or_csr_to_der( - rawkey, rawkey_size, &rawkey_size, pem_buf, pem_content_size); - if (result == 0) - { - data = rawkey; - data_size = rawkey_size; - } - } - - if (result == 0) - { - struct se05x_key_transmission_s args = { - .entry = {.id = settings->key_id, - .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256}, - .content = {.buffer = data, - .buffer_size = data_size, - .buffer_content_size = data_size} - }; - - result = ioctl(se05x_fd, - settings->raw_data_in_device ? SEIOC_SET_DATA - : SEIOC_SET_KEY, - &args); - } - - if (result == 0) - { - printf("Data stored successfully\n"); - } - } - else if (settings->operation == KEYSTORE_READ) - { - uint8_t buffer[DEFAULT_BUFFER_SIZE]; - struct se05x_key_transmission_s args = { - .entry = {.id = settings->key_id}, - .content = {.buffer = buffer, .buffer_size = sizeof(buffer)} - }; - - result = - ioctl(se05x_fd, - settings->raw_data_in_device ? SEIOC_GET_DATA : SEIOC_GET_KEY, - &args); - - FAR char *data = (FAR char *)args.content.buffer; - if ((result == 0) - && settings->raw_data_in_device - && !settings->interface_with_pem) - { - args.content.buffer_content_size = add_zero_termination_character( - data, args.content.buffer_content_size, - args.content.buffer_size); - } - - char pem_buf[DEFAULT_BUFFER_SIZE]; - if ((result == 0) && !settings->raw_data_in_device) - { - result = convert_public_key_raw_to_pem( - pem_buf, sizeof(pem_buf), args.content.buffer, - args.content.buffer_content_size); - - data = pem_buf; - } - - if ((result == 0) && settings->interface_with_pem) - { - size_t pem_content_size; - result = convert_der_certificate_or_csr_to_pem( - pem_buf, sizeof(pem_buf), &pem_content_size, - args.content.buffer, args.content.buffer_content_size); - - data = pem_buf; - } - - if (result == 0) - { - puts(data); - } - } - else if (settings->operation == KEYSTORE_DELETE) - { - result = ioctl(se05x_fd, SEIOC_DELETE_KEY, settings->key_id); - - if (result == 0) - { - printf("Deleted key successfully\n"); - } - } - else if (settings->operation == KEYSTORE_DERIVE_SYMM_KEY) - { - uint8_t buffer[SYMM_KEY_BUFFER_SIZE]; - struct se05x_derive_key_s args = { - .private_key_id = settings->private_key_id, - .public_key_id = settings->key_id, - .content = {.buffer = buffer, .buffer_size = sizeof(buffer)}, - }; - - result = ioctl(se05x_fd, SEIOC_DERIVE_SYMM_KEY, &args); - - if (result == 0) - { - for (size_t i = 0; i < args.content.buffer_content_size; i++) - { - printf("%02x", args.content.buffer[i]); - } - - printf("\n"); - } - } - else if (settings->operation == KEYSTORE_CREATE_SIGNATURE) - { - uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; - size_t tbs_content_size; - read_from_file_and_convert("Enter tbs(hex):", settings->input_filename, - tbs_buffer, sizeof(tbs_buffer), - &tbs_content_size); - uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE]; - size_t signature_content_len = 0; - if (result == 0) - { - struct se05x_signature_s args = { - .key_id = settings->key_id, - .algorithm = SE05X_ALGORITHM_SHA256, - .tbs = {.buffer = tbs_buffer, - .buffer_size = tbs_content_size, - .buffer_content_size = tbs_content_size}, - .signature = {.buffer = signature_buffer, - .buffer_size = sizeof(signature_buffer)}, - }; - - result = ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args); - signature_content_len = args.signature.buffer_content_size; - } - - if (result == 0) - { - for (size_t i = 0; i < signature_content_len; i++) - { - printf("%02x", signature_buffer[i]); - } - - printf("\n"); - } - } - else if (settings->operation == KEYSTORE_VERIFY_SIGNATURE) - { - uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; - size_t tbs_content_size; - result = read_from_file_and_convert( - "Enter tbs(hex):", settings->input_filename, tbs_buffer, - sizeof(tbs_buffer), &tbs_content_size); - - uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE]; - size_t signature_content_size; - if (result == 0) - { - result = read_from_file_and_convert( - "Enter signature(hex):", settings->signature_filename, - signature_buffer, sizeof(signature_buffer), - &signature_content_size); - } - - if (result == 0) - { - struct se05x_signature_s args = { - .key_id = settings->key_id, - .algorithm = SE05X_ALGORITHM_SHA256, - .tbs = {.buffer = tbs_buffer, - .buffer_size = tbs_content_size, - .buffer_content_size = tbs_content_size}, - .signature = {.buffer = signature_buffer, - .buffer_size = signature_content_size, - .buffer_content_size = signature_content_size}, - }; - - result = ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args); - } - - if (result == 0) - { - printf("Signature verified successfully\n"); - } - } - else if (settings->operation == KEYSTORE_SIGN_CSR) - { - char csr_pem_buf[DEFAULT_BUFFER_SIZE]; - size_t csr_pem_buf_content_size = - read_from_file("enter csr(pem)", settings->input_filename, - csr_pem_buf, sizeof(csr_pem_buf)); - - csr_pem_buf_content_size = add_zero_termination_character(csr_pem_buf, - csr_pem_buf_content_size, sizeof(csr_pem_buf)); - - char crt_pem_buf[DEFAULT_BUFFER_SIZE]; - result = sign_csr(se05x_fd, settings->key_id, crt_pem_buf, - sizeof(crt_pem_buf), csr_pem_buf, - csr_pem_buf_content_size); - if (result == 0) - { - puts(crt_pem_buf); - } - } - else if (settings->operation == KEYSTORE_VERIFY_CERTIFICATE) - { - char pem_buf[DEFAULT_BUFFER_SIZE]; - size_t pem_content_size = - read_from_file("enter crt(pem)", settings->input_filename, pem_buf, - sizeof(pem_buf)); - - pem_content_size = add_zero_termination_character(pem_buf, - pem_content_size, sizeof(pem_buf)); - - mbedtls_x509_crt crt; - mbedtls_x509_crt_init(&crt); - result = mbedtls_x509_crt_parse(&crt, (FAR uint8_t *)pem_buf, - pem_content_size); - - uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; - - if (result == 0) - { - result = mbedtls_sha256(crt.tbs.p, - crt.tbs.len, tbs_buffer, 0 - ); - } - - if (result == 0) - { - struct se05x_signature_s args = { - .key_id = settings->key_id, - .algorithm = SE05X_ALGORITHM_SHA256, - .tbs = {.buffer = tbs_buffer, - .buffer_size = sizeof(tbs_buffer), - .buffer_content_size = sizeof(tbs_buffer)}, - .signature = {.buffer = crt.sig.p, - .buffer_size = crt.sig.len, - .buffer_content_size = - crt.sig.len}, - }; - - result = ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args); - } - - if (result == 0) - { - printf("Signature verified successfully\n"); - } - - mbedtls_x509_crt_free(&crt); - } - - return result; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int main(int argc, FAR char *argv[]) -{ - struct settings_t settings = DEFAULT_SETTINGS; - int result = parse_arguments(argc, argv, &settings); - - if ((result == 0) && (!settings.skip_process)) - { - int fd = open(settings.se05x_dev_filename, O_RDONLY); - if (fd == -1) - { - result = -ENODEV; - } - else - { - result = process(fd, &settings); - close(fd); - } - } - - if (result != 0) - { - fprintf(stderr, "err %i: %s\n", -result, strerror(-result)); - } - - if (settings.show_stack_used) - { -#ifdef CONFIG_STACK_COLORATION - FAR struct tcb_s *tcb; - tcb = nxsched_get_tcb(getpid()); - fprintf(stderr, "\nStack used: %zu / %zu\n", - up_check_tcbstack(tcb), tcb->adj_stack_size); -#else - fprintf(stderr, "\nStack used: unknown" - " (STACK_COLORATION must be enabled)\n"); -#endif - } - - return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE; -} diff --git a/crypto/controlse/controlse_main.cxx b/crypto/controlse/controlse_main.cxx new file mode 100644 index 000000000..238a85233 --- /dev/null +++ b/crypto/controlse/controlse_main.cxx @@ -0,0 +1,711 @@ +//*************************************************************************** +// apps/crypto/controlse/controlse_main.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2023, 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/ccertificate.hxx" +#include "crypto/controlse/ccsr.hxx" +#include "crypto/controlse/chex_util.hxx" +#include "crypto/controlse/cpublic_key.hxx" +#include "crypto/controlse/csecure_element.hxx" +#include "crypto/controlse/cstring.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CONFIG_STACK_COLORATION +#include +#include +#endif + +//*************************************************************************** +// Pre-processor Definitions +//************************************************************************** + +#define EOT 0x04 + +#define DEFAULT_SETTINGS \ + { \ + .se05x_dev_filename = default_se05x_device, 0 \ + } + +#define TBS_HASH_BUFFER_SIZE 32 +#define SIGNATURE_BUFFER_SIZE 300 +#define SYMM_KEY_BUFFER_SIZE 300 +#define RAW_KEY_BUFFER_SIZE 600 +#define DEFAULT_BUFFER_SIZE 1000 + +//*************************************************************************** +// Private Types +//************************************************************************** + +typedef enum +{ + KEYSTORE_NO_ACTION = 0, + KEYSTORE_READ, + KEYSTORE_WRITE, + KEYSTORE_GENERATE, + KEYSTORE_DELETE, + KEYSTORE_DERIVE_SYMM_KEY, + KEYSTORE_CREATE_SIGNATURE, + KEYSTORE_VERIFY_SIGNATURE, + KEYSTORE_SIGN_CSR, + KEYSTORE_VERIFY_CERTIFICATE, + KEYSTORE_GET_INFO, + KEYSTORE_GET_UID, +} EKeystoreOperation; + +typedef enum +{ + KEYSTORE_DATA_TYPE_KEY = 0, + KEYSTORE_DATA_TYPE_CERT_OR_CSR, + KEYSTORE_DATA_TYPE_STRING, +} EKeystoreDataType; + +struct SSettings +{ + FAR const char *se05x_dev_filename; + FAR char *input_filename; + FAR char *signature_filename; + bool skip_process; + EKeystoreOperation operation; + EKeystoreDataType data_type; + uint32_t key_id; + uint32_t private_key_id; + bool show_stack_used; +}; + +//*************************************************************************** +// Private Function Prototypes +//************************************************************************** + +extern "C" int main(int argc, FAR char *argv[]); + +//*************************************************************************** +// Private Data +//************************************************************************** + +static const char default_se05x_device[] = "/dev/se05x"; +static const char enter_key_hex[] = "enter key(hex)"; +static const char enter_data_pem[] = "enter data(pem)"; +static const char enter_data_raw[] = "enter data(raw)"; + +//*************************************************************************** +// Public Data +//************************************************************************** + +//*************************************************************************** +// Private Functions +//************************************************************************** + +static void printUsage(FAR FILE *f, FAR char *prg) +{ + fprintf(f, "%s - Control SE05x Secure Element\n", prg); + fprintf(f, "\nUsage: %s [options] \n", prg); + fprintf(f, "Options:\n"); + fprintf(f, " -r (read item from keystore at )\n"); + fprintf(f, " -w (set item in keystore at )\n"); + fprintf(f, " -g (generate keypair at )\n"); + fprintf(f, " -d (delete key at )\n"); + fprintf(f, " -s (create signature for data\n"); + fprintf(f, " with key at )\n"); + fprintf(f, " -S (Sign CSR with key at )\n"); + fprintf(f, " -v (verify signature for data\n"); + fprintf(f, " with key at )\n"); + fprintf(f, " -V (verify CRT with key at \n"); + fprintf(f, " -a (derive symm key\n"); + fprintf(f, " from public key \n"); + fprintf(f, " and private key)\n"); + fprintf(f, " -t (interface using raw data\n"); + fprintf(f, " use with -r, -w)\n"); + fprintf(f, " -c (interface with PEM format\n"); + fprintf(f, " internally using DER\n"); + fprintf(f, " use with -r, -w)\n"); + fprintf(f, " -p (select private key\n"); + fprintf(f, " use with -a)\n"); + fprintf(f, " -n (Read input from file)\n"); + fprintf(f, " -N (Read signature from file)\n"); + fprintf(f, " -i (show generic information)\n"); + fprintf(f, " -u (show UID)\n"); + fprintf(f, " -m (show used stack memory space)\n"); + fprintf(f, " -h (show this help)\n"); + fprintf(f, "\n"); +} + +static int setOperation(FAR struct SSettings *settings, + EKeystoreOperation operation, FAR char *key_id_text) +{ + int result = -EPERM; + if (settings->operation == KEYSTORE_NO_ACTION) + { + settings->operation = operation; + settings->key_id = 0; + if (key_id_text != NULL) + { + settings->key_id = (uint32_t)strtoul(key_id_text, NULL, 0); + } + + result = 0; + } + + return result; +} + +static int parseArguments(int argc, FAR char *argv[], + FAR struct SSettings *settings) +{ + int result = 0; + int opt; + FAR char *prg = basename(argv[0]); + while (((opt = getopt(argc, argv, "iug:w:r:d:s:v:S:V:tca:p:n:N:mh")) != -1) + && (result == 0)) + { + switch (opt) + { + case 'i': + result = setOperation(settings, KEYSTORE_GET_INFO, optarg); + break; + case 'u': + result = setOperation(settings, KEYSTORE_GET_UID, optarg); + break; + case 'g': + result = setOperation(settings, KEYSTORE_GENERATE, optarg); + break; + case 'r': + result = setOperation(settings, KEYSTORE_READ, optarg); + break; + case 'w': + result = setOperation(settings, KEYSTORE_WRITE, optarg); + break; + case 't': + settings->data_type = KEYSTORE_DATA_TYPE_STRING; + break; + case 'c': + settings->data_type = KEYSTORE_DATA_TYPE_CERT_OR_CSR; + break; + case 'd': + result = setOperation(settings, KEYSTORE_DELETE, optarg); + break; + case 's': + result = setOperation(settings, KEYSTORE_CREATE_SIGNATURE, optarg); + break; + case 'v': + result = setOperation(settings, KEYSTORE_VERIFY_SIGNATURE, optarg); + break; + case 'S': + result = setOperation(settings, KEYSTORE_SIGN_CSR, optarg); + break; + case 'V': + result = setOperation(settings, KEYSTORE_VERIFY_CERTIFICATE, optarg); + break; + case 'a': + result = setOperation(settings, KEYSTORE_DERIVE_SYMM_KEY, optarg); + break; + case 'p': + settings->private_key_id = (uint32_t)strtoul(optarg, NULL, 0); + break; + case 'n': + settings->input_filename = optarg; + break; + case 'N': + settings->signature_filename = optarg; + break; + case 'm': + settings->show_stack_used = TRUE; + break; + case 'h': + printUsage(stdout, prg); + settings->skip_process = TRUE; + break; + default: + printUsage(stderr, prg); + result = -EINVAL; + break; + } + } + + if ((result == 0) && (!settings->skip_process)) + { + if (settings->operation == KEYSTORE_NO_ACTION) + { + printUsage(stderr, prg); + result = -EINVAL; + } + + // if device is specified as positional argument + + if (optind != argc) + { + settings->se05x_dev_filename = argv[optind]; + } + } + + return result; +} + +// TODO: use chexutil +static int convert_array_hex_to_bin(FAR char *hex_buffer, + size_t hex_buffer_size, + FAR uint8_t *bin_buffer, + size_t bin_buffer_size, + FAR size_t *bin_buffer_content_size) +{ + hex_buffer_size = strcspn(hex_buffer, " \r\n"); + if (hex_buffer_size & 1) + { + return -1; + } + + *bin_buffer_content_size = 0; + size_t hex_buffer_pos; + for (hex_buffer_pos = 0; (hex_buffer_pos < hex_buffer_size) + && (*bin_buffer_content_size < bin_buffer_size); + hex_buffer_pos += 2) + { + sscanf(&hex_buffer[hex_buffer_pos], "%2hhx", + &bin_buffer[*bin_buffer_content_size]); + (*bin_buffer_content_size)++; + } + + return hex_buffer_pos == hex_buffer_size ? 0 : -1; +} + +static int readFromFile(FAR const char *prompt, FAR char *filename, + FAR char *buffer, size_t buffer_size) +{ + FAR FILE *f = stdin; + if (filename != NULL) + { + f = fopen(filename, "r"); + } + else + { + puts(prompt); + } + + size_t buffer_content_size = 0; + if (f != NULL) + { + FAR char *c = buffer; + int result = fgetc(f); + // keep looping until EOF or EOT are received or the buffer has only 1 + // space left (needed for the zero termination character) + while ((result != EOF) && (result != EOT) + && ((buffer_content_size + 1) < buffer_size)) + { + *c = result & 0xff; + c++; + buffer_content_size++; + result = fgetc(f); + } + // Add zero termination character + *c = 0; + buffer_content_size++; + } + + puts("\n"); + + if (filename != NULL) + { + fclose(f); + } + + return buffer_content_size; +} + +static int readFromFileAndConvert(FAR const char *prompt, FAR char *filename, + FAR uint8_t *buffer, size_t buffer_size, + FAR size_t *buffer_content_size) +{ + char file_buffer[DEFAULT_BUFFER_SIZE]; + size_t file_buffer_content_size; + int result; + + file_buffer_content_size = readFromFile( + prompt, filename, (FAR char *)file_buffer, sizeof(file_buffer)); + result = convert_array_hex_to_bin(file_buffer, file_buffer_content_size, + buffer, buffer_size, buffer_content_size); + + return result; +} + +static size_t addZeroTerminationCharacter(char *data, size_t content_size, + size_t buf_size) +{ + size_t zero_termination_char_position = content_size - 1; + if ((content_size + 1) <= buf_size) + { + zero_termination_char_position = content_size; + content_size++; + } + + data[zero_termination_char_position] = 0; + return content_size; +} + +static int process(int se05x_fd, FAR struct SSettings *settings) +{ + int result = 0; + Controlse::CSecureElement se(se05x_fd); + if (settings->operation == KEYSTORE_GET_INFO) + { + struct se05x_info_s info; + result = se.GetInfo(info) ? 0 : -EPERM; + + if (result == 0) + { + printf("OEF ID: %04x\n", info.oef_id); + } + } + else if (settings->operation == KEYSTORE_GET_UID) + { + struct se05x_uid_s uid; + result = se.GetUid(uid) ? 0 : -EPERM; + if (result == 0) + { + printf("UID: "); + for (size_t i = 0; i < SE05X_MODULE_UNIQUE_ID_LEN; i++) + { + printf("%02x", uid.uid[i]); + } + + printf("\n"); + } + } + else if (settings->operation == KEYSTORE_GENERATE) + { + struct se05x_generate_keypair_s args + = { .id = settings->key_id, + .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 }; + + result = se.GenerateKey(args) ? 0 : -EPERM; + + if (result == 0) + { + printf("Keypair generated successfully\n"); + } + } + else if (settings->operation == KEYSTORE_WRITE) + { + char data[DEFAULT_BUFFER_SIZE]; + FAR const char *prompt = settings->data_type == KEYSTORE_DATA_TYPE_STRING + ? enter_data_raw + : enter_data_pem; + + size_t data_size + = readFromFile(prompt, settings->input_filename, data, sizeof(data)); + + result = -EINVAL; + if (data_size != 0) + { + Controlse::ISecureElementObject *object = nullptr; + if (settings->data_type == KEYSTORE_DATA_TYPE_STRING) + { + object = new Controlse::CString( + data, + data_size - 1); // -1 because no zero termination character + // required + } + else if (settings->data_type == KEYSTORE_DATA_TYPE_KEY) + { + object = new Controlse::CPublicKey(data); + } + else if (settings->data_type == KEYSTORE_DATA_TYPE_CERT_OR_CSR) + { + object = new Controlse::CCertificate( + reinterpret_cast(data), data_size); + if (object) + { + if (!object->IsLoaded()) + { + delete object; + object = new Controlse::CCsr( + reinterpret_cast(data), data_size); + } + } + } + + result = -EPERM; + if (object) + { + if (object->IsLoaded()) + { + result = object->StoreOnSecureElement(se, settings->key_id) + ? 0 + : -EPERM; + } + delete object; + } + } + + if (result == 0) + { + printf("Data stored successfully\n"); + } + } + else if (settings->operation == KEYSTORE_READ) + { + char *data = nullptr; + if (settings->data_type == KEYSTORE_DATA_TYPE_STRING) + { + Controlse::CString string(se, settings->key_id); + if (string.IsLoaded()) + { + data = string.c_str(); + } + } + else if (settings->data_type == KEYSTORE_DATA_TYPE_KEY) + { + Controlse::CPublicKey key(se, settings->key_id); + if (key.IsLoaded()) + { + data = key.GetPem(); + } + } + else if (settings->data_type == KEYSTORE_DATA_TYPE_CERT_OR_CSR) + { + Controlse::CCertificate cert(se, settings->key_id); + if (cert.IsLoaded()) + { + data = cert.GetPem(); + } + else + { + Controlse::CCsr csr(se, settings->key_id); + if (csr.IsLoaded()) + { + data = csr.GetPem(); + } + } + } + if (data) + { + puts(data); + delete[] data; + } + else + { + result = -EPERM; + } + } + else if (settings->operation == KEYSTORE_DELETE) + { + result = se.DeleteKey(settings->key_id) ? 0 : -EPERM; + if (result == 0) + { + printf("Deleted key successfully\n"); + } + } + else if (settings->operation == KEYSTORE_DERIVE_SYMM_KEY) + { + uint8_t buffer[SYMM_KEY_BUFFER_SIZE]; + struct se05x_derive_key_s args = { + .private_key_id = settings->private_key_id, + .public_key_id = settings->key_id, + .content = { .buffer = buffer, .buffer_size = sizeof(buffer) }, + }; + + result = se.DeriveSymmetricalKey(args) ? 0 : -EPERM; + + if (result == 0) + { + for (size_t i = 0; i < args.content.buffer_content_size; i++) + { + printf("%02x", args.content.buffer[i]); + } + printf("\n"); + } + } + else if (settings->operation == KEYSTORE_CREATE_SIGNATURE) + { + uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; + size_t tbs_content_size; + readFromFileAndConvert("Enter tbs(hex):", settings->input_filename, + tbs_buffer, sizeof(tbs_buffer), + &tbs_content_size); + uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE]; + size_t signature_content_len = 0; + if (result == 0) + { + struct se05x_signature_s args = { + .key_id = settings->key_id, + .algorithm = SE05X_ALGORITHM_SHA256, + .tbs = { .buffer = tbs_buffer, + .buffer_size = tbs_content_size, + .buffer_content_size = tbs_content_size }, + .signature = { .buffer = signature_buffer, + .buffer_size = sizeof(signature_buffer) }, + }; + + result = se.CreateSignature(args) ? 0 : -EPERM; + signature_content_len = args.signature.buffer_content_size; + } + + if (result == 0) + { + for (size_t i = 0; i < signature_content_len; i++) + { + printf("%02x", signature_buffer[i]); + } + + printf("\n"); + } + } + else if (settings->operation == KEYSTORE_VERIFY_SIGNATURE) + { + uint8_t tbs_buffer[TBS_HASH_BUFFER_SIZE]; + size_t tbs_content_size; + result = readFromFileAndConvert( + "Enter tbs(hex):", settings->input_filename, tbs_buffer, + sizeof(tbs_buffer), &tbs_content_size); + + uint8_t signature_buffer[SIGNATURE_BUFFER_SIZE]; + size_t signature_content_size; + if (result == 0) + { + result = readFromFileAndConvert( + "Enter signature(hex):", settings->signature_filename, + signature_buffer, sizeof(signature_buffer), + &signature_content_size); + } + + if (result == 0) + { + struct se05x_signature_s args = { + .key_id = settings->key_id, + .algorithm = SE05X_ALGORITHM_SHA256, + .tbs = { .buffer = tbs_buffer, + .buffer_size = tbs_content_size, + .buffer_content_size = tbs_content_size }, + .signature = { .buffer = signature_buffer, + .buffer_size = signature_content_size, + .buffer_content_size = signature_content_size }, + }; + + result = se.Verify(args) ? 0 : -EPERM; + } + + if (result == 0) + { + printf("Signature verified successfully\n"); + } + } + else if (settings->operation == KEYSTORE_SIGN_CSR) + { + char csr_pem_buf[DEFAULT_BUFFER_SIZE]; + size_t csr_pem_buf_content_size + = readFromFile("enter csr(pem)", settings->input_filename, + csr_pem_buf, sizeof(csr_pem_buf)); + + csr_pem_buf_content_size = addZeroTerminationCharacter( + csr_pem_buf, csr_pem_buf_content_size, sizeof(csr_pem_buf)); + + auto certificate = Controlse::CCertificate( + se, reinterpret_cast(csr_pem_buf), + csr_pem_buf_content_size, settings->key_id); + + auto crt_pem = certificate.GetPem(); + if (crt_pem) + { + puts(crt_pem); + delete[] crt_pem; + } + else + { + result = -EPERM; + } + } + else if (settings->operation == KEYSTORE_VERIFY_CERTIFICATE) + { + char pem_buf[DEFAULT_BUFFER_SIZE]; + size_t pem_content_size + = readFromFile("enter crt(pem)", settings->input_filename, pem_buf, + sizeof(pem_buf)); + + pem_content_size = addZeroTerminationCharacter(pem_buf, pem_content_size, + sizeof(pem_buf)); + + auto certificate = Controlse::CCertificate( + reinterpret_cast(pem_buf), pem_content_size); + + result = certificate.VerifyAgainst(se, settings->key_id) ? 0 : -EPERM; + + if (result == 0) + { + printf("Signature verified successfully\n"); + } + } + + return result; +} + +//*************************************************************************** +// Public Functions +//************************************************************************** + +int main(int argc, FAR char *argv[]) +{ + struct SSettings settings = DEFAULT_SETTINGS; + int result = parseArguments(argc, argv, &settings); + + if ((result == 0) && (!settings.skip_process)) + { + int fd = open(settings.se05x_dev_filename, O_RDONLY); + if (fd == -1) + { + result = -ENODEV; + } + else + { + result = process(fd, &settings); + close(fd); + } + } + + if (result != 0) + { + fprintf(stderr, "err %i: %s\n", -result, strerror(-result)); + } + + if (settings.show_stack_used) + { +#ifdef CONFIG_STACK_COLORATION + FAR struct tcb_s *tcb; + tcb = nxsched_get_tcb(getpid()); + fprintf(stderr, "\nStack used: %zu / %zu\n", up_check_tcbstack(tcb), + tcb->adj_stack_size); +#else + fprintf(stderr, "\nStack used: unknown" + " (STACK_COLORATION must be enabled)\n"); +#endif + } + + return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/crypto/controlse/cpublic_key.cxx b/crypto/controlse/cpublic_key.cxx new file mode 100644 index 000000000..10a7aad91 --- /dev/null +++ b/crypto/controlse/cpublic_key.cxx @@ -0,0 +1,243 @@ +//*************************************************************************** +// apps/crypto/controlse/cpublic_key.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include "crypto/controlse/cpublic_key.hxx" +#include "crypto/controlse/isecure_element.hxx" +#include "crypto/controlse/isecure_element_object.hxx" +#include +#include +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CPublicKey::CPublicKey(const ISecureElement &se, uint32_t keystore_id) +{ + (void)LoadFromSecureElement(se, keystore_id); +} + +CPublicKey::CPublicKey(const char *pem) +{ + uint8_t key_buf[300]; + m_key = nullptr; + if (0 + == convert_public_key_pem_to_raw(key_buf, sizeof(key_buf), &m_size, pem)) + { + m_key = new uint8_t[m_size]; + memcpy(m_key, key_buf, m_size); + } +} + +CPublicKey::CPublicKey(const uint8_t *buffer, size_t buffer_size) + : m_key(new uint8_t[buffer_size]), m_size(buffer_size) +{ + memcpy(m_key, buffer, m_size); +} + +CPublicKey::CPublicKey(const CPublicKey &p1) : CPublicKey(p1.m_key, p1.m_size) +{ +} + +CPublicKey::~CPublicKey() { Unload(); } + +CPublicKey &CPublicKey::operator=(const CPublicKey &other) +{ + if (this != &other) + { + auto new_key = new uint8_t[other.m_size]; + memcpy(new_key, other.m_key, other.m_size); + + delete[] m_key; + + m_key = new_key; + m_size = other.m_size; + } + return *this; +} + +void CPublicKey::Unload() +{ + if (IsLoaded()) + { + delete[] m_key; + m_key = NULL; + m_size = 0; + } +} + +bool CPublicKey::IsLoaded() const { return m_key != NULL; } + +bool CPublicKey::StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const +{ + if (!IsLoaded()) + { + return false; + } + + struct se05x_key_transmission_s args = { + .entry = { .id = keystore_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 }, + .content + = { .buffer = m_key, .buffer_size = m_size, .buffer_content_size = m_size } + }; + return se.SetKey(args); +} + +bool CPublicKey::LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) +{ + Unload(); + + m_size = 100; + m_key = new uint8_t[m_size]; + struct se05x_key_transmission_s args = { + .entry = { .id = keystore_id, .cipher = SE05X_ASYM_CIPHER_EC_NIST_P_256 }, + .content + = { .buffer = m_key, .buffer_size = m_size, .buffer_content_size = m_size } + }; + + bool result = se.GetKey(args); + + m_size = args.content.buffer_content_size; + if (!result) + { + Unload(); + } + + return result; +} + +bool CPublicKey::operator==(const CPublicKey &a) const +{ + if (this->m_size != a.m_size) + { + return false; + } + return 0 == memcmp(this->m_key, a.m_key, m_size); +} + +bool CPublicKey::operator!=(const CPublicKey &a) const +{ + return !operator==(a); +} + +size_t CPublicKey::GetRawSize() const { return m_size; } + +void CPublicKey::GetRaw(uint8_t *raw_buffer) const +{ + memcpy(raw_buffer, m_key, m_size); +} + +char *CPublicKey::GetPem() const +{ + char pem_buf[500]; + auto res + = convert_public_key_raw_to_pem(pem_buf, sizeof(pem_buf), m_key, m_size); + if (res < 0) + { + return nullptr; + } + auto pem_size = strlen(pem_buf); + auto pem = new char[pem_size + 1]; + memcpy(pem, pem_buf, pem_size); + pem[pem_size] = 0; + return pem; +} + +int CPublicKey::convert_public_key_raw_to_pem(char *pem_buf, + size_t pem_buf_size, + const uint8_t *key_buf, + size_t key_buf_size) +{ + mbedtls_pk_context key = { 0 }; + + mbedtls_pk_init(&key); + const mbedtls_pk_info_t *info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY); + + int result = -1; + if (info != NULL) + { + result = mbedtls_pk_setup(&key, info); + } + + mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx; + if (result == 0) + { + result = mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1); + } + + if (result == 0) + { + result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q, + key_buf, key_buf_size); + } + + if (result == 0) + { + result = mbedtls_pk_write_pubkey_pem(&key, (uint8_t *)pem_buf, + pem_buf_size); + } + + mbedtls_pk_free(&key); + return result < 0 ? -EINVAL : 0; +} + +int CPublicKey::convert_public_key_pem_to_raw(uint8_t *key_buf, + size_t key_buf_size, + size_t *key_size, + const char *pem_buf) +{ + int result = -1; + mbedtls_pk_context key = { 0 }; + + mbedtls_pk_init(&key); + + result = mbedtls_pk_parse_public_key(&key, (uint8_t *)pem_buf, + strlen(pem_buf) + 1); + + if (result == 0) + { + result = mbedtls_pk_can_do(&key, MBEDTLS_PK_ECKEY) == 1 ? 0 : -1; + } + + if (result == 0) + { + mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx; + result = mbedtls_ecp_point_write_binary(&keypair->grp, &keypair->Q, + MBEDTLS_ECP_PF_UNCOMPRESSED, + key_size, key_buf, key_buf_size); + } + + mbedtls_pk_free(&key); + return result < 0 ? -EINVAL : 0; +} + +} // namespace Controlse diff --git a/crypto/controlse/csan_builder.cxx b/crypto/controlse/csan_builder.cxx new file mode 100644 index 000000000..60a9040ae --- /dev/null +++ b/crypto/controlse/csan_builder.cxx @@ -0,0 +1,124 @@ +//*************************************************************************** +// apps/crypto/controlse/csan_builder.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/csan_builder.hxx" +#include "mbedtls/asn1write.h" +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CSanBuilder::~CSanBuilder() +{ + while (entry != nullptr) + { + delete[] entry->p; + auto next_entry = entry->next; + delete entry; + entry = next_entry; + } +} + +CSanBuilder *CSanBuilder::AddSan(uint8_t type, const char *value, + size_t value_size) +{ + auto old_entry = entry; + entry = new List(); + if (entry) + { + entry->type = type; + entry->p = new char[value_size]; + if (entry->p) + { + memcpy(entry->p, value, value_size); + entry->size = value_size; + entry->next = old_entry; + total_size += value_size; + total_size += 2; + } + else + { + delete entry; + } + } + return this; +} + +//* +// result: pointer to dynamically allocated san (to be deleted with delete[]) +// or error when size == 0 +/// +size_t CSanBuilder::Build(uint8_t **san) +{ + if (!entry) + { + return 0; + } + + const size_t reservation_for_additional_length_bytes = 8; + const size_t buffer_size + = total_size + reservation_for_additional_length_bytes; + auto *buffer = new uint8_t[buffer_size]; + auto current = entry; + const unsigned char *start = buffer; + unsigned char *p = buffer + buffer_size; + int ret = 0; + size_t len = 0; + while (current) + { + ret = mbedtls_asn1_write_tagged_string(&p, start, current->type, + current->p, current->size); + current = current->next; + } + + MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&p, start, total_size)); + MBEDTLS_ASN1_CHK_ADD( + len, mbedtls_asn1_write_tag( + &p, start, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)); + + *san = new uint8_t[total_size + len]; + memcpy(*san, p, total_size + len); + delete[] buffer; + return total_size + len; +} + +uint32_t CSanBuilder::GetNumberOfSan() +{ + auto e = entry; + uint32_t amount = 0; + while (e != nullptr) + { + e = e->next; + amount++; + } + return amount; +} + +} diff --git a/crypto/controlse/csecure_element.cxx b/crypto/controlse/csecure_element.cxx new file mode 100644 index 000000000..e6c11d894 --- /dev/null +++ b/crypto/controlse/csecure_element.cxx @@ -0,0 +1,189 @@ +//*************************************************************************** +// apps/crypto/controlse/csecure_element.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/csecure_element.hxx" + +#include "crypto/controlse/ccertificate.hxx" +#include "crypto/controlse/cpublic_key.hxx" +#include +#include +#include +#include +#include +extern "C" +{ +#include +} + +namespace Controlse +{ + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CSecureElement::CSecureElement(const char *se05x_device) + : se05x_fd(open(se05x_device, O_RDONLY)), close_device_at_destructor(true) +{ +} + +CSecureElement::CSecureElement(int fd) + : se05x_fd(fd), close_device_at_destructor(false) +{ +} + +CSecureElement::~CSecureElement() +{ + if ((se05x_fd >= 0) && close_device_at_destructor) + { + close(se05x_fd); + } +} + +bool CSecureElement::IsReady() const { return se05x_fd >= 0; } + +bool CSecureElement::GenerateKey(struct se05x_generate_keypair_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_GENERATE_KEYPAIR, &args); + } + return result; +} + +bool CSecureElement::SetKey(struct se05x_key_transmission_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_SET_KEY, &args); + } + return result; +} + +bool CSecureElement::GetKey(struct se05x_key_transmission_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_GET_KEY, &args); + } + return result; +} + +bool CSecureElement::DeleteKey(uint32_t id) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_DELETE_KEY, id); + } + return result; +} + +bool CSecureElement::SetData(struct se05x_key_transmission_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_SET_DATA, &args); + } + return result; +} + +bool CSecureElement::GetData(struct se05x_key_transmission_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_GET_DATA, &args); + } + return result; +} + +bool CSecureElement::CreateSignature(struct se05x_signature_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args); + } + return result; +} + +bool CSecureElement::Verify(struct se05x_signature_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_VERIFY_SIGNATURE, &args); + } + return result; +} + +bool CSecureElement::DeriveSymmetricalKey( + struct se05x_derive_key_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_DERIVE_SYMM_KEY, &args); + } + return result; +} + +bool CSecureElement::GetUid(struct se05x_uid_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_GET_UID, &args); + } + return result; +} + +bool CSecureElement::GetInfo(struct se05x_info_s &args) const +{ + bool result = false; + if (se05x_fd >= 0) + { + result = 0 == ioctl(se05x_fd, SEIOC_GET_INFO, &args); + } + return result; +} + +CCertificate *CSecureElement::GetCertificate(uint32_t keystore_id) +{ + return new CCertificate(*this, keystore_id); +} + +CPublicKey *CSecureElement::GetPublicKey(uint32_t keystore_id) +{ + return new CPublicKey(*this, keystore_id); +} + +} // namespace Controlse diff --git a/crypto/controlse/cserial_number.cxx b/crypto/controlse/cserial_number.cxx new file mode 100644 index 000000000..517d1b229 --- /dev/null +++ b/crypto/controlse/cserial_number.cxx @@ -0,0 +1,94 @@ +//*************************************************************************** +// apps/crypto/controlse/cserial_number.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/cserial_number.hxx" +#include "crypto/controlse/isecure_element.hxx" +#include + +namespace Controlse +{ +constexpr size_t CSerialNumber::SERIAL_NUMBER_SIZE; + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CSerialNumber::CSerialNumber(const ISecureElement &se, uint32_t keystore_id) +{ + is_loaded = LoadFromSecureElement(se, keystore_id); +} + +CSerialNumber::CSerialNumber(uint8_t const *serial_number_byte_array) +{ + memcpy(serial_number, serial_number_byte_array, SERIAL_NUMBER_SIZE); + is_loaded = true; +} + +bool CSerialNumber::operator==(CSerialNumber &a) const +{ + return 0 == (memcmp(a.serial_number, serial_number, SERIAL_NUMBER_SIZE)); +} + +bool CSerialNumber::operator!=(CSerialNumber &a) const +{ + return !operator==(a); +} + +bool CSerialNumber::operator<(const CSerialNumber &a) const +{ + return 0 < (memcmp(a.serial_number, serial_number, SERIAL_NUMBER_SIZE)); +} + +bool CSerialNumber::IsLoaded() const { return is_loaded; } + +bool CSerialNumber::GetSerialNumber( + uint8_t serial_number_destination[SERIAL_NUMBER_SIZE]) const +{ + if (!is_loaded) + { + return false; + } + + memcpy(serial_number_destination, serial_number, SERIAL_NUMBER_SIZE); + return true; +} + +bool CSerialNumber::StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const +{ + return false; +} + +bool CSerialNumber::LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) +{ + struct se05x_key_transmission_s args + = { .entry = { .id = keystore_id }, + .content + = { .buffer = serial_number, .buffer_size = SERIAL_NUMBER_SIZE } }; + return se.GetData(args); +} +} // namespace Controlse diff --git a/crypto/controlse/cstring.cxx b/crypto/controlse/cstring.cxx new file mode 100644 index 000000000..ff7637005 --- /dev/null +++ b/crypto/controlse/cstring.cxx @@ -0,0 +1,141 @@ +//*************************************************************************** +// apps/crypto/controlse/cstring.cxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/cstring.hxx" +#include "crypto/controlse/csecure_element.hxx" +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class Method Implementations +//*************************************************************************** + +CString::CString(const ISecureElement &se, uint32_t keystore_id) +{ + (void)LoadFromSecureElement(se, keystore_id); +} + +CString::CString(char *string, size_t size) : m_size(size) +{ + m_string = new char[m_size]; + memcpy(m_string, string, m_size); +} + +CString::CString(const CString &p1) : CString(p1.m_string, p1.m_size) {} + +CString::~CString() +{ + if (m_string != nullptr) + { + delete[] m_string; + m_size = 0; + } +} + +CString &CString::operator=(const CString &other) +{ + if (this != &other) + { + auto new_string = new char[other.m_size]; + memcpy(new_string, other.m_string, other.m_size); + + delete[] m_string; + + m_string = new_string; + m_size = other.m_size; + } + return *this; +} + +bool CString::operator==(CString &a) const +{ + if (a.m_size != m_size) + { + return false; + } + return 0 == (memcmp(a.m_string, m_string, m_size)); +} + +bool CString::operator!=(CString &a) const { return !operator==(a); } + +char *CString::c_str(void) const +{ + char *c_str = nullptr; + if (IsLoaded() && (m_size > 0)) + { + bool add_termination_character = false; + if (m_string[m_size - 1] != 0) + { + add_termination_character = true; + } + c_str = new char[m_size + (add_termination_character ? 1 : 0)]; + memcpy(c_str, m_string, m_size); + if (add_termination_character) + { + c_str[m_size] = 0; + } + } + return c_str; +} + +bool CString::IsLoaded() const { return m_string != nullptr; } + +bool CString::StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const +{ + auto result = false; + if (IsLoaded()) + { + struct se05x_key_transmission_s args + = { .entry = { .id = keystore_id }, + .content = { .buffer = reinterpret_cast(m_string), + .buffer_size = m_size } }; + result = se.SetData(args); + } + return result; +} + +bool CString::LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) +{ + uint8_t buffer[1000]; + struct se05x_key_transmission_s args + = { .entry = { .id = keystore_id }, + .content = { .buffer = buffer, .buffer_size = sizeof(buffer) } }; + auto result = se.GetData(args); + + if (result) + { + m_size = args.content.buffer_content_size; + m_string = new char[m_size + 1]; + memcpy(m_string, buffer, m_size); + m_string[m_size] = 0; + } + return result; +} +} // namespace Controlse diff --git a/crypto/controlse/mbedtls_extension.c b/crypto/controlse/mbedtls_extension.c deleted file mode 100644 index 3ec58ae74..000000000 --- a/crypto/controlse/mbedtls_extension.c +++ /dev/null @@ -1,310 +0,0 @@ -/**************************************************************************** - * apps/crypto/controlse/mbedtls_extension.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/* Copyright The Mbed TLS Contributors - * SPDX-License-Identifier: Apache-2.0 - * - * The source code in this file is based on - * mbedtls_x509write_crt_der() method from x509write_crt.c in Mbed TLS - */ - -/* Copyright 2023 NXP */ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#define MBEDTLS_ALLOW_PRIVATE_ACCESS -#include -#include -#include -#include -#include -#include -#include - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static int x509_write_time(FAR unsigned char **p, FAR unsigned char *start, - FAR const char *t, size_t size) -{ - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - size_t len = 0; - - /* write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter) */ - - if (t[0] == '2' && t[1] == '0' && t[2] < '5') - { - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_raw_buffer( - p, start, (FAR const unsigned char *)t + 2, size - 2)); - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_UTC_TIME)); - } - else - { - MBEDTLS_ASN1_CHK_ADD(len, - mbedtls_asn1_write_raw_buffer( - p, start, (FAR const unsigned char *)t, size)); - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len)); - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag( - p, start, MBEDTLS_ASN1_GENERALIZED_TIME)); - } - - return ((int)len); -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int mbedtls_x509write_crt_der_se05x(FAR mbedtls_x509write_cert *ctx, - FAR unsigned char *buf, size_t size, - int se05x_fd, uint32_t private_key_id) -{ - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - FAR const char *sig_oid; - size_t sig_oid_len = 0; - FAR unsigned char *c; - FAR unsigned char *c2; - unsigned char hash[64]; - unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE]; - size_t sub_len = 0; - size_t pub_len = 0; - size_t sig_and_oid_len = 0; - size_t sig_len; - size_t len = 0; - mbedtls_pk_type_t pk_alg; - - /* Prepare data to be signed at the end of the target buffer */ - - c = buf + size; - - /* Signature algorithm needed in TBS, and later for actual signature */ - - /* There's no direct way of extracting a signature algorithm - * (represented as an element of mbedtls_pk_type_t) from a PK instance. - */ - - if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_RSA)) - { - pk_alg = MBEDTLS_PK_RSA; - } - else if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_ECDSA)) - { - pk_alg = MBEDTLS_PK_ECDSA; - } - else - { - return (MBEDTLS_ERR_X509_INVALID_ALG); - } - - if ((ret = mbedtls_oid_get_oid_by_sig_alg(pk_alg, ctx->md_alg, &sig_oid, - &sig_oid_len)) != 0) - { - return (ret); - } - - /* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension */ - - /* Only for v3 */ - - if (ctx->version == MBEDTLS_X509_CRT_VERSION_3) - { - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_x509_write_extensions(&c, buf, ctx->extensions)); - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len)); - MBEDTLS_ASN1_CHK_ADD(len, - mbedtls_asn1_write_tag(&c, buf, - MBEDTLS_ASN1_CONSTRUCTED | - MBEDTLS_ASN1_SEQUENCE)); - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag(&c, buf, - MBEDTLS_ASN1_CONTEXT_SPECIFIC | - MBEDTLS_ASN1_CONSTRUCTED | 3)); - } - - /* SubjectPublicKeyInfo */ - - MBEDTLS_ASN1_CHK_ADD( - pub_len, mbedtls_pk_write_pubkey_der(ctx->subject_key, buf, c - buf)); - c -= pub_len; - len += pub_len; - - /* Subject ::= Name */ - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_x509_write_names(&c, buf, ctx->subject)); - - /* Validity ::= SEQUENCE { - * notBefore Time, - * notAfter Time } - */ - - sub_len = 0; - - MBEDTLS_ASN1_CHK_ADD(sub_len, - x509_write_time(&c, buf, ctx->not_after, - MBEDTLS_X509_RFC5280_UTC_TIME_LEN)); - - MBEDTLS_ASN1_CHK_ADD(sub_len, - x509_write_time(&c, buf, ctx->not_before, - MBEDTLS_X509_RFC5280_UTC_TIME_LEN)); - - len += sub_len; - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, sub_len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag( - &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)); - - /* Issuer ::= Name */ - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_x509_write_names(&c, buf, ctx->issuer)); - - /* Signature ::= AlgorithmIdentifier */ - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_algorithm_identifier( - &c, buf, sig_oid, strlen(sig_oid), 0)); - - /* Serial ::= INTEGER - * - * Written data is: - * - "ctx->serial_len" bytes for the raw serial buffer - * - if MSb of "serial" is 1, then prepend an extra 0x00 byte - * - 1 byte for the length - * - 1 byte for the TAG - */ - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(&c, buf, - ctx->serial, ctx->serial_len)); - if (*c & 0x80) - { - if (c - buf < 1) - { - return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL; - } - - *(--c) = 0x0; - len++; - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, - ctx->serial_len + 1)); - } - else - { - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, - ctx->serial_len)); - } - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, - MBEDTLS_ASN1_INTEGER)); - - /* Version ::= INTEGER { v1(0), v2(1), v3(2) } */ - - /* Can be omitted for v1 */ - - if (ctx->version != MBEDTLS_X509_CRT_VERSION_1) - { - sub_len = 0; - MBEDTLS_ASN1_CHK_ADD(sub_len, - mbedtls_asn1_write_int(&c, buf, ctx->version)); - len += sub_len; - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, sub_len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag(&c, buf, - MBEDTLS_ASN1_CONTEXT_SPECIFIC | - MBEDTLS_ASN1_CONSTRUCTED | 0)); - } - - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag( - &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)); - - /* Make signature - */ - - /* Compute hash of CRT. */ - - if ((ret = mbedtls_md(mbedtls_md_info_from_type(ctx->md_alg), c, len, - hash)) != 0) - { - return (ret); - } - - { - struct se05x_signature_s args = { - .key_id = private_key_id, - .algorithm = SE05X_ALGORITHM_SHA256, - .tbs = { - .buffer = hash, - .buffer_size = 32, - .buffer_content_size = 32 - }, - .signature = {.buffer = sig, .buffer_size = sizeof(sig)}, - }; - - ret = ioctl(se05x_fd, SEIOC_CREATE_SIGNATURE, &args); - if (ret != 0) - { - return ret; - } - - sig_len = args.signature.buffer_content_size; - } - - /* Move CRT to the front of the buffer to have space - * for the signature. - */ - - memmove(buf, c, len); - c = buf + len; - - /* Add signature at the end of the buffer, - * making sure that it doesn't underflow - * into the CRT buffer. - */ - - c2 = buf + size; - MBEDTLS_ASN1_CHK_ADD( - sig_and_oid_len, - mbedtls_x509_write_sig(&c2, c, sig_oid, sig_oid_len, sig, sig_len)); - - /* Memory layout after this step: - * - * buf c=buf+len c2 buf+size - * [CRT0,...,CRTn, UNUSED, ..., UNUSED, SIG0, ..., SIGm] - */ - - /* Move raw CRT to just before the signature. */ - - c = c2 - len; - memmove(c, buf, len); - - len += sig_and_oid_len; - MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len)); - MBEDTLS_ASN1_CHK_ADD( - len, mbedtls_asn1_write_tag( - &c, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)); - - return ((int)len); -} diff --git a/crypto/controlse/mbedtls_extension.h b/crypto/controlse/mbedtls_extension.h deleted file mode 100644 index 74a1c0349..000000000 --- a/crypto/controlse/mbedtls_extension.h +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - * apps/crypto/controlse/mbedtls_extension.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/* Copyright 2023 NXP */ - -#ifndef __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_ -#define __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int mbedtls_x509write_crt_der_se05x(mbedtls_x509write_cert *ctx, - unsigned char *buf, size_t size, - int se05x_fd, uint32_t private_key_id); - -#endif /* __INCLUDE_APPS_CRYPTO_CONTROLSE_MBEDTLS_EXTENSION_H_ */ diff --git a/crypto/controlse/x509_utils.c b/crypto/controlse/x509_utils.c deleted file mode 100644 index 873b54ec6..000000000 --- a/crypto/controlse/x509_utils.c +++ /dev/null @@ -1,350 +0,0 @@ -/**************************************************************************** - * apps/crypto/controlse/x509_utils.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/* Copyright 2023 NXP */ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#define MBEDTLS_ALLOW_PRIVATE_ACCESS -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/ecp.h" -#include "mbedtls/entropy.h" -#include "mbedtls/pem.h" -#include "mbedtls/pk.h" -#include "mbedtls/x509_crt.h" -#include "mbedtls/x509_csr.h" -#include "mbedtls_extension.h" -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define SECONDS_IN_DAY (60 * 60 * 24) - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static const char certificate_header[] = "-----BEGIN CERTIFICATE-----\n"; -static const char certificate_footer[] = "-----END CERTIFICATE-----\n"; - -static const char certificate_request_header[] = - "-----BEGIN CERTIFICATE REQUEST-----\n"; -static const char certificate_request_footer[] = - "-----END CERTIFICATE REQUEST-----\n"; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static int convert_der_certificate_to_pem(FAR char *pem_buf, - size_t pem_buf_size, - FAR size_t *pem_content_size, - FAR uint8_t *der_buf, - size_t der_buf_size) -{ - int result; - - { - mbedtls_x509_crt crt; - mbedtls_x509_crt_init(&crt); - result = mbedtls_x509_crt_parse(&crt, der_buf, der_buf_size); - mbedtls_x509_crt_free(&crt); - } - - if (result == 0) - { - result = mbedtls_pem_write_buffer( - certificate_header, certificate_footer, der_buf, der_buf_size, - (FAR uint8_t *)pem_buf, pem_buf_size, pem_content_size); - } - - return result; -} - -static int convert_der_csr_to_pem(FAR char *pem_buf, size_t pem_buf_size, - FAR size_t *pem_content_size, - FAR uint8_t *der_buf, size_t der_buf_size) -{ - int result; - - { - mbedtls_x509_csr csr; - mbedtls_x509_csr_init(&csr); - result = - mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)der_buf, der_buf_size); - mbedtls_x509_csr_free(&csr); - } - - if (result == 0) - { - result = mbedtls_pem_write_buffer(certificate_request_header, - certificate_request_footer, der_buf, - der_buf_size, (FAR uint8_t *)pem_buf, - pem_buf_size, pem_content_size); - } - - return result; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int convert_public_key_raw_to_pem(FAR char *pem_buf, size_t pem_buf_size, - FAR uint8_t *key_buf, size_t key_buf_size) -{ - mbedtls_pk_context key = - { - 0 - }; - - mbedtls_pk_init(&key); - FAR const mbedtls_pk_info_t *info = - mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY); - - int result = -1; - if (info != NULL) - { - result = mbedtls_pk_setup(&key, info); - } - - FAR mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx; - if (result == 0) - { - result = - mbedtls_ecp_group_load(&keypair->grp, MBEDTLS_ECP_DP_SECP256R1); - } - - if (result == 0) - { - result = mbedtls_ecp_point_read_binary(&keypair->grp, &keypair->Q, - key_buf, key_buf_size); - } - - if (result == 0) - { - result = mbedtls_pk_write_pubkey_pem(&key, (FAR uint8_t *)pem_buf, - pem_buf_size); - } - - mbedtls_pk_free(&key); - return result < 0 ? -EINVAL : 0; -} - -int convert_public_key_pem_to_raw(FAR uint8_t *key_buf, size_t key_buf_size, - FAR size_t *key_size, FAR char *pem_buf) -{ - int result = -1; - mbedtls_pk_context key = - { - 0 - }; - - mbedtls_pk_init(&key); - - result = mbedtls_pk_parse_public_key(&key, (FAR uint8_t *)pem_buf, - strlen(pem_buf) + 1); - - if (result == 0) - { - result = mbedtls_pk_can_do(&key, MBEDTLS_PK_ECKEY) == 1 ? 0 : -1; - } - - if (result == 0) - { - FAR mbedtls_ecp_keypair *keypair = (mbedtls_ecp_keypair *)key.pk_ctx; - result = mbedtls_ecp_point_write_binary( - &keypair->grp, &keypair->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, key_size, - key_buf, key_buf_size); - } - - mbedtls_pk_free(&key); - return result < 0 ? -EINVAL : 0; -} - -int convert_pem_certificate_or_csr_to_der(FAR uint8_t *der_buf, - size_t der_buf_size, - FAR size_t *der_content_size, - FAR char *pem_buf, - size_t pem_buf_size) -{ - int result; - - { - mbedtls_x509_crt crt; - mbedtls_x509_crt_init(&crt); - result = - mbedtls_x509_crt_parse(&crt, (FAR uint8_t *)pem_buf, pem_buf_size); - if ((result == 0) && (der_buf_size < crt.raw.len)) - { - result = -EINVAL; - } - - if (result == 0) - { - memcpy(der_buf, crt.raw.p, crt.raw.len); - *der_content_size = crt.raw.len; - } - - mbedtls_x509_crt_free(&crt); - } - - /* if bad input data then try parsing CSR */ - - if (result != 0) - { - mbedtls_x509_csr csr; - mbedtls_x509_csr_init(&csr); - result = - mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)pem_buf, pem_buf_size); - if ((result == 0) && (der_buf_size < csr.raw.len)) - { - result = -EINVAL; - } - - if (result == 0) - { - memcpy(der_buf, csr.raw.p, csr.raw.len); - *der_content_size = csr.raw.len; - } - - mbedtls_x509_csr_free(&csr); - } - - return result; -} - -int convert_der_certificate_or_csr_to_pem(FAR char *pem_buf, - size_t pem_buf_size, - FAR size_t *pem_content_size, - FAR uint8_t *der_buf, - size_t der_buf_size) -{ - int result = convert_der_certificate_to_pem( - pem_buf, pem_buf_size, pem_content_size, der_buf, der_buf_size); - - if (result != 0) - { - result = convert_der_csr_to_pem(pem_buf, pem_buf_size, - pem_content_size, - der_buf, der_buf_size); - } - - return result; -} - -int sign_csr(int se05x_fd, uint32_t private_key_id, FAR char *crt_pem_buf, - size_t crt_pem_buf_size, FAR char *csr_pem_buf, - size_t csr_pem_buf_content_size) -{ - mbedtls_x509_csr csr; - mbedtls_x509_csr_init(&csr); - int result = mbedtls_x509_csr_parse(&csr, (FAR uint8_t *)csr_pem_buf, - csr_pem_buf_content_size); - - mbedtls_x509write_cert crt; - mbedtls_x509write_crt_init(&crt); - char subject_name[200]; - if (result == 0) - { - mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3); - result = mbedtls_x509_dn_gets(subject_name, sizeof(subject_name), - &csr.subject); - } - - mbedtls_pk_context private_key; - mbedtls_pk_init(&private_key); - if (result >= 0) - { - mbedtls_x509write_crt_set_subject_key(&crt, &csr.pk); - result = mbedtls_pk_setup( - &private_key, - mbedtls_pk_info_from_type((mbedtls_pk_type_t)MBEDTLS_PK_ECDSA)); - } - - if (result == 0) - { - mbedtls_x509write_crt_set_issuer_key(&crt, &private_key); - result = mbedtls_x509write_crt_set_subject_name(&crt, subject_name); - } - - if (result == 0) - { - result = - mbedtls_x509write_crt_set_issuer_name(&crt, "CN=CA,O=NXP,C=NL"); - } - - mbedtls_mpi serial; - mbedtls_mpi_init(&serial); - if (result == 0) - { - mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256); - result = mbedtls_mpi_read_string(&serial, 10, "1"); - } - - if (result == 0) - { - result = mbedtls_x509write_crt_set_serial(&crt, &serial); - } - - if (result == 0) - { - time_t rawtime; - struct tm tm_info; - char from_datetime[20]; - char to_datetime[20]; - time(&rawtime); - strftime(from_datetime, sizeof(from_datetime), "%Y%m%d%H%M%S", - gmtime_r(&rawtime, &tm_info)); - rawtime += SECONDS_IN_DAY; - strftime(to_datetime, sizeof(to_datetime), "%Y%m%d%H%M%S", - gmtime_r(&rawtime, &tm_info)); - result = mbedtls_x509write_crt_set_validity(&crt, from_datetime, - to_datetime); - } - - if (result == 0) - { - result = mbedtls_x509write_crt_der_se05x( - &crt, (FAR uint8_t *)crt_pem_buf, crt_pem_buf_size, se05x_fd, - private_key_id); - } - - if (result >= 0) - { - size_t olen; - result = mbedtls_pem_write_buffer( - certificate_header, certificate_footer, - (FAR uint8_t *)(crt_pem_buf + crt_pem_buf_size - result), result, - (FAR uint8_t *)crt_pem_buf, crt_pem_buf_size, &olen); - } - - mbedtls_mpi_free(&serial); - mbedtls_pk_free(&private_key); - mbedtls_x509write_crt_free(&crt); - mbedtls_x509_csr_free(&csr); - return result; -} diff --git a/crypto/controlse/x509_utils.h b/crypto/controlse/x509_utils.h deleted file mode 100644 index 872136271..000000000 --- a/crypto/controlse/x509_utils.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** - * apps/crypto/controlse/x509_utils.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/* Copyright 2023 NXP */ - -#ifndef __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_ -#define __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int convert_public_key_raw_to_pem(FAR char *pem_buf, size_t pem_buf_size, - FAR uint8_t *key_buf, size_t key_buf_size); -int convert_public_key_pem_to_raw(FAR uint8_t *key_buf, size_t key_buf_size, - FAR size_t *key_size, char *pem_buf); -int convert_pem_certificate_or_csr_to_der(FAR uint8_t *der_buf, - size_t der_buf_size, - FAR size_t *der_content_size, - FAR char *pem_buf, - size_t pem_buf_size); -int convert_der_certificate_or_csr_to_pem(FAR char *pem_buf, - size_t pem_buf_size, - FAR size_t *pem_content_size, - FAR uint8_t *der_buf, - size_t der_buf_size); -int sign_csr(int se05x_fd, uint32_t private_key_id, FAR char *crt_pem_buf, - size_t crt_pem_buf_size, FAR char *csr_pem_buf, - size_t csr_pem_buf_content_size); - -#endif /* __INCLUDE_APPS_CRYPTO_CONTROLSE_X509_UTILS_H_ */ diff --git a/crypto/libsodium/Makefile b/crypto/libsodium/Makefile index dfee81651..aa74f888c 100644 --- a/crypto/libsodium/Makefile +++ b/crypto/libsodium/Makefile @@ -33,7 +33,6 @@ LIBSODIUM_UNPACKTESTDIR = $(LIBSODIUM_UNPACKNAME)$(DELIM)test$(DELIM)default CSRCS += $(shell find $(LIBSODIUM_UNPACKLIBDIR) -name "*.c") CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/libsodium/libsodium/src/libsodium/include/sodium -CFLAGS += -DDEV_MODE -DCONFIGURED=1 CFLAGS += -Wno-unused-function -Wno-undef -Wno-unused-variable -Wno-deprecated-declarations \ -Wno-shadow diff --git a/crypto/mbedtls/CMakeLists.txt b/crypto/mbedtls/CMakeLists.txt index f70dc8ed9..9d9561814 100644 --- a/crypto/mbedtls/CMakeLists.txt +++ b/crypto/mbedtls/CMakeLists.txt @@ -67,21 +67,17 @@ if(CONFIG_CRYPTO_MBEDTLS) # Include Directory # ############################################################################ - set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/include ${MBEDTLS_DIR}/include) + set(INCDIR ${MBEDTLS_DIR}/include) # ############################################################################ # Library Configuration # ############################################################################ - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${INCDIR}) - nuttx_add_library(mbedtls STATIC) + nuttx_export_header(TARGET mbedtls INCLUDE_DIRECTORIES ${MBEDTLS_DIR}/include) target_sources(mbedtls PRIVATE ${CSRCS}) target_include_directories(mbedtls PRIVATE ${INCDIR}) - target_compile_definitions(mbedtls PRIVATE unix) + target_compile_definitions(mbedtls PRIVATE __unix__) if(CONFIG_ARCH_SIM) target_compile_options(mbedtls PRIVATE -O0) diff --git a/crypto/mbedtls/Kconfig b/crypto/mbedtls/Kconfig index 1a87175d7..d61e6b3f5 100644 --- a/crypto/mbedtls/Kconfig +++ b/crypto/mbedtls/Kconfig @@ -17,7 +17,7 @@ config MBEDTLS_VERSION config MBEDTLS_DEBUG_C bool "This module provides debugging functions." - default DEBUG_CRYPTO_INFO + default DEBUG_FEATURES ---help--- This module provides debugging functions. @@ -72,10 +72,6 @@ config MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE depends on MBEDTLS_SSL_DTLS_HELLO_VERIFY default y -config MBEDTLS_BLOWFISH_C - bool "Enable the Blowfish block cipher." - default n - config MBEDTLS_CAMELLIA_C bool "Enable the Camellia block cipher." default y @@ -182,7 +178,6 @@ config MBEDTLS_X509_CSR_PARSE_C config MBEDTLS_X509_CRT_POOL bool "Enable the X509 Certificate Pool" - depends on MBEDTLS_THREADING_C default n config MBEDTLS_HAVE_ASM @@ -402,10 +397,6 @@ config MBEDTLS_AESCE_C depends on MBEDTLS_HAVE_ASM default y -config MBEDTLS_ARC4_C - bool "Enable the ARCFOUR stream cipher." - default n - config MBEDTLS_ARIA_C bool "Enable the ARIA block cipher." default y @@ -554,7 +545,7 @@ config MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH int "Size in bytes of a ticket nonce." default 32 -config MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH +config MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS int "Default number of NewSessionTicket messages to be sent by a TLS 1.3 server after handshake completion." default 1 @@ -576,16 +567,6 @@ config MBEDTLS_MD5_ALT select MBEDTLS_ALT default n -config MBEDTLS_POLY1305_ALT - bool "Enable Mbedt TLS POLY1305 module alted by nuttx crypto" - select MBEDTLS_ALT - default n - -config MBEDTLS_RIPEMD160_ALT - bool "Enable Mbedt TLS RIPEMD160 module alted by nuttx crypto" - select MBEDTLS_ALT - default n - config MBEDTLS_SHA1_ALT bool "Enable Mbedt TLS SHA1 module alted by nuttx crypto" select MBEDTLS_ALT @@ -601,11 +582,6 @@ config MBEDTLS_SHA512_ALT select MBEDTLS_ALT default n -config MBEDTLS_BIGNUM_ALT - bool "Enable Mbedt TLS Bignum module alted by nuttx mpi" - select MBEDTLS_ALT - default n - endif # CRYPTO_CRYPTODEV menuconfig MBEDTLS_APPS diff --git a/crypto/mbedtls/Make.defs b/crypto/mbedtls/Make.defs index 2c651da34..651c9acc5 100644 --- a/crypto/mbedtls/Make.defs +++ b/crypto/mbedtls/Make.defs @@ -23,10 +23,12 @@ CONFIGURED_APPS += $(APPDIR)/crypto/mbedtls # Allows `.h>` import. -MBEDTLS_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include -MBEDTLS_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include +CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include +CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include +CFLAGS += ${DEFINE_PREFIX}MBEDTLS_CONFIG_FILE="" -CFLAGS += ${MBEDTLS_FLAGS} -CXXFLAGS += ${MBEDTLS_FLAGS} +CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/include +CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/mbedtls/mbedtls/include +CXXFLAGS += ${DEFINE_PREFIX}MBEDTLS_CONFIG_FILE="" endif diff --git a/crypto/mbedtls/Makefile b/crypto/mbedtls/Makefile index 2a7c678c8..5e031ca52 100644 --- a/crypto/mbedtls/Makefile +++ b/crypto/mbedtls/Makefile @@ -36,7 +36,7 @@ MBEDTLS_UNPACKLIBDIR = $(MBEDTLS_UNPACKNAME)$(DELIM)library MBEDTLS_UNPACKPROGDIR = $(MBEDTLS_UNPACKNAME)$(DELIM)programs # This lets Mbed TLS better use some of the POSIX features we have -CFLAGS += ${DEFINE_PREFIX}unix +CFLAGS += ${DEFINE_PREFIX}__unix__ mbedtls/library/bignum.c_CFLAGS += -fno-lto @@ -48,7 +48,6 @@ mbedtls/library/bignum.c_CFLAGS += -fno-lto ifeq ($(CONFIG_FRAME_POINTER),y) ifeq ($(CONFIG_DEBUG_OPTLEVEL),"-O3") mbedtls/library/sha256.c_CFLAGS += -O2 - mbedtls/library/cmac.c_CFLAGS += -O2 endif endif @@ -123,14 +122,6 @@ ifeq ($(CONFIG_MBEDTLS_MD5_ALT),y) CSRCS += $(APPDIR)/crypto/mbedtls/source/md5_alt.c endif -ifeq ($(CONFIG_MBEDTLS_POLY1305_ALT),y) -CSRCS += $(APPDIR)/crypto/mbedtls/source/poly1305_alt.c -endif - -ifeq ($(CONFIG_MBEDTLS_RIPEMD160_ALT),y) -CSRCS += $(APPDIR)/crypto/mbedtls/source/ripemd160_alt.c -endif - ifeq ($(CONFIG_MBEDTLS_SHA1_ALT),y) CSRCS += $(APPDIR)/crypto/mbedtls/source/sha1_alt.c endif @@ -143,10 +134,6 @@ ifeq ($(CONFIG_MBEDTLS_SHA512_ALT),y) CSRCS += $(APPDIR)/crypto/mbedtls/source/sha512_alt.c endif -ifeq ($(CONFIG_MBEDTLS_BIGNUM_ALT),y) -CSRCS += $(APPDIR)/crypto/mbedtls/source/bignum_alt.c -endif - endif include $(APPDIR)/Application.mk diff --git a/crypto/mbedtls/include/aes_alt.h b/crypto/mbedtls/include/aes_alt.h index 590773829..c920b2bd3 100644 --- a/crypto/mbedtls/include/aes_alt.h +++ b/crypto/mbedtls/include/aes_alt.h @@ -30,7 +30,7 @@ * Pre-processor Definitions ****************************************************************************/ -#define MAX_KEY_SIZE 64 +#define MAX_KEY_SIZE 36 typedef struct mbedtls_aes_context { diff --git a/crypto/mbedtls/include/mbedtls/mbedtls_config.h b/crypto/mbedtls/include/mbedtls/mbedtls_config.h index 3e97a1570..9f7c3bb5f 100644 --- a/crypto/mbedtls/include/mbedtls/mbedtls_config.h +++ b/crypto/mbedtls/include/mbedtls/mbedtls_config.h @@ -371,13 +371,9 @@ #ifdef CONFIG_MBEDTLS_MD5_ALT #define MBEDTLS_MD5_ALT #endif -#ifdef CONFIG_MBEDTLS_POLY1305_ALT -#define MBEDTLS_POLY1305_ALT -#endif -#ifdef CONFIG_MBEDTLS_RIPEMD160_ALT -#define MBEDTLS_RIPEMD160_ALT -#endif -/* #define MBEDTLS_RSA_ALT +/* #define MBEDTLS_POLY1305_ALT + * #define MBEDTLS_RIPEMD160_ALT + * #define MBEDTLS_RSA_ALT */ #ifdef CONFIG_MBEDTLS_SHA1_ALT #define MBEDTLS_SHA1_ALT @@ -388,9 +384,6 @@ #ifdef CONFIG_MBEDTLS_SHA512_ALT #define MBEDTLS_SHA512_ALT #endif -#ifdef CONFIG_MBEDTLS_BIGNUM_ALT -#define MBEDTLS_BIGNUM_ALT -#endif /* #define MBEDTLS_XTEA_ALT */ @@ -987,6 +980,21 @@ #define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED #endif +/** + * \def MBEDTLS_X509_CRT_POOL + * + * Enable X.509 certificate pool. + * + * Module: library/x509_crt_pool.c + * + * Requires: MBEDTLS_THREADING_C + * + * This module is required for X.509 certificate pool. + */ +#ifdef CONFIG_MBEDTLS_X509_CRT_POOL +#define MBEDTLS_X509_CRT_POOL +#endif + /** * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED * @@ -3830,21 +3838,6 @@ */ #define MBEDTLS_X509_CRT_PARSE_C -/** - * \def MBEDTLS_X509_CRT_POOL - * - * Enable X.509 certificate pool. - * - * Module: library/x509_crt_pool.c - * - * Requires: MBEDTLS_THREADING_C - * - * This module is required for X.509 certificate pool. - */ -#ifdef CONFIG_MBEDTLS_X509_CRT_POOL -#define MBEDTLS_X509_CRT_POOL -#endif - /** * \def MBEDTLS_X509_CRL_PARSE_C * diff --git a/crypto/mbedtls/include/poly1305_alt.h b/crypto/mbedtls/include/poly1305_alt.h deleted file mode 100644 index fa6e29a41..000000000 --- a/crypto/mbedtls/include/poly1305_alt.h +++ /dev/null @@ -1,31 +0,0 @@ -/**************************************************************************** - * apps/crypto/mbedtls/include/poly1305_alt.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H -#define __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "dev_alt.h" - -#define mbedtls_poly1305_context cryptodev_context_t - -#endif /* __APPS_CRYPTO_MBEDTLS_INCLUDE_POLY1305_ALT_H */ diff --git a/crypto/mbedtls/include/ripemd160_alt.h b/crypto/mbedtls/include/ripemd160_alt.h deleted file mode 100644 index 03ba2a4b0..000000000 --- a/crypto/mbedtls/include/ripemd160_alt.h +++ /dev/null @@ -1,31 +0,0 @@ -/**************************************************************************** - * apps/crypto/mbedtls/include/ripemd160_alt.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H -#define __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "dev_alt.h" - -#define mbedtls_ripemd160_context cryptodev_context_t - -#endif /* __APPS_CRYPTO_MBEDTLS_INCLUDE_RIPEMD160_ALT_H */ diff --git a/crypto/mbedtls/source/aes_alt.c b/crypto/mbedtls/source/aes_alt.c index 57d6cc80e..34ec26604 100644 --- a/crypto/mbedtls/source/aes_alt.c +++ b/crypto/mbedtls/source/aes_alt.c @@ -51,18 +51,6 @@ int mbedtls_aes_setkey_enc(FAR mbedtls_aes_context *ctx, FAR const unsigned char *key, unsigned int keybits) { - switch (keybits) - { - case 128: - break; - case 192: - break; - case 256: - break; - default: - return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; - } - memcpy(ctx->key, key, keybits / 8); ctx->dev.session.key = (caddr_t)ctx->key; ctx->dev.session.keylen = keybits / 8; @@ -86,11 +74,6 @@ int mbedtls_aes_crypt_ecb(FAR mbedtls_aes_context *ctx, int ret; unsigned char iv[16]; - if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - ctx->dev.session.cipher = CRYPTO_AES_CBC; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) @@ -124,16 +107,6 @@ int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx, { int ret; - if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - - if (length % 16) - { - return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; - } - ctx->dev.session.cipher = CRYPTO_AES_CBC; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) @@ -168,11 +141,6 @@ int mbedtls_aes_crypt_ctr(FAR mbedtls_aes_context *ctx, { int ret; - if (*nc_off > 0x0f) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - ctx->dev.session.cipher = CRYPTO_AES_CTR; memcpy(ctx->key + ctx->dev.session.keylen, nonce_counter, NONCE_LENGTH); @@ -215,22 +183,14 @@ int mbedtls_aes_xts_setkey_enc(FAR mbedtls_aes_xts_context *ctx, FAR const unsigned char *key, unsigned int keybits) { - if (keybits != 256 && keybits != 512) - { - return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; - } - - memcpy(ctx->key, key, keybits / 8); - ctx->dev.session.key = (caddr_t)ctx->key; - ctx->dev.session.keylen = keybits / 8; - return 0; + return mbedtls_aes_setkey_enc(ctx, key, keybits); } int mbedtls_aes_xts_setkey_dec(FAR mbedtls_aes_xts_context *ctx, FAR const unsigned char *key, unsigned int keybits) { - return mbedtls_aes_xts_setkey_enc(ctx, key, keybits); + return mbedtls_aes_setkey_dec(ctx, key, keybits); } int mbedtls_aes_crypt_xts(FAR mbedtls_aes_xts_context *ctx, @@ -243,25 +203,6 @@ int mbedtls_aes_crypt_xts(FAR mbedtls_aes_xts_context *ctx, int ret; unsigned char iv[16]; - if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - - /* Data units must be at least 16 bytes long. */ - - if (length < 16) - { - return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; - } - - /* NIST SP 800-38E disallows data units larger than 2**20 blocks. */ - - if (length > (1 << 20) * 16) - { - return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; - } - ctx->dev.session.cipher = CRYPTO_AES_XTS; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) @@ -297,16 +238,6 @@ int mbedtls_aes_crypt_cfb128(FAR mbedtls_aes_context *ctx, { int ret; - if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - - if (*iv_off > 15) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - ctx->dev.session.cipher = CRYPTO_AES_CFB_128; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) @@ -342,11 +273,6 @@ int mbedtls_aes_crypt_cfb8(FAR mbedtls_aes_context *ctx, { int ret; - if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - ctx->dev.session.cipher = CRYPTO_AES_CFB_8; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) @@ -380,11 +306,6 @@ int mbedtls_aes_crypt_ofb(FAR mbedtls_aes_context *ctx, { int ret; - if (*iv_off > 15) - { - return MBEDTLS_ERR_AES_BAD_INPUT_DATA; - } - ctx->dev.session.cipher = CRYPTO_AES_OFB; ret = cryptodev_get_session(&ctx->dev); if (ret != 0) diff --git a/crypto/mbedtls/source/bignum_alt.c b/crypto/mbedtls/source/bignum_alt.c deleted file mode 100644 index 06bd7f516..000000000 --- a/crypto/mbedtls/source/bignum_alt.c +++ /dev/null @@ -1,299 +0,0 @@ -/**************************************************************************** - * apps/crypto/mbedtls/source/bignum_alt.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define MBEDTLS_ROUNDUP(v, size) (((v) + (size - 1)) & ~(size - 1)) - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static inline -void mbedtls_mpi_to_mpiparam(FAR struct mpiparam *a, - FAR const mbedtls_mpi *A) -{ - a->n = A->n * sizeof(mbedtls_mpi_uint); - a->s = A->s; - a->p = (uint8_t *)A->p; -} - -static inline -void mpiparam_to_mbedtls_mpi(FAR mbedtls_mpi *A, - FAR const struct mpiparam *a) -{ - A->n = a->n / sizeof(mbedtls_mpi_uint); - A->s = a->s; - A->p = (mbedtls_mpi_uint *)a->p; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int mbedtls_mpi_add_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_ADD; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - - mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(MAX(A->n, B->n) + 1, - sizeof(mbedtls_mpi_uint))); - mbedtls_mpi_to_mpiparam(&mpi.param[2], X); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(X, &mpi.param[2]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_sub_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_SUB; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - - mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(MAX(A->n, B->n) + 1, - sizeof(mbedtls_mpi_uint))); - mbedtls_mpi_to_mpiparam(&mpi.param[2], X); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(X, &mpi.param[2]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_mul_mpi(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_MUL; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - - mbedtls_mpi_grow(X, MBEDTLS_ROUNDUP(A->n + B->n, - sizeof(mbedtls_mpi_uint))); - mbedtls_mpi_to_mpiparam(&mpi.param[2], X); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(X, &mpi.param[2]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_div_mpi(FAR mbedtls_mpi *Q, FAR mbedtls_mpi *R, - FAR const mbedtls_mpi *A, FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_DIV; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - mbedtls_mpi_grow(Q, A->n); - mbedtls_mpi_grow(R, B->n); - mbedtls_mpi_to_mpiparam(&mpi.param[2], Q); - mbedtls_mpi_to_mpiparam(&mpi.param[3], R); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(Q, &mpi.param[2]); - mpiparam_to_mbedtls_mpi(R, &mpi.param[3]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_mod_mpi(FAR mbedtls_mpi *R, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_MOD; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - mbedtls_mpi_grow(R, B->n); - mbedtls_mpi_to_mpiparam(&mpi.param[2], R); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(R, &mpi.param[2]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_exp_mod(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *E, FAR const mbedtls_mpi *N, - FAR mbedtls_mpi *) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_EXP_MOD; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], E); - mbedtls_mpi_to_mpiparam(&mpi.param[2], N); - mbedtls_mpi_grow(X, N->n); - mbedtls_mpi_to_mpiparam(&mpi.param[3], X); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(X, &mpi.param[3]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_gcd(FAR mbedtls_mpi *G, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *B) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_GCD; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], B); - mbedtls_mpi_grow(G, MIN(A->n, B->n)); - mbedtls_mpi_to_mpiparam(&mpi.param[2], G); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(G, &mpi.param[2]); - } - - close(fd); - return ret; -} - -int mbedtls_mpi_inv_mod(FAR mbedtls_mpi *X, FAR const mbedtls_mpi *A, - FAR const mbedtls_mpi *N) -{ - int ret = 0; - int fd; - struct mpi_calc_s mpi; - - fd = open("/dev/mpi0", O_RDWR); - if (fd < 0) - { - return -errno; - } - - mpi.op = MPI_CALC_FUNC_INV_MOD; - mbedtls_mpi_to_mpiparam(&mpi.param[0], A); - mbedtls_mpi_to_mpiparam(&mpi.param[1], N); - mbedtls_mpi_grow(X, N->n); - mbedtls_mpi_to_mpiparam(&mpi.param[2], X); - ret = ioctl(fd, MATHIOC_MPI_CALC, (unsigned long)((uintptr_t)&mpi)); - if (ret >= 0) - { - mpiparam_to_mbedtls_mpi(X, &mpi.param[2]); - } - - close(fd); - return ret; -} diff --git a/crypto/mbedtls/source/dev_alt.c b/crypto/mbedtls/source/dev_alt.c index 9f9206445..adaada619 100644 --- a/crypto/mbedtls/source/dev_alt.c +++ b/crypto/mbedtls/source/dev_alt.c @@ -94,5 +94,5 @@ int cryptodev_clone(FAR cryptodev_context_t *dst, { dst->session = src->session; dst->crypt = src->crypt; - return dup2(src->fd, dst->fd); + return cryptodev_get_session(dst); } diff --git a/crypto/mbedtls/source/poly1305_alt.c b/crypto/mbedtls/source/poly1305_alt.c deleted file mode 100644 index 4326d19ff..000000000 --- a/crypto/mbedtls/source/poly1305_alt.c +++ /dev/null @@ -1,101 +0,0 @@ -/**************************************************************************** - * apps/crypto/mbedtls/source/poly1305_alt.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "mbedtls/error.h" -#include "mbedtls/poly1305.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void mbedtls_poly1305_init(FAR mbedtls_poly1305_context *ctx) -{ - cryptodev_init(ctx); -} - -void mbedtls_poly1305_free(FAR mbedtls_poly1305_context *ctx) -{ - cryptodev_free(ctx); -} - -int mbedtls_poly1305_starts(mbedtls_poly1305_context *ctx, - const unsigned char key[32]) -{ - ctx->session.mac = CRYPTO_POLY1305; - ctx->session.mackey = (caddr_t)key; - ctx->session.mackeylen = 32; - return cryptodev_get_session(ctx); -} - -int mbedtls_poly1305_update(FAR mbedtls_poly1305_context *ctx, - FAR const unsigned char *input, - size_t ilen) -{ - ctx->crypt.op = COP_ENCRYPT; - ctx->crypt.flags |= COP_FLAG_UPDATE; - ctx->crypt.src = (caddr_t)input; - ctx->crypt.len = ilen; - return cryptodev_crypt(ctx); -} - -int mbedtls_poly1305_finish(FAR mbedtls_poly1305_context *ctx, - unsigned char mac[16]) -{ - int ret; - - ctx->crypt.op = COP_ENCRYPT; - ctx->crypt.flags = 0; - ctx->crypt.mac = (caddr_t)mac; - ret = cryptodev_crypt(ctx); - cryptodev_free_session(ctx); - return ret; -} - -int mbedtls_poly1305_mac(const unsigned char key[32], - FAR const unsigned char *input, - size_t ilen, - unsigned char mac[16]) -{ - mbedtls_poly1305_context ctx; - int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; - - mbedtls_poly1305_init(&ctx); - - ret = mbedtls_poly1305_starts(&ctx, key); - if (ret != 0) - { - goto cleanup; - } - - ret = mbedtls_poly1305_update(&ctx, input, ilen); - if (ret != 0) - { - goto cleanup; - } - - ret = mbedtls_poly1305_finish(&ctx, mac); - -cleanup: - mbedtls_poly1305_free(&ctx); - return ret; -} diff --git a/crypto/mbedtls/source/ripemd160_alt.c b/crypto/mbedtls/source/ripemd160_alt.c deleted file mode 100644 index 46db7474b..000000000 --- a/crypto/mbedtls/source/ripemd160_alt.c +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************************** - * apps/crypto/mbedtls/source/ripemd160_alt.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "mbedtls/ripemd160.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void mbedtls_ripemd160_clone(FAR mbedtls_ripemd160_context *dst, - FAR const mbedtls_ripemd160_context *src) -{ - cryptodev_clone(dst, src); -} - -void mbedtls_ripemd160_init(FAR mbedtls_ripemd160_context *ctx) -{ - cryptodev_init(ctx); -} - -void mbedtls_ripemd160_free(FAR mbedtls_ripemd160_context *ctx) -{ - cryptodev_free(ctx); -} - -int mbedtls_ripemd160_starts(FAR mbedtls_ripemd160_context *ctx) -{ - ctx->session.mac = CRYPTO_RIPEMD160; - return cryptodev_get_session(ctx); -} - -int mbedtls_ripemd160_update(FAR mbedtls_ripemd160_context *ctx, - FAR const unsigned char *input, - size_t ilen) -{ - ctx->crypt.op = COP_ENCRYPT; - ctx->crypt.flags |= COP_FLAG_UPDATE; - ctx->crypt.src = (caddr_t)input; - ctx->crypt.len = ilen; - return cryptodev_crypt(ctx); -} - -int mbedtls_ripemd160_finish(FAR mbedtls_ripemd160_context *ctx, - unsigned char output[20]) -{ - int ret; - - ctx->crypt.op = COP_ENCRYPT; - ctx->crypt.flags = 0; - ctx->crypt.mac = (caddr_t)output; - ret = cryptodev_crypt(ctx); - cryptodev_free_session(ctx); - return ret; -} diff --git a/crypto/openssl_mbedtls_wrapper/Kconfig b/crypto/openssl_mbedtls_wrapper/Kconfig deleted file mode 100644 index 197adbc3e..000000000 --- a/crypto/openssl_mbedtls_wrapper/Kconfig +++ /dev/null @@ -1,9 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config OPENSSL_MBEDTLS_WRAPPER - depends on CRYPTO_MBEDTLS - bool "openssl mbedtls wrapper" - default n diff --git a/crypto/openssl_mbedtls_wrapper/Make.defs b/crypto/openssl_mbedtls_wrapper/Make.defs deleted file mode 100644 index 611dc7321..000000000 --- a/crypto/openssl_mbedtls_wrapper/Make.defs +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/crypto/openssl_mbedtls_wrapper/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_OPENSSL_MBEDTLS_WRAPPER),) -CONFIGURED_APPS += $(APPDIR)/crypto/openssl_mbedtls_wrapper -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/openssl_mbedtls_wrapper/include -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/crypto/openssl_mbedtls_wrapper/include -endif diff --git a/crypto/openssl_mbedtls_wrapper/Makefile b/crypto/openssl_mbedtls_wrapper/Makefile deleted file mode 100644 index b8fb81b48..000000000 --- a/crypto/openssl_mbedtls_wrapper/Makefile +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/crypto/openssl_mbedtls_wrapper/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs -CSRCS += $(wildcard $(APPDIR)/crypto/openssl_mbedtls_wrapper/mbedtls/*.c) -include $(APPDIR)/Application.mk diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/aes.h b/crypto/openssl_mbedtls_wrapper/include/openssl/aes.h deleted file mode 100644 index a76646aab..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/aes.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/aes.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_AES_H -#define OPENSSL_MBEDTLS_WRAPPER_AES_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define AES_ENCRYPT 1 -#define AES_DECRYPT 0 - -#define AES_BLOCK_SIZE 16 -#define AES_MAXNR 14 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct aes_key_st -{ - uint32_t rd_key[4 * (AES_MAXNR + 1)]; - unsigned rounds; -}; - -typedef struct aes_key_st AES_KEY; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int AES_set_encrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey); - -void AES_encrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); - -int AES_set_decrypt_key(const uint8_t *key, unsigned bits, - AES_KEY *aeskey); - -void AES_decrypt(const uint8_t *in, uint8_t *out, - const AES_KEY *key); - -void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, - size_t len, const AES_KEY *key, - uint8_t *ivec, const int enc); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_AES_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/asn1.h b/crypto/openssl_mbedtls_wrapper/include/openssl/asn1.h deleted file mode 100644 index 3c0284bc9..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/asn1.h +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/asn1.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_ASN1_H -#define OPENSSL_MBEDTLS_WRAPPER_ASN1_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define MBSTRING_FLAG 0x1000 -#define MBSTRING_UTF8 (MBSTRING_FLAG) -#define MBSTRING_ASC (MBSTRING_FLAG | 1) - -#define V_ASN1_NULL 5 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -void ASN1_BIT_STRING_free(ASN1_BIT_STRING *a); - -void ASN1_INTEGER_free(ASN1_INTEGER *a); - -void ASN1_OBJECT_free(ASN1_OBJECT *a); - -void ASN1_OCTET_STRING_free(ASN1_OCTET_STRING *a); - -void ASN1_TIME_free(ASN1_TIME *a); - -ASN1_BIT_STRING *ASN1_BIT_STRING_new(void); - -int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *str, int n, int value); - -ASN1_OCTET_STRING *ASN1_OCTET_STRING_new(void); - -int i2d_ASN1_BIT_STRING(const ASN1_BIT_STRING *in, uint8_t **outp); - -int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, - const unsigned char *data, int len); - -ASN1_INTEGER *ASN1_INTEGER_new(void); - -ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai); - -ASN1_TIME *ASN1_TIME_new(void); - -ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_ASN1_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/base.h b/crypto/openssl_mbedtls_wrapper/include/openssl/base.h deleted file mode 100644 index b621aabe8..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/base.h +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/base.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_BASE_H -#define OPENSSL_MBEDTLS_WRAPPER_BASE_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define ASN1_BIT_STRING ASN1_STRING - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef struct EVP_CIPHER EVP_CIPHER; -typedef struct EVP_CIPHER_CTX EVP_CIPHER_CTX; -typedef struct ENGINE ENGINE; -typedef struct EVP_MD EVP_MD; -typedef struct EVP_MD_CTX EVP_MD_CTX; -typedef struct ASN1_BIT_STRING ASN1_BIT_STRING; -typedef struct ASN1_INTEGER ASN1_INTEGER; -typedef struct ASN1_OBJECT ASN1_OBJECT; -typedef struct ASN1_OCTET_STRING ASN1_OCTET_STRING; -typedef struct ASN1_TIME ASN1_TIME; -typedef struct BN_CTX BN_CTX; -typedef struct EC_GROUP EC_GROUP; -typedef struct EC_KEY EC_KEY; -typedef struct EC_POINT EC_POINT; -typedef struct evp_pkey_st EVP_PKEY; -typedef struct EVP_PKEY_CTX EVP_PKEY_CTX; -typedef struct PKCS8_PRIV_KEY_INFO PKCS8_PRIV_KEY_INFO; -typedef struct X509_ALGOR X509_ALGOR; -typedef struct X509_EXTENSION X509_EXTENSION; -typedef struct X509_NAME X509_NAME; -typedef struct BIGNUM BIGNUM; -typedef struct HMAC_CTX HMAC_CTX; -typedef struct rsa_meth_st RSA_METHOD; -typedef struct ecdsa_method_st ECDSA_METHOD; -typedef struct BN_GENCB BN_GENCB; -typedef struct sha256_state_st SHA256_CTX; -typedef struct sha_state_st SHA_CTX; -typedef struct cbb_st CBB; -typedef struct ecdsa_sig_st ECDSA_SIG; -typedef void RSA; - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_BASE_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/bio.h b/crypto/openssl_mbedtls_wrapper/include/openssl/bio.h deleted file mode 100644 index b2a55b3fb..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/bio.h +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/bio.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_BIO_H -#define OPENSSL_MBEDTLS_WRAPPER_BIO_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_BIO_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/bn.h b/crypto/openssl_mbedtls_wrapper/include/openssl/bn.h deleted file mode 100644 index 0080c0f02..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/bn.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/bn.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_BN_H -#define OPENSSL_MBEDTLS_WRAPPER_BN_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define BN_ULONG uint32_t -#define BN_BITS2 32 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef uint32_t BN_ULONG; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -BN_CTX *BN_CTX_new(void); -void BN_CTX_free(BN_CTX *a); -void BN_free(BIGNUM *a); - -BN_ULONG BN_get_word(const BIGNUM *bn); - -unsigned BN_num_bits(const BIGNUM *bn); - -BIGNUM *BN_new(void); - -int BN_bn2binpad(const BIGNUM *in, uint8_t *out, int len); - -int BN_set_word(BIGNUM *bn, BN_ULONG value); - -BIGNUM *BN_dup(const BIGNUM *src); - -BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret); - -int BN_one(BIGNUM *bn); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_BN_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/bytestring.h b/crypto/openssl_mbedtls_wrapper/include/openssl/bytestring.h deleted file mode 100644 index 76f1272c4..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/bytestring.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/bytestring.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H -#define OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct cbb_buffer_st -{ - uint8_t * buf; - - /* len is the number of valid bytes in |buf|. */ - - size_t len; - - /* cap is the size of |buf|. */ - - size_t cap; - - /* can_resize is one iff |buf| is owned by this object. If not then |buf| - * cannot be resized. - */ - - unsigned can_resize : 1; - - /* error is one if there was an error writing to this CBB. All future - * operations will fail. - */ - - unsigned error : 1; -}; - -struct cbb_child_st -{ - /* base is a pointer to the buffer this |CBB| writes to. */ - - struct cbb_buffer_st * base; - - /* offset is the number of bytes from the start of - * |base->buf| to this |CBB|'s - * pending length prefix. - */ - - size_t offset; - - /* pending_len_len contains the number of bytes in this |CBB|'s pending - * length-prefix, or zero if no length-prefix is pending. - */ - - uint8_t pending_len_len; - unsigned pending_is_asn1 : 1; -}; - -struct cbb_st -{ - /* child points to a child CBB if a length-prefix is pending. - * CBB* child; - * is_child is one if this is a child |CBB| and zero if it is a top-level - * |CBB|. This determines which arm of the union is valid. - */ - - char is_child; - union - { - struct cbb_buffer_st base; - struct cbb_child_st child; - } u; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int CBB_init(CBB *cbb, size_t initial_capacity); - -int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len); - -void CBB_cleanup(CBB *cbb); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_BYTESTRING_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/cipher.h b/crypto/openssl_mbedtls_wrapper/include/openssl/cipher.h deleted file mode 100644 index d057adb53..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/cipher.h +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/cipher.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_CIPER_H -#define OPENSSL_MBEDTLS_WRAPPER_CIPER_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define CIPHER_R_BAD_DECRYPT 101 -#define EVP_CTRL_GCM_GET_TAG 0x10 -#define EVP_CTRL_GCM_SET_TAG 0x11 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx); -int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *ctx); - -const EVP_CIPHER *EVP_aes_128_ecb(void); -const EVP_CIPHER *EVP_aes_192_ecb(void); -const EVP_CIPHER *EVP_aes_256_ecb(void); -const EVP_CIPHER *EVP_aes_128_cbc(void); -const EVP_CIPHER *EVP_aes_192_cbc(void); -const EVP_CIPHER *EVP_aes_256_cbc(void); -const EVP_CIPHER *EVP_aes_128_ctr(void); -const EVP_CIPHER *EVP_aes_192_ctr(void); -const EVP_CIPHER *EVP_aes_256_ctr(void); -const EVP_CIPHER *EVP_aes_128_gcm(void); -const EVP_CIPHER *EVP_aes_192_gcm(void); -const EVP_CIPHER *EVP_aes_256_gcm(void); - -const EVP_CIPHER *EVP_des_ede(void); -const EVP_CIPHER *EVP_des_ede3(void); -const EVP_CIPHER *EVP_des_ede_cbc(void); -const EVP_CIPHER *EVP_des_ede3_cbc(void); - -int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); -int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad); -int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - ENGINE *impl, const unsigned char *key, - const unsigned char *iv, int enc); -int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, - int *outl, const unsigned char *in, - int inl); -int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, - int *outl); - -int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx); - -EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void); - -void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx); - -int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - ENGINE *impl, const uint8_t *key, - const uint8_t *iv); - -int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - ENGINE *impl, const uint8_t *key, - const uint8_t *iv); - -int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - int in_len); - -int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len); - -int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, - int *out_len, const uint8_t *in, - int in_len); - -int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_CIPER_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/curve25519.h b/crypto/openssl_mbedtls_wrapper/include/openssl/curve25519.h deleted file mode 100644 index e339a2a76..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/curve25519.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/curve25519.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H -#define OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define X25519_PRIVATE_KEY_LEN 32 -#define X25519_PUBLIC_VALUE_LEN 32 -#define X25519_SHARED_KEY_LEN 32 -#define ED25519_PRIVATE_KEY_LEN 64 -#define ED25519_PUBLIC_KEY_LEN 32 -#define ED25519_SIGNATURE_LEN 64 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -/* ED25519_keypair sets |out_public_key| and |out_private_key| to a freshly - * generated, public–private key pair. - */ - -void ED25519_keypair(uint8_t out_public_key[32], - uint8_t out_private_key[64]); - -void X25519_keypair(uint8_t out_public_value[32], - uint8_t out_private_key[32]); - -int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32], - const uint8_t peer_public_value[32]); - -int ED25519_sign(uint8_t out_sig[64], const uint8_t *message, - size_t message_len, const uint8_t private_key[64]); - -int ED25519_verify(const uint8_t *message, size_t message_len, - const uint8_t signature[64], - const uint8_t public_key[32]); - -void ED25519_keypair_from_seed(uint8_t out_public_key[32], - uint8_t out_private_key[64], - const uint8_t seed[32]); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_CURVE25519_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/des.h b/crypto/openssl_mbedtls_wrapper/include/openssl/des.h deleted file mode 100644 index 46c2f62ce..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/des.h +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/des.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_DES_H -#define OPENSSL_MBEDTLS_WRAPPER_DES_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_DES_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/digest.h b/crypto/openssl_mbedtls_wrapper/include/openssl/digest.h deleted file mode 100644 index 19d86a411..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/digest.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/digest.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef KEYMASTER_DIGEST_H -#define KEYMASTER_DIGEST_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define EVP_MAX_MD_SIZE 64 // SHA-512 is the longest so far. -#define EVP_MAX_MD_BLOCK_SIZE 128 // SHA-512 is the longest so far. - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -const EVP_MD *EVP_md4(void); -const EVP_MD *EVP_md5(void); -const EVP_MD *EVP_sha1(void); -const EVP_MD *EVP_sha224(void); -const EVP_MD *EVP_sha256(void); -const EVP_MD *EVP_sha384(void); -const EVP_MD *EVP_sha512(void); -const EVP_MD *EVP_sha512_256(void); -const EVP_MD *EVP_blake2b256(void); - -const EVP_MD *EVP_md5_sha1(void); - -const EVP_MD *EVP_get_digestbynid(int nid); - -const EVP_MD *EVP_get_digestbyobj(const ASN1_OBJECT *obj); - -void EVP_MD_CTX_init(EVP_MD_CTX *ctx); - -EVP_MD_CTX *EVP_MD_CTX_new(void); - -int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx); - -void EVP_MD_CTX_cleanse(EVP_MD_CTX *ctx); - -void EVP_MD_CTX_free(EVP_MD_CTX *ctx); - -int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in); - -void EVP_MD_CTX_move(EVP_MD_CTX *out, EVP_MD_CTX *in); - -int EVP_MD_CTX_reset(EVP_MD_CTX *ctx); - -/* Digest operations. */ - -int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, - ENGINE *engine); - -int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type); - -int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t len); - -int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, uint8_t *md_out, - unsigned int *out_size); - -int EVP_DigestFinal(EVP_MD_CTX *ctx, uint8_t *md_out, - unsigned int *out_size); - -int EVP_Digest(const void *data, size_t len, - uint8_t *md_out, unsigned int *md_out_size, - const EVP_MD *type, ENGINE *impl); - -size_t EVP_MD_size(const EVP_MD *md); - -#ifdef __cplusplus -} -#endif - -#endif /* KEYMASTER_DIGEST_H */ - diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ec.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ec.h deleted file mode 100644 index 80fb6644a..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ec.h +++ /dev/null @@ -1,112 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ec.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_EC_H -#define OPENSSL_MBEDTLS_WRAPPER_EC_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define OPENSSL_EC_NAMED_CURVE 1 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -/* point_conversion_form_t enumerates forms, as defined in X9.62 (ECDSA), for - * the encoding of a elliptic curve point (x,y) - */ - -typedef enum -{ - /* POINT_CONVERSION_COMPRESSED indicates that the point is encoded as z||x, - * where the octet z specifies which solution of the quadratic equation y - * is. - */ - - POINT_CONVERSION_COMPRESSED = 2, - - /* POINT_CONVERSION_UNCOMPRESSED indicates that the point is encoded as - * z||x||y, where z is the octet 0x04. - */ - - POINT_CONVERSION_UNCOMPRESSED = 4, - - /* POINT_CONVERSION_HYBRID indicates that the point is encoded as z||x||y, - * where z specifies which solution of the quadratic equation y is. This is - * not supported by the code and has never been observed in use. - * - * TODO(agl): remove once node.js no longer references this. - */ - - POINT_CONVERSION_HYBRID = 6, -} point_conversion_form_t; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -void EC_GROUP_free(EC_GROUP *a); - -void EC_KEY_free(EC_KEY *a); - -void EC_POINT_free(EC_POINT *a); - -int EC_GROUP_get_curve_name(const EC_GROUP *group); - -EC_GROUP *EC_GROUP_new_by_curve_name(int nid); - -int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx); - -int EC_POINT_get_affine_coordinates_GFp(const EC_GROUP *group, - const EC_POINT *point, BIGNUM *x, - BIGNUM *y, BN_CTX *ctx); - -/* EC_GROUP_set_point_conversion_form aborts the process if |form| is not - * |POINT_CONVERSION_UNCOMPRESSED| and otherwise does nothing. - */ - -void EC_GROUP_set_point_conversion_form(EC_GROUP *group, - point_conversion_form_t form); - -void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag); - -EC_POINT *EC_POINT_new(const EC_GROUP *group); - -int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *point, - const uint8_t *buf, size_t len, - BN_CTX *ctx); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_EC_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ec_key.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ec_key.h deleted file mode 100644 index dcb4042aa..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ec_key.h +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ec_key.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_EC_KEY_H -#define OPENSSL_MBEDTLS_WRAPPER_EC_KEY_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define ECDSA_FLAG_OPAQUE 1 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct ecdsa_method_st -{ - struct openssl_method_common_st common; - - void *app_data; - - int (*init)(EC_KEY *key); - int (*finish)(EC_KEY *key); - - /* group_order_size returns the number of bytes needed to - * represent the order of the group. This is used to - * calculate the maximum size of an ECDSA signature - * in |ECDSA_size|. - */ - - size_t (*group_order_size)(const EC_KEY *key); - - /* sign matches the arguments and behaviour of |ECDSA_sign|. */ - - int (*sign)(const uint8_t *digest, size_t digest_len, uint8_t *sig, - unsigned int *sig_len, EC_KEY *eckey); - - int flags; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -EC_KEY *EC_KEY_new(void); - -const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key); - -const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key); - -int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group); - -int EC_KEY_generate_key(EC_KEY *key); - -int EC_KEY_check_key(const EC_KEY *key); - -int EC_KEY_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_unused *unused, - CRYPTO_EX_dup *dup_unused, - CRYPTO_EX_free *free_func); - -EC_KEY *EC_KEY_new_method(const ENGINE *engine); - -int EC_KEY_set_ex_data(EC_KEY *r, int idx, void *arg); - -void *EC_KEY_get_ex_data(const EC_KEY *r, int idx); - -int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub); - -EC_KEY *EC_KEY_new_by_curve_name(int nid); - -int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_EC_KEY_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ecdsa.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ecdsa.h deleted file mode 100644 index e053bb337..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ecdsa.h +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ecdsa.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_ECDSA_H -#define OPENSSL_MBEDTLS_WRAPPER_ECDSA_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct ecdsa_sig_st -{ - BIGNUM *r; - BIGNUM *s; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -size_t ECDSA_size(const EC_KEY *key); - -int ECDSA_sign(int type, const uint8_t *digest, size_t digest_len, - uint8_t *sig, unsigned int *sig_len, - const EC_KEY *key); - -int ECDSA_verify(int type, const uint8_t *digest, - size_t digest_len, const uint8_t *sig, - size_t sig_len, const EC_KEY *key); - -int i2d_ECDSA_SIG(const ECDSA_SIG *sig, uint8_t **outp); - -ECDSA_SIG *d2i_ECDSA_SIG(ECDSA_SIG **out, const uint8_t **inp, long len); - -const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig); - -const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig); - -ECDSA_SIG *ECDSA_SIG_new(void); - -void ECDSA_SIG_free(ECDSA_SIG *sig); - -ECDSA_SIG *ECDSA_do_sign(const uint8_t *digest, size_t digest_len, - const EC_KEY *key); - -int ECDSA_do_verify(const uint8_t *digest, size_t digest_len, - const ECDSA_SIG *sig, const EC_KEY *key); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_ECDSA_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/engine.h b/crypto/openssl_mbedtls_wrapper/include/openssl/engine.h deleted file mode 100644 index dea3f35da..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/engine.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/engine.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_ENGINE_H -#define OPENSSL_MBEDTLS_WRAPPER_ENGINE_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct openssl_method_common_st -{ - int references; /* dummy – not used. */ - char is_static; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -ENGINE *ENGINE_new(void); - -void ENGINE_free(ENGINE *a); - -int ENGINE_set_RSA_method(ENGINE *engine, const RSA_METHOD *method, - size_t method_size); - -int ENGINE_set_ECDSA_method(ENGINE *engine, const ECDSA_METHOD *method, - size_t method_size); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_ENGINE_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/evp.h b/crypto/openssl_mbedtls_wrapper/include/openssl/evp.h deleted file mode 100644 index ae5fae9cf..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/evp.h +++ /dev/null @@ -1,171 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/evp.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_EVP_H -#define OPENSSL_MBEDTLS_WRAPPER_EVP_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define EVP_PKEY_RSA NID_rsaEncryption -#define EVP_PKEY_EC NID_X9_62_id_ecPublicKey -#define EVP_PKEY_ED25519 NID_ED25519 - -#define EVP_PKEY_X25519 NID_X25519 - -struct evp_pkey_st -{ - void *pkey_pm; - const PKEY_METHOD *method; -}; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int EVP_PKEY_id(const EVP_PKEY *pkey); - -RSA *EVP_PKEY_get1_RSA(const EVP_PKEY *pkey); - -int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key); - -EVP_PKEY *__EVP_PKEY_new(EVP_PKEY *ipk); - -EVP_PKEY *EVP_PKEY_new(void); - -void EVP_PKEY_free(EVP_PKEY *pkey); - -void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx); - -EC_KEY *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey); - -EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey); - -int EVP_PKEY_type(int nid); - -EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **out, - const uint8_t **inp, long len); - -int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp); - -EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *unused, - const uint8_t *in, size_t len); - -int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key); - -int EVP_PKEY_bits(const EVP_PKEY *pkey); - -int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); - -int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t len); - -int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, - size_t *out_sig_len); - -int EVP_DigestSign(EVP_MD_CTX *ctx, uint8_t *out_sig, - size_t *out_sig_len, const uint8_t *data, - size_t data_len); - -int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, - EVP_PKEY *pkey); - -int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, - size_t len); - -int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len); - -EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp, - long len); - -int EVP_PKEY_size(const EVP_PKEY *pkey); - -int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int padding); - -int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int salt_len); - -int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md); - -int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md); - -EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e); - -int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx); - -int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, - size_t *out_len, const uint8_t *in, - size_t in_len); - -int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx); - -int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, - size_t *out_len, const uint8_t *in, - size_t in_len); - -int i2d_PrivateKey(const EVP_PKEY *key, uint8_t **outp); - -EVP_PKEY *X509_get_pubkey(X509 *x509); - -int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key); - -int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx); - -int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer); - -int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len); - -int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, uint8_t *out, - size_t *out_len); - -int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *out_key_len); - -int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, - const uint8_t *salt, size_t salt_len, - unsigned iterations, const EVP_MD *digest, - size_t key_len, uint8_t *out_key); - -const PKEY_METHOD *EVP_PKEY_method(void); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_EVP_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ex_data.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ex_data.h deleted file mode 100644 index a00d0b9f8..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ex_data.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ex_data.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_EX_DATA_H -#define OPENSSL_MBEDTLS_WRAPPER_EX_DATA_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef int CRYPTO_EX_unused; -typedef struct CRYPTO_EX_DATA CRYPTO_EX_DATA; - -typedef int CRYPTO_EX_dup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from, - void **from_d, int index, - long argl, void *argp); - -typedef void CRYPTO_EX_free(void *parent, void *ptr, - CRYPTO_EX_DATA *ad, int index, - long argl, void *argp); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_EX_DATA_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/hkdf.h b/crypto/openssl_mbedtls_wrapper/include/openssl/hkdf.h deleted file mode 100644 index 988cff53a..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/hkdf.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/hkdf.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_HKDF_H -#define OPENSSL_MBEDTLS_WRAPPER_HKDF_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int HKDF(uint8_t *out_key, size_t out_len, - const EVP_MD *digest, const uint8_t *secret, - size_t secret_len, const uint8_t *salt, - size_t salt_len, const uint8_t *info, - size_t info_len); - -/* HKDF_extract computes a HKDF PRK (as specified by RFC 5869) from initial - * keying material |secret| and salt |salt| using |digest|, and outputs - * |out_len| bytes to |out_key|. The maximum output size is - * |EVP_MAX_MD_SIZE|. It returns one on success and zero on error. - * - * WARNING: This function orders the inputs differently from RFC 5869 - * specification. Double-check which parameter is the secret/IKM and which is - * the salt when using. - */ - -int HKDF_extract(uint8_t *out_key, size_t *out_len, - const EVP_MD *digest, const uint8_t *secret, - size_t secret_len, const uint8_t *salt, - size_t salt_len); - -/* HKDF_expand computes a HKDF OKM (as specified by RFC 5869) of length - * |out_len| from the PRK |prk| and info |info| using |digest|, and outputs - * the result to |out_key|. It returns one on success and zero on error. - */ - -int HKDF_expand(uint8_t *out_key, size_t out_len, - const EVP_MD *digest, const uint8_t *prk, - size_t prk_len, const uint8_t *info, - size_t info_len); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_HKDF_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/hmac.h b/crypto/openssl_mbedtls_wrapper/include/openssl/hmac.h deleted file mode 100644 index 9e3aead63..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/hmac.h +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/hmac.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_HMAC_H -#define OPENSSL_MBEDTLS_WRAPPER_HMAC_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -/* HMAC calculates the HMAC of |data_len| bytes of |data|, using the given - * key and hash function, and writes the result to |out|. On entry, |out| - * must contain at least |EVP_MD_size| bytes of space. The actual length - * of the result is written to |*out_len|. An output size of - * |EVP_MAX_MD_SIZE| will always be large enough. It returns |out| - * or NULL on error. - */ - -uint8_t *HMAC(const EVP_MD *evp_md, const void *key, - size_t key_len, const uint8_t *data, size_t data_len, - uint8_t *out, unsigned int *out_len); - -HMAC_CTX *HMAC_CTX_new(void); - -void HMAC_CTX_init(HMAC_CTX *ctx); - -int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, - size_t key_len, const EVP_MD *md, - ENGINE *impl); - -int HMAC_Update(HMAC_CTX *ctx, const uint8_t *data, size_t data_len); - -int HMAC_Final(HMAC_CTX *ctx, uint8_t *out, unsigned int *out_len); - -void HMAC_CTX_cleanup(HMAC_CTX *ctx); - -void HMAC_CTX_free(HMAC_CTX *ctx); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_HMAC_H */ - diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/md5.h b/crypto/openssl_mbedtls_wrapper/include/openssl/md5.h deleted file mode 100644 index 492d9a3bb..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/md5.h +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/md5.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_MD5_H -#define OPENSSL_MBEDTLS_WRAPPER_MD5_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -/* MD5_DIGEST_LENGTH is the length of an MD5 digest. */ - -#define MD5_DIGEST_LENGTH 16 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -uint8_t *MD5(const uint8_t *data, size_t len, - uint8_t out[MD5_DIGEST_LENGTH]); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_MD5_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/mem.h b/crypto/openssl_mbedtls_wrapper/include/openssl/mem.h deleted file mode 100644 index f1c001c57..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/mem.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/mem.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_MEM_H -#define OPENSSL_MBEDTLS_WRAPPER_MEM_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -/* CRYPTO_memcmp returns zero iff the |len| bytes at - * |a| and |b| are equal. It takes an amount of time - * dependent on |len|, but independent of the contents - * of |a| and |b|. Unlike memcmp, it cannot be used to - * put elements into a defined order as the return value - * when a != b is undefined, other than to be non-zero. - */ - -int CRYPTO_memcmp(const void *a, const void *b, size_t len); - -void OPENSSL_free(void *ptr); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_MEM_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/nid.h b/crypto/openssl_mbedtls_wrapper/include/openssl/nid.h deleted file mode 100644 index 2aa36b077..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/nid.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/nid.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_NID_H -#define OPENSSL_MBEDTLS_WRAPPER_NID_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define NID_rsaEncryption 6 -#define NID_commonName 13 -#define NID_key_usage 83 -#define NID_X9_62_id_ecPublicKey 408 -#define NID_X9_62_prime256v1 415 -#define NID_sha256WithRSAEncryption 668 -#define NID_secp224r1 713 -#define NID_secp384r1 715 -#define NID_secp521r1 716 -#define NID_X25519 948 -#define NID_ED25519 949 - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_NID_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/obj.h b/crypto/openssl_mbedtls_wrapper/include/openssl/obj.h deleted file mode 100644 index 2e011a486..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/obj.h +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/obj.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_OBJ_H -#define OPENSSL_MBEDTLS_WRAPPER_OBJ_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -ASN1_OBJECT *OBJ_nid2obj(int nid); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_OBJ_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/pem.h b/crypto/openssl_mbedtls_wrapper/include/openssl/pem.h deleted file mode 100644 index b14a6c979..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/pem.h +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/pem.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_PEM_H -#define OPENSSL_MBEDTLS_WRAPPER_PEM_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_PEM_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/rand.h b/crypto/openssl_mbedtls_wrapper/include/openssl/rand.h deleted file mode 100644 index 3f14f94a2..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/rand.h +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/rand.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_RAND_H -#define OPENSSL_MBEDTLS_WRAPPER_RAND_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int RAND_bytes(unsigned char *buf, int num); - -void RAND_add(const void *buf, int num, double randomness); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_RAND_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/rsa.h b/crypto/openssl_mbedtls_wrapper/include/openssl/rsa.h deleted file mode 100644 index 0337b4ff9..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/rsa.h +++ /dev/null @@ -1,140 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/rsa.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_RSA_H -#define OPENSSL_MBEDTLS_WRAPPER_RSA_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define RSA_PKCS1_PADDING 1 -#define RSA_FLAG_OPAQUE 1 -#define RSA_NO_PADDING 3 -#define RSA_PKCS1_OAEP_PADDING 4 -#define RSA_PKCS1_PSS_PADDING 6 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct rsa_meth_st -{ - struct openssl_method_common_st common; - - void *app_data; - - int (*init)(RSA *rsa); - int (*finish)(RSA *rsa); - - /* size returns the size of the RSA modulus in bytes. */ - - size_t (*size)(const RSA *rsa); - - int (*sign)(int type, const uint8_t *m, - unsigned int m_length, uint8_t *sigret, - unsigned int *siglen, const RSA *rsa); - - /* These functions mirror the |RSA_*| functions of the same name. */ - - int (*sign_raw)(RSA *rsa, size_t *out_len, - uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, - int padding); - int (*decrypt)(RSA *rsa, size_t *out_len, - uint8_t *out, size_t max_out, - const uint8_t *in, size_t in_len, - int padding); - - /* private_transform takes a big-endian integer from |in|, calculates the - * d'th power of it, modulo the RSA modulus and writes the result as a - * big-endian integer to |out|. Both |in| and |out| are |len| bytes long - * and |len| is always equal to |RSA_size(rsa)|. If the result of - * the transform can be represented in fewer than |len| bytes, - * then |out| must be zero padded on the left. - * - * It returns one on success and zero otherwise. - * - * RSA decrypt and sign operations will call this, - * thus an ENGINE might wish - * to override it in order to avoid having to implement the padding - * functionality demanded by those, higher level, operations. - */ - - int (*private_transform)(RSA *rsa, uint8_t *out, - const uint8_t *in, size_t len); - - int flags; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -RSA *RSA_new(void); - -void RSA_free(RSA *a); - -unsigned RSA_size(const RSA *rsa); - -const BIGNUM *RSA_get0_e(const RSA *rsa); - -const BIGNUM *RSA_get0_n(const RSA *rsa); - -int RSA_generate_key_ex(RSA *rsa, int bits, - const BIGNUM *e, BN_GENCB *cb); - -int RSA_get_ex_new_index(long argl, void *argp, - CRYPTO_EX_unused *unused, - CRYPTO_EX_dup *dup_unused, - CRYPTO_EX_free *free_func); - -RSA *RSA_new_method(const ENGINE *engine); - -int RSA_set_ex_data(RSA *rsa, int idx, void *arg); - -void *RSA_get_ex_data(const RSA *rsa, int idx); - -int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d); - -int RSA_private_encrypt(size_t flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - -int RSA_public_decrypt(size_t flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_RSA_H */ - diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/sha.h b/crypto/openssl_mbedtls_wrapper/include/openssl/sha.h deleted file mode 100644 index 423d2b335..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/sha.h +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/sha.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SHA_H -#define OPENSSL_MBEDTLS_WRAPPER_SHA_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -/* SHA256_DIGEST_LENGTH is the length of a SHA-256 digest */ - -#define SHA256_DIGEST_LENGTH 32 - -/* SHA_CBLOCK is the block size of SHA-1. */ - -#define SHA_CBLOCK 64 - -/* SHA_DIGEST_LENGTH is the length of a SHA-1 digest. */ - -#define SHA_DIGEST_LENGTH 20 - -#define SHA256_CBLOCK 64 - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct sha_state_st -{ - /* wpa_supplicant accesses |h0|..|h4| so we must support those names - * for compatibility with it until it can be updated. - */ - - union - { - uint32_t h[5]; - struct - { - uint32_t h0; - uint32_t h1; - uint32_t h2; - uint32_t h3; - uint32_t h4; - }; - }; - uint32_t Nl; - uint32_t Nh; - uint8_t data[SHA_CBLOCK]; - unsigned num; -}; - -struct sha256_state_st -{ - uint32_t h[8]; - uint32_t Nl; - uint32_t Nh; - uint8_t data[SHA256_CBLOCK]; - unsigned num; - unsigned md_len; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -/* SHA1_Init initialises |sha| and returns one. */ - -int SHA1_Init(SHA_CTX *sha); - -/* SHA1_Update adds |len| bytes from |data| to |sha| and returns one. */ - -int SHA1_Update(SHA_CTX *sha, const void *data, size_t len); - -/* SHA1_Final adds the final padding to |sha| and writes the - * resulting digest to |out|, which must have at least - * |SHA_DIGEST_LENGTH| bytes of space. It returns one. - */ - -int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha); - -/* SHA1 writes the digest of |len| bytes from |data| to |out| and returns - * |out|. There must be at least |SHA_DIGEST_LENGTH| bytes of space in - * |out|. - */ - -uint8_t *SHA1(const uint8_t *data, size_t len, - uint8_t out[SHA_DIGEST_LENGTH]); - -void SHA1_Transform(SHA_CTX *sha, const uint8_t block[SHA_CBLOCK]); - -int SHA256_Init(SHA256_CTX *sha); - -int SHA256_Update(SHA256_CTX *sha, const void *data, size_t len); - -int SHA256_Final(uint8_t out[SHA256_DIGEST_LENGTH], SHA256_CTX *sha); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SHA_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ssl.h deleted file mode 100644 index c8d29788e..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl.h +++ /dev/null @@ -1,305 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ssl.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */ -#define SSL_SENT_SHUTDOWN 1 -#define SSL_RECEIVED_SHUTDOWN 2 - -#define SSL_VERIFY_NONE 0x00 -#define SSL_VERIFY_PEER 0x01 -#define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02 -#define SSL_VERIFY_CLIENT_ONCE 0x04 - -/* The following 3 states are kept in ssl->rlayer.rstate when reads fail, you - * should not need these - */ -#define SSL_ST_READ_HEADER 0xF0 -#define SSL_ST_READ_BODY 0xF1 -#define SSL_ST_READ_DONE 0xF2 - -#define SSL_NOTHING 1 -#define SSL_WRITING 2 -#define SSL_READING 3 -#define SSL_X509_LOOKUP 4 -#define SSL_ASYNC_PAUSED 5 -#define SSL_ASYNC_NO_JOBS 6 - -#define SSL_ERROR_NONE 0 -#define SSL_ERROR_SSL 1 -#define SSL_ERROR_WANT_READ 2 -#define SSL_ERROR_WANT_WRITE 3 -#define SSL_ERROR_WANT_X509_LOOKUP 4 -#define SSL_ERROR_SYSCALL 5/* look at error stack/return value/errno */ -#define SSL_ERROR_ZERO_RETURN 6 -#define SSL_ERROR_WANT_CONNECT 7 -#define SSL_ERROR_WANT_ACCEPT 8 -#define SSL_ERROR_WANT_ASYNC 9 -#define SSL_ERROR_WANT_ASYNC_JOB 10 - -typedef enum -{ - TLS_ST_BEFORE, - TLS_ST_OK, - DTLS_ST_CR_HELLO_VERIFY_REQUEST, - TLS_ST_CR_SRVR_HELLO, - TLS_ST_CR_CERT, - TLS_ST_CR_CERT_STATUS, - TLS_ST_CR_KEY_EXCH, - TLS_ST_CR_CERT_REQ, - TLS_ST_CR_SRVR_DONE, - TLS_ST_CR_SESSION_TICKET, - TLS_ST_CR_CHANGE, - TLS_ST_CR_FINISHED, - TLS_ST_CW_CLNT_HELLO, - TLS_ST_CW_CERT, - TLS_ST_CW_KEY_EXCH, - TLS_ST_CW_CERT_VRFY, - TLS_ST_CW_CHANGE, - TLS_ST_CW_NEXT_PROTO, - TLS_ST_CW_FINISHED, - TLS_ST_SW_HELLO_REQ, - TLS_ST_SR_CLNT_HELLO, - DTLS_ST_SW_HELLO_VERIFY_REQUEST, - TLS_ST_SW_SRVR_HELLO, - TLS_ST_SW_CERT, - TLS_ST_SW_KEY_EXCH, - TLS_ST_SW_CERT_REQ, - TLS_ST_SW_SRVR_DONE, - TLS_ST_SR_CERT, - TLS_ST_SR_KEY_EXCH, - TLS_ST_SR_CERT_VRFY, - TLS_ST_SR_NEXT_PROTO, - TLS_ST_SR_CHANGE, - TLS_ST_SR_FINISHED, - TLS_ST_SW_SESSION_TICKET, - TLS_ST_SW_CERT_STATUS, - TLS_ST_SW_CHANGE, - TLS_ST_SW_FINISHED -} -OSSL_HANDSHAKE_STATE; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); - -int X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -int X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); - -int SSL_CTX_add_client_CA_ASN1(SSL_CTX *ssl, int len, - const unsigned char *d); - -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); - -int SSL_use_certificate(SSL *ssl, X509 *x); - -X509 *SSL_get_certificate(const SSL *ssl); - -int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, - const unsigned char *d); - -int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len); - -int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); - -int SSL_use_certificate_file(SSL *ssl, const char *file, int type); - -X509 *SSL_get_peer_certificate(const SSL *ssl); - -int SSL_want(const SSL *ssl); - -int SSL_want_nothing(const SSL *ssl); - -int SSL_want_read(const SSL *ssl); - -int SSL_want_write(const SSL *ssl); - -int SSL_want_x509_lookup(const SSL *ssl); - -void _ssl_set_alpn_list(const SSL *ssl); - -int SSL_get_error(const SSL *ssl, int ret_code); - -OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); - -SSL_CTX *SSL_CTX_new(const SSL_METHOD *method, void *rngctx); - -void SSL_CTX_free(SSL_CTX *ctx); - -int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); - -const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); - -SSL *SSL_new(SSL_CTX *ctx); - -void SSL_free(SSL *ssl); - -int SSL_do_handshake(SSL *ssl); - -int SSL_connect(SSL *ssl); - -int SSL_accept(SSL *ssl); - -int SSL_shutdown(SSL *ssl); - -int SSL_clear(SSL *ssl); - -int SSL_read(SSL *ssl, void *buffer, int len); - -int SSL_write(SSL *ssl, const void *buffer, int len); - -SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); - -const SSL_METHOD *SSL_get_ssl_method(SSL *ssl); - -int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method); - -int SSL_get_shutdown(const SSL *ssl); - -void SSL_set_shutdown(SSL *ssl, int mode); - -int SSL_pending(const SSL *ssl); - -int SSL_has_pending(const SSL *ssl); - -unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); - -unsigned long SSL_CTX_get_options(SSL_CTX *ctx); - -unsigned long SSL_clear_options(SSL *ssl, unsigned long op); - -unsigned long SSL_get_options(SSL *ssl); - -unsigned long SSL_set_options(SSL *ssl, unsigned long op); - -int SSL_get_fd(const SSL *ssl); - -int SSL_get_rfd(const SSL *ssl); - -int SSL_get_wfd(const SSL *ssl); - -int SSL_set_fd(SSL *ssl, int fd); - -int SSL_set_rfd(SSL *ssl, int fd); - -int SSL_set_wfd(SSL *ssl, int fd); - -int SSL_version(const SSL *ssl); - -const char *SSL_alert_type_string(int value); - -void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); - -void SSL_set_default_read_buffer_len(SSL *ssl, size_t len); - -void SSL_set_info_callback(SSL *ssl, - void (*cb) (const SSL *ssl, int type, int val)); - -int SSL_CTX_up_ref(SSL_CTX *ctx); - -void SSL_set_security_level(SSL *ssl, int level); - -int SSL_get_security_level(const SSL *ssl); - -int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); - -long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); - -long SSL_CTX_get_timeout(const SSL_CTX *ctx); - -void SSL_set_read_ahead(SSL *ssl, int yes); - -void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); - -int SSL_get_read_ahead(const SSL *ssl); - -long SSL_CTX_get_read_ahead(SSL_CTX *ctx); - -long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx); - -long SSL_set_time(SSL *ssl, long t); - -long SSL_set_timeout(SSL *ssl, long t); - -long SSL_get_verify_result(const SSL *ssl); - -int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); - -void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); - -int SSL_get_verify_depth(const SSL *ssl); - -void SSL_set_verify_depth(SSL *ssl, int depth); - -void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, - int (*verify_callback)(int, X509_STORE_CTX *)); - -void SSL_set_verify(SSL *ssl, int mode, - int (*verify_callback)(int, X509_STORE_CTX *)); - -void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx); - -void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg); - -void SSL_set_alpn_select_cb(SSL *ssl, void *arg); - -int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); - -int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey); - -int SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx, - const unsigned char *d, long len); - -int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, - const unsigned char *d, long len); - -int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); - -int SSL_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); - -int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, - long len); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl3.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ssl3.h deleted file mode 100644 index 43a809a3b..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl3.h +++ /dev/null @@ -1,49 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ssl3.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_SSL3_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_SSL3_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define SSL3_AD_CLOSE_NOTIFY 0 -#define SSL3_AD_UNEXPECTED_MESSAGE 10/* fatal */ -#define SSL3_AD_BAD_RECORD_MAC 20/* fatal */ -#define SSL3_AD_DECOMPRESSION_FAILURE 30/* fatal */ -#define SSL3_AD_HANDSHAKE_FAILURE 40/* fatal */ -#define SSL3_AD_NO_CERTIFICATE 41 -#define SSL3_AD_BAD_CERTIFICATE 42 -#define SSL3_AD_UNSUPPORTED_CERTIFICATE 43 -#define SSL3_AD_CERTIFICATE_REVOKED 44 -#define SSL3_AD_CERTIFICATE_EXPIRED 45 -#define SSL3_AD_CERTIFICATE_UNKNOWN 46 -#define SSL3_AD_ILLEGAL_PARAMETER 47/* fatal */ - -#define SSL3_AL_WARNING 1 -#define SSL3_AL_FATAL 2 - -#define SSL3_VERSION 0x0300 - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_SSL3_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_dbg.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_dbg.h deleted file mode 100644 index 1d433e44a..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_dbg.h +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_dbg.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_DBG_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_DBG_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef CONFIG_OPENSSL_DEBUG_LEVEL -# define SSL_DEBUG_LEVEL CONFIG_OPENSSL_DEBUG_LEVEL -#else -# define SSL_DEBUG_LEVEL 0 -#endif - -#define SSL_DEBUG_ON (SSL_DEBUG_LEVEL + 1) -#define SSL_DEBUG_OFF (SSL_DEBUG_LEVEL - 1) - -#ifdef CONFIG_OPENSSL_DEBUG -# ifndef SSL_DEBUG_LOG -# error "SSL_DEBUG_LOG is not defined" -# endif - -# ifndef SSL_DEBUG_FL -# define SSL_DEBUG_FL "\n" -# endif - -# define SSL_SHOW_LOCATION() \ - SSL_DEBUG_LOG("SSL assert : %s %d\n", \ - __FILE__, __LINE__) - -# define SSL_DEBUG(level, fmt, ...) \ -{ \ - if (level > SSL_DEBUG_LEVEL) \ - { \ - SSL_DEBUG_LOG(fmt SSL_DEBUG_FL, ##__VA_ARGS__); \ - } \ -} -#else /* CONFIG_OPENSSL_DEBUG */ -# define SSL_SHOW_LOCATION() - -# define SSL_DEBUG(level, fmt, ...) -#endif /* CONFIG_OPENSSL_DEBUG */ - -/* OpenSSL assert function - * - * if select "CONFIG_OPENSSL_ASSERT_DEBUG", SSL_ASSERT* will show error - * file name and line - * if select "CONFIG_OPENSSL_ASSERT_EXIT", SSL_ASSERT* will just return - * error code. - * if select "CONFIG_OPENSSL_ASSERT_DEBUG_EXIT" SSL_ASSERT* will show error - * file name and line, then return error code. - * if select "CONFIG_OPENSSL_ASSERT_DEBUG_BLOCK", SSL_ASSERT* will show error - * file name and line, then block here with "while (1)" - * - * SSL_ASSERT1 may will return "-1", so function's return argument is - * integer. - * SSL_ASSERT2 may will return "NULL", so function's return argument is a - * point. - * SSL_ASSERT2 may will return nothing, so function's return argument is - * "void". - */ - -#if defined(CONFIG_OPENSSL_ASSERT_DEBUG) -# define SSL_ASSERT1(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - } \ -} - -# define SSL_ASSERT2(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - } \ -} - -# define SSL_ASSERT3(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - } \ -} -#elif defined(CONFIG_OPENSSL_ASSERT_EXIT) -# define SSL_ASSERT1(s) \ -{ \ - if (!(s)) \ - { \ - return -1; \ - } \ -} - -# define SSL_ASSERT2(s) \ -{ \ - if (!(s)) \ - { \ - return NULL; \ - } \ -} - -# define SSL_ASSERT3(s) \ -{ \ - if (!(s)) \ - { \ - return ; \ - } \ -} -#elif defined(CONFIG_OPENSSL_ASSERT_DEBUG_EXIT) -# define SSL_ASSERT1(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - return -1; \ - } \ -} - -# define SSL_ASSERT2(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - return NULL; \ - } \ -} - -# define SSL_ASSERT3(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - return ; \ - } \ -} -#elif defined(CONFIG_OPENSSL_ASSERT_DEBUG_BLOCK) -# define SSL_ASSERT1(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - while (1); \ - } \ -} - -# define SSL_ASSERT2(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - while (1); \ - } \ -} - -# define SSL_ASSERT3(s) \ -{ \ - if (!(s)) \ - { \ - SSL_SHOW_LOCATION(); \ - while (1); \ - } \ -} -#else -# define SSL_ASSERT1(s) -# define SSL_ASSERT2(s) -# define SSL_ASSERT3(s) -#endif - -#define SSL_PLATFORM_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_PLATFORM_ERROR_LEVEL SSL_DEBUG_ON - -#define SSL_CERT_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_CERT_ERROR_LEVEL SSL_DEBUG_ON - -#define SSL_PKEY_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_PKEY_ERROR_LEVEL SSL_DEBUG_ON - -#define SSL_X509_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_X509_ERROR_LEVEL SSL_DEBUG_ON - -#define SSL_LIB_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_LIB_ERROR_LEVEL SSL_DEBUG_ON - -#define SSL_STACK_DEBUG_LEVEL SSL_DEBUG_OFF -#define SSL_STACK_ERROR_LEVEL SSL_DEBUG_ON - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_DBG_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_local.h b/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_local.h deleted file mode 100644 index 082be2bcc..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_local.h +++ /dev/null @@ -1,148 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/ssl_local.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_LOCAL_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_LOCAL_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct record_layer_st -{ - int rstate; - int read_ahead; -}; - -struct ssl_ctx_st -{ - int version; - int references; - unsigned long options; - const SSL_METHOD *method; - CERT *cert; - X509 *client_CA; - const char **alpn_protos; - next_proto_cb alpn_cb; - int verify_mode; - int (*default_verify_callback) (int ok, X509_STORE_CTX *ctx); - long session_timeout; - int read_ahead; - int read_buffer_len; - X509_VERIFY_PARAM param; -}; - -struct ssl_method_func_st -{ - int (*ssl_new)(SSL *ssl); - void (*ssl_free)(SSL *ssl); - int (*ssl_handshake)(SSL *ssl); - int (*ssl_shutdown)(SSL *ssl); - int (*ssl_clear)(SSL *ssl); - int (*ssl_read)(SSL *ssl, void *buffer, int len); - int (*ssl_send)(SSL *ssl, const void *buffer, int len); - int (*ssl_pending)(const SSL *ssl); - void (*ssl_set_fd)(SSL *ssl, int fd, int mode); - int (*ssl_get_fd)(const SSL *ssl, int mode); - void (*ssl_set_bufflen)(SSL *ssl, int len); - long (*ssl_get_verify_result)(const SSL *ssl); - OSSL_HANDSHAKE_STATE (*ssl_get_state)(const SSL *ssl); -}; - -struct ssl_method_st -{ - /* protocol version(one of SSL3.0, TLS1.0, etc.) */ - - int version; - - /* SSL mode(client(0) , server(1), not known(-1)) */ - - int endpoint; - const SSL_METHOD_FUNC *func; -}; - -struct ssl_session_st -{ - long timeout; - long time; - X509 *peer; -}; - -struct ssl_st -{ -/* protocol version(one of SSL3.0, TLS1.0, etc.) */ - - int version; - unsigned long options; - -/* shut things down(0x01 : sent, 0x02 : received) */ - - int shutdown; - CERT *cert; - X509 *client_CA; - SSL_CTX *ctx; - const SSL_METHOD *method; - const char **alpn_protos; - RECORD_LAYER rlayer; - -/* where we are */ - - OSSL_STATEM statem; - SSL_SESSION *session; - int verify_mode; - int (*verify_callback) (int ok, X509_STORE_CTX *ctx); - int rwstate; - int interrupted_remaining_write; - long verify_result; - X509_VERIFY_PARAM param; - int err; - void (*info_callback) (const SSL *ssl, int type, int val); - -/* SSL low-level system arch point */ - - void *ssl_pm; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -CERT *__ssl_cert_new(CERT *ic); -CERT *ssl_cert_new(void); -void ssl_cert_free(CERT *cert); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_LOCAL_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/stack.h b/crypto/openssl_mbedtls_wrapper/include/openssl/stack.h deleted file mode 100644 index 9419b22db..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/stack.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/stack.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_STACK_H -#define OPENSSL_MBEDTLS_WRAPPER_STACK_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct stack_st -{ - char **data; - int num_alloc; - OPENSSL_sk_compfunc c; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc c); -OPENSSL_STACK *OPENSSL_sk_new_null(void); -void OPENSSL_sk_free(OPENSSL_STACK *stack); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_STACK_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/statem.h b/crypto/openssl_mbedtls_wrapper/include/openssl/statem.h deleted file mode 100644 index bdd6dd281..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/statem.h +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/statem.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_STATEM_H -#define OPENSSL_MBEDTLS_WRAPPER_STATEM_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef enum -{ -/* No handshake in progress */ - - MSG_FLOW_UNINITED, - -/* A permanent error with this connection */ - - MSG_FLOW_ERROR, - -/* We are about to renegotiate */ - - MSG_FLOW_RENEGOTIATE, - -/* We are reading messages */ - - MSG_FLOW_READING, - -/* We are writing messages */ - - MSG_FLOW_WRITING, - -/* Handshake has finished */ - - MSG_FLOW_FINISHED -} -MSG_FLOW_STATE; - -struct ossl_statem_st -{ - MSG_FLOW_STATE state; - int hand_state; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int ossl_statem_in_error(const SSL *ssl); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_STACK_H */ \ No newline at end of file diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/tls1.h b/crypto/openssl_mbedtls_wrapper/include/openssl/tls1.h deleted file mode 100644 index 3b0468221..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/tls1.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/tls1.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_TLS1_H -#define OPENSSL_MBEDTLS_WRAPPER_TLS1_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define TLS1_AD_DECRYPTION_FAILED 21 -#define TLS1_AD_RECORD_OVERFLOW 22 -#define TLS1_AD_UNKNOWN_CA 48/* fatal */ -#define TLS1_AD_ACCESS_DENIED 49/* fatal */ -#define TLS1_AD_DECODE_ERROR 50/* fatal */ -#define TLS1_AD_DECRYPT_ERROR 51 -#define TLS1_AD_EXPORT_RESTRICTION 60/* fatal */ -#define TLS1_AD_PROTOCOL_VERSION 70/* fatal */ -#define TLS1_AD_INSUFFICIENT_SECURITY 71/* fatal */ -#define TLS1_AD_INTERNAL_ERROR 80/* fatal */ -#define TLS1_AD_INAPPROPRIATE_FALLBACK 86/* fatal */ -#define TLS1_AD_USER_CANCELLED 90 -#define TLS1_AD_NO_RENEGOTIATION 100 -/* codes 110-114 are from RFC3546 */ -#define TLS1_AD_UNSUPPORTED_EXTENSION 110 -#define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111 -#define TLS1_AD_UNRECOGNIZED_NAME 112 -#define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113 -#define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114 -#define TLS1_AD_UNKNOWN_PSK_IDENTITY 115/* fatal */ -#define TLS1_AD_NO_APPLICATION_PROTOCOL 120/* fatal */ - -/* Special value for method supporting multiple versions */ -#define TLS_ANY_VERSION 0x10000 - -#define TLS1_VERSION 0x0301 -#define TLS1_1_VERSION 0x0302 -#define TLS1_2_VERSION 0x0303 - -#define SSL_TLSEXT_ERR_OK 0 -#define SSL_TLSEXT_ERR_NOACK 3 - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_TLS1_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/types.h b/crypto/openssl_mbedtls_wrapper/include/openssl/types.h deleted file mode 100644 index b66b2c6b7..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/types.h +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/types.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_TYPES_H -#define OPENSSL_MBEDTLS_WRAPPER_TYPES_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -typedef void SSL_CIPHER; -typedef void X509_STORE; - -typedef void RSA; -typedef void BIO; - -typedef int (*OPENSSL_sk_compfunc)(const void *, const void *); - -typedef struct stack_st OPENSSL_STACK; -typedef struct ssl_method_st SSL_METHOD; -typedef struct ssl_method_func_st SSL_METHOD_FUNC; -typedef struct record_layer_st RECORD_LAYER; -typedef struct ossl_statem_st OSSL_STATEM; -typedef struct ssl_session_st SSL_SESSION; -typedef struct ssl_ctx_st SSL_CTX; -typedef struct ssl_st SSL; -typedef struct cert_st CERT; -typedef struct x509_st X509; -typedef struct X509_VERIFY_PARAM_st X509_VERIFY_PARAM; -typedef struct evp_pkey_st EVP_PKEY; -typedef struct x509_method_st X509_METHOD; -typedef struct pkey_method_st PKEY_METHOD; - -#define ossl_inline inline -#define OPENSSL_NPN_NEGOTIATED 1 - -#define SSL_METHOD_CALL(f, s, ...) s->method->func->ssl_##f(s, ##__VA_ARGS__) -#define X509_METHOD_CALL(f, x, ...) x->method->x509_##f(x, ##__VA_ARGS__) -#define EVP_PKEY_METHOD_CALL(f, k, ...) k->method->pkey_##f(k, ##__VA_ARGS__) - -typedef int (*next_proto_cb)(SSL *ssl, unsigned char **out, - unsigned char *outlen, const unsigned char *in, - unsigned int inlen, void *arg); - -struct pkey_method_st -{ - int (*pkey_new)(EVP_PKEY *pkey, EVP_PKEY *m_pkey); - void (*pkey_free)(EVP_PKEY *pkey); - int (*pkey_load)(EVP_PKEY *pkey, const unsigned char *buf, int len); -}; - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_TYPES_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/x509.h b/crypto/openssl_mbedtls_wrapper/include/openssl/x509.h deleted file mode 100644 index d7d83847e..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/x509.h +++ /dev/null @@ -1,144 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/x509.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_X509_H -#define OPENSSL_MBEDTLS_WRAPPER_X509_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -struct x509_st -{ -/* X509 certification platform private point */ - - void *x509_pm; - const X509_METHOD *method; -}; - -struct x509_method_st -{ - int (*x509_new)(X509 *x, X509 *m_x); - void (*x509_free)(X509 *x); - int (*x509_load)(X509 *x, const unsigned char *buf, int len); - int (*x509_show_info)(X509 *x); -}; - -struct cert_st -{ - int sec_level; - X509 *x509; - EVP_PKEY *pkey; -}; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -void PKCS8_PRIV_KEY_INFO_free(PKCS8_PRIV_KEY_INFO *key); - -X509 *X509_new(void); - -void X509_free(X509 *a); - -void X509_ALGOR_free(X509_ALGOR *a); - -void X509_EXTENSION_free(X509_EXTENSION *a); - -void X509_NAME_free(X509_NAME *a); - -EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8); - -X509_ALGOR *X509_ALGOR_new(void); - -int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *obj, - int param_type, void *param_value); - -int X509_set1_signature_algo(X509 *x509, const X509_ALGOR *algo); - -int X509_set1_signature_value(X509 *x509, const uint8_t *sig, - size_t sig_len); - -X509_NAME *X509_NAME_new(void); - -int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid, - char *buf, int len); - -int X509_set_issuer_name(X509 *x509, X509_NAME *name); - -int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, - int type, const uint8_t *bytes, - int len, int loc, int set); - -X509_NAME *d2i_X509_NAME(X509_NAME **out, const uint8_t **inp, long len); - -X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, - int nid, int crit, - const ASN1_OCTET_STRING *data); - -int X509_set_version(X509 *x509, long version); - -int X509_set_serialNumber(X509 *x509, const ASN1_INTEGER *serial); - -int X509_set_subject_name(X509 *x509, X509_NAME *name); - -int X509_set_notBefore(X509 *x509, const ASN1_TIME *tm); - -int X509_set_notAfter(X509 *x509, const ASN1_TIME *tm); - -int X509_set_pubkey(X509 *x509, EVP_PKEY *pkey); - -int X509_add_ext(X509 *x, const X509_EXTENSION *ex, int loc); - -int X509_sign(X509 *x509, EVP_PKEY *pkey, const EVP_MD *md); - -int i2d_X509(X509 *x509, uint8_t **outp); - -PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO(PKCS8_PRIV_KEY_INFO *info, - const uint8_t **key_data, - size_t key_length); - -X509 *d2i_X509(X509 **out, const uint8_t **inp, long len); - -const char *X509_verify_cert_error_string(long n); - -X509 *__X509_new(X509 *ix); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_X509_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/x509_local.h b/crypto/openssl_mbedtls_wrapper/include/openssl/x509_local.h deleted file mode 100644 index ddecc6209..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/x509_local.h +++ /dev/null @@ -1,36 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/x509_local.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_X509_LOCAL_H -#define OPENSSL_MBEDTLS_WRAPPER_X509_LOCAL_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -struct X509_VERIFY_PARAM_st -{ - int depth; -}; - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_X509_LOCAL_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/x509_vfy.h b/crypto/openssl_mbedtls_wrapper/include/openssl/x509_vfy.h deleted file mode 100644 index 1cda9abd7..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/x509_vfy.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/x509_vfy.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_X509_VFY_H -#define OPENSSL_MBEDTLS_WRAPPER_X509_VFY_H - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define X509_V_OK 0 -#define X509_V_ERR_UNSPECIFIED 1 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 -#define X509_V_ERR_UNABLE_TO_GET_CRL 3 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 -#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 -#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 -#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 -#define X509_V_ERR_CERT_NOT_YET_VALID 9 -#define X509_V_ERR_CERT_HAS_EXPIRED 10 -#define X509_V_ERR_CRL_NOT_YET_VALID 11 -#define X509_V_ERR_CRL_HAS_EXPIRED 12 -#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 -#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 -#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 -#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 -#define X509_V_ERR_OUT_OF_MEM 17 -#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 -#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 -#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 -#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 -#define X509_V_ERR_CERT_REVOKED 23 -#define X509_V_ERR_INVALID_CA 24 -#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 -#define X509_V_ERR_INVALID_PURPOSE 26 -#define X509_V_ERR_CERT_UNTRUSTED 27 -#define X509_V_ERR_CERT_REJECTED 28 -/* These are 'informational' when looking for issuer cert */ -#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 -#define X509_V_ERR_AKID_SKID_MISMATCH 30 -#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 -#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 -#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 -#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 -#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 -#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 -#define X509_V_ERR_INVALID_NON_CA 37 -#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 -#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 -#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 -#define X509_V_ERR_INVALID_EXTENSION 41 -#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 -#define X509_V_ERR_NO_EXPLICIT_POLICY 43 -#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 -#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 -#define X509_V_ERR_UNNESTED_RESOURCE 46 -#define X509_V_ERR_PERMITTED_VIOLATION 47 -#define X509_V_ERR_EXCLUDED_VIOLATION 48 -#define X509_V_ERR_SUBTREE_MINMAX 49 -/* The application is not happy */ -#define X509_V_ERR_APPLICATION_VERIFICATION 50 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 -#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 -#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 -/* Another issuer check debug option */ -#define X509_V_ERR_PATH_LOOP 55 -/* Suite B mode algorithm violation */ -#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 -#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 -#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 -#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 -#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 -#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 -/* Host, email and IP check errors */ -#define X509_V_ERR_HOSTNAME_MISMATCH 62 -#define X509_V_ERR_EMAIL_MISMATCH 63 -#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 -/* DANE TLSA errors */ -#define X509_V_ERR_DANE_NO_MATCH 65 -/* security level errors */ -#define X509_V_ERR_EE_KEY_TOO_SMALL 66 -#define X509_V_ERR_CA_KEY_TOO_SMALL 67 -#define X509_V_ERR_CA_MD_TOO_WEAK 68 -/* Caller error */ -#define X509_V_ERR_INVALID_CALL 69 -/* Issuer lookup error */ -#define X509_V_ERR_STORE_LOOKUP 70 -/* Certificate transparency */ -#define X509_V_ERR_NO_VALID_SCTS 71 - -#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 - -typedef void X509_STORE_CTX; -int X509_STORE_CTX_get_error(X509_STORE_CTX *ctx); -int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_X509_VFY_H */ diff --git a/crypto/openssl_mbedtls_wrapper/include/openssl/x509v3.h b/crypto/openssl_mbedtls_wrapper/include/openssl/x509v3.h deleted file mode 100644 index e82e0231a..000000000 --- a/crypto/openssl_mbedtls_wrapper/include/openssl/x509v3.h +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/include/openssl/x509v3.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_X509V3_H -#define OPENSSL_MBEDTLS_WRAPPER_X509V3_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -extern "C" -{ -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_X509V3_H */ diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/aes.c b/crypto/openssl_mbedtls_wrapper/mbedtls/aes.c deleted file mode 100644 index 7cc64b634..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/aes.c +++ /dev/null @@ -1,208 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/aes.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx) -{ - mbedtls_cipher_init((mbedtls_cipher_context_t *)ctx); -} - -int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *ctx) -{ - mbedtls_cipher_free((mbedtls_cipher_context_t *)ctx); - return 1; -} - -const EVP_CIPHER *EVP_aes_128_ecb(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_128_ECB); -} - -const EVP_CIPHER *EVP_aes_192_ecb(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_192_ECB); -} - -const EVP_CIPHER *EVP_aes_256_ecb(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_256_ECB); -} - -const EVP_CIPHER *EVP_aes_128_cbc(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_128_CBC); -} - -const EVP_CIPHER *EVP_aes_192_cbc(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_192_CBC); -} - -const EVP_CIPHER *EVP_aes_256_cbc(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_256_CBC); -} - -const EVP_CIPHER *EVP_aes_128_ctr(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_128_CTR); -} - -const EVP_CIPHER *EVP_aes_192_ctr(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_192_CTR); -} - -const EVP_CIPHER *EVP_aes_256_ctr(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_256_CTR); -} - -const EVP_CIPHER *EVP_aes_128_gcm(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_128_GCM); -} - -const EVP_CIPHER *EVP_aes_192_gcm(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_192_GCM); -} - -const EVP_CIPHER *EVP_aes_256_gcm(void) -{ - return (const EVP_CIPHER *)mbedtls_cipher_info_from_type( - MBEDTLS_CIPHER_AES_256_GCM); -} - -int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad) -{ - mbedtls_cipher_padding_t padding = MBEDTLS_PADDING_PKCS7; - if (pad == 0) - { - padding = MBEDTLS_PADDING_NONE; - } - - mbedtls_cipher_set_padding_mode((mbedtls_cipher_context_t *)c, padding); - return 1; -} - -int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, - ENGINE *impl, const unsigned char *key, - const unsigned char *iv, int enc) -{ - mbedtls_cipher_context_t *ctx_ = (mbedtls_cipher_context_t *)ctx; - mbedtls_cipher_set_padding_mode(ctx_, MBEDTLS_PADDING_PKCS7); - const mbedtls_operation_t operation = enc - ? MBEDTLS_ENCRYPT : MBEDTLS_DECRYPT; - int ret = mbedtls_cipher_setup(ctx_, - (mbedtls_cipher_info_t *)cipher); - if (ret != 0) - { - goto error; - } - - ret = mbedtls_cipher_setkey(ctx_, key, - mbedtls_cipher_get_key_bitlen(ctx_), - operation); - if (ret != 0) - { - goto error; - } - - ret = mbedtls_cipher_set_iv(ctx_, iv, - mbedtls_cipher_get_iv_size(ctx_)); - if (ret != 0) - { - goto error; - } - - return 1; -error: - errno = ret; - return 0; -} - -int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, - const unsigned char *in, int inl) -{ - size_t out_len = 0; - int ret = mbedtls_cipher_update((mbedtls_cipher_context_t *)ctx, - in, inl, out, &out_len); - if (ret != 0) - { - errno = ret; - return 0; - } - - *outl = out_len; - return 1; -} - -int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, - unsigned char *outm, int *outl) -{ - size_t out_len = 0; - int ret = mbedtls_cipher_finish((mbedtls_cipher_context_t *)ctx, - outm, &out_len); - if (ret != 0) - { - errno = ret; - return 0; - } - - *outl = out_len; - return 1; -} - -EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) -{ - return (EVP_CIPHER_CTX *)(malloc(sizeof(mbedtls_cipher_context_t))); -} - -void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) -{ - if (ctx == NULL) - return; - - free(ctx); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/asn1.c b/crypto/openssl_mbedtls_wrapper/mbedtls/asn1.c deleted file mode 100644 index 7d33fd680..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/asn1.c +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/asn1.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void ASN1_TIME_free(ASN1_TIME *a) -{ -} - -void ASN1_INTEGER_free(ASN1_INTEGER *a) -{ -} - -void ASN1_OCTET_STRING_free(ASN1_OCTET_STRING *a) -{ -} - -void ASN1_BIT_STRING_free(ASN1_BIT_STRING *a) -{ -} - -ASN1_TIME *ASN1_TIME_new(void) -{ - return NULL; -} - -ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t) -{ - return NULL; -} - -int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *str, int n, int value) -{ - return 0; -} - -int i2d_ASN1_BIT_STRING(const ASN1_BIT_STRING *in, uint8_t **outp) -{ - return 0; -} - -ASN1_OCTET_STRING *ASN1_OCTET_STRING_new(void) -{ - return NULL; -} - -int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, - const unsigned char *data, int len) -{ - return 0; -} - -ASN1_INTEGER *ASN1_INTEGER_new(void) -{ - return NULL; -} - -ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai) -{ - return NULL; -} - -ASN1_BIT_STRING *ASN1_BIT_STRING_new(void) -{ - return NULL; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/bn.c b/crypto/openssl_mbedtls_wrapper/mbedtls/bn.c deleted file mode 100644 index 3a8dfdc73..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/bn.c +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/bn.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) -{ - return NULL; -} - -int BN_one(BIGNUM *bn) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/bytestring.c b/crypto/openssl_mbedtls_wrapper/mbedtls/bytestring.c deleted file mode 100644 index c6866bafe..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/bytestring.c +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/bytestring.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) -{ - return 0; -} - -void CBB_cleanup(CBB *cbb) -{ -} - -int CBB_init(CBB *cbb, size_t initial_capacity) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/cipher.c b/crypto/openssl_mbedtls_wrapper/mbedtls/cipher.c deleted file mode 100644 index 8b4a202c1..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/cipher.c +++ /dev/null @@ -1,172 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/cipher.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER * cipher, - ENGINE *impl, const uint8_t *key, const uint8_t *iv) -{ - mbedtls_cipher_context_t *m_ctx = (mbedtls_cipher_context_t *)ctx; - mbedtls_cipher_init(m_ctx); - mbedtls_cipher_setup(m_ctx, (const mbedtls_cipher_info_t *)cipher); - mbedtls_cipher_setkey(m_ctx, key, m_ctx->cipher_info->key_bitlen, - MBEDTLS_DECRYPT); - mbedtls_cipher_set_iv(m_ctx, iv, m_ctx->cipher_info->iv_size); - return 1; -} - -int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len, - const uint8_t *in, int in_len) -{ - size_t len = 0; - int ret = mbedtls_cipher_update((mbedtls_cipher_context_t *)ctx, - in, in_len, out, &len); - *out_len = len; - return !ret; -} - -int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) -{ - size_t len = 0; - int ret = mbedtls_cipher_finish((mbedtls_cipher_context_t *)ctx, - out, &len); - *out_len = len; - return !ret; -} - -const EVP_CIPHER *EVP_des_ede(void) -{ - return NULL; -} - -const EVP_CIPHER *EVP_des_ede3(void) -{ - return NULL; -} - -const EVP_CIPHER *EVP_des_ede_cbc(void) -{ - return NULL; -} - -const EVP_CIPHER *EVP_des_ede3_cbc(void) -{ - return NULL; -} - -int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, - ENGINE *impl, const unsigned char *key, - const unsigned char *iv) -{ - mbedtls_cipher_context_t *m_ctx = (mbedtls_cipher_context_t *)ctx; - mbedtls_cipher_init(m_ctx); - if (mbedtls_cipher_setup(m_ctx, (const mbedtls_cipher_info_t *)type) != 0) - { - mbedtls_cipher_free(m_ctx); - return 0; - } - - if (mbedtls_cipher_setkey(m_ctx, key, - m_ctx->cipher_info->key_bitlen, - MBEDTLS_ENCRYPT) != 0) - { - mbedtls_cipher_free(m_ctx); - return 0; - } - - if (mbedtls_cipher_set_iv(m_ctx, iv, m_ctx->cipher_info->iv_size) != 0) - { - mbedtls_cipher_free(m_ctx); - return 0; - } - - return 1; -} - -int EVP_EncryptUpdate(EVP_CIPHER_CTX * ctx, uint8_t *out, int *out_len, - const uint8_t *in, int in_len) -{ - return !mbedtls_cipher_update((mbedtls_cipher_context_t *)ctx, - in, in_len, out, (size_t *)out_len); -} - -int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, - unsigned char *out, int *out_len) -{ - return !mbedtls_cipher_finish((mbedtls_cipher_context_t *)ctx, out, - (size_t *)out_len); -} - -void AES_cbc_encrypt(const uint8_t *in, uint8_t *out, size_t len, - const AES_KEY *key, uint8_t *ivec, const int enc) -{ - const mbedtls_aes_context *ctx = (const mbedtls_aes_context *)key; - mbedtls_aes_crypt_cbc((mbedtls_aes_context *)ctx, enc, len, ivec, in, out); -} - -int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int command, - int tag_len, void *tag) -{ - mbedtls_cipher_context_t *m_ctx = (mbedtls_cipher_context_t *)ctx; - int ret = 0; - if (command == EVP_CTRL_GCM_GET_TAG) - { - ret = mbedtls_cipher_write_tag(m_ctx, (unsigned char *)tag, tag_len); - } - else if (command == EVP_CTRL_GCM_SET_TAG) - { - ret = mbedtls_cipher_check_tag(m_ctx, - (const unsigned char *)tag, - tag_len); - } - - return !ret; -} - -int AES_set_encrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) -{ - return -1; -} - -int AES_set_decrypt_key(const uint8_t *key, unsigned bits, AES_KEY *aeskey) -{ - return -1; -} - -void AES_encrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) -{ -} - -void AES_decrypt(const uint8_t *in, uint8_t *out, const AES_KEY *key) -{ -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/curve25519.c b/crypto/openssl_mbedtls_wrapper/mbedtls/curve25519.c deleted file mode 100644 index db80f0bfe..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/curve25519.c +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/curve25519.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void ED25519_keypair(uint8_t out_public_key[32], - uint8_t out_private_key[64]) -{ -} - -void X25519_keypair(uint8_t out_public_value[32], - uint8_t out_private_key[32]) -{ -} - -int X25519(uint8_t out_shared_key[32], - const uint8_t private_key[32], - const uint8_t peer_public_value[32]) -{ - return 0; -} - -void ED25519_keypair_from_seed(uint8_t out_public_key[32], - uint8_t out_private_key[64], - const uint8_t seed[32]) -{ -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/digest.c b/crypto/openssl_mbedtls_wrapper/mbedtls/digest.c deleted file mode 100644 index 14e85b533..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/digest.c +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/digest.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -EVP_MD_CTX *EVP_MD_CTX_new(void) -{ - mbedtls_md_context_t *ctx = - (mbedtls_md_context_t *)malloc(sizeof(mbedtls_md_context_t)); - EVP_MD_CTX_init((EVP_MD_CTX *)ctx); - return (EVP_MD_CTX *)ctx; -} - -void EVP_MD_CTX_free(EVP_MD_CTX *ctx) -{ - if (ctx != NULL) - { - EVP_MD_CTX_cleanup(ctx); - free(ctx); - } -} - -const EVP_MD *EVP_md5(void) -{ - return NULL; -} - -int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type, ENGINE *engine) -{ - mbedtls_md_context_t *m_ctx = (mbedtls_md_context_t *)ctx; - if (mbedtls_md_setup(m_ctx, (const mbedtls_md_info_t *)type, 0) != 0) - { - return 0; - } - - if (mbedtls_md_starts(m_ctx) != 0) - { - return 0; - } - - return 1; -} - -int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) -{ - if (mbedtls_md_update((mbedtls_md_context_t *)ctx, - (const unsigned char *)data, len) != 0) - { - return 0; - } - - return 1; -} - -int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, uint8_t *md_out, - unsigned int *size) -{ - const mbedtls_md_info_t *md_info = ((mbedtls_md_context_t *)ctx)->md_info; - if (md_info == NULL) - { - return 0; - } - - *size = mbedtls_md_get_size(md_info); - if (mbedtls_md_finish((mbedtls_md_context_t *)ctx, md_out) != 0) - { - return 0; - } - - return 1; -} - -int EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx) -{ - mbedtls_md_free((mbedtls_md_context_t *)ctx); - return 1; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ec.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ec.c deleted file mode 100644 index 9e07cea95..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ec.c +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ec.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void EC_KEY_free(EC_KEY *a) -{ -} - -EC_GROUP *EC_GROUP_new_by_curve_name(int nid) -{ - return NULL; -} - -void EC_GROUP_free(EC_GROUP *a) -{ -} - -int EC_GROUP_get_curve_name(const EC_GROUP *group) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ec_key.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ec_key.c deleted file mode 100644 index c5e26b2f2..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ec_key.c +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ec_key.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int EC_KEY_check_key(const EC_KEY *key) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ecdsa.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ecdsa.c deleted file mode 100644 index 76b1352d5..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ecdsa.c +++ /dev/null @@ -1,46 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ecdsa.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -size_t ECDSA_size(const EC_KEY *key) -{ - return 0; -} - -int ECDSA_sign(int type, const uint8_t *digest, size_t digest_len, - uint8_t *sig, unsigned int *sig_len, const EC_KEY *key) -{ - return 0; -} - -int ECDSA_verify(int type, const uint8_t *digest, size_t digest_len, - const uint8_t *sig, size_t sig_len, const EC_KEY *key) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/engine.c b/crypto/openssl_mbedtls_wrapper/mbedtls/engine.c deleted file mode 100644 index 81d736640..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/engine.c +++ /dev/null @@ -1,33 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/engine.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void ENGINE_free(ENGINE *a) -{ -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/err.c b/crypto/openssl_mbedtls_wrapper/mbedtls/err.c deleted file mode 100644 index d69459217..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/err.c +++ /dev/null @@ -1,42 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/err.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -unsigned long ERR_peek_last_error() -{ - return errno; -} - -void ERR_error_string_n(unsigned long e, char *buf, size_t len) -{ - mbedtls_strerror(e, buf, len); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/evp.c b/crypto/openssl_mbedtls_wrapper/mbedtls/evp.c deleted file mode 100644 index 1f2b8af6c..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/evp.c +++ /dev/null @@ -1,344 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/evp.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include "ssl_port.h" - -#include -#include -#include - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -EVP_PKEY *__EVP_PKEY_new(EVP_PKEY *ipk) -{ - int ret; - EVP_PKEY *pkey; - - pkey = ssl_mem_zalloc(sizeof(EVP_PKEY)); - if (!pkey) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "no enough memory > (pkey)"); - goto no_mem; - } - - if (ipk) - { - pkey->method = ipk->method; - } - else - { - pkey->method = EVP_PKEY_method(); - } - - ret = EVP_PKEY_METHOD_CALL(new, pkey, ipk); - if (ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "EVP_PKEY_METHOD_CALL(new) return %d", ret); - goto failed; - } - - return pkey; - -failed: - ssl_mem_free(pkey); -no_mem: - return NULL; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int EVP_PKEY_id(const EVP_PKEY *pkey) -{ - const mbedtls_pk_context *mbedtls_pkey = (const mbedtls_pk_context *)pkey; - return mbedtls_pk_get_type(mbedtls_pkey); -} - -RSA *EVP_PKEY_get1_RSA(const EVP_PKEY *pkey) -{ - mbedtls_pk_context *mbedtls_pkey = (mbedtls_pk_context *)pkey; - if (pkey == NULL || mbedtls_pk_get_type(mbedtls_pkey) != MBEDTLS_PK_RSA) - { - return NULL; - } - - mbedtls_rsa_context *rsa = mbedtls_pk_rsa(* mbedtls_pkey); - return (RSA *)rsa; -} - -void EVP_PKEY_free(EVP_PKEY *pkey) -{ - SSL_ASSERT3(pkey); - - EVP_PKEY_METHOD_CALL(free, pkey); - - ssl_mem_free(pkey); -} - -int EVP_PKEY_type(int nid) -{ - return 0; -} - -EC_KEY *EVP_PKEY_get1_EC_KEY(const EVP_PKEY *pkey) -{ - return NULL; -} - -EVP_PKEY *EVP_PKEY_new(void) -{ - return __EVP_PKEY_new(NULL); -} - -int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key) -{ - return 0; -} - -void EVP_MD_CTX_init(EVP_MD_CTX *ctx) -{ - mbedtls_md_init((mbedtls_md_context_t *)ctx); -} - -EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *unused, - const uint8_t *in, size_t len) -{ - return NULL; -} - -const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key) -{ - return NULL; -} - -EC_KEY *EC_KEY_new(void) -{ - return NULL; -} - -void EC_GROUP_set_point_conversion_form(EC_GROUP *group, - point_conversion_form_t form) -{ -} - -void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag) -{ -} - -int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group) -{ - return 0; -} - -int EC_KEY_generate_key(EC_KEY *key) -{ - return 0; -} - -BIGNUM *BN_new(void) -{ - return NULL; -} - -void BN_free(BIGNUM *bn) -{ -} - -int BN_set_word(BIGNUM *bn, BN_ULONG value) -{ - return 0; -} - -BN_ULONG BN_get_word(const BIGNUM *bn) -{ - return 0; -} - -int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const uint8_t *sig, - size_t sig_len) -{ - return 0; -} - -int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) -{ - return 0; -} - -int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) -{ - return 0; -} - -int EVP_DigestSignFinal(EVP_MD_CTX *ctx, uint8_t *out_sig, - size_t *out_sig_len) -{ - return 0; -} - -int i2d_PUBKEY(const EVP_PKEY *pkey, uint8_t **outp) -{ - return 0; -} - -EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **out, - const uint8_t **inp, long len) -{ - return NULL; -} - -int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, EC_KEY *key) -{ - return 0; -} - -int EVP_PKEY_bits(const EVP_PKEY *pkey) -{ - return 0; -} - -int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx, - const EVP_MD *type, ENGINE *e, EVP_PKEY *pkey) -{ - return 0; -} - -int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t len) -{ - return 0; -} - -int EVP_marshal_private_key(CBB *cbb, const EVP_PKEY *key) -{ - return 0; -} - -int EVP_DigestSign(EVP_MD_CTX *ctx, uint8_t *out_sig, size_t *out_sig_len, - const uint8_t *data, size_t data_len) -{ - return 0; -} - -int EVP_PKEY_size(const EVP_PKEY *pkey) -{ - return 0; -} - -int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) -{ - return 0; -} - -int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int padding) -{ - return 0; -} - -int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int salt_len) -{ - return 0; -} - -int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md) -{ - return 0; -} - -EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e) -{ - return NULL; -} - -int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx) -{ - return 0; -} - -int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len, - const uint8_t *in, size_t in_len) -{ - return 0; -} - -int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx) -{ - return 0; -} - -int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx, uint8_t *out, size_t *out_len, - const uint8_t *in, size_t in_len) -{ - return 0; -} - -void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx) -{ -} - -int i2d_PrivateKey(const EVP_PKEY *key, uint8_t **outp) -{ - return 0; -} - -int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx) -{ - return 0; -} - -int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer) -{ - return 0; -} - -int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, uint8_t *key, size_t *out_key_len) -{ - return 0; -} - -int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, - uint8_t *out, size_t *out_len) -{ - return 0; -} - -EVP_PKEY *d2i_PUBKEY(EVP_PKEY **out, const uint8_t **inp, long len) -{ - return NULL; -} - -int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, - uint8_t *out, size_t *out_len) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/hkdf.c b/crypto/openssl_mbedtls_wrapper/mbedtls/hkdf.c deleted file mode 100644 index 305e1a1c4..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/hkdf.c +++ /dev/null @@ -1,45 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/hkdf.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int HKDF_extract(uint8_t *out_key, size_t *out_len, - const EVP_MD *digest, const uint8_t *secret, - size_t secret_len, const uint8_t *salt, - size_t salt_len) -{ - return 0; -} - -int HKDF_expand(uint8_t *out_key, size_t out_len, - const EVP_MD *digest, const uint8_t *prk, - size_t prk_len, const uint8_t *info, - size_t info_len) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/hmac.c b/crypto/openssl_mbedtls_wrapper/mbedtls/hmac.c deleted file mode 100644 index 0b16617fd..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/hmac.c +++ /dev/null @@ -1,168 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/hmac.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -uint8_t *HMAC(const EVP_MD *evp_md, const void *key, - size_t key_len, const uint8_t *data, - size_t data_len, uint8_t *out, - unsigned int *out_len) -{ - if (mbedtls_md_hmac((const mbedtls_md_info_t *)evp_md, - (const unsigned char *)key, key_len, data, data_len, - out) != 0) - { - return NULL; - } - - if (out_len != NULL) - { - *out_len = mbedtls_md_get_size((const mbedtls_md_info_t *)evp_md); - } - - return out; -} - -HMAC_CTX *HMAC_CTX_new(void) -{ - mbedtls_md_context_t *ctx = - (mbedtls_md_context_t *)malloc(sizeof(mbedtls_md_context_t)); - if (ctx != NULL) - { - mbedtls_md_init(ctx); - } - - return (HMAC_CTX *)ctx; -} - -void HMAC_CTX_init(HMAC_CTX *ctx) -{ - mbedtls_md_init((mbedtls_md_context_t *)ctx); -} - -int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, size_t key_len, - const EVP_MD *md, ENGINE *impl) -{ - int ret = mbedtls_md_setup((mbedtls_md_context_t *)ctx, - (const mbedtls_md_info_t *)md, 1); - if (ret != 0) - { - goto error; - } - - ret = mbedtls_md_hmac_starts((mbedtls_md_context_t *)ctx, - (const unsigned char *)key, key_len); - if (ret != 0) - { - goto error; - } - - return 1; -error: - errno = ret; - return 0; -} - -int HMAC_Update(HMAC_CTX *ctx, const uint8_t *data, size_t data_len) -{ - errno = mbedtls_md_hmac_update((mbedtls_md_context_t *)ctx, - data, data_len); - return !errno; -} - -int HMAC_Final(HMAC_CTX *ctx, uint8_t *out, unsigned int *out_len) -{ - size_t md_size; - - const mbedtls_md_info_t *md_info = - ((mbedtls_md_context_t *)(ctx))->md_info; - if (md_info == NULL) - { - return 0; - } - - md_size = mbedtls_md_get_size(md_info); - *out_len = md_size; - errno = mbedtls_md_hmac_finish((mbedtls_md_context_t *)ctx, out); - return !errno; -} - -void HMAC_CTX_cleanup(HMAC_CTX *ctx) -{ - mbedtls_md_free((mbedtls_md_context_t *)ctx); -} - -void HMAC_CTX_free(HMAC_CTX *ctx) -{ - mbedtls_md_free((mbedtls_md_context_t *)ctx); - free(ctx); -} - -size_t EVP_MD_size(const EVP_MD *md) -{ - return mbedtls_md_get_size((const mbedtls_md_info_t *)md); -} - -const EVP_MD *EVP_sha1() -{ - const mbedtls_md_info_t *md_info = - mbedtls_md_info_from_type(MBEDTLS_MD_SHA1); - return (const EVP_MD *)md_info; -} - -const EVP_MD *EVP_sha224() -{ - const mbedtls_md_info_t *md_info = - mbedtls_md_info_from_type(MBEDTLS_MD_SHA224); - return (const EVP_MD *)md_info; -} - -const EVP_MD *EVP_sha256() -{ - const mbedtls_md_info_t *md_info = - mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); - return (const EVP_MD *)md_info; -} - -const EVP_MD *EVP_sha384() -{ - const mbedtls_md_info_t *md_info = - mbedtls_md_info_from_type(MBEDTLS_MD_SHA384); - return (const EVP_MD *)md_info; -} - -const EVP_MD *EVP_sha512() -{ - const mbedtls_md_info_t *md_info = - mbedtls_md_info_from_type(MBEDTLS_MD_SHA512); - return (const EVP_MD *)md_info; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/md5.c b/crypto/openssl_mbedtls_wrapper/mbedtls/md5.c deleted file mode 100644 index 7f32322ff..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/md5.c +++ /dev/null @@ -1,41 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/md5.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -uint8_t *MD5(const uint8_t *data, size_t len, - uint8_t out[MD5_DIGEST_LENGTH]) -{ - if (mbedtls_md5(data, len, out) != 0) - { - return NULL; - } - - return out; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/mem.c b/crypto/openssl_mbedtls_wrapper/mbedtls/mem.c deleted file mode 100644 index 3d8776105..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/mem.c +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/mem.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) -{ - return mbedtls_ct_memcmp(in_a, in_b, len); -} - -void OPENSSL_free(void *ptr) -{ -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/obj.c b/crypto/openssl_mbedtls_wrapper/mbedtls/obj.c deleted file mode 100644 index 11b7e2d8a..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/obj.c +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/obj.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -ASN1_OBJECT *OBJ_nid2obj(int nid) -{ - return NULL; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/pbkdf.c b/crypto/openssl_mbedtls_wrapper/mbedtls/pbkdf.c deleted file mode 100644 index b36e58a65..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/pbkdf.c +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/pbkdf.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int PKCS5_PBKDF2_HMAC(const char *password, size_t password_len, - const uint8_t *salt, size_t salt_len, - unsigned iterations, const EVP_MD *digest, - size_t key_len, uint8_t *out_key) -{ - mbedtls_md_context_t md_ctx; - int generate_result = 0; - int ret = 0; - mbedtls_md_init(&md_ctx); - ret = mbedtls_md_setup(&md_ctx, (const mbedtls_md_info_t *)digest, 1); - if (ret == 0 - && mbedtls_pkcs5_pbkdf2_hmac(&md_ctx, - (const unsigned char *)password, - password_len, salt, salt_len, - iterations, key_len, out_key) == 0) - { - generate_result = 1; - } - - mbedtls_md_free(&md_ctx); - return generate_result; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/rand.c b/crypto/openssl_mbedtls_wrapper/mbedtls/rand.c deleted file mode 100644 index 7266ef7e0..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/rand.c +++ /dev/null @@ -1,71 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/rand.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/* RAND_bytes() generates num random bytes using a - * cryptographically secure pseudo random generator - * (CSPRNG) and stores them in buf. - * - * @param buf the buffer to contains the generated random data - * @param num the length of the generated random data - * @return return 1 on success, other value on failure - */ - -int RAND_bytes(unsigned char *buf, int num) -{ - int ret; - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; - const char *keymaster_personalization = - "softkeymaster_random_generator"; - mbedtls_entropy_init(&entropy); - mbedtls_ctr_drbg_init(&ctr_drbg); - - ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, - &entropy, (const unsigned char *)keymaster_personalization, - strlen(keymaster_personalization)) == 0 - && mbedtls_ctr_drbg_random(&ctr_drbg, buf, num) == 0 ? 1 : 0; - mbedtls_ctr_drbg_free(&ctr_drbg); - mbedtls_entropy_free(&entropy); - return ret; -} - -/* RAND_add method using to seed the random generator - * This function also do nothing on android - * https://github.com/google/boringssl/blob/ - * 94b477cea5057d9372984a311aba9276f737f748/ - * crypto/rand_extra/rand_extra.c#L39 - */ - -void RAND_add(const void *buf, int num, double randomness) -{ -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/rsa.c b/crypto/openssl_mbedtls_wrapper/mbedtls/rsa.c deleted file mode 100644 index 8b9741e50..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/rsa.c +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/rsa.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -unsigned RSA_size(const RSA *rsa) -{ - return (mbedtls_rsa_get_len((const mbedtls_rsa_context *)rsa) + 7) / 8; -} - -const BIGNUM *RSA_get0_e(const RSA *rsa) -{ - return NULL; -} - -RSA *RSA_new(void) -{ - return NULL; -} - -void RSA_free(RSA *rsa) -{ -} - -int RSA_generate_key_ex(RSA *rsa, int bits, - const BIGNUM *e_value, BN_GENCB *cb) -{ - return 0; -} - -int RSA_private_encrypt(size_t flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding) -{ - return 0; -} - -int RSA_public_decrypt(size_t flen, const uint8_t *from, - uint8_t *to, RSA *rsa, int padding) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/sha.c b/crypto/openssl_mbedtls_wrapper/mbedtls/sha.c deleted file mode 100644 index 4541332fb..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/sha.c +++ /dev/null @@ -1,74 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/sha.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int SHA1_Init(SHA_CTX *sha) -{ - mbedtls_sha1_init((mbedtls_sha1_context *)sha); - mbedtls_sha1_starts((mbedtls_sha1_context *)sha); - return 0; -} - -int SHA1_Update(SHA_CTX *sha, const void *data, size_t len) -{ - return mbedtls_sha1_update((mbedtls_sha1_context *)sha, data, len); -} - -int SHA1_Final(uint8_t out[SHA_DIGEST_LENGTH], SHA_CTX *sha) -{ - return mbedtls_sha1_finish((mbedtls_sha1_context *)sha, - (unsigned char *)out); -} - -uint8_t *SHA1(const uint8_t *data, size_t len, - uint8_t out[SHA_DIGEST_LENGTH]) -{ - if (mbedtls_sha1(data, len, out) != 0) - { - return NULL; - } - - return out; -} - -int SHA256_Init(SHA256_CTX *sha) -{ - return 0; -} - -int SHA256_Update(SHA256_CTX *sha, const void *data, size_t len) -{ - return 0; -} - -int SHA256_Final(uint8_t out[SHA256_DIGEST_LENGTH], SHA256_CTX *sha) -{ - return 0; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_cert.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_cert.c deleted file mode 100644 index 49f05b5da..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_cert.c +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_cert.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -#include -#include -#include -#include -#include -#include "ssl_port.h" - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -CERT *__ssl_cert_new(CERT *ic) -{ - CERT *cert; - - X509 *ix; - EVP_PKEY *ipk; - - cert = ssl_mem_zalloc(sizeof(CERT)); - if (!cert) - { - SSL_DEBUG(SSL_CERT_ERROR_LEVEL, "no enough memory > (cert)"); - goto no_mem; - } - - if (ic) - { - ipk = ic->pkey; - ix = ic->x509; - } - else - { - ipk = NULL; - ix = NULL; - } - - cert->pkey = __EVP_PKEY_new(ipk); - if (!cert->pkey) - { - SSL_DEBUG(SSL_CERT_ERROR_LEVEL, "__EVP_PKEY_new() return NULL"); - goto pkey_err; - } - - cert->x509 = __X509_new(ix); - if (!cert->x509) - { - SSL_DEBUG(SSL_CERT_ERROR_LEVEL, "__X509_new() return NULL"); - goto x509_err; - } - - return cert; - -x509_err: - EVP_PKEY_free(cert->pkey); -pkey_err: - ssl_mem_free(cert); -no_mem: - return NULL; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x) -{ - SSL_ASSERT1(ctx); - SSL_ASSERT1(x); - assert(ctx); - if (ctx->client_CA == x) - { - return 1; - } - - X509_free(ctx->client_CA); - ctx->client_CA = x; - return 1; -} - -int SSL_CTX_add_client_CA_ASN1(SSL_CTX *ctx, int len, - const unsigned char *d) -{ - X509 *x; - - x = d2i_X509(NULL, &d, len); - if (!x) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_X509() return NULL"); - return 0; - } - - SSL_ASSERT1(ctx); - X509_free(ctx->client_CA); - ctx->client_CA = x; - - return 1; -} - -CERT *ssl_cert_new(void) -{ - return __ssl_cert_new(NULL); -} - -void ssl_cert_free(CERT *cert) -{ - SSL_ASSERT3(cert); - - X509_free(cert->x509); - - EVP_PKEY_free(cert->pkey); - - ssl_mem_free(cert); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_lib.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_lib.c deleted file mode 100644 index 7f289247d..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_lib.c +++ /dev/null @@ -1,1015 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_lib.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include "ssl_port.h" - -#define SSL_SEND_DATA_MAX_LENGTH 1460 - -struct alpn_ctx -{ - unsigned char data[23]; - unsigned char len; -}; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static SSL_SESSION *SSL_SESSION_new(void) -{ - SSL_SESSION *session; - - session = ssl_mem_zalloc(sizeof(SSL_SESSION)); - if (!session) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "no enough memory > (session)"); - goto failed1; - } - - session->peer = X509_new(); - if (!session->peer) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "X509_new() return NULL"); - goto failed2; - } - - return session; - -failed2: - ssl_mem_free(session); -failed1: - return NULL; -} - -static void SSL_SESSION_free(SSL_SESSION *session) -{ - X509_free(session->peer); - ssl_mem_free(session); -} - -static void -_openssl_alpn_to_mbedtls(struct alpn_ctx *ac, char ***palpn_protos) -{ - unsigned char *p = ac->data; - unsigned char *q; - unsigned char len; - char **alpn_protos; - int count = 0; - - /* find out how many entries he gave us */ - - len = *p++; - while (p - ac->data < ac->len) - { - if (len--) - { - p++; - continue; - } - - count++; - len = *p++; - if (!len) - { - break; - } - } - - if (!len) - { - count++; - } - - if (!count) - { - return; - } - - /* allocate space for count + 1 pointers and the data afterwards */ - - alpn_protos = ssl_mem_zalloc((count + 1) * sizeof(char *) + ac->len + 1); - if (!alpn_protos) - { - return; - } - - *palpn_protos = alpn_protos; - - /* convert to mbedtls format */ - - q = (unsigned char *)alpn_protos + (count + 1) * sizeof(char *); - p = ac->data; - count = 0; - - len = *p++; - alpn_protos[count] = (char *)q; - while (p - ac->data < ac->len) - { - if (len--) - { - *q++ = *p++; - continue; - } - - *q++ = '\0'; - count++; - len = *p++; - alpn_protos[count] = (char *)q; - if (!len) - { - break; - } - } - - if (!len) - { - *q++ = '\0'; - count++; - len = *p++; - alpn_protos[count] = (char *)q; - } - - alpn_protos[count] = NULL; /* last pointer ends list with NULL */ -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl) -{ - return &ssl->param; -} - -X509 *SSL_get_certificate(const SSL *ssl) -{ - SSL_ASSERT2(ssl); - - return ssl->cert->x509; -} - -X509 *SSL_get_peer_certificate(const SSL *ssl) -{ - SSL_ASSERT2(ssl); - - return ssl->session->peer; -} - -int SSL_want(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->rwstate; -} - -int SSL_want_nothing(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - if (ssl->err) - { - return 1; - } - - return (SSL_want(ssl) == SSL_NOTHING); -} - -int SSL_want_read(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - if (ssl->err) - { - return 0; - } - - return (SSL_want(ssl) == SSL_READING); -} - -int SSL_want_x509_lookup(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return (SSL_want(ssl) == SSL_WRITING); -} - -int SSL_get_error(const SSL *ssl, int ret_code) -{ - int ret = SSL_ERROR_SYSCALL; - - SSL_ASSERT1(ssl); - - if (ret_code > 0) - { - ret = SSL_ERROR_NONE; - } - else if (ret_code < 0) - { - if (ssl->err == SSL_ERROR_WANT_READ || SSL_want_read(ssl)) - { - ret = SSL_ERROR_WANT_READ; - } - else if (ssl->err == SSL_ERROR_WANT_WRITE || SSL_want_write(ssl)) - { - ret = SSL_ERROR_WANT_WRITE; - } - else - { - ret = SSL_ERROR_SYSCALL; - } - } - else - { - if (ssl->shutdown & SSL_RECEIVED_SHUTDOWN) - { - ret = SSL_ERROR_ZERO_RETURN; - } - else - { - ret = SSL_ERROR_SYSCALL; - } - } - - return ret; -} - -SSL_CTX *SSL_CTX_new(const SSL_METHOD *method, void *rngctx) -{ - SSL_CTX *ctx; - CERT *cert; - X509 *client_ca; - - if (!method) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "no no_method"); - return NULL; - } - - client_ca = X509_new(); - if (!client_ca) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "X509_new() return NULL"); - goto failed1; - } - - cert = ssl_cert_new(); - if (!cert) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "ssl_cert_new() return NULL"); - goto failed2; - } - - ctx = (SSL_CTX *)ssl_mem_zalloc(sizeof(SSL_CTX)); - if (!ctx) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "no enough memory > (ctx)"); - goto failed3; - } - - ctx->method = method; - ctx->client_CA = client_ca; - ctx->cert = cert; - ctx->version = method->version; - return ctx; - -failed3: - ssl_cert_free(cert); -failed2: - X509_free(client_ca); -failed1: - return NULL; -} - -void SSL_CTX_free(SSL_CTX *ctx) -{ - SSL_ASSERT3(ctx); - - ssl_cert_free(ctx->cert); - - X509_free(ctx->client_CA); - - if (ctx->alpn_protos) - { - ssl_mem_free(ctx->alpn_protos); - } - - ssl_mem_free(ctx); -} - -int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth) -{ - SSL_ASSERT1(ctx); - SSL_ASSERT1(meth); - - ctx->method = meth; - - ctx->version = meth->version; - - return 1; -} - -const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx) -{ - SSL_ASSERT2(ctx); - - return ctx->method; -} - -SSL *SSL_new(SSL_CTX *ctx) -{ - int ret = 0; - SSL *ssl; - - if (!ctx) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "no ctx"); - return NULL; - } - - ssl = (SSL *)ssl_mem_zalloc(sizeof(SSL)); - if (!ssl) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "no enough memory > (ssl)"); - goto failed1; - } - - ssl->session = SSL_SESSION_new(); - if (!ssl->session) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "SSL_SESSION_new() return NULL"); - goto failed2; - } - - ssl->cert = __ssl_cert_new(ctx->cert); - if (!ssl->cert) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "__ssl_cert_new() return NULL"); - goto failed3; - } - - ssl->client_CA = __X509_new(ctx->client_CA); - if (!ssl->client_CA) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "__X509_new() return NULL"); - goto failed4; - } - - ssl->ctx = ctx; - ssl->method = ctx->method; - - ssl->version = ctx->version; - ssl->options = ctx->options; - - ssl->verify_mode = ctx->verify_mode; - - ret = SSL_METHOD_CALL(new, ssl); - if (ret) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "SSL_METHOD_CALL(new) return %d", ret); - goto failed5; - } - - _ssl_set_alpn_list(ssl); - - ssl->rwstate = SSL_NOTHING; - - return ssl; - -failed5: - X509_free(ssl->client_CA); -failed4: - ssl_cert_free(ssl->cert); -failed3: - SSL_SESSION_free(ssl->session); -failed2: - ssl_mem_free(ssl); -failed1: - return NULL; -} - -void SSL_free(SSL *ssl) -{ - SSL_ASSERT3(ssl); - - SSL_METHOD_CALL(free, ssl); - - X509_free(ssl->client_CA); - - ssl_cert_free(ssl->cert); - - SSL_SESSION_free(ssl->session); - - if (ssl->alpn_protos) - { - ssl_mem_free(ssl->alpn_protos); - } - - ssl_mem_free(ssl); -} - -int SSL_do_handshake(SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_METHOD_CALL(handshake, ssl); - - return ret; -} - -int SSL_connect(SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return SSL_do_handshake(ssl); -} - -int SSL_accept(SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return SSL_do_handshake(ssl); -} - -int SSL_shutdown(SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - if (SSL_get_state(ssl) != TLS_ST_OK) - { - return 1; - } - - ret = SSL_METHOD_CALL(shutdown, ssl); - - return ret; -} - -int SSL_clear(SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_shutdown(ssl); - if (1 != ret) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "SSL_shutdown return %d", ret); - goto failed1; - } - - SSL_METHOD_CALL(free, ssl); - - ret = SSL_METHOD_CALL(new, ssl); - if (!ret) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "SSL_METHOD_CALL(new) return %d", ret); - goto failed1; - } - - return 1; - -failed1: - return ret; -} - -int SSL_read(SSL *ssl, void *buffer, int len) -{ - int ret; - - SSL_ASSERT1(ssl); - SSL_ASSERT1(buffer); - SSL_ASSERT1(len); - - ssl->rwstate = SSL_READING; - - ret = SSL_METHOD_CALL(read, ssl, buffer, len); - - if (ret == len) - { - ssl->rwstate = SSL_NOTHING; - } - - return ret; -} - -int SSL_write(SSL *ssl, const void *buffer, int len) -{ - int ret; - int send_bytes; - int bytes; - const unsigned char *pbuf; - - SSL_ASSERT1(ssl); - SSL_ASSERT1(buffer); - SSL_ASSERT1(len); - - ssl->rwstate = SSL_WRITING; - - send_bytes = len; - pbuf = (const unsigned char *)buffer; - - do - { - if (send_bytes > SSL_SEND_DATA_MAX_LENGTH) - { - bytes = SSL_SEND_DATA_MAX_LENGTH; - } - else - { - bytes = send_bytes; - } - - if (ssl->interrupted_remaining_write) - { - bytes = ssl->interrupted_remaining_write; - ssl->interrupted_remaining_write = 0; - } - - ret = SSL_METHOD_CALL(send, ssl, pbuf, bytes); - - /* the return is a NEGATIVE OpenSSL error code, or the length sent */ - - if (ret > 0) - { - pbuf += ret; - send_bytes -= ret; - } - else - { - ssl->interrupted_remaining_write = bytes; - } - } - while (ret > 0 && send_bytes && ret == bytes); - - if (ret >= 0) - { - ret = len - send_bytes; - if (!ret) - { - ssl->rwstate = SSL_NOTHING; - } - } - else - { - if (send_bytes == len) - { - ret = -1; - } - else - { - ret = len - send_bytes; - } - } - - return ret; -} - -SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl) -{ - SSL_ASSERT2(ssl); - - return ssl->ctx; -} - -const SSL_METHOD *SSL_get_ssl_method(SSL *ssl) -{ - SSL_ASSERT2(ssl); - - return ssl->method; -} - -int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method) -{ - int ret; - - SSL_ASSERT1(ssl); - SSL_ASSERT1(method); - - if (ssl->version != method->version) - { - ret = SSL_shutdown(ssl); - if (1 != ret) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, "SSL_shutdown return %d", ret); - goto failed1; - } - - SSL_METHOD_CALL(free, ssl); - - ssl->method = method; - - ret = SSL_METHOD_CALL(new, ssl); - if (!ret) - { - SSL_DEBUG(SSL_LIB_ERROR_LEVEL, - "SSL_METHOD_CALL(new) return %d", ret); - goto failed1; - } - } - else - { - ssl->method = method; - } - - return 1; - -failed1: - return ret; -} - -int SSL_get_shutdown(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->shutdown; -} - -void SSL_set_shutdown(SSL *ssl, int mode) -{ - SSL_ASSERT3(ssl); - - ssl->shutdown = mode; -} - -int SSL_pending(const SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_METHOD_CALL(pending, ssl); - - return ret; -} - -int SSL_has_pending(const SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - if (SSL_pending(ssl)) - { - ret = 1; - } - else - { - ret = 0; - } - - return ret; -} - -unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op) -{ - SSL_ASSERT1(ctx); - - return ctx->options &= ~op; -} - -unsigned long SSL_CTX_get_options(SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->options; -} - -unsigned long SSL_clear_options(SSL *ssl, unsigned long op) -{ - SSL_ASSERT1(ssl); - - return ssl->options & ~op; -} - -unsigned long SSL_get_options(SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->options; -} - -unsigned long SSL_set_options(SSL *ssl, unsigned long op) -{ - SSL_ASSERT1(ssl); - - return ssl->options |= op; -} - -int SSL_get_fd(const SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_METHOD_CALL(get_fd, ssl, 0); - - return ret; -} - -int SSL_get_rfd(const SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_METHOD_CALL(get_fd, ssl, 0); - - return ret; -} - -int SSL_get_wfd(const SSL *ssl) -{ - int ret; - - SSL_ASSERT1(ssl); - - ret = SSL_METHOD_CALL(get_fd, ssl, 0); - - return ret; -} - -int SSL_set_fd(SSL *ssl, int fd) -{ - SSL_ASSERT1(ssl); - SSL_ASSERT1(fd >= 0); - - SSL_METHOD_CALL(set_fd, ssl, fd, 0); - - return 1; -} - -int SSL_set_rfd(SSL *ssl, int fd) -{ - SSL_ASSERT1(ssl); - SSL_ASSERT1(fd >= 0); - - SSL_METHOD_CALL(set_fd, ssl, fd, 0); - - return 1; -} - -int SSL_set_wfd(SSL *ssl, int fd) -{ - SSL_ASSERT1(ssl); - SSL_ASSERT1(fd >= 0); - - SSL_METHOD_CALL(set_fd, ssl, fd, 0); - - return 1; -} - -int SSL_version(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->version; -} - -const char *SSL_alert_type_string(int value) -{ - const char *str; - - switch (value >> 8) - { - case SSL3_AL_WARNING: - str = "W"; - break; - case SSL3_AL_FATAL: - str = "F"; - break; - default: - str = "U"; - break; - } - - return str; -} - -void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len) -{ - SSL_ASSERT3(ctx); - - ctx->read_buffer_len = (int)len; -} - -void SSL_set_default_read_buffer_len(SSL *ssl, size_t len) -{ - SSL_ASSERT3(ssl); - SSL_ASSERT3(len); - - SSL_METHOD_CALL(set_bufflen, ssl, (int)len); -} - -void SSL_set_info_callback(SSL *ssl, - void (*cb) (const SSL *ssl, int type, int val)) -{ - SSL_ASSERT3(ssl); - - ssl->info_callback = cb; -} - -int SSL_CTX_up_ref(SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - /* no support multi-thread SSL here */ - - ctx->references++; - - return 1; -} - -void SSL_set_security_level(SSL *ssl, int level) -{ - SSL_ASSERT3(ssl); - - ssl->cert->sec_level = level; -} - -int SSL_get_security_level(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->cert->sec_level; -} - -int SSL_CTX_get_verify_mode(const SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->verify_mode; -} - -long SSL_CTX_set_timeout(SSL_CTX *ctx, long t) -{ - long l; - - SSL_ASSERT1(ctx); - - l = ctx->session_timeout; - ctx->session_timeout = t; - - return l; -} - -long SSL_CTX_get_timeout(const SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->session_timeout; -} - -void SSL_set_read_ahead(SSL *ssl, int yes) -{ - SSL_ASSERT3(ssl); - - ssl->rlayer.read_ahead = yes; -} - -void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes) -{ - SSL_ASSERT3(ctx); - - ctx->read_ahead = yes; -} - -int SSL_get_read_ahead(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->rlayer.read_ahead; -} - -long SSL_CTX_get_read_ahead(SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->read_ahead; -} - -long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->read_ahead; -} - -long SSL_set_time(SSL *ssl, long t) -{ - SSL_ASSERT1(ssl); - - ssl->session->time = t; - - return t; -} - -long SSL_set_timeout(SSL *ssl, long t) -{ - SSL_ASSERT1(ssl); - - ssl->session->timeout = t; - - return t; -} - -long SSL_get_verify_result(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return SSL_METHOD_CALL(get_verify_result, ssl); -} - -int SSL_CTX_get_verify_depth(const SSL_CTX *ctx) -{ - SSL_ASSERT1(ctx); - - return ctx->param.depth; -} - -void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth) -{ - SSL_ASSERT3(ctx); - - ctx->param.depth = depth; -} - -int SSL_get_verify_depth(const SSL *ssl) -{ - SSL_ASSERT1(ssl); - - return ssl->param.depth; -} - -void SSL_set_verify_depth(SSL *ssl, int depth) -{ - SSL_ASSERT3(ssl); - - ssl->param.depth = depth; -} - -void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, - int (*verify_callback)(int, X509_STORE_CTX *)) -{ - SSL_ASSERT3(ctx); - - ctx->verify_mode = mode; - ctx->default_verify_callback = verify_callback; -} - -void SSL_set_verify(SSL *ssl, int mode, - int (*verify_callback)(int, X509_STORE_CTX *)) -{ - SSL_ASSERT3(ssl); - - ssl->verify_mode = mode; - ssl->verify_callback = verify_callback; -} - -void *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx) -{ - return NULL; -} - -void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, next_proto_cb cb, void *arg) -{ - struct alpn_ctx *ac = arg; - - ctx->alpn_cb = cb; - - _openssl_alpn_to_mbedtls(ac, (char * **)&ctx->alpn_protos); -} - -void SSL_set_alpn_select_cb(SSL *ssl, void *arg) -{ - struct alpn_ctx *ac = arg; - - _openssl_alpn_to_mbedtls(ac, (char * **)&ssl->alpn_protos); - - _ssl_set_alpn_list(ssl); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.c deleted file mode 100644 index 981a20535..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.c +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include "ssl_methods.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/** - * TLS method function collection - */ - -IMPLEMENT_TLS_METHOD_FUNC(TLS_method_func, - ssl_pm_new, ssl_pm_free, - ssl_pm_handshake, ssl_pm_shutdown, ssl_pm_clear, - ssl_pm_read, ssl_pm_send, ssl_pm_pending, - ssl_pm_set_fd, ssl_pm_get_fd, - ssl_pm_set_bufflen, - ssl_pm_get_verify_result, - ssl_pm_get_state); - -/** - * TLS or SSL client method collection - */ - -IMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, 0, TLS_method_func, TLS_client_method); - -IMPLEMENT_TLS_METHOD(TLS1_2_VERSION, 0, - TLS_method_func, TLSv1_2_client_method); - -IMPLEMENT_TLS_METHOD(TLS1_1_VERSION, 0, - TLS_method_func, TLSv1_1_client_method); - -IMPLEMENT_TLS_METHOD(TLS1_VERSION, 0, TLS_method_func, TLSv1_client_method); - -IMPLEMENT_SSL_METHOD(SSL3_VERSION, 0, TLS_method_func, SSLv3_client_method); - -/** - * TLS or SSL server method collection - */ - -IMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, 1, TLS_method_func, TLS_server_method); - -IMPLEMENT_TLS_METHOD(TLS1_1_VERSION, 1, - TLS_method_func, TLSv1_1_server_method); - -IMPLEMENT_TLS_METHOD(TLS1_2_VERSION, 1, - TLS_method_func, TLSv1_2_server_method); - -IMPLEMENT_TLS_METHOD(TLS1_VERSION, 0, TLS_method_func, TLSv1_server_method); - -IMPLEMENT_SSL_METHOD(SSL3_VERSION, 1, TLS_method_func, SSLv3_server_method); - -/** - * TLS or SSL method collection - */ - -IMPLEMENT_TLS_METHOD(TLS_ANY_VERSION, -1, TLS_method_func, TLS_method); - -IMPLEMENT_SSL_METHOD(TLS1_2_VERSION, -1, TLS_method_func, TLSv1_2_method); - -IMPLEMENT_SSL_METHOD(TLS1_1_VERSION, -1, TLS_method_func, TLSv1_1_method); - -IMPLEMENT_SSL_METHOD(TLS1_VERSION, -1, TLS_method_func, TLSv1_method); - -IMPLEMENT_SSL_METHOD(SSL3_VERSION, -1, TLS_method_func, SSLv3_method); - -/** - * @brief get X509 object method - */ - -IMPLEMENT_X509_METHOD(X509_method, - x509_pm_new, x509_pm_free, - x509_pm_load, x509_pm_show_info); - -/** - * @brief get private key object method - */ - -IMPLEMENT_PKEY_METHOD(EVP_PKEY_method, - pkey_pm_new, pkey_pm_free, - pkey_pm_load); diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.h b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.h deleted file mode 100644 index 4b090f509..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.h +++ /dev/null @@ -1,141 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_methods.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_METHODS_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_METHODS_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include "ssl_pm.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* TLS method function implement */ - -#define IMPLEMENT_TLS_METHOD_FUNC(func_name, \ - new, free, \ - handshake, shutdown, clear, \ - read, send, pending, \ - set_fd, get_fd, \ - set_bufflen, \ - get_verify_result, \ - get_state) \ - static const SSL_METHOD_FUNC func_name LOCAL_ATRR = \ - { \ - new, \ - free, \ - handshake, \ - shutdown, \ - clear, \ - read, \ - send, \ - pending, \ - set_fd, \ - get_fd, \ - set_bufflen, \ - get_verify_result, \ - get_state \ - }; - -#define IMPLEMENT_TLS_METHOD(ver, mode, fun, func_name) \ - const SSL_METHOD* func_name(void) \ - { \ - static const SSL_METHOD func_name##_data LOCAL_ATRR = \ - { \ - ver, \ - mode, \ - &(fun), \ - }; \ - return &func_name##_data; \ - } - -#define IMPLEMENT_SSL_METHOD(ver, mode, fun, func_name) \ - const SSL_METHOD* func_name(void) \ - { \ - static const SSL_METHOD func_name##_data LOCAL_ATRR = \ - { \ - ver, \ - mode, \ - &(fun), \ - }; \ - return &func_name##_data; \ - } - -#define IMPLEMENT_X509_METHOD(func_name, \ - new, \ - free, \ - load, \ - show_info) \ - const X509_METHOD* func_name(void) \ - { \ - static const X509_METHOD func_name##_data LOCAL_ATRR = \ - { \ - new, \ - free, \ - load, \ - show_info \ - }; \ - return &func_name##_data; \ - } - -#define IMPLEMENT_PKEY_METHOD(func_name, \ - new, \ - free, \ - load) \ - const PKEY_METHOD* func_name(void) \ - { \ - static const PKEY_METHOD func_name##_data LOCAL_ATRR = \ - { \ - new, \ - free, \ - load \ - }; \ - return &func_name##_data; \ - } - -/** - * @brief get X509 object method - * - * @param none - * - * @return X509 object method point - */ - -const X509_METHOD *X509_method(void); - -/** - * @brief get private key object method - * - * @param none - * - * @return private key object method point - */ - -const PKEY_METHOD *EVP_PKEY_method(void); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_METHODS_H */ diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.c deleted file mode 100644 index 39cdabb12..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.c +++ /dev/null @@ -1,1076 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#include "ssl_pm.h" -#include "ssl_port.h" -#include -#include -#include -#include - -/* mbedtls include */ -#include "mbedtls/platform.h" -#include "mbedtls/net_sockets.h" -#include "mbedtls/debug.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/error.h" - -#define X509_INFO_STRING_LENGTH 8192 - -struct ssl_pm -{ - /* local socket file description */ - - mbedtls_net_context fd; - - /* remote client socket file description */ - - mbedtls_net_context cl_fd; - mbedtls_ssl_config conf; - mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; - mbedtls_entropy_context entropy; - SSL *owner; -}; - -struct x509_pm -{ - mbedtls_x509_crt *x509_crt; - mbedtls_x509_crt *ex_crt; -}; - -struct pkey_pm -{ - mbedtls_pk_context *pkey; - mbedtls_pk_context *ex_pkey; -}; - -unsigned int max_content_len; - -/* mbedtls debug level */ -#define MBEDTLS_DEBUG_LEVEL 4 - -/** - * @brief mbedtls debug function - */ - -static void ssl_platform_debug(void *ctx, int level, - const char *file, int line, - const char *str) -{ - /* Shorten 'file' from the whole file path to just the filename - - * This is a bit wasteful because the macros are compiled in with - * the full _FILE_ path in each case. - */ - - printf("%s:%d %s", file, line, str); -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/** - * @brief create SSL low-level object - */ - -int ssl_pm_new(SSL *ssl) -{ - struct ssl_pm *ssl_pm; - int ret; - - const unsigned char pers[] = "OpenSSL PM"; - size_t pers_len = sizeof(pers); - - int endpoint; - int version; - - const SSL_METHOD *method = ssl->method; - - ssl_pm = ssl_mem_zalloc(sizeof(struct ssl_pm)); - if (!ssl_pm) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (ssl_pm)"); - goto no_mem; - } - - ssl_pm->owner = ssl; - - if (!ssl->ctx->read_buffer_len) - { - ssl->ctx->read_buffer_len = 2048; - } - - max_content_len = ssl->ctx->read_buffer_len; - - mbedtls_net_init(&ssl_pm->fd); - mbedtls_net_init(&ssl_pm->cl_fd); - - mbedtls_ssl_config_init(&ssl_pm->conf); - mbedtls_ctr_drbg_init(&ssl_pm->ctr_drbg); - mbedtls_entropy_init(&ssl_pm->entropy); - mbedtls_ssl_init(&ssl_pm->ssl); - - ret = mbedtls_ctr_drbg_seed(&ssl_pm->ctr_drbg, mbedtls_entropy_func, - &ssl_pm->entropy, pers, pers_len); - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ctr_drbg_seed() return -0x%x", -ret); - goto mbedtls_err1; - } - - if (method->endpoint) - { - endpoint = MBEDTLS_SSL_IS_SERVER; - } - else - { - endpoint = MBEDTLS_SSL_IS_CLIENT; - } - - ret = mbedtls_ssl_config_defaults(&ssl_pm->conf, endpoint, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_config_defaults() return -0x%x", -ret); - goto mbedtls_err2; - } - - if (TLS_ANY_VERSION != ssl->version) - { - if (TLS1_2_VERSION == ssl->version) - { - version = MBEDTLS_SSL_MINOR_VERSION_3; - } - else if (TLS1_1_VERSION == ssl->version) - { - version = MBEDTLS_SSL_MINOR_VERSION_2; - } - else if (TLS1_VERSION == ssl->version) - { - version = MBEDTLS_SSL_MINOR_VERSION_1; - } - else - { - version = MBEDTLS_SSL_MINOR_VERSION_0; - } - - mbedtls_ssl_conf_max_version(&ssl_pm->conf, - MBEDTLS_SSL_MAJOR_VERSION_3, version); - mbedtls_ssl_conf_min_version(&ssl_pm->conf, - MBEDTLS_SSL_MAJOR_VERSION_3, version); - } - else - { - mbedtls_ssl_conf_max_version(&ssl_pm->conf, - MBEDTLS_SSL_MAJOR_VERSION_3, - MBEDTLS_SSL_MINOR_VERSION_3); - mbedtls_ssl_conf_min_version(&ssl_pm->conf, - MBEDTLS_SSL_MAJOR_VERSION_3, - MBEDTLS_SSL_MINOR_VERSION_0); - } - - mbedtls_ssl_conf_rng(&ssl_pm->conf, - mbedtls_ctr_drbg_random, &ssl_pm->ctr_drbg); - mbedtls_ssl_conf_dbg(&ssl_pm->conf, ssl_platform_debug, NULL); - - ret = mbedtls_ssl_setup(&ssl_pm->ssl, &ssl_pm->conf); - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_setup() return -0x%x", -ret); - goto mbedtls_err2; - } - - mbedtls_ssl_set_bio(&ssl_pm->ssl, &ssl_pm->fd, - mbedtls_net_send, mbedtls_net_recv, NULL); - - ssl->ssl_pm = ssl_pm; - - return 0; - -mbedtls_err2: - mbedtls_ssl_config_free(&ssl_pm->conf); - mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg); -mbedtls_err1: - mbedtls_entropy_free(&ssl_pm->entropy); - ssl_mem_free(ssl_pm); -no_mem: - return -1; -} - -/** - * @brief free SSL low-level object - */ - -void ssl_pm_free(SSL *ssl) -{ - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - mbedtls_ctr_drbg_free(&ssl_pm->ctr_drbg); - mbedtls_entropy_free(&ssl_pm->entropy); - mbedtls_ssl_config_free(&ssl_pm->conf); - mbedtls_ssl_free(&ssl_pm->ssl); - - ssl_mem_free(ssl_pm); - ssl->ssl_pm = NULL; -} - -/** - * @brief reload SSL low-level certification object - */ - -static int ssl_pm_reload_crt(SSL *ssl) -{ - int ret; - int mode; - struct ssl_pm *ssl_pm = ssl->ssl_pm; - struct x509_pm *ca_pm = (struct x509_pm *)ssl->client_CA->x509_pm; - - struct pkey_pm *pkey_pm = (struct pkey_pm *)ssl->cert->pkey->pkey_pm; - struct x509_pm *crt_pm = (struct x509_pm *)ssl->cert->x509->x509_pm; - - if (ssl->verify_mode == SSL_VERIFY_PEER) - { - mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - } - else if (ssl->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT) - { - mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - } - else if (ssl->verify_mode == SSL_VERIFY_CLIENT_ONCE) - { - mode = MBEDTLS_SSL_VERIFY_UNSET; - } - else - { - mode = MBEDTLS_SSL_VERIFY_NONE; - } - - mbedtls_ssl_conf_authmode(&ssl_pm->conf, mode); - - if (ca_pm->x509_crt) - { - mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->x509_crt, NULL); - } - else if (ca_pm->ex_crt) - { - mbedtls_ssl_conf_ca_chain(&ssl_pm->conf, ca_pm->ex_crt, NULL); - } - - if (crt_pm->x509_crt && pkey_pm->pkey) - { - ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, - crt_pm->x509_crt, pkey_pm->pkey); - } - else if (crt_pm->ex_crt && pkey_pm->ex_pkey) - { - ret = mbedtls_ssl_conf_own_cert(&ssl_pm->conf, - crt_pm->ex_crt, pkey_pm->ex_pkey); - } - else - { - ret = 0; - } - - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_conf_own_cert() return -0x%x", -ret); - ret = -1; - } - - return ret; -} - -/* Perform the mbedtls SSL handshake instead of mbedtls_ssl_handshake. - * We can add debug here. - */ - -static int mbedtls_handshake(mbedtls_ssl_context *ssl) -{ - int ret = 0; - - while (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) - { - ret = mbedtls_ssl_handshake_step(ssl); - - if (ret != 0) - { - break; - } - } - - return ret; -} - -int ssl_pm_handshake(SSL *ssl) -{ - int ret; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ssl->err = 0; - errno = 0; - - ret = ssl_pm_reload_crt(ssl); - if (ret) - { - printf("%s: cert reload failed\n", __func__); - return 0; - } - - if (ssl_pm->ssl.state != MBEDTLS_SSL_HANDSHAKE_OVER) - { - ssl_speed_up_enter(); - - /* mbedtls return codes - * 0 = successful, or MBEDTLS_ERR_SSL_WANT_READ/WRITE - * anything else = death - */ - - ret = mbedtls_handshake(&ssl_pm->ssl); - ssl_speed_up_exit(); - } - else - { - ret = 0; - } - - /* OpenSSL return codes: - * 0 = did not complete, but may be retried - * 1 = successfully completed - * <0 = death - */ - - if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) - { - ssl->err = ret; - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_handshake() return -0x%x", -ret); - return 0; /* OpenSSL: did not complete but may be retried */ - } - - if (ret == 0) - { - /* successful */ - - struct x509_pm *x509_pm = - (struct x509_pm *)ssl->session->peer->x509_pm; - - x509_pm->ex_crt = (mbedtls_x509_crt *) - mbedtls_ssl_get_peer_cert(&ssl_pm->ssl); - return 1; /* openssl successful */ - } - - if (errno == 11) - { - ssl->err = ret == MBEDTLS_ERR_SSL_WANT_READ; - - return 0; - } - - printf("%s: mbedtls_ssl_handshake() returned -0x%x\n", __func__, -ret); - - /* it's had it */ - - ssl->err = SSL_ERROR_SYSCALL; - - return -1; /* openssl death */ -} - -mbedtls_x509_crt * -ssl_ctx_get_mbedtls_x509_crt(SSL_CTX *ssl_ctx) -{ - struct x509_pm *x509_pm = (struct x509_pm *)ssl_ctx->cert->x509->x509_pm; - - if (!x509_pm) - { - return NULL; - } - - return x509_pm->x509_crt; -} - -mbedtls_x509_crt * -ssl_get_peer_mbedtls_x509_crt(SSL *ssl) -{ - struct x509_pm *x509_pm = (struct x509_pm *)ssl->session->peer->x509_pm; - - if (!x509_pm) - { - return NULL; - } - - return x509_pm->ex_crt; -} - -int ssl_pm_shutdown(SSL *ssl) -{ - int ret; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_close_notify(&ssl_pm->ssl); - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_close_notify() return -0x%x", -ret); - if (ret == MBEDTLS_ERR_NET_CONN_RESET) - { - ssl->err = SSL_ERROR_SYSCALL; - } - - ret = -1; /* OpenSSL: "Call SSL_get_error with the return value to find the reason */ - } - else - { - struct x509_pm *x509_pm = - (struct x509_pm *)ssl->session->peer->x509_pm; - - x509_pm->ex_crt = NULL; - ret = 1; /* OpenSSL: "The shutdown was successfully completed" - * ...0 means retry */ - } - - return ret; -} - -int ssl_pm_clear(SSL *ssl) -{ - return ssl_pm_shutdown(ssl); -} - -int ssl_pm_read(SSL *ssl, void *buffer, int len) -{ - int ret; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_read(&ssl_pm->ssl, buffer, len); - if (ret < 0) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_read() return -0x%x", -ret); - if (ret == MBEDTLS_ERR_NET_CONN_RESET || - ret <= MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) /* fatal errors */ - { - ssl->err = SSL_ERROR_SYSCALL; - } - - ret = -1; - } - - return ret; -} - -/* This returns -1, or the length sent. - * If -1, then you need to find out if the error was - * fatal or recoverable using SSL_get_error() - */ - -int ssl_pm_send(SSL *ssl, const void *buffer, int len) -{ - int ret; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_write(&ssl_pm->ssl, buffer, len); - /* We can get a positive number, which may be less than len... that - * much was sent successfully and you can call again to send more. - * - * We can get a negative mbedtls error code... if WANT_WRITE or WANT_READ, - * it's nonfatal and means it should be retried as-is. If something else, - * it's fatal actually. - * - * If this function returns something other than a positive value or - * MBEDTLS_ERR_SSL_WANT_READ/WRITE, the ssl context becomes unusable, and - * you should either free it or call mbedtls_ssl_session_reset() on it - * before re-using it for a new connection; the current connection must - * be closed. - * - * When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, it must be - * called later with the same arguments, until it returns a positive value. - */ - - if (ret < 0) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_write() return -0x%x", -ret); - switch (ret) - { - case MBEDTLS_ERR_NET_SEND_FAILED: - case MBEDTLS_ERR_NET_CONN_RESET: - ssl->err = SSL_ERROR_SYSCALL; - break; - case MBEDTLS_ERR_SSL_WANT_WRITE: - ssl->err = SSL_ERROR_WANT_WRITE; - break; - case MBEDTLS_ERR_SSL_WANT_READ: - ssl->err = SSL_ERROR_WANT_READ; - break; - default: - break; - } - - ret = -1; - } - - return ret; -} - -int ssl_pm_pending(const SSL *ssl) -{ - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - return (int)mbedtls_ssl_get_bytes_avail(&ssl_pm->ssl); -} - -void ssl_pm_set_fd(SSL *ssl, int fd, int mode) -{ - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ssl_pm->fd.fd = fd; -} - -int ssl_pm_get_fd(const SSL *ssl, int mode) -{ - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - return ssl_pm->fd.fd; -} - -OSSL_HANDSHAKE_STATE ssl_pm_get_state(const SSL *ssl) -{ - OSSL_HANDSHAKE_STATE state; - - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - switch (ssl_pm->ssl.state) - { - case MBEDTLS_SSL_CLIENT_HELLO: - state = TLS_ST_CW_CLNT_HELLO; - break; - case MBEDTLS_SSL_SERVER_HELLO: - state = TLS_ST_SW_SRVR_HELLO; - break; - case MBEDTLS_SSL_SERVER_CERTIFICATE: - state = TLS_ST_SW_CERT; - break; - case MBEDTLS_SSL_SERVER_HELLO_DONE: - state = TLS_ST_SW_SRVR_DONE; - break; - case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: - state = TLS_ST_CW_KEY_EXCH; - break; - case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: - state = TLS_ST_CW_CHANGE; - break; - case MBEDTLS_SSL_CLIENT_FINISHED: - state = TLS_ST_CW_FINISHED; - break; - case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: - state = TLS_ST_SW_CHANGE; - break; - case MBEDTLS_SSL_SERVER_FINISHED: - state = TLS_ST_SW_FINISHED; - break; - case MBEDTLS_SSL_CLIENT_CERTIFICATE: - state = TLS_ST_CW_CERT; - break; - case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: - state = TLS_ST_SR_KEY_EXCH; - break; - case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET: - state = TLS_ST_SW_SESSION_TICKET; - break; - case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT: - state = TLS_ST_SW_CERT_REQ; - break; - case MBEDTLS_SSL_HANDSHAKE_OVER: - state = TLS_ST_OK; - break; - default : - state = TLS_ST_BEFORE; - break; - } - - return state; -} - -int x509_pm_show_info(X509 *x) -{ - int ret; - char *buf; - mbedtls_x509_crt *x509_crt; - struct x509_pm *x509_pm = x->x509_pm; - - if (x509_pm->x509_crt) - { - x509_crt = x509_pm->x509_crt; - } - else if (x509_pm->ex_crt) - { - x509_crt = x509_pm->ex_crt; - } - else - { - x509_crt = NULL; - } - - if (!x509_crt) - { - return -1; - } - - buf = ssl_mem_malloc(X509_INFO_STRING_LENGTH); - if (!buf) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (buf)"); - goto no_mem; - } - - ret = mbedtls_x509_crt_info(buf, X509_INFO_STRING_LENGTH - 1, - "", x509_crt); - if (ret <= 0) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_x509_crt_info() return -0x%x", -ret); - goto mbedtls_err1; - } - - buf[ret] = 0; - - ssl_mem_free(buf); - - SSL_DEBUG(SSL_DEBUG_ON, "%s", buf); - - return 0; - -mbedtls_err1: - ssl_mem_free(buf); -no_mem: - return -1; -} - -int x509_pm_new(X509 *x, X509 *m_x) -{ - struct x509_pm *x509_pm; - - x509_pm = ssl_mem_zalloc(sizeof(struct x509_pm)); - if (!x509_pm) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (x509_pm)"); - goto failed1; - } - - x->x509_pm = x509_pm; - - if (m_x) - { - struct x509_pm *m_x509_pm = (struct x509_pm *)m_x->x509_pm; - - x509_pm->ex_crt = m_x509_pm->x509_crt; - } - - return 0; - -failed1: - return -1; -} - -void x509_pm_free(X509 *x) -{ - struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm; - - if (x509_pm->x509_crt) - { - mbedtls_x509_crt_free(x509_pm->x509_crt); - - ssl_mem_free(x509_pm->x509_crt); - x509_pm->x509_crt = NULL; - } - - ssl_mem_free(x->x509_pm); - x->x509_pm = NULL; -} - -int x509_pm_load(X509 *x, const unsigned char *buffer, int len) -{ - int ret; - unsigned char *load_buf; - struct x509_pm *x509_pm = (struct x509_pm *)x->x509_pm; - - if (x509_pm->x509_crt) - { - mbedtls_x509_crt_free(x509_pm->x509_crt); - } - - if (!x509_pm->x509_crt) - { - x509_pm->x509_crt = ssl_mem_malloc(sizeof(mbedtls_x509_crt)); - if (!x509_pm->x509_crt) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "no enough memory > (x509_pm->x509_crt)"); - goto no_mem; - } - } - - mbedtls_x509_crt_init(x509_pm->x509_crt); - if (buffer[0] != 0x30) - { - load_buf = ssl_mem_malloc(len + 1); - if (!load_buf) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "no enough memory > (load_buf)"); - goto failed; - } - - ssl_memcpy(load_buf, buffer, len); - load_buf[len] = '\0'; - - ret = mbedtls_x509_crt_parse(x509_pm->x509_crt, load_buf, len + 1); - ssl_mem_free(load_buf); - } - else - { - printf("parsing as der\n"); - - ret = mbedtls_x509_crt_parse_der(x509_pm->x509_crt, buffer, len); - } - - if (ret) - { - printf("mbedtls_x509_crt_parse return -0x%x", -ret); - goto failed; - } - - return 0; - -failed: - mbedtls_x509_crt_free(x509_pm->x509_crt); - ssl_mem_free(x509_pm->x509_crt); - x509_pm->x509_crt = NULL; -no_mem: - return -1; -} - -int pkey_pm_new(EVP_PKEY *pk, EVP_PKEY *m_pkey) -{ - struct pkey_pm *pkey_pm; - - pkey_pm = ssl_mem_zalloc(sizeof(struct pkey_pm)); - if (!pkey_pm) - { - return -1; - } - - pk->pkey_pm = pkey_pm; - - if (m_pkey) - { - struct pkey_pm *m_pkey_pm = (struct pkey_pm *)m_pkey->pkey_pm; - - pkey_pm->ex_pkey = m_pkey_pm->pkey; - } - - return 0; -} - -void pkey_pm_free(EVP_PKEY *pk) -{ - struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm; - - if (pkey_pm->pkey) - { - mbedtls_pk_free(pkey_pm->pkey); - - ssl_mem_free(pkey_pm->pkey); - pkey_pm->pkey = NULL; - } - - ssl_mem_free(pk->pkey_pm); - pk->pkey_pm = NULL; -} - -int pkey_pm_load(EVP_PKEY *pk, const unsigned char *buffer, int len) -{ - int ret; - unsigned char *load_buf; - struct pkey_pm *pkey_pm = (struct pkey_pm *)pk->pkey_pm; - mbedtls_ctr_drbg_context ctr_drbg; - - if (pkey_pm->pkey) - { - mbedtls_pk_free(pkey_pm->pkey); - } - - if (!pkey_pm->pkey) - { - pkey_pm->pkey = ssl_mem_malloc(sizeof(mbedtls_pk_context)); - if (!pkey_pm->pkey) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "no enough memory > (pkey_pm->pkey)"); - goto no_mem; - } - } - - load_buf = ssl_mem_malloc(len + 1); - if (!load_buf) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, "no enough memory > (load_buf)"); - goto failed; - } - - ssl_memcpy(load_buf, buffer, len); - load_buf[len] = '\0'; - - mbedtls_pk_init(pkey_pm->pkey); - mbedtls_ctr_drbg_init(&ctr_drbg); - - ret = mbedtls_pk_parse_key(pkey_pm->pkey, load_buf, len + 1, - NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg); - ssl_mem_free(load_buf); - - if (ret) - { - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_pk_parse_key return -0x%x", -ret); - goto failed; - } - - mbedtls_ctr_drbg_free(&ctr_drbg); - - return 0; - -failed: - mbedtls_ctr_drbg_free(&ctr_drbg); - mbedtls_pk_free(pkey_pm->pkey); - ssl_mem_free(pkey_pm->pkey); - pkey_pm->pkey = NULL; -no_mem: - return -1; -} - -void ssl_pm_set_bufflen(SSL *ssl, int len) -{ - max_content_len = len; -} - -long ssl_pm_get_verify_result(const SSL *ssl) -{ - uint32_t ret; - long verify_result; - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - ret = mbedtls_ssl_get_verify_result(&ssl_pm->ssl); - if (!ret) - { - return X509_V_OK; - } - - if (ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED || - (ret & MBEDTLS_X509_BADCRL_NOT_TRUSTED)) - { - verify_result = X509_V_ERR_INVALID_CA; - } - else if (ret & MBEDTLS_X509_BADCERT_CN_MISMATCH) - { - verify_result = X509_V_ERR_HOSTNAME_MISMATCH; - } - else if ((ret & MBEDTLS_X509_BADCERT_BAD_KEY) || - (ret & MBEDTLS_X509_BADCRL_BAD_KEY)) - { - verify_result = X509_V_ERR_CA_KEY_TOO_SMALL; - } - else if ((ret & MBEDTLS_X509_BADCERT_BAD_MD) || - (ret & MBEDTLS_X509_BADCRL_BAD_MD)) - { - verify_result = X509_V_ERR_CA_MD_TOO_WEAK; - } - else if ((ret & MBEDTLS_X509_BADCERT_FUTURE) || - (ret & MBEDTLS_X509_BADCRL_FUTURE)) - { - verify_result = X509_V_ERR_CERT_NOT_YET_VALID; - } - else if ((ret & MBEDTLS_X509_BADCERT_EXPIRED) || - (ret & MBEDTLS_X509_BADCRL_EXPIRED)) - { - verify_result = X509_V_ERR_CERT_HAS_EXPIRED; - } - else - { - verify_result = X509_V_ERR_UNSPECIFIED; - } - - SSL_DEBUG(SSL_PLATFORM_ERROR_LEVEL, - "mbedtls_ssl_get_verify_result() return 0x%x", ret); - - return verify_result; -} - -/** - * @brief set expected hostname on peer cert CN - */ - -int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, - const char *name, size_t namelen) -{ - SSL *ssl = (SSL *)((char *)param - offsetof(SSL, param)); - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - char *name_cstr = NULL; - - if (namelen) - { - name_cstr = malloc(namelen + 1); - if (!name_cstr) - { - return 0; - } - - memcpy(name_cstr, name, namelen); - name_cstr[namelen] = '\0'; - name = name_cstr; - } - - mbedtls_ssl_set_hostname(&ssl_pm->ssl, name); - - if (namelen) - { - free(name_cstr); - } - - return 1; -} - -void _ssl_set_alpn_list(const SSL *ssl) -{ - if (ssl->alpn_protos) - { - if (mbedtls_ssl_conf_alpn_protocols( - &((struct ssl_pm *)(ssl->ssl_pm))->conf, - ssl->alpn_protos)) - { - fprintf(stderr, "mbedtls_ssl_conf_alpn_protocols failed\n"); - } - - return; - } - - if (!ssl->ctx->alpn_protos) - { - return; - } - - if (mbedtls_ssl_conf_alpn_protocols( - &((struct ssl_pm *)(ssl->ssl_pm))->conf, - ssl->ctx->alpn_protos)) - { - fprintf(stderr, "mbedtls_ssl_conf_alpn_protocols failed\n"); - } -} - -void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data, - unsigned int *len) -{ - const char *alp = mbedtls_ssl_get_alpn_protocol( - &((struct ssl_pm *)(ssl->ssl_pm))->ssl); - - *data = (const unsigned char *)alp; - if (alp) - { - *len = (int)strlen(alp); - } - else - { - *len = 0; - } -} - -int SSL_set_sni_callback(SSL *ssl, - int(*cb)(void *, mbedtls_ssl_context *, - const unsigned char *, size_t), void *param) -{ - struct ssl_pm *ssl_pm = (struct ssl_pm *)ssl->ssl_pm; - - mbedtls_ssl_conf_sni(&ssl_pm->conf, cb, param); - - return 0; -} - -SSL *SSL_SSL_from_mbedtls_ssl_context(mbedtls_ssl_context *msc) -{ - struct ssl_pm *ssl_pm = - (struct ssl_pm *)((char *)msc - offsetof(struct ssl_pm, ssl)); - - return ssl_pm->owner; -} - -void SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx) -{ - struct ssl_pm *ssl_pm = ssl->ssl_pm; - struct x509_pm *x509_pm = (struct x509_pm *)ctx->cert->x509->x509_pm; - struct x509_pm *x509_pm_ca = (struct x509_pm *)ctx->client_CA->x509_pm; - - struct pkey_pm *pkey_pm = (struct pkey_pm *)ctx->cert->pkey->pkey_pm; - int mode; - - if (ssl->cert) - { - ssl_cert_free(ssl->cert); - } - - ssl->ctx = ctx; - ssl->cert = __ssl_cert_new(ctx->cert); - - if (ctx->verify_mode == SSL_VERIFY_PEER) - { - mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - } - else if (ctx->verify_mode == SSL_VERIFY_FAIL_IF_NO_PEER_CERT) - { - mode = MBEDTLS_SSL_VERIFY_OPTIONAL; - } - else if (ctx->verify_mode == SSL_VERIFY_CLIENT_ONCE) - { - mode = MBEDTLS_SSL_VERIFY_UNSET; - } - else - { - mode = MBEDTLS_SSL_VERIFY_NONE; - } - - /* apply new ctx cert to ssl */ - - ssl->verify_mode = ctx->verify_mode; - - mbedtls_ssl_set_hs_ca_chain(&ssl_pm->ssl, x509_pm_ca->x509_crt, NULL); - mbedtls_ssl_set_hs_own_cert(&ssl_pm->ssl, x509_pm->x509_crt, - pkey_pm->pkey); - mbedtls_ssl_set_hs_authmode(&ssl_pm->ssl, mode); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.h b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.h deleted file mode 100644 index 6d1b0f629..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_pm.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_PM_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_PM_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include "ssl_port.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -#define LOCAL_ATRR - -int ssl_pm_new(SSL *ssl); -void ssl_pm_free(SSL *ssl); - -int ssl_pm_handshake(SSL *ssl); -int ssl_pm_shutdown(SSL *ssl); -int ssl_pm_clear(SSL *ssl); - -int ssl_pm_read(SSL *ssl, void *buffer, int len); -int ssl_pm_send(SSL *ssl, const void *buffer, int len); -int ssl_pm_pending(const SSL *ssl); - -void ssl_pm_set_fd(SSL *ssl, int fd, int mode); -int ssl_pm_get_fd(const SSL *ssl, int mode); - -OSSL_HANDSHAKE_STATE ssl_pm_get_state(const SSL *ssl); - -void ssl_pm_set_bufflen(SSL *ssl, int len); - -int x509_pm_show_info(X509 *x); -int x509_pm_new(X509 *x, X509 *m_x); -void x509_pm_free(X509 *x); -int x509_pm_load(X509 *x, const unsigned char *buffer, int len); - -int pkey_pm_new(EVP_PKEY *pk, EVP_PKEY *m_pk); -void pkey_pm_free(EVP_PKEY *pk); -int pkey_pm_load(EVP_PKEY *pk, const unsigned char *buffer, int len); - -long ssl_pm_get_verify_result(const SSL *ssl); - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_PM_H */ diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.c deleted file mode 100644 index b1ff4ee8b..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.c +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "ssl_port.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void *ssl_mem_zalloc(size_t size) -{ - void *p = malloc(size); - - if (p) - { - memset(p, 0, size); - } - - return p; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.h b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.h deleted file mode 100644 index 2ff053253..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.h +++ /dev/null @@ -1,55 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_port.h - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -#ifndef OPENSSL_MBEDTLS_WRAPPER_SSL_PORT_H -#define OPENSSL_MBEDTLS_WRAPPER_SSL_PORT_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "string.h" -#include "stdlib.h" -#if defined(LWS_HAVE_MALLOC_H) -#include "malloc.h" -#endif - -#ifdef __cplusplus -extern "C" -{ -#endif - -void *ssl_mem_zalloc(size_t size); - -#define ssl_mem_malloc malloc -#define ssl_mem_free free - -#define ssl_memcpy memcpy -#define ssl_strlen strlen - -#define ssl_speed_up_enter() -#define ssl_speed_up_exit() - -#define SSL_DEBUG_FL -#define SSL_DEBUG_LOG(fmt, ...) ESP_LOGI("openssl", fmt, ##__VA_ARGS__) - -#ifdef __cplusplus -} -#endif - -#endif /* OPENSSL_MBEDTLS_WRAPPER_SSL_PORT_H */ diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_rsa.c b/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_rsa.c deleted file mode 100644 index 8c0e584cd..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_rsa.c +++ /dev/null @@ -1,242 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/ssl_rsa.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#include -#include -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x) -{ - SSL_ASSERT1(ctx); - SSL_ASSERT1(x); - - if (ctx->cert->x509 == x) - { - return 1; - } - - X509_free(ctx->cert->x509); - ctx->cert->x509 = x; - return 1; -} - -int SSL_use_certificate(SSL *ssl, X509 *x) -{ - SSL_ASSERT1(ssl); - SSL_ASSERT1(x); - - if (ssl->cert->x509 == x) - { - return 1; - } - - X509_free(ssl->cert->x509); - ssl->cert->x509 = x; - return 1; -} - -int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, - const unsigned char *d) -{ - int ret; - X509 *x; - - x = d2i_X509(NULL, &d, len); - if (!x) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_X509() return NULL"); - goto failed1; - } - - ret = SSL_CTX_use_certificate(ctx, x); - if (!ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "SSL_CTX_use_certificate() return %d", ret); - goto failed2; - } - - return 1; - -failed2: - X509_free(x); -failed1: - return 0; -} - -int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len) -{ - int ret; - X509 *x; - - x = d2i_X509(NULL, &d, len); - if (!x) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_X509() return NULL"); - goto failed1; - } - - ret = SSL_use_certificate(ssl, x); - if (!ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "SSL_use_certificate() return %d", ret); - goto failed2; - } - - return 1; - -failed2: - X509_free(x); -failed1: - return 0; -} - -int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type) -{ - return 0; -} - -int SSL_use_certificate_file(SSL *ssl, const char *file, int type) -{ - return 0; -} - -int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey) -{ - SSL_ASSERT1(ctx); - SSL_ASSERT1(pkey); - - if (ctx->cert->pkey == pkey) - { - return 1; - } - - if (ctx->cert->pkey) - { - EVP_PKEY_free(ctx->cert->pkey); - } - - ctx->cert->pkey = pkey; - - return 1; -} - -int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey) -{ - SSL_ASSERT1(ssl); - SSL_ASSERT1(pkey); - - if (ssl->cert->pkey == pkey) - { - return 1; - } - - if (ssl->cert->pkey) - { - EVP_PKEY_free(ssl->cert->pkey); - } - - ssl->cert->pkey = pkey; - - return 1; -} - -int SSL_CTX_use_PrivateKey_ASN1(int type, SSL_CTX *ctx, - const unsigned char *d, long len) -{ - int ret; - EVP_PKEY *pk; - - pk = d2i_PrivateKey(0, NULL, &d, len); - if (!pk) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_PrivateKey() return NULL"); - goto failed1; - } - - ret = SSL_CTX_use_PrivateKey(ctx, pk); - if (!ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "SSL_CTX_use_PrivateKey() return %d", ret); - goto failed2; - } - - return 1; - -failed2: - EVP_PKEY_free(pk); -failed1: - return 0; -} - -int SSL_use_PrivateKey_ASN1(int type, SSL *ssl, - const unsigned char *d, long len) -{ - int ret; - EVP_PKEY *pk; - - pk = d2i_PrivateKey(0, NULL, &d, len); - if (!pk) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "d2i_PrivateKey() return NULL"); - goto failed1; - } - - ret = SSL_use_PrivateKey(ssl, pk); - if (!ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "SSL_use_PrivateKey() return %d", ret); - goto failed2; - } - - return 1; - -failed2: - EVP_PKEY_free(pk); -failed1: - return 0; -} - -int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type) -{ - return 0; -} - -int SSL_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type) -{ - return 0; -} - -int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, - long len) -{ - return SSL_CTX_use_PrivateKey_ASN1(0, ctx, d, len); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/stack.c b/crypto/openssl_mbedtls_wrapper/mbedtls/stack.c deleted file mode 100644 index 0ab5e2956..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/stack.c +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/stack.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include "ssl_port.h" - -#ifndef CONFIG_MIN_NODES - #define MIN_NODES 4 -#else - #define MIN_NODES CONFIG_MIN_NODES -#endif - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc c) -{ - OPENSSL_STACK *stack; - char **data; - - stack = ssl_mem_zalloc(sizeof(OPENSSL_STACK)); - if (!stack) - { - SSL_DEBUG(SSL_STACK_ERROR_LEVEL, "no enough memory > (stack)"); - goto no_mem1; - } - - data = ssl_mem_zalloc(sizeof(*data) * MIN_NODES); - if (!data) - { - SSL_DEBUG(SSL_STACK_ERROR_LEVEL, "no enough memory > (data)"); - goto no_mem2; - } - - stack->data = data; - stack->num_alloc = MIN_NODES; - stack->c = c; - - return stack; - -no_mem2: - ssl_mem_free(stack); -no_mem1: - return NULL; -} - -OPENSSL_STACK *OPENSSL_sk_new_null(void) -{ - return OPENSSL_sk_new((OPENSSL_sk_compfunc)NULL); -} - -void OPENSSL_sk_free(OPENSSL_STACK *stack) -{ - SSL_ASSERT3(stack); - - ssl_mem_free(stack->data); - ssl_mem_free(stack); -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/statem.c b/crypto/openssl_mbedtls_wrapper/mbedtls/statem.c deleted file mode 100644 index d7b13b2e4..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/statem.c +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/statem.c - * - * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl) -{ - OSSL_HANDSHAKE_STATE state; - - SSL_ASSERT1(ssl); - - state = SSL_METHOD_CALL(get_state, ssl); - - return state; -} diff --git a/crypto/openssl_mbedtls_wrapper/mbedtls/x509.c b/crypto/openssl_mbedtls_wrapper/mbedtls/x509.c deleted file mode 100644 index 787c0af7c..000000000 --- a/crypto/openssl_mbedtls_wrapper/mbedtls/x509.c +++ /dev/null @@ -1,253 +0,0 @@ -/**************************************************************************** - * apps/crypto/openssl_mbedtls_wrapper/mbedtls/x509.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include "ssl_port.h" -#include "ssl_methods.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void X509_free(X509 *a) -{ - SSL_ASSERT3(a); - - X509_METHOD_CALL(free, a); - - ssl_mem_free(a); -} - -void X509_EXTENSION_free(X509_EXTENSION *a) -{ -} - -int X509_set_notAfter(X509 *x509, const ASN1_TIME *tm) -{ - return 0; -} - -void X509_NAME_free(X509_NAME *a) -{ -} - -void X509_ALGOR_free(X509_ALGOR *a) -{ -} - -int X509_sign(X509 *x509, EVP_PKEY *pkey, const EVP_MD *md) -{ - return 0; -} - -int X509_add_ext(X509 *x, const X509_EXTENSION *ex, int loc) -{ - return 0; -} - -int X509_set_pubkey(X509 *x509, EVP_PKEY *pkey) -{ - return 0; -} - -X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, - int nid, int crit, - const ASN1_OCTET_STRING *data) -{ - return NULL; -} - -X509 *X509_new(void) -{ - return __X509_new(NULL); -} - -int X509_set_version(X509 *x509, long version) -{ - return 0; -} - -int X509_set_serialNumber(X509 *x509, const ASN1_INTEGER *serial) -{ - return 0; -} - -int X509_set_subject_name(X509 *x509, X509_NAME *name) -{ - return 0; -} - -int X509_set_issuer_name(X509 *x509, X509_NAME *name) -{ - return 0; -} - -int X509_set_notBefore(X509 *x509, const ASN1_TIME *tm) -{ - return 0; -} - -int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *obj, - int param_type, void *param_value) -{ - return 0; -} - -int X509_set1_signature_algo(X509 *x509, const X509_ALGOR *algo) -{ - return 0; -} - -int X509_set1_signature_value(X509 *x509, - const uint8_t *sig, - size_t sig_len) -{ - return 0; -} - -X509_NAME *X509_NAME_new(void) -{ - return NULL; -} - -int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, - int type, const uint8_t *bytes, - int len, int loc, int set) -{ - return 0; -} - -X509_NAME *d2i_X509_NAME(X509_NAME **out, const uint8_t **inp, long len) -{ - return NULL; -} - -X509_ALGOR *X509_ALGOR_new(void) -{ - return NULL; -} - -int i2d_X509(X509 *x509, uint8_t **outp) -{ - return 0; -} - -PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO(PKCS8_PRIV_KEY_INFO *info, - const uint8_t **key_data, - size_t key_length) -{ - return NULL; -} - -void PKCS8_PRIV_KEY_INFO_free(PKCS8_PRIV_KEY_INFO *key) -{ -} - -EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8) -{ - return NULL; -} - -X509 *d2i_X509(X509 **out, const unsigned char **inp, long len) -{ - int m = 0; - int ret; - X509 *x; - - SSL_ASSERT2(inp); - SSL_ASSERT2(len); - - if (out && *out) - { - x = *out; - } - else - { - x = X509_new(); - if (!x) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, "X509_new() return NULL"); - goto failed1; - } - - m = 1; - } - - ret = X509_METHOD_CALL(load, x, *inp, (int)len); - if (ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "X509_METHOD_CALL(load) return %d", ret); - goto failed2; - } - - return x; - -failed2: - if (m) - { - X509_free(x); - } - -failed1: - return NULL; -} - -X509 *__X509_new(X509 *ix) -{ - int ret; - X509 *x; - - x = ssl_mem_zalloc(sizeof(X509)); - if (!x) - { - SSL_DEBUG(SSL_X509_ERROR_LEVEL, "no enough memory > (x)"); - goto no_mem; - } - - if (ix) - { - x->method = ix->method; - } - else - { - x->method = X509_method(); - } - - ret = X509_METHOD_CALL(new, x, ix); - if (ret) - { - SSL_DEBUG(SSL_PKEY_ERROR_LEVEL, - "X509_METHOD_CALL(new) return %d", ret); - goto failed; - } - - return x; - -failed: - ssl_mem_free(x); -no_mem: - return NULL; -} diff --git a/crypto/tinycrypt/CMakeLists.txt b/crypto/tinycrypt/CMakeLists.txt index 88c33b976..fd9781797 100644 --- a/crypto/tinycrypt/CMakeLists.txt +++ b/crypto/tinycrypt/CMakeLists.txt @@ -56,8 +56,6 @@ if(CONFIG_TINYCRYPT) set(INCDIR ${TINYCRYPT_DIR}/lib/include) - nuttx_export_header(TARGET tinycrypt INCLUDE_DIRECTORIES ${INCDIR}) - # ############################################################################ # Sources # ############################################################################ diff --git a/crypto/wolfssl/Kconfig b/crypto/wolfssl/Kconfig index 9dd0d20e9..51da239db 100644 --- a/crypto/wolfssl/Kconfig +++ b/crypto/wolfssl/Kconfig @@ -7,6 +7,7 @@ if ALLOW_GPL_COMPONENTS menuconfig CRYPTO_WOLFSSL bool "wolfSSL SSL/TLS Cryptography Library" default n + depends on ALLOW_GPL_COMPONENTS ---help--- Enable support for wolfSSL diff --git a/crypto/wolfssl/README.md b/crypto/wolfssl/README.md deleted file mode 100644 index a5709ce1b..000000000 --- a/crypto/wolfssl/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# NuttX + wolfSSL - -## Installation - -### Installing from nuttx-apps - -Skip to step 6 - -### Installing from wolfssl - -1) Create working directory (e.g. ~/nuttxspace): - ``` - $ cd ~ - $ mkdir nuttxspace - ``` -2) Install dependencies: - ``` - $ cd ~/nuttxspace - $ sudo apt install -y bison flex gettext texinfo libncurses5-dev libncursesw5-dev gperf automake libtool pkg-config build-essential gperf genromfs libgmp-dev libmpc-dev libmpfr-dev libisl-dev binutils-dev libelf-dev libexpat-dev gcc-multilib g++-multilib picocom u-boot-tools util-linux - $ sudo apt install -y kconfig-frontends - $ sudo apt install -y gcc-arm-none-eabi binutils-arm-none-eabi - ``` -3) Clone nuttx and nuttx-apps into working directory: - ``` - $ git clone https://github.com/apache/nuttx.git nuttx - $ git clone https://github.com/apache/nuttx-apps apps - ``` -4) Copy this directory into the working directory applications: - ``` - $ cp -R RTOS/nuttx/wolfssl ~/nuttxspace/apps/crypto/wolfssl - ``` -5) Setup wolfSSL in preparation for the build, `WOLFSSL_DIR` must be the path to the original wolfssl repo: - ``` - $ cd ~/nuttxspace/apps/crypto/wolfssl - $ WOLFSSL_DIR= ./setup-wolfssl.sh - ``` -6) Setup baseline NuttX configuration (board + NuttX Shell): - ``` - $ cd ~/nuttxspace/nuttx - $ ./tools/configure.sh -l :nsh - ``` - If you are using wolfSSL for TLS you should use the `netnsh` target if your board supports it - ``` - $ ./tools/configure.sh -l :netnsh - ``` -> **EXAMPLES:** -> - For NuttX Simulator: `$ ./tools/configure.sh sim:nsh` -> - For BL602 (RISC-V): `$ ./tools/configure.sh -l bl602evb:nsh` -> - For NUCLEO-L552ZE-Q (Cortex-M33): `$ ./tools/configure.sh -l nucleo-l552ze:nsh` -> - For NUCLEO-H753ZI: `$ ./tools/configure.sh -l nucleo-h743zi:nsh` -> - For NUCLEO-F756ZG: `./tools/configure.sh -l nucleo-144:f746-nsh` - -7) Start custom configuration system: - ``` - $ make menuconfig - ``` -8) Configure NuttX to enable the wolfSSL crypto library test applications: - - From main menu select: **Application Configuration > Cryptography Library Support** - - Enable and then select **wolfSSL SSL/TLS Cryptography Library** - - Enable and then select **wolfSSL applications** - - Enable applications: - - **wolfCrypt Benchmark application** - - **wolfCrypt Test application** - - **wolfSSL client and server example** - - Select Save from bottom menu, saving to `.config` file - - Exit configuration tool - - If you are using wolfSSL for TLS you should use the `netnsh` target and should enable an NTP or some for of system time keeping so that wolfSSL has the current date to check certificates. You will also need to set the right networking settings for NuttX to connect to the internet. -9) Build NuttX and wolfSSL: - ``` - $ make - ``` -10) Flash the target - ### Simulator - ./nuttx - ### STM32 Targets (address may vary) - STM32_Programmer_CLI -c port=swd -d ./nuttx.bin 0x08000000 -11) Connect to the target with a serial monitoring tool, the device on linux is usually /dev/ttyACM0 but it may vary - - minicom -D /dev/ttyACM0 -12) Run the wolfcrypt benchmark and/or test in the NuttX Shell: - ``` - nsh> wolfcrypt_test - nsh> wolfcrypt_benchmark - nsh> wolfssl_client_server - ``` -## Notes -- Developed using the following targets: - - STM NUCLEO-L552ZE-Q (Cortex-M33) - - STM NUCLEO-H753ZI - - STM NUCLEO-F756ZG - - DT-BL10 / BL602 (RISC-V) - - NuttX simulator diff --git a/examples/module/.gitignore b/database/.gitignore similarity index 100% rename from examples/module/.gitignore rename to database/.gitignore diff --git a/math/ruy/Kconfig b/database/Make.defs similarity index 91% rename from math/ruy/Kconfig rename to database/Make.defs index 71b4890e2..577407990 100644 --- a/math/ruy/Kconfig +++ b/database/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/ruy/Kconfig +# apps/database/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,8 +18,4 @@ # ############################################################################ -config MATH_RUY - bool "Ruy" - default n - ---help--- - Enable ruy. +include $(wildcard $(APPDIR)/database/*/Make.defs) diff --git a/math/kissfft/Kconfig b/database/Makefile similarity index 89% rename from math/kissfft/Kconfig rename to database/Makefile index 686c116e6..3cf46e8e3 100644 --- a/math/kissfft/Kconfig +++ b/database/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/kissfft/Kconfig +# apps/database/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,8 +18,6 @@ # ############################################################################ -config MATH_KISSFFT - bool "kissfft" - default n - ---help--- - Enable kissfft. +MENUDESC = "Database" + +include $(APPDIR)/Directory.mk diff --git a/database/sqlite/.gitignore b/database/sqlite/.gitignore new file mode 100644 index 000000000..4292e4d3b --- /dev/null +++ b/database/sqlite/.gitignore @@ -0,0 +1,3 @@ +/build +/sqlite +*.zip diff --git a/database/sqlite/Kconfig b/database/sqlite/Kconfig new file mode 100644 index 000000000..fb15805ff --- /dev/null +++ b/database/sqlite/Kconfig @@ -0,0 +1,26 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config LIB_SQLITE + bool "SQLITE library" + depends on CONFIG_FS_LOCK_BUCKET_SIZE > 0 + default n + +if LIB_SQLITE + +config LIB_SQLITE_VERSION + string "SQLITE version" + default "3.45.1" + +config UTILS_SQLITE + tristate "SQLite cmd line tool" + default n + +config UTILS_SQLITE_STACKSIZE + int "SQLite3 cmd line tool stack size" + default 8192 + depends on UTILS_SQLITE + +endif diff --git a/examples/tlpi/Make.defs b/database/sqlite/Make.defs similarity index 89% rename from examples/tlpi/Make.defs rename to database/sqlite/Make.defs index 2809debfe..2b9ff26ce 100644 --- a/examples/tlpi/Make.defs +++ b/database/sqlite/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/tlpi/Make.defs +# apps/database/sqlite/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,6 @@ # ############################################################################ -ifneq ($(CONFIG_EXAMPLES_TLPI),) -CONFIGURED_APPS += $(APPDIR)/examples/tlpi +ifneq ($(CONFIG_LIB_SQLITE),) +CONFIGURED_APPS += $(APPDIR)/database/sqlite endif diff --git a/system/flatbuffers/Makefile b/database/sqlite/Makefile similarity index 50% rename from system/flatbuffers/Makefile rename to database/sqlite/Makefile index 3b01f6bac..f178a65a3 100644 --- a/system/flatbuffers/Makefile +++ b/database/sqlite/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/system/flatbuffers/Makefile +# apps/database/sqlite/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,21 +20,49 @@ include $(APPDIR)/Make.defs -FLATBUFFERS_VER = 23.5.26 -FLATBUFFERS_UNPACK = flatbuffers +SQLITEDIR=$(APPDIR)/database/sqlite +BUILDDIR=$(SQLITEDIR)/build + +CSRCS += ${BUILDDIR}/sqlite3.c + +CFLAGS += ${INCDIR_PREFIX}$(SQLITEDIR) +CFLAGS += ${DEFINE_PREFIX}_HAVE_SQLITE_CONFIG_H +CFLAGS += ${DEFINE_PREFIX}NDEBUG +CFLAGS += -Wno-unused-variable -Wno-undef -Wno-unused-function -Wno-shadow + +ifneq ($(CONFIG_UTILS_SQLITE),) +PROGNAME = sqlite3 +PRIORITY = 100 +STACKSIZE = ${CONFIG_UTILS_SQLITE_STACKSIZE} +MAINSRC = ${BUILDDIR}/shell.c +endif -flatbuffers.tar.gz: - $(Q) curl -L https://github.com/google/flatbuffers/archive/v$(FLATBUFFERS_VER).tar.gz -o flatbuffers.tar.gz - $(Q) tar -xzf flatbuffers.tar.gz - $(Q) mv flatbuffers-$(FLATBUFFERS_VER) flatbuffers - $(Q) patch -d $(FLATBUFFERS_UNPACK) -p1 < flatbuffers.patch # Download and unpack tarball if no git repo found -ifeq ($(wildcard flatbuffers/.git),) -context:: flatbuffers.tar.gz + +sqlite.zip: +ifeq ($(wildcard sqlite/.git),) + $(Q) curl -L https://codeload.github.com/sqlite/sqlite/zip/refs/tags/vesion-${CONFIG_LIB_SQLITE_VERSION} -o sqlite.zip + $(Q) unzip -q -o sqlite.zip + $(Q) mv sqlite-vesion-* sqlite + $(call DELFILE, sqlite.zip) +endif + +context:: sqlite.zip + $(Q) mkdir -p ${BUILDDIR} && \ + cd ${BUILDDIR} && \ + echo "Generate SQLite amalgamation version" && \ + ${SQLITEDIR}/sqlite/configure 1> /dev/null && \ + make sqlite3.c -j 1> /dev/null + +clean:: + $(call DELFILE, ${BUILDDIR}/*.o) + distclean:: - $(call DELDIR, flatbuffers) - $(call DELFILE, flatbuffers.tar.gz) + $(call DELDIR, ${BUILDDIR}) +ifeq ($(wildcard sqlite/.git),) + $(call DELDIR, sqlite) endif include $(APPDIR)/Application.mk + diff --git a/database/sqlite/sqlite_cfg.h b/database/sqlite/sqlite_cfg.h new file mode 100644 index 000000000..fcd1d7f07 --- /dev/null +++ b/database/sqlite/sqlite_cfg.h @@ -0,0 +1,145 @@ +/* sqlite_cfg.h. Generated from sqlite_cfg.h.in by configure. */ +/* sqlite_cfg.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the `fdatasync' function. */ +#define HAVE_FDATASYNC 1 + +/* Define to 1 if you have the `gmtime_r' function. */ +#define HAVE_GMTIME_R 1 + +/* Define to 1 if the system has the type `int16_t'. */ +#define HAVE_INT16_T 1 + +/* Define to 1 if the system has the type `int32_t'. */ +#define HAVE_INT32_T 1 + +/* Define to 1 if the system has the type `int64_t'. */ +#define HAVE_INT64_T 1 + +/* Define to 1 if the system has the type `int8_t'. */ +#define HAVE_INT8_T 1 + +/* Define to 1 if the system has the type `intptr_t'. */ +#define HAVE_INTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `isnan' function. */ +#define HAVE_ISNAN 1 + +/* Define to 1 if you have the `localtime_r' function. */ +#define HAVE_LOCALTIME_R 1 + +/* Define to 1 if you have the `localtime_s' function. */ +/* #undef HAVE_LOCALTIME_S */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MALLOC_H 1 + +/* Define to 1 if you have the `malloc_usable_size' function. */ +#define HAVE_MALLOC_USABLE_SIZE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `pread' function. */ +#define HAVE_PREAD 1 + +/* Define to 1 if you have the `pread64' function. */ +#define HAVE_PREAD64 1 + +/* Define to 1 if you have the `pwrite' function. */ +#define HAVE_PWRITE 1 + +/* Define to 1 if you have the `pwrite64' function. */ +#define HAVE_PWRITE64 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strchrnul' function. */ +#define HAVE_STRCHRNUL 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if the system has the type `uint16_t'. */ +#define HAVE_UINT16_T 1 + +/* Define to 1 if the system has the type `uint32_t'. */ +#define HAVE_UINT32_T 1 + +/* Define to 1 if the system has the type `uint64_t'. */ +#define HAVE_UINT64_T 1 + +/* Define to 1 if the system has the type `uint8_t'. */ +#define HAVE_UINT8_T 1 + +/* Define to 1 if the system has the type `uintptr_t'. */ +#define HAVE_UINTPTR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `usleep' function. */ +#define HAVE_USLEEP 1 + +/* Define to 1 if you have the `utime' function. */ +#define HAVE_UTIME 1 + +/* Define to 1 if you have the header file. */ +#ifdef CONFIG_LIB_ZLIB +# define HAVE_ZLIB_H 1 +#endif + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "sqlite" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "sqlite 3.45.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "sqlite" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.45.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Enable large inode numbers on Mac OS X 10.5. */ +#ifndef _DARWIN_USE_64_BIT_INODE +# define _DARWIN_USE_64_BIT_INODE 1 +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index ed91792be..000000000 --- a/examples/README.md +++ /dev/null @@ -1,2187 +0,0 @@ -# Examples - -### Selecting Examples - -The examples directory contains several sample applications that can be linked -with NuttX. The specific example is selected in the -`boards////configs//defconfig` file -via the `CONFIG_EXAMPLES_xyz` setting where `xyz` is the name of the example. -For example: - -```conf -CONFIG_EXAMPLES_HELLO=y -``` - -Selects the `examples/hello` _Hello, World!_ example. - -### Built-In Functions - -Some of the examples may be built as _built-in_ functions that can be executed -at run time (rather than as NuttX _main_ programs). These _built-in_ examples -can be also be executed from the NuttShell (NSH) command line. In order to -configure these built-in NSH functions, you have to set up the following: - -- `CONFIG_NSH_BUILTIN_APPS` – Enable support for external registered, _named_ - applications that can be executed from the NSH command line (see - `apps/README.md` for more information). - -## `adc` Read from ADC - -A mindlessly simple test of an ADC devices. It simply reads from the ADC device -and dumps the data to the console forever. - -This test depends on these specific ADC/NSH configurations settings (your -specific ADC settings might require additional settings). - -- `CONFIG_ADC` – Enabled ADC support. -- `CONFIG_NSH_BUILTIN_APPS` – Build the ADC test as an NSH built-in function. - Default: Built as a standalone program. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_ADC_DEVPATH` – The default path to the ADC device. Default: - `/dev/adc0`. -- `CONFIG_EXAMPLES_ADC_NSAMPLES` – This number of samples is collected and the - program terminates. Default: Samples are collected indefinitely. -- `CONFIG_EXAMPLES_ADC_GROUPSIZE` – The number of samples to read at once. - Default: `4`. - -## `ajoystick` Analog Joystick - -This is a simple test of the analog joystick driver. See details about this -driver in `nuttx/include/nuttx/input/ajoystick.h`. - -Configuration Pre-requisites: - -- `CONFIG_AJOYSTICK` – The analog joystick driver. - -Example Configuration: -- `CONFIG_EXAMPLES_AJOYSTICK` – Enabled the analog joystick example. -- `CONFIG_EXAMPLES_AJOYSTICK_DEVNAME` – Joystick device name. Default - `/dev/adjoy0`. -- `CONFIG_EXAMPLES_AJOYSTICK_SIGNO` – Signal used to signal the test - application. Default `32`. - -## `alarm` RTC Alarm - -A simple example that tests the alarm IOCTLs of the RTC driver. - -Dependencies: - -- `CONFIG_RTC_DRIVER` – RTC driver must be initialized to allow user space - access to the RTC. -- `CONFIG_RTC_ALARM` – Support for RTC alarms must be enabled. - -Configuration: - -- `CONFIG_EXAMPLES_ALARM` – Enable the RTC driver alarm test. -- `CONFIG_EXAMPLES_ALARM_PROGNAME` – This is the name of the program that will - be used when the NSH ELF program is installed. -- `CONFIG_EXAMPLES_ALARM_PRIORITY` – Alarm daemon priority. -- `CONFIG_EXAMPLES_ALARM_STACKSIZE` – Alarm daemon stack size. -- `CONFIG_EXAMPLES_ALARM_DEVPATH` – RTC device path (`/dev/rtc0`). -- `CONFIG_EXAMPLES_ALARM_SIGNO` – Alarm signal. - -## `apa102` Rainbow on `APA102` LED Strip - -Rainbow example for `APA102` LED Strip. - -## `bastest` Bas BASIC Interpreter - -This directory contains a small program that will mount a ROMFS file system -containing the BASIC test files extracted from the Bas `2.4` release. See -`examples/bastest/README.md` for licensing and usage information. - -- `CONFIG_EXAMPLES_BASTEST_DEVMINOR` – The minor device number of the ROMFS - block driver. For example, the `N` in `/dev/ramN`. Used for registering the - RAM block driver that will hold the ROMFS file system containing the BASIC - files to be tested. Default: `0`. - -- `CONFIG_EXAMPLES_BASTEST_DEVPATH` – The path to the ROMFS block driver device. - This must match `EXAMPLES_BASTEST_DEVMINOR`. Used for registering the RAM - block driver that will hold the ROMFS file system containing the BASIC files - to be tested. Default: `/dev/ram0`. - -## `bridge` Network Bridge - -A simple test of a system with multiple networks. It simply echoes all UDP -packets received on network `1` and network `2` to network `2` and network `1`, -respectively. Interface `1` and interface may or may not lie on the same -network. - -- `CONFIG_EXAMPLES_BRIDGE` – Enables the simple UDP bridge test. - -There identical configurations for each of the two networks, `NETn` where `n` -refers to the network being configured `n={1,2}`. Let `m` refer to the other -network. - -- `CONFIG_EXAMPLES_BRIDGE_NETn_IFNAME` – The register name of the network `n` - device. Must match the previously registered driver name and must not be the - same as other network device name, `CONFIG_EXAMPLES_BRIDGE_NETm_IFNAME`. -- `CONFIG_EXAMPLES_BRIDGE_NETn_RECVPORT` – Network `n` listen port number. -- `CONFIG_EXAMPLES_BRIDGE_NETn_SNDPORT` – Network `2` send port number. -- `CONFIG_EXAMPLES_BRIDGE_NETn_IOBUFIZE` – Size of the network `n` UDP - send/receive I/O buffer. -- `CONFIG_EXAMPLES_BRIDGE_NETn_STACKSIZE` – Network `n` daemon stacksize. -- `CONFIG_EXAMPLES_BRIDGE_NETn_PRIORITY` – Network `n` daemon task priority. - -If used as a NSH add-on, then it is assumed that initialization of both networks -was performed externally prior to the time that this test was started. -Otherwise, the following options are available: - -- `CONFIG_EXAMPLES_BRIDGE_NETn_NOMAC` – Select of the network `n` hardware does - not have a built-in MAC address. If selected, the MAC address. provided by - `CONFIG_EXAMPLES_BRIDGE_NETn_MACADDR` will be used to assign the MAC address - to the network n device. -- `CONFIG_EXAMPLES_BRIDGE_NETn_DHCPC` – Use DHCP Client to get the network n IP - address. -- `CONFIG_EXAMPLES_BRIDGE_NETn_IPADDR` – If `CONFIG_EXAMPLES_BRIDGE_NETn_DHCPC` - is not selected, then this is the fixed IP address for network `n`. -- `CONFIG_EXAMPLES_BRIDGE_NETn_DRIPADDR` – Network `n` default router IP address - (Gateway). -- `CONFIG_EXAMPLES_BRIDGE_NETn_NETMASK` – Network `n` mask. - -## `buttons` Read GPIO Buttons - -To be provided. - -## `can` CAN Device Test - -If the CAN device is configured in loopback mode, then this example can be used -to test the CAN device in loop back mode. It simple sinces a sequence of CAN -messages and verifies that those messages are returned exactly as sent. - -This test depends on these specific CAN/NSH configurations settings (your -specific CAN settings might require additional settings). - -- `CONFIG_CAN` – Enables CAN support. -- `CONFIG_CAN_LOOPBACK` – A CAN driver may or may not support a loopback mode - for testing. The STM32 CAN driver does support loopback mode. -- `CONFIG_NSH_BUILTIN_APPS` – Build the CAN test as an NSH built-in function. - Default: Built as a standalone program. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_CAN_DEVPATH` – The path to the CAN device. Default: - `/dev/can0`. -- `CONFIG_EXAMPLES_CAN_NMSGS` – This number of CAN message is collected and the - program terminates. Default: messages are sent and received indefinitely. - -The default behavior assumes loopback mode. Messages are sent, then read and -verified. The behavior can be altered for other kinds of testing where the test -only sends or received (but does not verify) can messages. - -- `CONFIG_EXAMPLES_CAN_READONLY` – Only receive messages. -- `CONFIG_EXAMPLES_CAN_WRITEONLY` – Only send messages. - -## `canard` - -Example application for `canutils/libcarnard`. - -## `cctype` - -Verifies all possible inputs for all functions defined in the header file -`cctype`. - -## `chat` AT over TTY - -Demonstrates AT chat functionality over a TTY device. This is useful with AT -modems, for example, to establish a `pppd` connection (see the related `pppd` -example). Moreover, some AT modems – such as ones made by u-blox – have an -internal TCP/IP stack, often with an implementation of TLS/SSL. In such cases -the chat utility can be used to configure the internal TCP/IP stack, establish -socket connections, set up security (e.g., download base64-encoded certificates -to the modem), and perform data exchange through sockets over the TTY device. - -Useful configuration parameters: - -- `CONFIG_EXAMPLES_CHAT_PRESET[0..3]` – preset chat scripts. -- `CONFIG_EXAMPLES_CHAT_TTY_DEVNODE` – TTY device node name. -- `CONFIG_EXAMPLES_CHAT_TIMEOUT_SECONDS` – default receive timeout. - -## `configdata` - -This is a Unit Test for the MTD configuration data driver. - -## `cpuhog` Keep CPU Busy - -Attempts to keep the system busy by passing data through a pipe in loop back -mode. This may be useful if you are trying run down other problems that you -think might only occur when the system is very busy. - -## `cordic` - -A simple test of the CORDIC character driver. - -## `dac` Write to DAC - -This is a tool for writing values to DAC device. - -## `dhcpd` DHCP Server - -This examples builds a tiny DHCP server for the target system. - -**Note**: For test purposes, this example can be built as a host-based DHCPD -server. This can be built as follows: - -```bash -cd examples/dhcpd -make -f Makefile.host TOPDIR= -``` - -NuttX configuration settings: - -- `CONFIG_NET=y` – of course. -- `CONFIG_NET_UDP=y` – UDP support is required for DHCP (as well as various - other UDP-related configuration settings). -- `CONFIG_NET_BROADCAST=y` – UDP broadcast support is needed. -- `CONFIG_NETUTILS_NETLIB=y` – The networking library is needed. -- `CONFIG_EXAMPLES_DHCPD_NOMAC` – (May be defined to use software assigned MAC) - -See also `CONFIG_NETUTILS_DHCPD_*` settings described elsewhere and used in -`netutils/dhcpd/dhcpd.c`. These settings are required to described the behavior -of the daemon. - -## `discover` UDP Discover Daemon - -This example exercises `netutils/discover` utility. This example initializes and -starts the UDP discover daemon. This daemon is useful for discovering devices in -local networks, especially with DHCP configured devices. It listens for UDP -broadcasts which also can include a device class so that groups of devices can -be discovered. It is also possible to address all classes with a kind of -broadcast discover. - -This example will automatically be built as an NSH built-in if -`CONFIG_NSH_BUILTIN_APPS` is selected. Otherwise, it will be a standalone -program with entry point `discover_main`. - -NuttX configuration settings: - -- `CONFIG_EXAMPLES_DISCOVER_DHCPC` – DHCP Client. -- `CONFIG_EXAMPLES_DISCOVER_NOMAC` – Use canned MAC address. -- `CONFIG_EXAMPLES_DISCOVER_IPADDR` – Target IP address. -- `CONFIG_EXAMPLES_DISCOVER_DRIPADDR` – Router IP address. -- `CONFIG_EXAMPLES_DISCOVER_NETMASK` – Network Mask. - -## `djoystick` Discrete Joystick - -This is a simple test of the discrete joystick driver. See details about this -driver in `nuttx/include/nuttx/input/djoystick.h`. - -Configuration Pre-requisites: - -- `CONFIG_INPUT_DJOYSTICK` – The discrete joystick driver. - -Example Configuration: - -- `CONFIG_EXAMPLES_DJOYSTICK` – Enabled the discrete joystick example. -- `CONFIG_EXAMPLES_DJOYSTICK_DEVNAME` – Joystick device name. Default - `/dev/djoy0`. -- `CONFIG_EXAMPLES_DJOYSTICK_SIGNO` – Signal used to signal the test - application. Default `32`. - -## `elf` ELF loader - -This example builds a small ELF loader test case. This includes several test -programs under `examples/elf` tests. These tests are build using the relocatable -ELF format and installed in a ROMFS file system. At run time, each program in -the ROMFS file system is executed. Requires `CONFIG_ELF`. Other configuration -options: - -- `CONFIG_EXAMPLES_ELF_DEVMINOR` – The minor device number of the ROMFS block - driver. For example, the `N` in `/dev/ramN`. Used for registering the RAM - block driver that will hold the ROMFS file system containing the ELF - executables to be tested. Default: `0`. - -- `CONFIG_EXAMPLES_ELF_DEVPATH` – The path to the ROMFS block driver device. - This must match `EXAMPLES_ELF_DEVMINOR`. Used for registering the RAM block - driver that will hold the ROMFS file system containing the ELF executables to - be tested. Default: `/dev/ram0`. - -**Notes**: - -1. `CFLAGS` should be provided in `CELFFLAGS`. RAM and FLASH memory regions may - require long allcs. For ARM, this might be: - - ```makefile - CELFFLAGS = $(CFLAGS) -mlong-calls - ``` - - Similarly for C++ flags which must be provided in `CXXELFFLAGS`. - -2. Your top-level `nuttx/Make.defs` file must also include an appropriate - definition, `LDELFFLAGS`, to generate a relocatable ELF object. With GNU LD, - this should include `-r` and `-e main` (or `_main` on some platforms). - - ```makefile - LDELFFLAGS = -r -e main - ``` - - If you use GCC to link, you make also need to include `-nostdlib`. - -3. This example also requires `genromfs`. `genromfs` can be build as part of the - nuttx toolchain. Or can built from the `genromfs` sources that can be found - in the NuttX tools repository (`genromfs-0.5.2.tar.gz`). In any event, the - `PATH` variable must include the path to the genromfs executable. - -4. ELF size: The ELF files in this example are, be default, quite large because - they include a lot of _build garbage_. You can greatly reduce the size of the - ELF binaries are using the `objcopy --strip-unneeded` command to remove - un-necessary information from the ELF files. - -5. Simulator. You cannot use this example with the NuttX simulator on Cygwin. - That is because the Cygwin GCC does not generate ELF file but rather some - Windows-native binary format. - - If you really want to do this, you can create a NuttX x86 buildroot toolchain - and use that be build the ELF executables for the ROMFS file system. - -6. Linker scripts. You might also want to use a linker scripts to combine - sections better. An example linker script is at - `nuttx/binfmt/libelf/gnu-elf.ld`. That example might have to be tuned for - your particular linker output to position additional sections correctly. The - GNU LD `LDELFFLAGS` then might be: - - ```makefile - LDELFFLAGS = -r -e main -T$(TOPDIR)/binfmt/libelf/gnu-elf.ld - ``` - -## `fb` Framebuffer - -A simple test of the framebuffer character driver. - -## `flash_test` SMART Flash - -This example performs a SMART flash block device test. This test performs a -sector allocate, read, write, free and garbage collection test on a SMART MTD -block device. - -- `CONFIG_EXAMPLES_FLASH_TEST=y` – Enables the FLASH Test. - -Dependencies: - -- `CONFIG_MTD_SMART=y` – SMART block driver support. -- `CONFIG_BUILD_PROTECTED=n` and `CONFIG_BUILD_KERNEL=n` – This test uses - internal OS interfaces and so is not available in the NUTTX kernel builds. - -## `foc` FOC motor controller - -A FOC motor controller based on the NuttX FOC driver and the NuttX FOC library. -See `apps/foc/README.md` for more information. - -## `flowc` Serial Hardware Flow Control - -A simple test of serial hardware flow control. - -## `ft80x` FT80x GUI Chip - -This examples has ports of several FTDI demos for the FTDI/BridgeTek FT80x GUI -chip. As an example configuration, see -`nuttx/boards/arm/stm32/viewtool-stm32f107/configs/ft80x/defconfig`. - -## `ftpc` FTP Client - -This is a simple FTP client shell used to exercise the capabilities of the FTPC -library (`apps/netutils/ftpc`). - -From NSH, the startup command sequence is as follows. This is only an example, -your configuration could have different mass storage devices, mount paths, and -FTP directories: - -``` -nsh> mount -t vfat /dev/mmcsd0 /tmp # Mount the SD card at /tmp -nsh> cd /tmp # cd into the /tmp directory -nsh> ftpc # Start the FTP client -nfc> login # Log into the FTP server -nfc> help # See a list of FTP commands -``` - -where `` is the IP address or hostname of the FTP server and `` is -an optional port number. - -**Note**: By default, FTPC uses `readline` to get data from `stdin`. So your -defconfig file must have the following build path: - -```conf -CONFIG_SYSTEM_READLINE=y -``` - -**Note**: If you use the ftpc task over a telnet NSH connection, then you should -set the following configuration item: - -```conf -CONFIG_EXAMPLES_FTPC_FGETS=y -``` - -By default, the FTPC client will use `readline()` to get characters from the -console. Readline includes and command-line editor and echos characters received -in stdin back through `stdout`. Neither of these behaviors are desire-able if -Telnet is used. - -You may also want to define the following in your configuration file. Otherwise, -you will have not feedback about what is going on: - -```conf -CONFIG_DEBUG_FEATURES=y -CONFIG_DEBUG_INFO=y -CONFIG_DEBUG_FTPC=y -``` - -## `ftpd` FTP daemon - -This example exercises the FTPD daemon at `apps/netutils/ftpd`. Below are -configurations specific to the FTPD example (the FTPD daemon itself may require -other configuration options as well). - -- `CONFIG_EXAMPLES_FTPD` – Enable the FTPD example. -- `CONFIG_EXAMPLES_FTPD_PRIO` – Priority of the FTP daemon. Default: - `SCHED_PRIORITY_DEFAULT`. -- `CONFIG_EXAMPLES_FTPD_STACKSIZE` – Stack size allocated for the FTP daemon. - Default: `2048`. -- `CONFIG_EXAMPLES_FTPD_NONETINIT` – Define to suppress configuration of the - network by `apps/examples/ftpd`. You would need to suppress network - configuration if the network is configuration prior to running the example. - -NSH always initializes the network so if `CONFIG_NSH_NETINIT` is defined, so is -`CONFIG_EXAMPLES_FTPD_NONETINIT` (se it does not explicitly need to be defined -in that case): - -- `CONFIG_NSH_BUILTIN_APPS` – Build the FTPD daemon example test as an NSH - built-in function. By default the FTPD daemon will be built as a standalone - application. - -If `CONFIG_EXAMPLES_FTPD_NONETINIT` is not defined, then the following may be -specified to customized the network configuration: - -- `CONFIG_EXAMPLES_FTPD_NOMAC` – If the hardware has no MAC address of its own, - define this `=y` to provide a bogus address for testing. -- `CONFIG_EXAMPLES_FTPD_IPADDR` – The target IP address. Default `10.0.0.2`. -- `CONFIG_EXAMPLES_FTPD_DRIPADDR` – The default router address. Default: - `10.0.0.1`. -- `CONFIG_EXAMPLES_FTPD_NETMASK` – The network mask. Default: `255.255.255.0`. - -TCP networking support is required. So are pthreads so this must be set to 'n': - -- `CONFIG_DISABLE_PTHREAD` – `pthread` support is required. - -Other FTPD configuration options they may be of interest: - -- `CONFIG_FTPD_VENDORID` – The vendor name to use in FTP communications. - Default: `NuttX`. -- `CONFIG_FTPD_SERVERID` – The server name to use in FTP communications. - Default: `NuttX FTP Server`. -- `CONFIG_FTPD_CMDBUFFERSIZE` – The maximum size of one command. Default: `512` - bytes. -- `CONFIG_FTPD_DATABUFFERSIZE` – The size of the I/O buffer for data transfers. - Default: `2048` bytes. -- `CONFIG_FTPD_WORKERSTACKSIZE` – The stacksize to allocate for each FTP daemon - worker thread. Default: `2048` bytes. - -The following netutils libraries should be enabled in your `defconfig` file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_FTPD=y -``` - -## `gpio` GPIO Read and Write - -A simple `test/example` of the NuttX GPIO driver. - -## `hello` Hello World - -This is the mandatory, _Hello, World!!_ example. It is little more than -`examples/null` with a single `printf` statement. Really useful only for -bringing up new NuttX architectures. - -- `CONFIG_NSH_BUILTIN_APPS` – Build the _Hello, World_ example as an NSH - built-in application. - -## `helloxx` Hello World in C++ - -This is C++ version of the _Hello, World!!_ example. It is intended only to -verify that the C++ compiler is functional, that basic C++ library support is -available, and that class are instantiated correctly. - -NuttX configuration prerequisites: - -- `CONFIG_HAVE_CXX` – Enable C++ Support. - -Optional NuttX configuration settings: - -- `CONFIG_HAVE_CXXINITIALIZE` – Enable support for static constructors (may not - be available on all platforms). - -NuttX configuration settings specific to this example: - -- `CONFIG_NSH_BUILTIN_APPS` – Build the helloxx example as a _built-in_ that can - be executed from the NSH command line. - -Also needed: - -- `CONFIG_HAVE_CXX=y` - -And you may have to tinker with the following to get libxx to compile properly: - -- `CCONFIG_ARCH_SIZET_LONG=y` or `=n`. - -The argument of the `new` operators should take a type of `size_t`. But `size_t` -has an unknown underlying. In the nuttx `sys/types.h` header file, `size_t` is -typed as `uint32_t` (which is determined by architecture-specific logic). But -the C++ compiler may believe that `size_t` is of a different type resulting in -compilation errors in the operator. Using the underlying integer type Instead of -`size_t` seems to resolve the compilation issues. - -## `hidkbd` USB Host HID keyboard - -This is a simple test to `debug/verify` the USB host HID keyboard class driver. - -- `CONFIG_EXAMPLES_HIDKBD_DEFPRIO` – Priority of _waiter_ thread. Default: `50`. -- `CONFIG_EXAMPLES_HIDKBD_STACKSIZE` – Stacksize of _waiter_ thread. Default - `1024`. -- `CONFIG_EXAMPLES_HIDKBD_DEVNAME` – Name of keyboard device to be used. - Default: `/dev/kbda`. -- `CONFIG_EXAMPLES_HIDKBD_ENCODED` – Decode special key press events in the - user buffer. In this case, the example coded will use the interfaces defined - in `include/nuttx/input/kbd_codec.h` to decode the returned keyboard data. - These special keys include such things as up/down arrows, home and end keys, - etc. If this not defined, only 7-bit printable and control ASCII characters - will be provided to the user. Requires `CONFIG_HIDKBD_ENCODED` and - `CONFIG_LIBC_KBDCODEC`. - -## `igmp` Trivial IGMP - -This is a trivial test of the NuttX IGMP capability. It present it does not do -much of value – Much more is needed in order to verify the IGMP features! - -- `CONFIG_EXAMPLES_IGMP_NOMAC` – Set if the hardware has no MAC address; one - will be assigned. -- `CONFIG_EXAMPLES_IGMP_IPADDR` – Target board IP address. -- `CONFIG_EXAMPLES_IGMP_DRIPADDR` – Default router address. -- `CONFIG_EXAMPLES_IGMP_NETMASK` – Network mask. -- `CONFIG_EXAMPLES_IGMP_GRPADDR` – Multicast group address. -- `CONFIG_EXAMPLES_NETLIB` – The networking library is needed. - -## `i2cchar` Transfer Through I2C - -A mindlessly simple test of an I2C driver. It reads an write garbage data to the -I2C transmitter and/or received as fast possible. - -This test depends on these specific I2S/AUDIO/NSH configurations settings (your -specific I2S settings might require additional settings). - -- `CONFIG_I2S` – Enabled I2S support. -- `CONFIG_AUDIO` – Enabled audio support. -- `CONFIG_DRIVERS_AUDIO` – Enable audio device support. -- `CONFIG_AUDIO_I2SCHAR` – Enabled support for the I2S character device. -- `CONFIG_NSH_BUILTIN_APPS` – Build the I2S test as an NSH built-in function. - Default: Built as a standalone program. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_I2SCHAR` – Enables the I2C test. - -- `CONFIG_EXAMPLES_I2SCHAR_DEVPATH` – The default path to the ADC device. - Default: `/dev/i2schar0`. - -- `CONFIG_EXAMPLES_I2SCHAR_TX` – This should be set if the I2S device supports a - transmitter. - -- `CONFIG_EXAMPLES_I2SCHAR_TXBUFFERS` – This is the default number of audio - buffers to send before the TX transfers terminate. When both TX and RX - transfers terminate, the task exits (and, if an NSH builtin, the `i2schar` - command returns). This number can be changed from the NSH command line. - -- `CONFIG_EXAMPLES_I2SCHAR_TXSTACKSIZE` – This is the stack size to use when - starting the transmitter thread. Default `1536`. - -- `CONFIG_EXAMPLES_I2SCHAR_RX` – This should be set if the I2S device supports a - transmitter. - -- `CONFIG_EXAMPLES_I2SCHAR_RXBUFFERS` – This is the default number of audio - buffers to receive before the RX transfers terminate. When both TX and RX - transfers terminate, the task exits (and, if an NSH builtin, the `i2schar` - command returns). This number can be changed from the NSH command line. - -- `CONFIG_EXAMPLES_I2SCHAR_RXSTACKSIZE` – This is the stack size to use when - starting the receiver thread. Default `1536`. - -- `CONFIG_EXAMPLES_I2SCHAR_BUFSIZE` – The size of the data payload in one audio - buffer. Applies to both TX and RX audio buffers. - -- `CONFIG_EXAMPLES_I2SCHAR_DEVINIT` – Define if architecture-specific I2S device - initialize is available. If defined, the platform specific code must provide a - function `i2schar_devinit()` that will be called each time that this test - executes. Not available in the kernel build mode. - -## `ina219` Current/Power Monitor `INA219` - -This is a simple infinite loop that polls the `INA219` sensor and displays the -measurements. - -## `ipforward` IP Forwarding Using TUN - -A simple test of IP forwarding using TUN devices. This can be used on any -platform, but was intended for use on the simulation platform because it -performs a test of IP forwarding without the use of hardware. - -## `json` cJSON - -This example exercises the cJSON implementation at `apps/netutils/json`. This -example contains logic taken from the cJSON project: - -http://sourceforge.net/projects/cjson/ - -The example corresponds to SVN revision `r42` (with lots of changes for NuttX -coding standards). As of `r42`, the SVN repository was last updated on -`2011-10-10` so I presume that the code is stable and there is no risk of -maintaining duplicate logic in the NuttX repository. - -## `leds` Toggle LEDs - -This is a simple test of the board LED driver at -`nuttx/drivers/leds/userled_*.c`. - -## `libtest` Static Library Test - -This example illustrates how you may create a static library. It does the following: - -It creates a static library called libtest.a that contains an object that provides the symbol library_test(). - -At adds the library as an EXTRA_LIB in the build - -EXTRA_LIBS += -ltest -E XTRA_LIBPATHS += -L$(APPDIR)/examples/libtest - -And optionally, it can be configured to: - -Generate a built-in command that can be executed by NSH. This command logic links with the symbol library_test() that will provided by the libtest.a static library. - -## `luamod_hello` Hello World Lua module - -A Lua C module showing how to add built-in modules to the Lua interpreter. -Usage: - -```lua -> hello.say_hello() -"Hello World!" -``` - -## `lis2csh_reader` `LIS3DSH` Accelerometer - -A simple reader example for the `LIS3DSH` acceleration sensor as found on -STM32F4Discovery rev. C. - -## `hts221_reader` `HTS221` Humidity Sensor - -A simple reader example for the `HTS221` humidity sensor. - -## `lsm303_reader` `LSM303` Accelerometer/Magnetometer - -A simple reader example for the `LSM303` acc-mag sensor. - -## `lsm6dsl_reader` `LSM6DSL` Accelerometer/Gyroscope - -A simple reader example for the `LSM6DSL` acc-gyro sensor. - -## `lvglterm` LVGL Terminal for NuttShell (NSH) - -LVGL application that executes NuttShell (NSH) commands entered with a -Touchscreen Keyboard and displays the NSH output. Prerequisite configuration -settings: - -- `CONFIG_NSH_ARCHINIT=n` – NSH architecture initialization must be disabled. -- `CONFIG_NSH_CONSOLE=y` – NSH must be configured to use a console. -- `CONFIG_LIBC_EXECFUNCS=y` – posix_spawn() must be enabled. -- `CONFIG_PIPES=y` – Pipes must be enabled. -- `CONFIG_GRAPHICS_LVGL=y` – LVGL graphics must be enabled. -- `CONFIG_LV_FONT_UNSCII_16=y` – LVGL font UNSCII 16 must be enabled. - -## `media` - -The media test simply writes values onto the media hidden behind a character -driver and verifies that the media can be successfully written and read. This -low level test is useful in the early phases of the bringup of a new block or -mtd driver because it avoids the complexity of a file system. - -This test uses a character driver and cannot directly access block or mtd -drivers. This test is suitable for use EEPROM character drivers (see -`nuttx/drivers/eeprom`), or with block drivers wrapped as character drivers (see -`nuttx/drivers/bch`) - -```c -int ret = bchdev_register(, - , false); -``` - -MTD drivers need an additional wrapper layer, the FTL wrapper must first be used -to convert the MTD driver to a block device: - -```c -int ret = ftl_initialize(, mtd); -ret = bchdev_register(/dev/mtdblock, , - false); -``` - -## `module` Loadable Module - -This example builds a small loadable module test case. This includes a character -driver under `examples/module/drivers`. This driver is built using the -relocatable ELF format and installed in a ROMFS file system. At run time, the -driver module is loaded and exercised. Requires `CONFIG_MODULE`. Other -configuration options: - -- `CONFIG_EXAMPLES_ELF_DEVMINOR` – The minor device number of the ROMFS block - driver. For example, the `N` in `/dev/ramN`. Used for registering the RAM - block driver that will hold the ROMFS file system containing the ELF - executables to be tested. Default: `0`. - -- `CONFIG_EXAMPLES_ELF_DEVPATH` – The path to the ROMFS block driver device. - This must match `EXAMPLES_ELF_DEVMINOR`. Used for registering the RAM block - driver that will hold the ROMFS file system containing the ELF executables to - be tested. Default: `/dev/ram0`. - -**Notes**: - -1. `CFLAGS` should be provided in `CMODULEFLAGS`. RAM and FLASH memory regions - may require long allcs. For ARM, this might be: - - ```makefile - CMODULEFLAGS = $(CFLAGS) -mlong-calls - ``` - - Similarly for C++ flags which must be provided in `CXXMODULEFLAGS`. - -2. Your top-level `nuttx/Make.defs` file must also include an appropriate - definition, LDMODULEFLAGS, to generate a relocatable ELF object. With GNU LD, - this should include `-r` and `-e `. - - ```makefile - LDMODULEFLAGS = -r -e module_initialize - ``` - - If you use GCC to link, you make also need to include `-nostdlib`. - -3. This example also requires `genromfs`. `genromfs` can be build as part of the - nuttx toolchain. Or can built from the `genromfs` sources that can be found - in the NuttX tools repository (`genromfs-0.5.2.tar.gz`). In any event, the - PATH variable must include the path to the `genromfs` executable. - -4. ELF size: The ELF files in this example are, be default, quite large because - they include a lot of _build garbage_. You can greatly reduce the size of the - ELF binaries are using the `objcopy --strip-unneeded` command to remove - un-necessary information from the ELF files. - -5. Simulator. You cannot use this example with the NuttX simulator on Cygwin. - That is because the Cygwin GCC does not generate ELF file but rather some - Windows-native binary format. - - If you really want to do this, you can create a NuttX x86 `buildroot` - toolchain and use that be build the ELF executables for the ROMFS file - system. - -6. Linker scripts. You might also want to use a linker scripts to combine - sections better. An example linker script is at - `nuttx/libc/modlib/gnu-elf.ld`. That example might have to be tuned for your - particular linker output to position additional sections correctly. The GNU - LD `LDMODULEFLAGS` then might be: - - ```makefile - LDMODULEFLAGS = -r -e module_initialize -T$(TOPDIR)/libc/modlib/gnu-elf.ld - ``` - -## `modbus` FreeModbus - -This is a port of the FreeModbus Linux demo. It derives from the demos/LINUX -directory of the FreeModBus version `1.5.0` (June 6, 2010) that can be -downloaded in its entirety from -http://developer.berlios.de/project/showfiles.php?group_id=6120. - -- `CONFIG_EXAMPLES_MODBUS_PORT`, Default `0` (for `/dev/ttyS0`). -- `CONFIG_EXAMPLES_MODBUS_BAUD`, Default B`38400`. -- `CONFIG_EXAMPLES_MODBUS_PARITY`, Default `MB_PAR_EVEN`. -- `CONFIG_EXAMPLES_MODBUS_REG_INPUT_START`, Default `1000`. -- `CONFIG_EXAMPLES_MODBUS_REG_INPUT_NREGS`, Default `4`. -- `CONFIG_EXAMPLES_MODBUS_REG_HOLDING_START`, Default `2000`. -- `CONFIG_EXAMPLES_MODBUS_REG_HOLDING_NREGS`, Default `130`. - -The FreeModBus library resides at `apps/modbus`. See `apps/modbus/README.txt` -for additional configuration information. - -## `mount` Mount Filesystem - -This contains a simple test of filesystem mountpoints. - -- `CONFIG_EXAMPLES_MOUNT_DEVNAME` – The name of the user-provided block device - to mount. If `CONFIG_EXAMPLES_MOUNT_DEVNAME` is not provided, then a RAM disk - will be configured. - -- `CONFIG_EXAMPLES_MOUNT_NSECTORS` – The number of _sectors_ in the RAM disk - used when `CONFIG_EXAMPLES_MOUNT_DEVNAME` is not defined. - -- `CONFIG_EXAMPLES_MOUNT_SECTORSIZE` – The size of each sectors in the RAM disk - used when `CONFIG_EXAMPLES_MOUNT_DEVNAME` is not defined. - -- `CONFIG_EXAMPLES_MOUNT_RAMDEVNO` – The RAM device minor number used to mount - the RAM disk used when `CONFIG_EXAMPLES_MOUNT_DEVNAME` is not defined. The - default is zero (meaning that `/dev/ram0` will be used). - -## `mtdpart` MTD Partition Test - -This examples provides a simple test of MTD partition logic. - -- `CONFIG_EXAMPLES_MTDPART` – Enables the MTD partition test example. - -- `CONFIG_EXAMPLES_MTDPART_ARCHINIT` – The default is to use the RAM MTD device - at `drivers/mtd/rammtd.c`. But an architecture-specific MTD driver can be used - instead by defining `CONFIG_EXAMPLES_MTDPART_ARCHINIT`. In this case, the - initialization logic will call `mtdpart_archinitialize()` to obtain the MTD - driver instance. - -- `CONFIG_EXAMPLES_MTDPART_NPARTITIONS` – This setting provides the number of - partitions to test. The test will divide the reported size of the MTD device - into equal-sized sub-regions for each test partition. Default: `3`. - -When `CONFIG_EXAMPLES_MTDPART_ARCHINIT` is not defined, this test will use the -RAM MTD device at `drivers/mtd/rammtd.c` to simulate FLASH. The size of the -allocated RAM drive will be: `CONFIG_EXMPLES_RAMMTD_ERASESIZE * -CONFIG_EXAMPLES_MTDPART_NEBLOCKS`. - -* `CONFIG_EXAMPLES_MTDPART_ERASESIZE` – This value gives the size of one erase - block in the MTD RAM device. This must exactly match the default configuration - in `drivers/mtd/rammtd.c`! - -* `CONFIG_EXAMPLES_MTDPART_NEBLOCKS` – This value gives the number of erase - blocks in MTD RAM device. - -## `mtdrwb` MTD Read-ahead and Write Buffering - -This examples provides a simple test of MTD Read-Ahead/Write buffering logic. - -- `CONFIG_EXAMPLES_MTDRWB` – Enables the MTD R/W buffering test example. - -- `CONFIG_EXAMPLES_MTDRWB_ARCHINIT` – The default is to use the RAM MTD device - at `drivers/mtd/rammtd.c`. But an architecture-specific MTD driver can be used - instead by defining `CONFIG_EXAMPLES_MTDRWB_ARCHINIT`. In this case, the - initialization logic will call `mtdrwb_archinitialize()` to obtain the MTD - driver instance. - -When `CONFIG_EXAMPLES_MTDRWB_ARCHINIT` is not defined, this test will use the -RAM MTD device at `drivers/mtd/rammtd.c` to simulate FLASH. The size of the -allocated RAM drive will be: `CONFIG_EXMPLES_RAMMTD_ERASESIZE * -CONFIG_EXAMPLES_MTDRWB_NEBLOCKS` - -- `CONFIG_EXAMPLES_MTDRWB_ERASESIZE` – This value gives the size of one erase - block in the MTD RAM device. This must exactly match the default configuration - in `drivers/mtd/rammtd.c`! - -- `CONFIG_EXAMPLES_MTDRWB_NEBLOCKS` – This value gives the number of erase - blocks in MTD RAM device. - -## `netpkt` `AF_PACKET` _Raw_ Sockets - -A test of `AF_PACKET`, _raw_ sockets. Contributed by Lazlo Sitzer. - -## `netloop` Network loopback device - -This is a simple test of the netwok loopback device. `examples/nettest` can also -be configured to provide (better) test of local loopback transfers. This version -derives from `examples/poll` and is focused on testing `poll()` with loopback -devices. - -- `CONFIG_EXAMPLES_NETLOOP=y` – Enables the nettest example. - -Dependencies: - -- `CONFIG_NET_LOOPBACK` – Requires local loopback support. -- `CONFIG_NET_TCP` – Requires TCP support with the following: - - `CONFIG_NET_TCPBACKLOG` - - `CONFIG_NET_TCP_WRITE_BUFFERS` -- `CONFIG_NET_IPv4` – Currently supports only IPv4. - -## `nettest` Client/Server Over TCP - -This is a simple network test for verifying client- and server- functionality in -a TCP/IP connection. - -- `CONFIG_EXAMPLES_NETTEST=y` – Enables the nettest example. -- `CONFIG_EXAMPLES_NETLIB=y` – The networking library in needed. - -Configurations: - -- Server on target hardware; client on host. -- Client on target hardware; server on host. -- Server and Client on different targets. -- Loopback configuration with both client and server on the same target. - -See also `examples/tcpecho`. - -## `nrf24l01_term` NRF24L01 Wireless Connection - -These is a simple test of NRF24L01-based wireless connectivity. Enabled with: - -- `CONFIG_EXAMPLES_NRF24L01TERM` - -Options: - -- `CONFIG_NSH_BUILTIN_APPS` – Built as an NSH built-in applications. - -## `nx` - -This directory contains a simple test of a subset of the NX APIs defined in -`include/nuttx/nx/nx.h`. The following configuration options can be selected: - -- `CONFIG_NSH_BUILTIN_APPS` – Build the NX example as a _built-in_ that can be - executed from the NSH command line -- `CONFIG_EXAMPLES_NX_BGCOLOR` – The color of the background. Default depends on - `CONFIG_EXAMPLES_NX_BPP`. -- `CONFIG_EXAMPLES_NX_COLOR1` – The color of window 1. Default depends on - `CONFIG_EXAMPLES_NX_BPP`. -- `CONFIG_EXAMPLES_NX_COLOR2` – The color of window 2. Default depends on - `CONFIG_EXAMPLES_NX_BPP`. -- `CONFIG_EXAMPLES_NX_TBCOLOR` – The color of the toolbar. Default depends on - `CONFIG_EXAMPLES_NX_BPP`. -- `CONFIG_EXAMPLES_NX_FONTID` – Selects the font (see font ID numbers in - `include/nuttx/nx/nxfonts.h`). -- `CONFIG_EXAMPLES_NX_FONTCOLOR` – The color of the fonts. Default depends on - `CONFIG_EXAMPLES_NX_BPP`. -- `CONFIG_EXAMPLES_NX_BPP` – Pixels per pixel to use. Valid options include `2`, - `4`, `8`, `16`, `24` and `32`. Default is `32`. -- `CONFIG_EXAMPLES_NX_RAWWINDOWS` – Use raw windows; Default is to use pretty, - framed NXTK windows with toolbars. -- `CONFIG_EXAMPLES_NX_STACKSIZE` – The stacksize to use when creating the NX - server. Default `2048`. -- `CONFIG_EXAMPLES_NX_CLIENTPRIO` – The client priority. Default: `100` -- `CONFIG_EXAMPLES_NX_SERVERPRIO` – The server priority. Default: `120` -- `CONFIG_EXAMPLES_NX_LISTENERPRIO` – The priority of the event listener thread. - Default `80`. - -The example also has the following settings and will generate an error if they -are not as expected: - -```conf -CONFIG_DISABLE_MQUEUE=n -CONFIG_DISABLE_PTHREAD=n -CONFIG_NX_BLOCKING=y -CONFIG_BOARDCTL=y -``` - -## `nxterm` Display NuttShell (NSH) as NX Console - -This directory contains yet another version of the NuttShell (NSH). This version -uses the NX console device defined in `include/nuttx/nx/nxterm.h` for output. -the result is that the NSH input still come from the standard console input -(probably a serial console). But the text output will go to an NX winbdow. -Prerequisite configuration settings for this test include: - -- `CONFIG_NX=y` – NX graphics must be enabled -- `CONFIG_NXTERM=y` – The NX console driver must be built -- `CONFIG_DISABLE_MQUEUE=n` – Message queue support must be available. -- `CONFIG_DISABLE_PTHREAD=n` – pthreads are needed -- `CONFIG_NX_BLOCKING=y` – pthread APIs must be blocking -- `CONFIG_NSH_CONSOLE=y` – NSH must be configured to use a console. - -The following configuration options can be selected to customize the test: - -- `CONFIG_EXAMPLES_NXTERM_BGCOLOR` – The color of the background. Default - Default is a darker royal blue. -- `CONFIG_EXAMPLES_NXTERM_WCOLOR` – The color of the window. Default is a light - slate blue. -- `CONFIG_EXAMPLES_NXTERM_FONTID` – Selects the font (see font ID numbers in - `include/nuttx/nx/nxfonts.h`). -- `CONFIG_EXAMPLES_NXTERM_FONTCOLOR` – The color of the fonts. Default is black. -- `CONFIG_EXAMPLES_NXTERM_BPP` – Pixels per pixel to use. Valid options include - `2`, `4`, `8`, `16`, `24` and `32`. Default is `32`. -- `CONFIG_EXAMPLES_NXTERM_TOOLBAR_HEIGHT` – The height of the toolbar. Default: - `16`. -- `CONFIG_EXAMPLES_NXTERM_TBCOLOR` – The color of the toolbar. Default is a - medium grey. -- `CONFIG_EXAMPLES_NXTERM_MINOR` – The NX console device minor number. Default - is `0` corresponding to `/dev/nxterm0`. -- `CONFIG_EXAMPLES_NXTERM_DEVNAME` – The quoted, full path to the NX console - device corresponding to `CONFIG_EXAMPLES_NXTERM_MINOR`. Default: - `/dev/nxterm0`. -- `CONFIG_EXAMPLES_NXTERM_PRIO` – Priority of the NxTerm task. Default: - `SCHED_PRIORITY_DEFAULT`. -- `CONFIG_EXAMPLES_NXTERM_STACKSIZE` – Stack size allocated for the NxTerm task. - Default: `2048`. -- `CONFIG_EXAMPLES_NXTERM_STACKSIZE` – The stacksize to use when creating the NX - server. Default: `2048`. -- `CONFIG_EXAMPLES_NXTERM_CLIENTPRIO` – The client priority. Default: `100`. -- `CONFIG_EXAMPLES_NXTERM_SERVERPRIO` – The server priority. Default: `120`. -- `CONFIG_EXAMPLES_NXTERM_LISTENERPRIO` – The priority of the event listener - thread. Default: `80`. - -## `nxflat` NXFLAT Binary - -This example builds a small NXFLAT test case. This includes several test -programs under `examples/nxflat` tests. These tests are build using the NXFLAT -format and installed in a ROMFS file system. At run time, each program in the -ROMFS file system is executed. Requires `CONFIG_NXFLAT`. - -## `nxhello` - -A very simple graphics example that just says _Hello, World!_ in the center of -the display. - -The following configuration options can be selected: - -- `CONFIG_NSH_BUILTIN_APPS` – Build the `NXHELLO` example as a _built-in_ that - can be executed from the NSH command line -- `CONFIG_EXAMPLES_NXHELLO_VPLANE` – The plane to select from the frame- buffer - driver for use in the test. Default: `0`. -- `CONFIG_EXAMPLES_NXHELLO_DEVNO` – The LCD device to select from the LCD driver - for use in the test. Default: `0`. -- `CONFIG_EXAMPLES_NXHELLO_BGCOLOR` – The color of the background. Default - depends on `CONFIG_EXAMPLES_NXHELLO_BPP`. -- `CONFIG_EXAMPLES_NXHELLO_FONTID` – Selects the font (see font ID numbers in - include/nuttx/nx/nxfonts.h). -- `CONFIG_EXAMPLES_NXHELLO_FONTCOLOR` – The color of the fonts used in the - background window. Default depends on `CONFIG_EXAMPLES_NXHELLO_BPP`. -- `CONFIG_EXAMPLES_NXHELLO_BPP` – Pixels per pixel to use. Valid options include - `2`, `4`, `8`, `16`, `24` and `32`. Default: `32`. - -## `nximage` Display NuttX Logo - -This is a simple example that just puts the NuttX logo image in the center of -the display. This only works for `RGB23` (`888`), `RGB16` (`656`), `RGB8` -(`332`), and 8-bit greyscale for now. - -- `CONFIG_NSH_BUILTIN_APPS` – Build the `NXIMAGE` example as a _built-in_ that - can be executed from the NSH command line. -- `CONFIG_EXAMPLES_NXIMAGE_VPLANE` – The plane to select from the frame- buffer - driver for use in the test. Default: `0`. -- `CONFIG_EXAMPLES_NXIMAGE_DEVNO` – The LCD device to select from the LCD driver - for use in the test: Default: `0`. -- `CONFIG_EXAMPLES_NXIMAGE_BPP` – Pixels per pixel to use. Valid options include - `8`, `16` and `24`. Default is `16`. -- `CONFIG_EXAMPLES_NXIMAGE_XSCALEp5`, `CONFIG_EXAMPLES_NXIMAGE_XSCALE1p5` or - `CONFIG_EXAMPLES_NXIMAGE_XSCALE2p0` – The logo image width is 160 columns. One - of these may be defined to rescale the image horizontally by .5, 1.5 or 2.0. -- `CONFIG_EXAMPLES_NXIMAGE_YSCALEp5`, `CONFIG_EXAMPLES_NXIMAGE_YSCALE1p5` or - `CONFIG_EXAMPLES_NXIMAGE_YSCALE2p0` – The logo image height is 160 rows. One - of these may be defined to rescale the image vertically by .5, 1.5 or 2.0. -- `CONFIG_EXAMPLES_NXIMAGE_GREYSCALE` – Grey scale image. Default: `RGB`. - -How was that run-length encoded image produced? - -1. I used GIMP output the image as a `.c` file. -2. I added some C logic to palette-ize the RGB image in the GIMP `.c` file. -3. Then I add some simple run-length encoding to palette-ized image. - -But now there is a tool that can be found in the NxWidgets package at -`NxWidgets/tools/bitmap_converter.py` that can be used to convert any graphics -format to the NuttX RLE format. - -**Note**: As of this writing, most of the pixel depth, scaling options, and -combinations thereof have not been tested. - -## `nxlines` NX Line Drawing - -A very simple graphics example that just exercised the NX line drawing logic. - -The following configuration options can be selected: - -- `CONFIG_EXAMPLES_NXLINES_VPLANE` – The plane to select from the frame- buffer - driver for use in the test. Default: `0`. -- `CONFIG_EXAMPLES_NXLINES_DEVNO` – The LCD device to select from the LCD driver - for use in the test: Default: `0`. -- `CONFIG_EXAMPLES_NXLINES_BGCOLOR` – The color of the background. Default - depends on `CONFIG_EXAMPLES_NXLINES_BPP`. -- `CONFIG_EXAMPLES_NXLINES_LINEWIDTH` – Selects the width of the lines in pixels - (default: `16`). -- `CONFIG_EXAMPLES_NXLINES_LINECOLOR` – The color of the central lines drawn in - the background window. Default depends on `CONFIG_EXAMPLES_NXLINES_BPP` (there - really is no meaningful default). -- `CONFIG_EXAMPLES_NXLINES_BORDERWIDTH` – The width of the circular border drawn - in the background window. (default: `16`). -- `CONFIG_EXAMPLES_NXLINES_BORDERCOLOR` – The color of the circular border drawn - in the background window. Default depends on `CONFIG_EXAMPLES_NXLINES_BPP` - (there really is no meaningful default). -- `CONFIG_EXAMPLES_NXLINES_CIRCLECOLOR` – The color of the circular region - filled in the background window. Default depends on - `CONFIG_EXAMPLES_NXLINES_BPP` (there really is no meaningful default). -- `CONFIG_EXAMPLES_NXLINES_BORDERCOLOR` – The color of the lines drawn in the - background window. Default depends on `CONFIG_EXAMPLES_NXLINES_BPP` (there - really is no meaningful default). -- `CONFIG_EXAMPLES_NXLINES_BPP` – Pixels per pixel to use. Valid options include - `2`, `4`, `8`, `16`, `24`, and `32`. Default is `16`. -- `CONFIG_NSH_BUILTIN_APPS` – Build the NX lines examples as an NSH built-in - function. - -## `nxtext` Display NX Text - -This directory contains another simple test of a subset of the NX APIs defined -in `include/nuttx/nx/nx.h`. This text focuses on text displays on the display -background combined with pop-up displays over the text. The text display will -continue to update while the pop-up is visible. - -**Note**: This example will **only** work with FB drivers and with LCD drivers -that support reading the contents of the internal LCD memory **unless** you -define `CONFIG_EXAMPLES_NXTEXT_NOGETRUN`. If you notice garbage on the display -or a failure at the point where the display should scroll, it is probably -because you have an LCD driver that is write-only. - -The following configuration options can be selected: - -- `CONFIG_NSH_BUILTIN_APPS` – Build the `NXTEXT` example as a _built-in_ that - can be executed from the NSH command line. -- `CONFIG_EXAMPLES_NXTEXT_BGCOLOR` – The color of the background. Default - depends on `CONFIG_EXAMPLES_NXTEXT_BPP`. -- `CONFIG_EXAMPLES_NXTEXT_BGFONTID` – Selects the font to use in the background - text (see font ID numbers in `include/nuttx/nx/nxfonts.h`). -- `CONFIG_EXAMPLES_NXTEXT_BGFONTCOLOR` – The color of the fonts used in the - background window. Default depends on `CONFIG_EXAMPLES_NXTEXT_BPP`. -- `CONFIG_EXAMPLES_NXTEXT_PUCOLOR` – The color of the pop-up window. Default - depends on `CONFIG_EXAMPLES_NXTEXT_BPP`. -- `CONFIG_EXAMPLES_NXTEXT_PUFONTID` – Selects the font to use in the pop-up - windows (see font ID numbers in `include/nuttx/nx/nxfonts.h`). -- `CONFIG_EXAMPLES_NXTEXT_PUFONTCOLOR` – The color of the fonts used in the - background window. Default depends on `CONFIG_EXAMPLES_NXTEXT_BPP`. -- `CONFIG_EXAMPLES_NXTEXT_BPP` – Pixels per pixel to use. Valid options include - `2`, `4`, `8`, `16`, `24` and `32`. Default is `32`. -- `CONFIG_EXAMPLES_NXTEXT_NOGETRUN` – If your display is read-only OR if reading - is not reliable, then select this configuration to avoid reading from the - display. -- `CONFIG_EXAMPLES_NXTEXT_BMCACHE` – The maximum number of characters that can - be put in the background window. Default is `128`. -- `CONFIG_EXAMPLES_NXTEXT_GLCACHE` – The maximum number of pre-rendered fonts - that can be retained for the background window. -- `CONFIG_EXAMPLES_NXTEXT_STACKSIZE` – The stacksize to use when creating the NX - server. Default `2048`. -- `CONFIG_EXAMPLES_NXTEXT_CLIENTPRIO` – The client priority. Default: `100`. -- `CONFIG_EXAMPLES_NXTEXT_SERVERPRIO` – The server priority. Default: `120`. -- `CONFIG_EXAMPLES_NXTEXT_LISTENERPRIO` – The priority of the event listener - thread. Default: `80`. -- `CONFIG_EXAMPLES_NXTEXT_NOTIFYSIGNO` – The signal number to use with - `nx_eventnotify()`. Default: `32`. - -The example also expects the following settings and will generate an error if -they are not as expected: - -```conf -CONFIG_DISABLE_MQUEUE=n -CONFIG_DISABLE_PTHREAD=n -CONFIG_NX_BLOCKING=y -``` - -## `null` - -This is the do nothing application. It is only used for bringing up new NuttX -architectures in the most minimal of environments. - -## `obd2` - -A simple test of `apps/canutils/libobd2`. - -## `oneshot` Oneshot Timer - -Simple test of a oneshot driver. - -## `pca9635` `PCA9635PW` LED - -A simple test of the `PCA9635PW` LED driver. - -## `pdcurses` - -This directory contains the `demo/test` programs that accompany the public -domain cursors package (`pdcurses`) that can be found at -`apps/graphics/pdcurs34`. - -## `pipe` - -A test of the `mkfifo()` and `pipe()` APIs. Requires `CONFIG_PIPES` - -- `CONFIG_EXAMPLES_PIPE_STACKSIZE` – Sets the size of the stack to use when - creating the child tasks. The default size is `1024`. - -## `poll` - -A test of the `poll()` and `select()` APIs using FIFOs and, if available, -`stdin`, and a TCP/IP socket. In order to use the TCP/IP select test, you must -have the following things selected in your NuttX configuration file: - -- `CONFIG_NET` – Defined for general network support. -- `CONFIG_NET_TCP` – Defined for TCP/IP support. -- `CONFIG_NET_NTCP_READAHEAD_BUFFERS` – Defined to be greater than zero. -- `CONFIG_EXAMPLES_POLL_NOMAC` – (May be defined to use software assigned - MAC) -- `CONFIG_EXAMPLES_POLL_IPADDR` – Target IP address. -- `CONFIG_EXAMPLES_POLL_DRIPADDR` – Default router IP address. -- `CONFIG_EXAMPLES_POLL_NETMASK` – Network mask. - -In order to for select to work with incoming connections, you must also select: - -- `CONFIG_NET_TCPBACKLOG` – Incoming connections pend in a backlog until - `accept()` is called. - -In additional to the target device-side example, there is also a host-side -application in this directory. It can be compiled under Linux or Cygwin as -follows: - -```makefile -cd examples/usbserial -make -f Makefile.host TOPDIR= TARGETIP= -``` - -Where `` is the IP address of your target board. - -This will generate a small program called 'host'. Usage: - -1. Build the `examples/poll` target program with TCP/IP poll support and start - the target. - -2. Then start the host application: - - ```bash - ./host - ``` - -The host and target will exchange are variety of small messages. Each message -sent from the host should cause the select to return in target. The target -example should read the small message and send it back to the host. The host -should then receive the echo'ed message. - -If networking is enabled, applications using this example will need to provide -the following definition in the `defconfig` file to enable the networking -library: - -- `CONFIG_NETUTILS_NETLIB=y` - -## `posix_spawn` - -This is a simple test of the `posix_spawn()` API. The example derives from -`examples/elf`. As a result, these tests are built using the relocatable ELF -format installed in a ROMFS file system. At run time, the test program in the -ROMFS file system is spawned using `posix_spawn()`. - -Requires: - -- `CONFIG_BINFMT_DISABLE=n` – Don't disable the binary loader. -- `CONFIG_ELF=y` – Enable ELF binary loader. -- `CONFIG_LIBC_EXECFUNCS=y` – Enable support for posix_spawn. -- `CONFIG_EXECFUNCS_SYMTAB_ARRAY="g_spawn_exports"` – The name of the symbol - table created by the test. -- `CONFIG_EXECFUNCS_NSYMBOLS_VAR="g_spawn_nexports"` – Name of variable holding - the number of symbols. -- `CONFIG_POSIX_SPAWN_STACKSIZE=768` – This default setting. - -Test-specific configuration options: - -- `CONFIG_EXAMPLES_POSIXSPAWN_DEVMINOR` – The minor device number of the ROMFS - block. driver. For example, the `N` in `/dev/ramN`. Used for registering the - RAM block driver that will hold the ROMFS file system containing the ELF - executables to be tested. Default: `0`. - -- `CONFIG_EXAMPLES_POSIXSPAWN_DEVPATH` – The path to the ROMFS block driver - device. This must match `EXAMPLES_POSIXSPAWN_DEVMINOR`. Used for registering - the RAM block driver that will hold the ROMFS file system containing the ELF - executables to be tested. Default: `/dev/ram0`. - -**Notes**: - -1. `CFLAGS` should be provided in `CELFFLAGS`. RAM and FLASH memory regions may - require long allcs. For ARM, this might be: - - ```makefile - CELFFLAGS = $(CFLAGS) -mlong-calls - ``` - - Similarly for C++ flags which must be provided in `CXXELFFLAGS`. - -2. Your top-level `nuttx/Make.defs` file must also include an appropriate - definition, `LDELFFLAGS`, to generate a relocatable ELF object. With GNU LD, - this should include `-r` and `-e main` (or `_main` on some platforms). - - ```makefile - LDELFFLAGS = -r -e main - ``` - - If you use GCC to link, you make also need to include `-nostdlib`. - -3. This example also requires `genromfs`. `genromfs` can be build as part of the - nuttx toolchain. Or can built from the `genromfs` sources that can be found - in the NuttX tools repository (`genromfs-0.5.2.tar.gz`). In any event, the - `PATH` variable must include the path to the `genromfs` executable. - -4. ELF size: The ELF files in this example are, be default, quite large because - they include a lot of _build garbage_. You can greatly reduce the size of the - ELF binaries are using the `objcopy --strip-unneeded` command to remove - un-necessary information from the ELF files. - -5. Simulator. You cannot use this example with the NuttX simulator on Cygwin. - That is because the Cygwin GCC does not generate ELF file but rather some - Windows-native binary format. - - If you really want to do this, you can create a NuttX x86 buildroot toolchain - and use that be build the ELF executables for the ROMFS file system. - -6. Linker scripts. You might also want to use a linker scripts to combine - sections better. An example linker script is at - `nuttx/binfmt/libelf/gnu-elf.ld`. That example might have to be tuned for - your particular linker output to position additional sections correctly. The - GNU LD `LDELFFLAGS` then might be: - - ```makefile - LDELFFLAGS = -r -e main -T$(TOPDIR)/binfmt/libelf/gnu-elf.ld - ``` - -## `powerled` - -This is a powerled driver example application. This application support three -operation modes which can be selected from NSH command line: - -1. Demo mode. -2. Continuous mode. -3. Flash mode. - -## `pty_test` Pseudo-Terminals - -A test of NuttX pseudo-terminals. Provided by Alan Carvalho de Assis. - -## `pwfb` - -A graphics example using pre-window frame buffers. The example shows three -windows containing text moving around, crossing each other from _above_ and from -_below_. The example application is NOT updating the windows any anyway! The -application is only changing the window position. The windows are being updated -from the per-winidow framebuffers automatically. - -This example is reminiscent of Pong: Each window travels in straight line until -it hits an edge, then it bounces off. The window is also raised when it hits the -edge (gets _focus_). This tests all combinations of overap. - -**Note**: A significant amount of RAM, usually external SDRAM, is required to -run this demo. At 16bpp and a 480x272 display, each window requires about 70Kb -of RAM for its framebuffer. - -## `pwm` General PWM - -A test of a PWM device driver. It simply enables a pulsed output for a specified -frequency and duty for a specified period of time. This example can ONLY be -built as an NSH built-in function. - -This test depends on these specific PWM/NSH configurations settings (your -specific PWM settings might require additional settings). - -- `CONFIG_PWM` – Enables PWM support. -- `CONFIG_PWM_PULSECOUNT` – Enables PWM pulse count support (if the hardware - supports it). -- `CONFIG_NSH_BUILTIN_APPS` – Build the PWM test as an NSH built-in function. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_PWM_DEVPATH` – The path to the default PWM device. Default: - `/dev/pwm0`. -- `CONFIG_EXAMPLES_PWM_FREQUENCY` – The initial PWM frequency. Default: `100` Hz -- `CONFIG_EXAMPLES_PWM_DUTYPCT` – The initial PWM duty as a percentage. Default: - `50`%. -- `CONFIG_EXAMPLES_PWM_DURATION` – The initial PWM pulse train duration in - seconds. Used only if the current pulse count is zero (pulse count is only - supported if `CONFIG_PWM_PULSECOUNT` is defined). Default: `5` seconds. -- `CONFIG_EXAMPLES_PWM_PULSECOUNT` – The initial PWM pulse count. This option is - only available if `CONFIG_PWM_PULSECOUNT` is non-zero. Default: `0` (i.e., use - the duration, not the count). - -## `qencoder` Quadrature Encoder - -This example is a simple test of a Quadrature Encoder driver. It simply reads -positional data from the encoder and prints it., - -This test depends on these specific QE/NSH configurations settings (your -specific PWM settings might require additional settings). - -- `CONFIG_SENSORS_QENCODER` – Enables quadrature encoder support (upper-half - driver). -- `CONFIG_NSH_BUILTIN_APPS` – Build the QE test as an NSH built-in function. - Default: Built as a standalone program. - -Additional configuration options will mostly likely be required for the board- -specific lower-half driver. See the `README.txt` file in your board -configuration directory. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_QENCODER_DEVPATH` – The path to the QE device. Default: - `/dev/qe0`. -- `CONFIG_EXAMPLES_QENCODER_NSAMPLES` – This number of samples is collected and - the program terminates. Default: Samples are collected indefinitely. -- `CONFIG_EXAMPLES_QENCODER_DELAY` – This value provides the delay (in - milliseconds) between each sample. Default: `100` milliseconds. - -## `random` Random Numbers - -This is a very simply test of `/dev/random`. It simple collects random numbers -and displays them on the console. - -Prerequistes: - -- `CONFIG_DEV_RANDOM` – Support for `/dev/random` must be enabled in order to - select this example. - -Configuration: - -- `CONFIG_EXAMPLES_RANDOM` – Enables the `/dev/random` test. -- `CONFIG_EXAMPLES_MAXSAMPLES` – This is the size of the `/dev/random` I/O - buffer in units of 32-bit samples. Careful! This buffer is allocated on the - stack as needed! Default `64`. -- `CONFIG_EXAMPLES_NSAMPLES` – When you execute the `rand` command, a number of - samples ranging from `1` to `EXAMPLES_MAXSAMPLES` may be specified. If no - argument is specified, this is the default number of samples that will be - collected and displayed. Default `8`. - -## `relays` Relays - -Requires `CONFIG_ARCH_RELAYS`. Contributed by Darcy Gong. - -**Note**: This test exercises internal relay driver interfaces. As such, it -relies on internal OS interfaces that are not normally available to a user-space -program. As a result, this example cannot be used if a NuttX is built as a -protected, supervisor kernel (`CONFIG_BUILD_PROTECTED` or -`CONFIG_BUILD_KERNEL`). - -## `rfid_readuid` RFID - -RFID `READUID` example. - -## `rgbled` RGB LED Using PWM - -This example demonstrates the use of the RGB led driver to drive an RGB LED with -PWM outputs so that all color characteristcs of RGB LED can be controlled. - -## `romfs` File System - -This example exercises the romfs filesystem. Configuration options include: - -- `CONFIG_EXAMPLES_ROMFS_RAMDEVNO` – The minor device number to use for the ROM - disk. The default is `1` (meaning `/dev/ram1`). -- `CONFIG_EXAMPLES_ROMFS_SECTORSIZE` – The ROM disk sector size to use. Default - is `64`. -- `CONFIG_EXAMPLES_ROMFS_MOUNTPOINT` – The location to mount the ROM disk. - Default: `/usr/local/share`. - -## `sendmail` SMTP Client - -This examples exercises the uIP SMTP logic by sending a test message to a -selected recipient. This test can also be built to execute on the Cygwin/Linux -host environment: - -```bash -cd examples/sendmail -make -f Makefile.host TOPDIR= -``` - -Settings unique to this example include: - -- `CONFIG_EXAMPLES_SENDMAIL_NOMAC` – May be defined to use software assigned - MAC (optional) -- `CONFIG_EXAMPLES_SENDMAIL_IPADDR` – Target IP address (required) -- `CONFIG_EXAMPLES_SENDMAIL_DRIPADDR` – Default router IP address (required) -- `CONFIG_EXAMPLES_SENDMAILT_NETMASK` – Network mask (required) -- `CONFIG_EXAMPLES_SENDMAIL_RECIPIENT` – The recipient of the email (required) -- `CONFIG_EXAMPLES_SENDMAIL_SENDER` – Optional. Default: - `nuttx-testing@example.com` -- `CONFIG_EXAMPLES_SENDMAIL_SUBJECT` – Optional. Default: `Testing SMTP from - NuttX` -- `CONFIG_EXAMPLES_SENDMAIL_BODY` – Optional. Default: `Test message sent - by NuttX` - -**Note 1**: This test has not been verified on the NuttX target environment. As -of this writing, unit-tested in the Cygwin/Linux host environment. - -**Note 2**: This sendmail example only works for the simplest of environments. -Virus protection software on your host may have to be disabled to allow you to -send messages. Only very open, unprotected recipients can be used. Most will -protect themselves from this test email because it looks like SPAM. - -Applications using this example will need to enable the following netutils -libraries in their defconfig file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_SMTP=y -``` - -## `serialblaster` - -Sends a repeating pattern (the alphabet) out a serial port continuously. This -may be useful if you are trying run down other problems that you think might -only occur when the serial port usage is high. - -## `serialrx` - -Constant receives serial data. This is the complement to `serialblaster`. This -may be useful if you are trying run down other problems that you think might -only occur when the serial port usage is high. - -## `serloop` Serial Loopback - -This is a mindlessly simple loopback test on the console. Useful for testing new -serial drivers. Configuration options include: - -- `CONFIG_EXAMPLES_SERLOOP_BUFIO` – Use C buffered I/O (`getchar`/`putchar`) vs. - raw console I/O (read/read). - -## `slcd` Alphanumeric Segment LCD - -A simple test of alphanumeric, segment LCDs (SLCDs). - -- `CONFIG_EXAMPLES_SLCD` – Enable the SLCD test - -## `smps` Switched-Mode Power Supply - -This is a SMPS (Switched-mode power supply) driver example application. - -## `sotest` Shared Library Module Test - -This example builds a small shared library module test case. The test shared -library is built using the relocatable ELF format and installed in a ROMFS file -system. At run time, the shared library is installed and exercised. Requires -`CONFIG_LIBC_DLFCN`. Other configuration options: - -- `CONFIG_EXAMPLES_SOTEST_DEVMINOR` – The minor device number of the ROMFS block - driver. For example, the `N` in `/dev/ramN`. Used for registering the RAM - block driver that will hold the ROMFS file system containing the ELF - executables to be tested. Default: `0`. - -- `CONFIG_EXAMPLES_SOTEST_DEVPATH` – The path to the ROMFS block driver device. - This must match `EXAMPLES_ELF_DEVMINOR`. Used for registering the RAM block - driver that will hold the ROMFS file system containing the ELF executables to - be tested. Default: `/dev/ram0`. - -**Notes**: - -1. `CFLAGS` should be provided in `CMODULEFLAGS`. RAM and FLASH memory regions - may require long allcs. For ARM, this might be: - - ```makefile - CMODULEFLAGS = $(CFLAGS) -mlong-calls - ``` - - Similarly for C++ flags which must be provided in `CXXMODULEFLAGS`. - -2. Your top-level `nuttx/Make.defs` file must also include an appropriate - definition, `LDMODULEFLAGS`, to generate a relocatable ELF object. With GNU - LD, this should include `-r` and `-e `. - - ```makefile - LDMODULEFLAGS = -r -e module_initialize - ``` - - If you use GCC to link, you make also need to include `-nostdlib`. - -3. This example also requires `genromfs`. `genromfs` can be build as part of the - nuttx toolchain. Or can built from the `genromfs` sources that can be found - in the NuttX tools repository (`genromfs-0.5.2.tar.gz`). In any event, the - `PATH` variable must include the path to the `genromfs` executable. - -4. ELF size: The ELF files in this example are, be default, quite large because - they include a lot of _build garbage_. You can greatly reduce the size of the - ELF binaries are using the `objcopy --strip-unneeded` command to remove - un-necessary information from the ELF files. - -5. Simulator. You cannot use this example with the NuttX simulator on Cygwin. - That is because the Cygwin GCC does not generate ELF file but rather some - Windows-native binary format. - - If you really want to do this, you can create a NuttX x86 buildroot toolchain - and use that be build the ELF executables for the ROMFS file system. - -6. Linker scripts. You might also want to use a linker scripts to combine - sections better. An example linker script is at - `nuttx/libc/modlib/gnu-elf.ld`. That example might have to be tuned for your - particular linker output to position additional sections correctly. The GNU - LD `LDMODULEFLAGS` then might be: - -```makefile -LDMODULEFLAGS = -r -e module_initialize -T$(TOPDIR)/libc/modlib/gnu-elf.ld -``` - -## `stat` - -A simple test of `stat()`, `fstat()`, and `statfs()`. This is useful primarily -for bringing up a new file system and verifying the correctness of these -operations. - -## `sx127x_demo` `SX127X` Radio - -This example demonstrates the use of the `SX127X` radio. - -## `system` - -This is a simple test of the `system()` command. The test simply executes this -`system` command: - -```c -ret = system("ls -Rl /"); -``` - -## `tcpblaster` TCP Performance Test - -The `tcpblaster` example derives from the `nettest` example and basically -duplicates that example when the `nettest` PERFORMANCE option is selected. -`tcpblaster` has a little better reporting of performance stats, however. - -## `tcpecho` TCP Echo Server - -Simple single threaded, poll based TCP echo server. This example implements the -TCP Echo Server from W. Richard Stevens _UNIX Network Programming_ Book. -Contributed by Max Holtberg. - -See also `examples/nettest` - -- `CONFIG_EXAMPLES_TCPECHO=y` – Enables the TCP echo server. -- `CONFIG_XAMPLES_TCPECHO_PORT` – Server Port, default `80`. -- `CONFIG_EXAMPLES_TCPECHO_BACKLOG` – Listen Backlog, default `8`. -- `CONFIG_EXAMPLES_TCPECHO_NCONN` – Number of Connections, default `8`. -- `CONFIG_EXAMPLES_TCPECHO_DHCPC` – DHCP Client, default `n`. -- `CONFIG_EXAMPLES_TCPECHO_NOMAC` – Use Canned MAC Address, default `n`. -- `CONFIG_EXAMPLES_TCPECHO_IPADDR` – Target IP address, default `0x0a000002`. -- `CONFIG_EXAMPLES_TCPECHO_DRIPADDR` – Default Router IP address (Gateway), - default `0x0a000001`. -- `CONFIG_EXAMPLES_TCPECHO_NETMASK` – Network Mask, default `0xffffff00`. - -## `telnetd` Simple Telnet Shell - -This directory contains a functional port of the tiny uIP shell. In the NuttX -environment, the NuttShell (at `apps/nshlib`) supersedes this tiny shell and -also supports `telnetd`. - -- `CONFIG_EXAMPLES_TELNETD` – Enable the Telnetd example. -- `CONFIG_NETUTILS_NETLIB`, `CONFIG_NETUTILS_TELNETD` – Enable netutils libraries - needed by the Telnetd example. -- `CONFIG_EXAMPLES_TELNETD_DAEMONPRIO` – Priority of the Telnet daemon. Default: - `SCHED_PRIORITY_DEFAULT`. -- `CONFIG_EXAMPLES_TELNETD_DAEMONSTACKSIZE` – Stack size allocated for the - Telnet daemon. Default: `2048`. -- `CONFIG_EXAMPLES_TELNETD_CLIENTPRIO` – Priority of the Telnet client. Default: - `SCHED_PRIORITY_DEFAULT`. -- `CONFIG_EXAMPLES_TELNETD_CLIENTSTACKSIZE` – Stack size allocated for the - Telnet client. Default: `2048`. -- `CONFIG_EXAMPLES_TELNETD_NOMAC` – If the hardware has no MAC address of its - own, define this `=y` to provide a bogus address for testing. -- `CONFIG_EXAMPLES_TELNETD_IPADDR` – The target IP address. Default `10.0.0.2`. -- `CONFIG_EXAMPLES_TELNETD_DRIPADDR` – The default router address. Default - `10.0.0.1`. -- `CONFIG_EXAMPLES_TELNETD_NETMASK` – The network mask. Default: - `255.255.255.0`. - -Also, make sure that you have the following set in the NuttX configuration file -or else the performance will be very bad (because there will be only one -character per TCP transfer): - -- `CONFIG_STDIO_BUFFER_SIZE` – Some value `>= 64` -- `CONFIG_STDIO_LINEBUFFER=y` - -## `termios` Simple Termios interface test - -This directory contains a simple application that uses the termios interface -to change serial parameters. Just import a `nsh` config and enable the -following symbols: - -- `CONFIG_SERIAL_TERMIOS` – Enable the termios support. -- `CONFIG_EXAMPLES_TERMIOS` – Enable the example itself. - -## `thttpd` THTTPD server - -An example that builds `netutils/thttpd` with some simple NXFLAT CGI programs. -See `boards/README.txt` for most THTTPD settings. In addition to those, this -example accepts: - -- `CONFIG_EXAMPLES_THTTPD_NOMAC` – (May be defined to use software assigned - MAC) -- `CONFIG_EXAMPLES_THTTPD_DRIPADDR` – Default router IP address. -- `CONFIG_EXAMPLES_THTTPD_NETMASK` – Network mask. - -Applications using this example will need to enable the following `netutils` -libraries in the `defconfig` file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_THTTPD=y -``` - -## `tiff` - -This is a simple unit test for the TIFF creation library at `apps/graphic/tiff`. -It is configured to work in the Linux user-mode simulation and has not been -tested in any other environment. - -At a minimum, to run in an embedded environment, you will probably have to -change the configured paths to the TIFF files defined in the example. - -- `CONFIG_EXAMPLES_TIFF_OUTFILE` – Name of the resulting TIFF file. Default is - `/tmp/result.tif`. -- `CONFIG_EXAMPLES_TIFF_TMPFILE1/2` – Names of two temporaries files that will - be used in the file creation. Defaults are `/tmp/tmpfile1.dat` and - `/tmp/tmpfile2.dat`. - -The following must also be defined in your `apps/` configuration file: - -```conf -CONFIG_EXAMPLES_TIFF=y -CONFIG_GRAPHICS_TIFF=y -``` - -## `timer` - -This is a simple test of the timer driver (see `include/nuttx/timers/timer.h`). - -Dependencies: - -- `CONFIG_TIMER` – The timer driver must be selected - -Example configuration: - -- `CONFIG_EXAMPLES_TIMER_DEVNAME` – This is the name of the timer device that - will be tested. Default: `/dev/timer0`. -- `CONFIG_EXAMPLES_TIMER_INTERVAL` – This is the timer interval in microseconds. - Default: `1000000`. -- `CONFIG_EXAMPLES_TIMER_DELAY` – This is the delay between timer samples in - microseconds. Default: `10000`. -- `CONFIG_EXAMPLES_TIMER_STACKSIZE` – This is the stack size allocated when the - timer task runs. Default: `2048`. -- `CONFIG_EXAMPLES_TIMER_PRIORITY` – This is the priority of the timer task: - Default: `100`. -- `CONFIG_EXAMPLES_TIMER_PROGNAME` – This is the name of the program that will - be used when the NSH ELF program is installed. Default: `timer`. - -## `timer_gpio` - -This example uses the timer interrupt to periodically change the state of a -digital output. The digital output may be a relay, a led or anything else. -This example can be very useful to validate timer drivers by using a logic -analyzer connected to the digital output. This example mainly differs from -the timer example because it waits on a sigwaitinfo() instead of using a -signal handler. This approach ensures a deterministic wake-up time when the -signal occurs. - -Dependencies: - -- `CONFIG_TIMER` – The timer driver must be selected. -- `CONFIG_DEV_GPIO` – The GPIO driver must be selected. - -Note: You should also select one timer instance and have the gpio driver -properly configured in your board logic. - -Example configuration: - -- `EXAMPLES_TIMER_GPIO_TIM_DEVNAME` – This is the name of the timer device - that will be used. - Default: `/dev/timer0`. -- `EXAMPLES_TIMER_GPIO_GPIO_DEVNAME` – This is the name of the gpio device - that will be used. - Default: `/dev/gpio0`. -- `EXAMPLES_TIMER_GPIO_INTERVAL` – This is the timer interval in - microseconds. - Default: `1000000`. -- `EXAMPLES_TIMER_GPIO_SIGNO` – This is the signal number that is used to - notify that a timer interrupt occurred. - Default: `32`. -- `EXAMPLES_TIMER_GPIO_STACKSIZE` – This is the stack size allocated when the - timer task runs. - Default: `2048`. -- `EXAMPLES_TIMER_GPIO_PRIORITY` – This is the priority of the timer task. - Default: `255`. -- `EXAMPLES_TIMER_GPIO_PROGNAME` – This is the name of the program that will - be used from the nsh. - Default: `timer_gpio`. - -## `touchscreen` Touchscreen Events - -This configuration implements a simple touchscreen test at -`apps/examples/touchscreen`. This test will create an empty X11 window and will -print the touchscreen output as it is received from the simulated touchscreen -driver. - -- `CONFIG_NSH_BUILTIN_APPS` – Build the touchscreen test as an NSH built-in - function. Default: Built as a standalone program. -- `CONFIG_EXAMPLES_TOUCHSCREEN_MINOR` – The minor device number. Minor `N` - corresponds to touchscreen device `/dev/inputN`. Note this value must with - `CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH`. Default `0`. -- `CONFIG_EXAMPLES_TOUCHSCREEN_DEVPATH` – The path to the touchscreen device. - This must be consistent with `CONFIG_EXAMPLES_TOUCHSCREEN_MINOR`. Default: - `/dev/input0`. -- `CONFIG_EXAMPLES_TOUCHSCREEN_NSAMPLES` – This number of samples is collected - and the program terminates. Default: Samples are collected indefinitely. -- `CONFIG_EXAMPLES_TOUCHSCREEN_MOUSE` – The touchscreen test can also be - configured to work with a mouse driver by setting this option. - -The following additional configurations must be set in the NuttX configuration -file: - -- `CONFIG_INPUT=y` (plus any touchscreen-specific settings) - -The following must also be defined in your apps configuration file: - -- `CONFIG_EXAMPLES_TOUCHSREEN=y` - -This example code will call `boardctl()` to setup the touchscreen driver for -texting. The implementation of `boardctl()` will require that board- specific -logic provide the following interfaces that will be called by the `boardctl()` -in order to initialize the touchscreen hardware: - -```c -int board_tsc_setup(int minor); -``` - -## `udp` Client/Server Over UDP - -This is a simple network test for verifying client- and server- functionality -over UDP. - -Applications using this example will need to enabled the following `netutils` -libraries in the `defconfig` file: - -- `CONFIG_NETUTILS_NETLIB=y` - -Possible configurations: - -- Server on target hardware; client on host. -- Client on target hardware; Server on host. -- Server and Client on different targets. - -## `udpblaster` - -This is a simple network test for stressing UDP transfers. It simply sends UDP -packets from both the host and the target and the highest possible rate. - -## `unionfs` Union File System - -This is at trivial test of the Union File System. See -`nuttx/fs/unionfs/README.txt`. Dependencies: - -- `CONFIG_DISABLE_MOUNTPOINT` – Mountpoint support must not be - disabled. -- `CONFIG_FS_ROMFS` – ROMFS support is required. -- `CONFIG_FS_UNIONFS` – Union File System support is required. - -Configuration options. Use the defaults if you are unsure of what you are doing: - -- `CONFIG_EXAMPLES_UNIONFS` – Enables the example. -- `CONFIG_EXAMPLES_UNIONFS_MOUNTPT` – Mountpoint path for the Union File - System. -- `CONFIG_EXAMPLES_UNIONFS_TMPA` – Temporary mount point for file system - `1`. -- `CONFIG_EXAMPLES_UNIONFS_TMPB` – Temporary mount point for file system - `2`. -- `CONFIG_EXAMPLES_UNIONFS_RAMDEVNO_A` – ROMFS file system `1` RAM disk device - number. -- `CONFIG_EXAMPLES_UNIONFS_RAMDEVNO_B` – ROMFS file system `2` RAM disk device - number. -- `CONFIG_EXAMPLES_UNIONFS_SECTORSIZE` – ROM disk sector size. - -See the `README.txt` file at `nuttx/boards/sim/sim/sim/README.txt` for a -walk-through of the output of this text. - -## `usbserial` USB Serial Hello World - -### Target configuration - -This is another implementation of _Hello, World_ but this one uses a USB serial -driver. Configuration options can be used to simply the test. These options -include: - -- `CONFIG_EXAMPLES_USBSERIAL_INONLY` – Only verify IN (device-to-host) data - transfers. Default: both. -- `CONFIG_EXAMPLES_USBSERIAL_OUTONLY` – Only verify OUT (host-to-device) data - transfers. Default: both. -- `CONFIG_EXAMPLES_USBSERIAL_ONLYSMALL` – Send only small, single packet - messages. Default: Send large and small. -- `CONFIG_EXAMPLES_USBSERIAL_ONLYBIG` – Send only large, multi-packet messages. - Default: Send large and small. - -If `CONFIG_USBDEV_TRACE` is enabled (or `CONFIG_DEBUG_FEATURES` and -`CONFIG_DEBUG_USB`), then the example code will also manage the USB trace -output. The amount of trace output can be controlled using: - -- `CONFIG_EXAMPLES_USBSERIAL_TRACEINIT` – Show initialization events. -- `CONFIG_EXAMPLES_USBSERIAL_TRACECLASS` – Show class driver events. -- `CONFIG_EXAMPLES_USBSERIAL_TRACETRANSFERS` – Show data transfer events. -- `CONFIG_EXAMPLES_USBSERIAL_TRACECONTROLLER` – Show controller events. -- `CONFIG_EXAMPLES_USBSERIAL_TRACEINTERRUPTS` – Show interrupt-related events. - -Error results are always shown in the trace output. - -### Host-side test program - -In additional to the target device-side example, there is also a host-side -application in this directory. This host side application must be executed on a -Linux host in order to perform the `USBSERIAL` test. The host application can be -compiled under Linux (or Cygwin?) as follows: - -```bash -cd examples/usbserial -make -f Makefile.host TOPDIR= -``` - -### Running the test - -This will generate a small program called `host`. Usage: - -1. Build the `examples/usbserial` target program and start the target. - -2. Wait a bit, then do enter: - - ```shell - dmesg - ``` - - At the end of the dmesg output, you should see the serial device was - successfully idenfied and assigned to a tty device, probably `/dev/ttyUSB0` - or `/dev/ttyACM0` (depending on the configured USB serial driver). - -3. Then start the host application: - - ```bash - ./host [] - ``` - - Where: - - - `` is the USB TTY device to use. The default is `/dev/ttyUSB0` - (for the PL2303 emulation) or `/dev/ttyACM0` (for the CDC/ACM serial - device). - -The host and target will exchange are variety of very small and very large -serial messages. - -## `userfs` UserFS File System - -A simple test of the UserFS file system. - -## `ustream` Unix Datagram Sockets - -This is the same test as `examples/udp` and similar to `examples/ustream`, but -using Unix domain datagram sockets. - -Dependencies: - -- `CONFIG_NET_LOCAL` – Depends on support for Unix domain sockets. - -Configuration: - -- `CONFIG_EXAMPLES_UDGRAM` – Enables the Unix domain socket example. -- `CONFIG_EXAMPLES_UDGRAM_ADDR` – Specifics the Unix domain address. Default: - `/dev/fifo`. - -## `ustream` Unix Stream Sockets - -This is the same test as `examples/udp` and similar to `examples/udgram`, but -using Unix domain stream sockets. - -Dependencies: - -- `CONFIG_NET_LOCAL` – Depends on support for Unix domain sockets. - -Configuration: - -- `CONFIG_EXAMPLES_USTREAM` – Enables the Unix domain socket example. -- `CONFIG_EXAMPLES_USTREAM_ADDR` – Specifics the Unix domain address. Default: - `/dev/fifo`. - -## `watchdog` Watchdog Timer - -A simple test of a watchdog timer driver. Initializes starts the watchdog timer. -It pings the watchdog timer for a period of time then lets the watchdog timer -expire... resetting the CPU is successful. This example can ONLY be built as an -NSH built-in function. - -This test depends on these specific Watchdog/NSH configurations settings (your -specific watchdog hardware settings might require additional settings). - -- `CONFIG_WATCHDOG` – Enables watchdog timer support support. -- `CONFIG_NSH_BUILTIN_APPS` – Build the watchdog time test as an NSH built-in - function. - -Specific configuration options for this example include: - -- `CONFIG_EXAMPLES_WATCHDOG_DEVPATH` – The path to the Watchdog device. Default: - `/dev/watchdog0`. -- `CONFIG_EXAMPLES_WATCHDOG_PINGTIME` – Time in milliseconds that the example - will ping the watchdog before letting the watchdog expire. Default: `5000` - milliseconds. -- `CONFIG_EXAMPLES_WATCHDOG_PINGDELAY` – Time delay between pings in - milliseconds. Default: `500` milliseconds. -- `CONFIG_EXAMPLES_WATCHDOG_TIMEOUT` – The watchdog timeout value in - milliseconds before the watchdog timer expires. Default: `2000` milliseconds. - -## `watcher` Watcher & Watched - -The watcher and watched examples are designed to work together. The watched -example will only appear after watcher is selected. -The watcher is a task that will monitor other tasks that subscribe to be watched. -If a watched task doesn't signal the watcher during the watchdog time period, -the watchdog timer will expire and the watcher will print the tasks that did -not signal and the ones that signaled. The tasks that did not signal will be printed -as the tasks that starved the dog and the tasks that signaled will be printed as -the tasks that fed the dog. -The watcher task will only feed the watchdog timer when all subscribed tasks have -asked to feed dog. - -To start the watcher, just run: - -`watcher` - -The watched example is not required to use the watcher. The watched example is simply -a task that creates 4 tasks that will subscribe to be watched. The first and fourth -will not feed the dog to expose the functionality. This example will show the user -how to subscribe, to feed the dog and to unsubscribe. - -To start the watched, just run: - -`watched` - -P.S: This example will only be supported by the chips that support interrupt on -timeout, i.e., which have the \"capture\" command implemented. - -This test depends on these specific configurations settings (your -specific watchdog hardware settings might require additional settings). - -- `CONFIG_EXAMPLES_WATCHER` – Includes this example. -- `CONFIG_WATCHDOG` – Enables watchdog timer support. -- `CONFIG_NSH_BUILTIN_APPS` – Build this example an NSH built-in - function. -- `CONFIG_DRIVERS_NOTE` and `CONFIG_SCHED_INSTRUMENTATION` – Allows the watcher - to get the tasks' names. -- `CONFIG_FS_FAT` – Allows the creation of a FAT filesystem on the ramdisk - to create a file with all the necessary info for the watched tasks. - -Specific configuration options for the `watcher` example include: - -- `CONFIG_EXAMPLES_WATCHER_PRIORITY` – Watcher Task Priority. -- `CONFIG_EXAMPLES_WATCHER_STACKSIZE` – Watcher Task Stack Size. -- `CONFIG_EXAMPLES_WATCHER_DEVPATH` – The path to the Watchdog device used by - the Watcher. Default: `/dev/watchdog0`. -- `CONFIG_EXAMPLES_WATCHER_TIMEOUT` – The watchdog timeout value in - milliseconds. -- `CONFIG_EXAMPLES_WATCHER_SIGNAL` – This is the Signal Number used for - communication between the watcher task and the watched tasks. - -Specific configuration options for the `watched` example include: - -- `CONFIG_EXAMPLES_WATCHED_PRIORITY` – Watched Task Priority. -- `CONFIG_EXAMPLES_WATCHED_STACKSIZE` – Watched Task Stack Size. - -## `webserver` Simple Webserver - -This is a port of uIP tiny webserver example application. Settings specific to -this example include: - -- `CONFIG_EXAMPLES_WEBSERVER_NOMAC` (may be defined to use software assigned - MAC) -- `CONFIG_EXAMPLES_WEBSERVER_IPADDR` – Target IP address. -- `CONFIG_EXAMPLES_WEBSERVER_DRIPADDR` – Default router IP address. -- `CONFIG_EXAMPLES_WEBSERVER_NETMASK` – Network mask. -- `CONFIG_EXAMPLES_WEBSERVER_DHCPC` – Select to get IP address via DHCP. - -If you use DHCPC, then some special configuration network options are required. -These include: - -- `CONFIG_NET=y` – of course. -- `CONFIG_NET_UDP=y` – UDP support is required for DHCP (as well as various - other UDP-related configuration settings). -- `CONFIG_NET_BROADCAST=y` – UDP broadcast support is needed. -- `CONFIG_NET_ETH_PKTSIZE=650` or larger. Per RFC2131 (p. 9), the DHCP client - must be prepared to receive DHCP messages of up to `576` bytes (excluding - Ethernet, IP, or UDP headers and FCS). **Note** that the actual MTU setting - will depend upon the specific link protocol. Here Ethernet is indicated. - -Other configuration items apply also to the selected `webserver` net utility. -Additional relevant settings for the uIP `webserver` net utility are: - -- `CONFIG_NETUTILS_HTTPDSTACKSIZE` -- `CONFIG_NETUTILS_HTTPDFILESTATS` -- `CONFIG_NETUTILS_HTTPDNETSTATS` - -Applications using this example will need to enable the following `netutils` -libraries in their `defconfig` file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_DHCPC=y -CONFIG_NETDB_DNSCLIENT=y -CONFIG_NETUTILS_WEBSERVER=y -``` - -**Note**: This example does depend on the `perl` script at -`nuttx/tools/mkfsdata.pl`. You must have `perl` installed on your development -system at `/usr/bin/perl`. - -## `wget` Web Client - -A simple web client example. It will obtain a file from a server using the HTTP -protocol. Settings unique to this example include: - -- `CONFIG_EXAMPLES_WGET_URL` – The URL of the file to get -- `CONFIG_EXAMPLES_WGET_NOMAC` – (May be defined to use software assigned MAC) -- `CONFIG_EXAMPLES_WGET_IPADDR` – Target IP address -- `CONFIG_EXAMPLES_WGET_DRIPADDR` – Default router IP address -- `CONFIG_EXAMPLES_WGET_NETMASK` – Network mask - -This example uses `netutils/webclient`. Additional configuration settings apply -to that code as follows (but built-in defaults are probably OK): - -- `CONFIG_WEBCLIENT_GETMIMETYPE` -- `CONFIG_WEBCLIENT_MAXHTTPLINE` -- `CONFIG_WEBCLIENT_MAXMIMESIZE` -- `CONFIG_WEBCLIENT_MAXHOSTNAME` -- `CONFIG_WEBCLIENT_MAXFILENAME` - -Of course, the example also requires other settings including `CONFIG_NET` and -`CONFIG_NET_TCP`. The example also uses the uIP resolver which requires -`CONFIG_UDP`. - -**Warning**: As of this writing, `wget` is untested on the target platform. At -present it has been tested only in the host-based configuration described in the -following note. The primary difference is that the target version will rely on -the also untested uIP name resolver. - -**Note**: For test purposes, this example can be built as a host-based `wget` -function. This can be built as follows: - -```bash -cd examples/wget -make -f Makefile.host -``` - -Applications using this example will need to enable the following `netutils` -libraries in the `defconfig` file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETDB_DNSCLIENT=y -CONFIG_NETUTILS_WEBCLIENT=y -``` - -## `wgetjson` GET JSON Using `wget` - -Uses `wget` to get a JSON encoded file, then decodes the file. - -- `CONFIG_EXAMPLES_WDGETJSON_MAXSIZE` – Max. JSON Buffer Size. -- `CONFIG_EXAMPLES_EXAMPLES_WGETJSON_URL` – `wget` URL - -## `xmlrpc` XML-RPC Server - -This example exercises the _Embeddable Lightweight XML-RPC Server_ which is -discussed at: - -http://www.drdobbs.com/web-development/an-embeddable-lightweight-xml-rpc-server/184405364 - -Configuration options: - -- `CONFIG_EXAMPLES_XMLRPC_BUFFERSIZE` – HTTP buffer size. Default `1024` -- `CONFIG_EXAMPLES_XMLRPC_DHCPC` – Use DHCP Client. Default `n`. Ignored if - `CONFIG_NSH_NETINIT` is selected. -- `CONFIG_EXAMPLES_XMLRPC_NOMAC` – Use Canned MAC Address. Default `n`. Ignored - if `CONFIG_NSH_NETINIT` is selected. -- `CONFIG_EXAMPLES_XMLRPC_IPADDR` – Target IP address. Default `0x0a000002`. - Ignored if `CONFIG_NSH_NETINIT` is selected. -- `CONFIG_EXAMPLES_XMLRPC_DRIPADDR` – Default Router IP address (Gateway). - Default `0x0a000001`. Ignored if `CONFIG_NSH_NETINIT` is selected. -- `CONFIG_EXAMPLES_XMLRPC_NETMASK` – Network Mask. Default `0xffffff00`. Ignored - if `CONFIG_NSH_NETINIT` is selected. - -## `zerocross` Zero Crossing Device - -A simple test of the Zero Crossing device driver. diff --git a/examples/abntcodi/CMakeLists.txt b/examples/abntcodi/CMakeLists.txt index 935284a6e..b1d9eb4b6 100644 --- a/examples/abntcodi/CMakeLists.txt +++ b/examples/abntcodi/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/examples/adntcodi/CMakeLists.txt +# apps/examples/abntcodi/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for diff --git a/examples/adjtime/Makefile b/examples/adjtime/Makefile index 5e102b223..487414566 100644 --- a/examples/adjtime/Makefile +++ b/examples/adjtime/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/adjtime/Make.defs +# apps/examples/adjtime/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/examples/adjtime/adjtime_main.c b/examples/adjtime/adjtime_main.c index 26e9a481d..a897fa153 100644 --- a/examples/adjtime/adjtime_main.c +++ b/examples/adjtime/adjtime_main.c @@ -148,7 +148,7 @@ int main(int argc, FAR char *argv[]) parse_args(&delta, argc, argv); printf("Delta time is %ld seconds and %ld micro seconds.\n", - delta.tv_sec, delta.tv_usec); + (long)delta.tv_sec, delta.tv_usec); /* Call adjtime function. */ @@ -160,7 +160,7 @@ int main(int argc, FAR char *argv[]) else { printf("Returned olddelta is %ld seconds and %ld micro seconds.\n", - olddelta.tv_sec, olddelta.tv_usec); + (long)olddelta.tv_sec, olddelta.tv_usec); } return ret; diff --git a/examples/apue/.gitignore b/examples/apue/.gitignore deleted file mode 100644 index ee8b684f5..000000000 --- a/examples/apue/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/apue diff --git a/examples/bastest/README.md b/examples/bastest/testcases.md similarity index 90% rename from examples/bastest/README.md rename to examples/bastest/testcases.md index b4c0bafb0..3e3875714 100644 --- a/examples/bastest/README.md +++ b/examples/bastest/testcases.md @@ -1,49 +1,3 @@ -# Examples / `bastest` Bas BASIC Tests - -This directory contains a small program that will mount a ROMFS file system -containing the BASIC test files extracted from the BAS `2.4` release. - -## Background - -Bas is an interpreter for the classic dialect of the programming language BASIC. -It is pretty compatible to typical BASIC interpreters of the 1980s, unlike some -other UNIX BASIC interpreters, that implement a different syntax, breaking -compatibility to existing programs. Bas offers many ANSI BASIC statements for -structured programming, such as procedures, local variables and various loop -types. Further there are matrix operations, automatic LIST indentation and many -statements and functions found in specific classic dialects. Line numbers are -not required. - -The interpreter tokenises the source and resolves references to variables and -jump targets before running the program. This compilation pass increases -efficiency and catches syntax errors, type errors and references to variables -that are never initialised. Bas is written in ANSI C for UNIX systems. - -## License - -BAS `2.4` is released as part of NuttX under the standard 3-clause BSD license -use by all components of NuttX. This is not incompatible with the original BAS -`2.4` licensing - -Copyright (c) 1999-2014 Michael Haardt - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - # Test Overview ## `test01.bas` diff --git a/examples/bmp180/Kconfig b/examples/bmp180/Kconfig index 19e778af9..f2b63ac87 100644 --- a/examples/bmp180/Kconfig +++ b/examples/bmp180/Kconfig @@ -4,11 +4,11 @@ # config EXAMPLES_BMP180 - tristate "BMP180/280 Barometer sensor example" + tristate "BMP180 Barometer sensor example" default n - depends on SENSORS_BMP180 || SENSORS_BMP280 + depends on SENSORS_BMP180 ---help--- - Enable the BMP180/BMP280 example + Enable the BMP180 example if EXAMPLES_BMP180 diff --git a/examples/calib_udelay/Kconfig b/examples/calib_udelay/Kconfig index a6a8e6932..97b059285 100644 --- a/examples/calib_udelay/Kconfig +++ b/examples/calib_udelay/Kconfig @@ -22,4 +22,10 @@ config EXAMPLES_CALIB_UDELAY_NUM_RESULTS int "Number of results to generate for calibration slope" default 20 +config EXAMPLES_CALIB_UDELAY_DELAY_TEST_ITERATIONS + int "Delay loop interrations per test." + default 100000 + ---help--- + Lower numbers decrease the time taken for the test to complete, + but may reduce the accuracy of the results. endif diff --git a/examples/calib_udelay/calib_udelay_main.c b/examples/calib_udelay/calib_udelay_main.c index 5f1abbf57..8f3638a13 100644 --- a/examples/calib_udelay/calib_udelay_main.c +++ b/examples/calib_udelay/calib_udelay_main.c @@ -43,7 +43,7 @@ # define CONFIG_EXAMPLES_CALIB_UDELAY_NUM_RESULTS 20 #endif -#define DELAY_TEST_ITERS 100000 +#define DELAY_TEST_ITERS CONFIG_EXAMPLES_CALIB_UDELAY_DELAY_TEST_ITERATIONS /**************************************************************************** * Private Types diff --git a/examples/camera/README.md b/examples/camera/README.md deleted file mode 100644 index 3c6750311..000000000 --- a/examples/camera/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Examples / `camera` Camera Snapshot - -This sample is implemented as `camera` command on NuttX Shell. The synopsis of -the command is as below. - -``` -nsh> camera ([-jpg]) ([capture num]) - - -jpg : this option is set for storing JPEG file into a strage. - : If this option isn't set capturing raw RGB565 data in a file. - : raw RGB565 is default. - - capture num : this option instructs number of taking pictures. - : 10 is default. -``` - -Storage will be selected automatically based on the available storage option. - -Execution example: - -``` -nsh> camera -nximage_listener: Connected -nximage_initialize: Screen resolution (320,240) -Take 10 pictures as RGB file in /mnt/sd0 after 5 seconds. -After finishing taking pictures, this app will be finished after 10 seconds. -Expier time is pasted. -Start capturing... -FILENAME:/mnt/sd0/VIDEO001.RGB -FILENAME:/mnt/sd0/VIDEO002.RGB -FILENAME:/mnt/sd0/VIDEO003.RGB -FILENAME:/mnt/sd0/VIDEO004.RGB -FILENAME:/mnt/sd0/VIDEO005.RGB -FILENAME:/mnt/sd0/VIDEO006.RGB -FILENAME:/mnt/sd0/VIDEO007.RGB -FILENAME:/mnt/sd0/VIDEO008.RGB -FILENAME:/mnt/sd0/VIDEO009.RGB -FILENAME:/mnt/sd0/VIDEO010.RGB -Finished capturing... -Expier time is pasted. -nximage_listener: Lost server connection: 117 -``` diff --git a/examples/can/can.h b/examples/can/can.h index b9446c5ab..9d598483b 100644 --- a/examples/can/can.h +++ b/examples/can/can.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/examples/can/can.h + * apps/examples/can/can.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -30,7 +30,9 @@ /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ + /* Configuration ************************************************************/ + /* This test depends on these specific CAN configurations settings (your * specific CAN settings might require additional settings). * @@ -41,7 +43,8 @@ * Specific configuration options for this example include: * * CONFIG_CAN_LOOPBACK - * CONFIG_EXAMPLES_CAN_DEVPATH - The path to the CAN device. Default: /dev/can0 + * CONFIG_EXAMPLES_CAN_DEVPATH - The path to the CAN device. + * Default: /dev/can0 * CONFIG_EXAMPLES_CAN_NMSGS - This number of CAN message is collected and * the program terminates. Default: 32. * CONFIG_EXAMPLES_CAN_READ - Only receive messages diff --git a/examples/capture/cap_main.c b/examples/capture/cap_main.c index f8a47cda5..d584dad03 100644 --- a/examples/capture/cap_main.c +++ b/examples/capture/cap_main.c @@ -213,7 +213,6 @@ int main(int argc, FAR char *argv[]) { int8_t dutycycle; int32_t frequence; - int32_t edges; int fd; int exitval = EXIT_SUCCESS; int ret; @@ -291,24 +290,6 @@ int main(int argc, FAR char *argv[]) printf("pwm frequence: %"PRId32" Hz \n", frequence); } - /* Get the edges data using the ioctl */ - - ret = ioctl(fd, CAPIOC_EDGES, - (unsigned long)((uintptr_t)&edges)); - if (ret < 0) - { - printf("cap_main: ioctl(CAPIOC_EDGES) failed: %d\n", errno); - exitval = EXIT_FAILURE; - goto errout_with_dev; - } - - /* Print the sample data on successful return */ - - else - { - printf("pwm edges counting: %"PRId32" \n", edges); - } - /* Delay a little bit */ usleep(g_capexample.delay * 1000); diff --git a/examples/dac/dac_main.c b/examples/dac/dac_main.c index d9dda7010..ac524be5b 100644 --- a/examples/dac/dac_main.c +++ b/examples/dac/dac_main.c @@ -48,6 +48,13 @@ # define CONFIG_EXAMPLES_DAC_DEVPATH "/dev/dac0" #endif +#define DEFAULT_COUNT 1 +#define DEFAULT_DELAY 0 +#define DEFAULT_CHANNEL 0 +#define DEFAULT_TEST_BIT_RES 8 +#define DEFAULT_TEST_STEP 8 +#define DEFAULT_INITIALIZED true + /**************************************************************************** * Private Types ****************************************************************************/ @@ -65,6 +72,8 @@ struct dac_state_s int count; int delay; uint8_t channel; + int test_bit_res; + int test_step; bool initialized; }; @@ -74,6 +83,7 @@ struct dac_state_s static int cmd_dac_put(int argc, FAR const char *argv[]); static int cmd_dac_putv(int argc, FAR const char *argv[]); +static int cmd_dac_test(int argc, FAR const char *argv[]); /**************************************************************************** * Private Data @@ -83,6 +93,7 @@ static const struct command commands[] = { { "put", cmd_dac_put, "DATA [DELAY]" }, { "putv", cmd_dac_putv, "DATA [DATA...]" }, + { "test", cmd_dac_test, "" }, }; static struct dac_state_s g_dacstate; @@ -91,6 +102,25 @@ static struct dac_state_s g_dacstate; * Private Functions ****************************************************************************/ +/**************************************************************************** + * Name: dac_devpath + * + * Description: + * Update the DAC device path in the DAC state structure. This function + * manages memory allocation for the device path and frees the previous + * path if it exists. + * + * Input Parameters: + * dac - Pointer to the DAC state structure. + * devpath - New DAC device path to be set. + * + * Operation: + * - Frees the existing DAC device path if it exists. + * - Allocates memory for the new DAC device path. + * - Updates the device path in the DAC state structure. + * + ****************************************************************************/ + static void dac_devpath(FAR struct dac_state_s *dac, FAR const char *devpath) { @@ -102,6 +132,28 @@ static void dac_devpath(FAR struct dac_state_s *dac, dac->devpath = strdup(devpath); } +/**************************************************************************** + * Name: print_cmds + * + * Description: + * Print a list of commands with their names, arguments, and a given header + * and trailer. This function is used to display available + * commands and their usage information. + * + * Input Parameters: + * header - Header string to be printed before the command list. + * cmds - Pointer to an array of command structures. + * ncmds - Number of commands in the array. + * trailer - Trailer string to be printed after the command list. + * + * Operation: + * - Prints the header. + * - Iterates through the array of command structures and prints + * their names, arguments, and a newline character after each command. + * - Prints the trailer. + * + ****************************************************************************/ + static void print_cmds(FAR const char *header, FAR const struct command *cmds, size_t ncmds, @@ -118,6 +170,29 @@ static void print_cmds(FAR const char *header, printf("%s", trailer); } +/**************************************************************************** + * Name: find_cmd + * + * Description: + * Find a command structure in an array of commands by comparing command + * names. + * + * Input Parameters: + * name - Name of the command to be found. + * cmds - Pointer to an array of command structures. + * ncmds - Number of commands in the array. + * + * Returned Value: + * Returns a pointer to the found command structure if successful; NULL + * if the command is not found. + * + * Operation: + * - Iterates through the array of command structures. + * - Compares the name of each command with the specified name. + * - Returns a pointer to the found command structure or NULL if not found. + * + ****************************************************************************/ + static const struct command *find_cmd(FAR const char *name, FAR const struct command *cmds, size_t ncmds) @@ -135,6 +210,30 @@ static const struct command *find_cmd(FAR const char *name, return NULL; } +/**************************************************************************** + * Name: execute_cmd + * + * Description: + * Execute a command function based on the command name. + * This function finds the corresponding command structure in the + * array and invokes the associated function. + * + * Input Parameters: + * argc - Number of command-line arguments. + * argv - Array of command-line argument strings. + * cmds - Pointer to an array of command structures. + * ncmds - Number of commands in the array. + * + * Returned Value: + * Returns the result of the executed command function. + * + * Operation: + * - Finds the command structure for the specified command name. + * - Invokes the associated command function with the provided arguments. + * - Prints an error message if the command is not found. + * + ****************************************************************************/ + static int execute_cmd(int argc, FAR const char *argv[], FAR const struct command *cmds, @@ -153,6 +252,35 @@ static int execute_cmd(int argc, return cmd->cmd(argc - 1, argv + 1); } +/**************************************************************************** + * Name: dac_put + * + * Description: + * Write DAC messages to the specified DAC device. This function writes + * multiple DAC messages, allowing the configuration of DAC channel and + * data values. It handles potential write retries in case of non-blocking + * write operations and provides debug information about the write process. + * + * Input Parameters: + * devpath - Path to the DAC device. + * msg - Pointer to an array of DAC messages to be written. + * nmsgs - Number of DAC messages in the array. + * delay - Delay between writes in milliseconds. + * + * Returned Value: + * Returns the number of successfully written messages on success; a + * negated errno value on failure. + * + * Operation: + * - Opens the specified DAC device for writing. + * - Iterates through the array of DAC messages and writes + * them to the device. + * - Handles non-blocking writes, retries on EAGAIN, and provides + * debug output. + * - Closes the DAC device after completing the write operations. + * + ****************************************************************************/ + static int dac_put(FAR const char *devpath, FAR struct dac_msg_s *msg, size_t nmsgs, @@ -203,6 +331,32 @@ static int dac_put(FAR const char *devpath, return (i > 0) ? i : ret; } +/**************************************************************************** + * Name: cmd_dac_put + * + * Description: + * Execute the 'put' command, writing a specified DAC value to the DAC + * device. + * + * Input Parameters: + * argc - Number of command-line arguments. + * argv - Array of command-line argument strings. + * + * Returned Value: + * Returns OK on success; a negated errno value on failure. + * + * Operation: + * - Parses the command-line arguments to extract the DAC value and delay. + * - Overrides the "sticky" delay option if provided in the arguments. + * - Repeats the DAC write operation for the specified number of times. + * + * Usage: + * `put [value] [delay]`: Write the specified DAC value to the device. + * - [value]: DAC value to be written (Default: 100). + * - [delay]: Delay between writes in milliseconds. + * + ****************************************************************************/ + static int cmd_dac_put(int argc, FAR const char *argv[]) { struct dac_msg_s msgs[1]; @@ -230,6 +384,28 @@ static int cmd_dac_put(int argc, FAR const char *argv[]) return ret; } +/**************************************************************************** + * Name: cmd_dac_putv + * + * Description: + * Execute the 'putv' command, writing DAC values specified in the command + * arguments to the DAC device. The command supports writing + * multiple values in a single execution. + * + * Input Parameters: + * argc - Number of command-line arguments. + * argv - Array of command-line argument strings. + * + * Returned Value: + * Returns OK on success; a negated errno value on failure. + * + * Operation: + * - Parses the command-line arguments to extract DAC values. + * - Constructs DAC messages with the specified channel and data values. + * - Repeats the DAC write operation for the specified number of times. + * + ****************************************************************************/ + static int cmd_dac_putv(int argc, FAR const char *argv[]) { struct dac_msg_s msgs[CONFIG_NSH_MAXARGUMENTS]; @@ -257,6 +433,105 @@ static int cmd_dac_putv(int argc, FAR const char *argv[]) return ret; } +/**************************************************************************** + * Name: cmd_dac_test + * + * Description: + * Perform DAC testing by generating a sequence of values and writing them + * to the DAC device specified in the global DAC state structure. + * + * Input Parameters: + * argc - Number of arguments in argv. + * argv - Array of command-line argument strings. + * + * Returned Value: + * Total return value, the sum of return values from write calls. Returns + * a negative errno on failure. + * + * Note: Utilizing the parameters can make testing much easier. If you are + * testing with one config test, you can change the constant definition for + * default value at the top and simply run `nsh> dat test` + * If you want setup for multimeter testing, set appropriate delay between + * writes (in ms). Example for 8 bit DAC using step in value of 16 + * nsh> dac -d 5000 -b 8 -s 16 test + * Example for oscilloscope test for 12 bit DAC: + * nsh> dac -d 10 -b 12 -s 4 test + * + ****************************************************************************/ + +static int cmd_dac_test(int argc, FAR const char *argv[]) +{ + struct dac_msg_s msg; + int fd; + int i; + bool count_up; + uint32_t value = 0; + uint32_t max_value = (1 << g_dacstate.test_bit_res); + int ret = OK; + int total_ret = 0; + + fd = open(g_dacstate.devpath, O_WRONLY | O_NONBLOCK); + if (fd < 0) + { + fprintf(stderr, "ERROR: open() failed: %d\n", errno); + return -ENODEV; + } + + for (i = 0; i < g_dacstate.count; i++) + { + count_up = true; + value = 0; + while (count_up || value) + { + msg.am_channel = g_dacstate.channel; + msg.am_data = value; + + if (count_up) + { + value += g_dacstate.test_step; + if (value >= max_value - 1) + { + value = max_value - 1; + count_up = false; + } + } + else + { + value -= g_dacstate.test_step; + + /* Check if value is underflow */ + + if (value > UINT32_MAX - g_dacstate.test_step) + { + value = 0; + } + } + + ret = write(fd, &msg, sizeof(struct dac_msg_s)); + total_ret += ret; + usleep(1000 * g_dacstate.delay); + } + } + + close(fd); + + return total_ret; +} + +/**************************************************************************** + * Name: dac_help + * + * Description: + * Display the help message for the DAC testing application. + * + * Input Parameters: + * None + * + * Returned Value: + * None + * + ****************************************************************************/ + static void dac_help(void) { printf("Usage: dac [OPTIONS] command [CMD OPTIONS]\n"); @@ -265,18 +540,41 @@ static void dac_help(void) printf("specified, that device will be re-used until it is changed.\n"); printf("\n\"sticky\" OPTIONS include:\n"); printf(" [-c channel] selects the DAC channel. " - "Default: 0 Current: %d\n", g_dacstate.channel); + "Default: %d Current: %d\n", DEFAULT_CHANNEL, g_dacstate.channel); printf(" [-d delay] pause for DELAY ms between writes. " - "Default: 0 Current: %d\n", g_dacstate.delay); + "Default: %d Current: %d\n", DEFAULT_DELAY, g_dacstate.delay); printf(" [-n count] repeats device write COUNT times. " - "Default: 1 Current: %d\n", g_dacstate.count); + "Default: %d Current: %d\n", DEFAULT_COUNT, g_dacstate.count); + printf(" [-b bit_resolution] Test-specific config - set DAC bit" + " resolution Default: %d Current: %d\n", + DEFAULT_TEST_BIT_RES, g_dacstate.test_bit_res); + printf(" [-s step] Test-specific config - test loop step " + "Default: %d Current: %d\n", + DEFAULT_TEST_STEP, g_dacstate.test_step); printf(" [-p devpath] selects the DAC device. " "Default: %s Current: %s\n", CONFIG_EXAMPLES_DAC_DEVPATH, g_dacstate.devpath ? g_dacstate.devpath : "NONE"); + printf(" [-h] Print this help and exit.\n"); print_cmds("\nCommands:\n", commands, nitems(commands), "\n"); } +/**************************************************************************** + * Name: arg_string + * + * Description: + * Extracts a string argument from a command-line option. + * + * Input Parameters: + * arg - Pointer to the current command-line argument being processed. + * value - Pointer to store the extracted string argument. + * + * Returned Value: + * Integer representing the number of arguments consumed + * (2 if the option takes an additional argument, 1 otherwise). + * + ****************************************************************************/ + static int arg_string(FAR const char **arg, FAR const char **value) { FAR const char *ptr = *arg; @@ -293,6 +591,26 @@ static int arg_string(FAR const char **arg, FAR const char **value) } } +/**************************************************************************** + * Name: arg_decimal + * + * Description: + * Extracts a decimal value from a command-line option. + * + * Input Parameters: + * arg - Pointer to the current command-line argument being processed. + * value - Pointer to store the extracted decimal value. + * + * Returned Value: + * Integer representing the number of arguments consumed + * (2 if the option takes an additional argument, 1 otherwise). + * + * Note: + * Utilizes arg_string internally to extract the string argument + * and then converts it to a long integer using strtol. + * + ****************************************************************************/ + static int arg_decimal(FAR const char **arg, FAR long *value) { FAR const char *string; @@ -307,12 +625,12 @@ static int parse_args(FAR struct dac_state_s *dac, int argc, const char *argv[]) { - FAR const char *ptr; - FAR const char *str; - long value; - int nargs; - int n; - int i; + FAR const char *ptr; /* Pointer to the current argument in argv */ + FAR const char *str; /* Pointer to a string argument extracted from argv */ + long value; /* Numerical argument value */ + int nargs; /* Number of args consumed by the current option */ + int n; /* Total number of arguments processed */ + int i; /* Loop counter */ for (i = n = 1; i < argc; ) { @@ -364,6 +682,32 @@ static int parse_args(FAR struct dac_state_s *dac, n += nargs; break; + case 'b': + nargs = arg_decimal(&argv[i], &value); + if (value < 0) + { + printf("Bit resolution must be non-negative: %ld\n", value); + exit(1); + } + + dac->test_bit_res = (uint32_t)value; + i += nargs; + n += nargs; + break; + + case 's': + nargs = arg_decimal(&argv[i], &value); + if (value < 0) + { + printf("Step must be non-negative: %ld\n", value); + exit(1); + } + + dac->test_step = (uint32_t)value; + i += nargs; + n += nargs; + break; + case 'p': nargs = arg_string(&argv[i], &str); dac_devpath(dac, str); @@ -371,6 +715,11 @@ static int parse_args(FAR struct dac_state_s *dac, n += nargs; break; + case 'h': + dac_help(); + exit(0); + break; + case '?': default: printf("Unsupported option: %s\n", ptr); @@ -386,6 +735,23 @@ static int parse_args(FAR struct dac_state_s *dac, * Public Functions ****************************************************************************/ +/**************************************************************************** + * Name: main + * + * Description: + * Entry point for the DAC testing application. + * Initializes the DAC hardware and processes command-line + * arguments to execute DAC testing commands. + * + * Input Parameters: + * argc - Number of command-line arguments. + * argv - Array of command-line argument strings. + * + * Returned Value: + * EXIT_SUCCESS on success, EXIT_FAILURE on failure. + * + ****************************************************************************/ + int main(int argc, FAR const char *argv[]) { int ret; @@ -400,9 +766,12 @@ int main(int argc, FAR const char *argv[]) /* Set the default values */ dac_devpath(&g_dacstate, CONFIG_EXAMPLES_DAC_DEVPATH); - g_dacstate.count = 1; - g_dacstate.channel = 0; /* This seems to be ignored by driver. */ - g_dacstate.initialized = true; + g_dacstate.delay = DEFAULT_DELAY; + g_dacstate.count = DEFAULT_COUNT; + g_dacstate.channel = DEFAULT_CHANNEL; + g_dacstate.test_bit_res = DEFAULT_TEST_BIT_RES; + g_dacstate.test_step = DEFAULT_TEST_STEP; + g_dacstate.initialized = DEFAULT_INITIALIZED; } /* Parse the command line */ diff --git a/examples/elf/elf_main.c b/examples/elf/elf_main.c index a8369553c..c0d7b578e 100644 --- a/examples/elf/elf_main.c +++ b/examples/elf/elf_main.c @@ -67,21 +67,25 @@ # define SECTORSIZE 512 # define NSECTORS(b) (((b) + SECTORSIZE - 1) / SECTORSIZE) -# define MOUNTPT "/mnt/elf/romfs" +# define MOUNTPT "/mnt/romfs" # ifndef CONFIG_EXAMPLES_ELF_DEVMINOR # define CONFIG_EXAMPLES_ELF_DEVMINOR 0 # endif +# ifndef CONFIG_EXAMPLES_ELF_DEVPATH +# define CONFIG_EXAMPLES_ELF_DEVPATH "/dev/ram0" +# endif + #elif defined(CONFIG_EXAMPLES_ELF_CROMFS) /* Describe the CROMFS file system */ -# define MOUNTPT "/mnt/elf/cromfs" +# define MOUNTPT "/mnt/cromfs" #elif defined(CONFIG_EXAMPLES_ELF_EXTERN) && defined(CONFIG_EXAMPLES_ELF_FSMOUNT) /* Describe the external file system */ -# define MOUNTPT "/mnt/elf/" CONFIG_EXAMPLES_ELF_FSTYPE +# define MOUNTPT "/mnt/" CONFIG_EXAMPLES_ELF_FSTYPE #else # undef MOUNTPT @@ -102,8 +106,6 @@ # define errmsg printf #endif -#define ELF_DEVPATH_FMT "/dev/ram%d" - /**************************************************************************** * Private Data ****************************************************************************/ @@ -124,8 +126,8 @@ static char fullpath[128]; ****************************************************************************/ #if defined(CONFIG_EXAMPLES_ELF_ROMFS) || defined(CONFIG_EXAMPLES_ELF_CROMFS) -extern const unsigned char elf_romfs_img[]; -extern const unsigned int elf_romfs_img_len; +extern const unsigned char romfs_img[]; +extern const unsigned int romfs_img_len; #elif !defined(CONFIG_EXAMPLES_ELF_EXTERN) # error "No file system selected" #endif @@ -198,7 +200,6 @@ static inline void testheader(FAR const char *progname) int main(int argc, FAR char *argv[]) { - char devname[32]; #ifdef CONFIG_EXAMPLES_ELF_FSREMOVEABLE struct stat buf; #endif @@ -213,8 +214,6 @@ int main(int argc, FAR char *argv[]) mm_initmonitor(); - sprintf(devname, ELF_DEVPATH_FMT, CONFIG_EXAMPLES_ELF_DEVMINOR); - #if defined(CONFIG_EXAMPLES_ELF_ROMFS) /* Create a ROM disk for the ROMFS filesystem */ @@ -223,9 +222,9 @@ int main(int argc, FAR char *argv[]) CONFIG_EXAMPLES_ELF_DEVMINOR); desc.minor = CONFIG_EXAMPLES_ELF_DEVMINOR; /* Minor device number of the ROM disk. */ - desc.nsectors = NSECTORS(elf_romfs_img_len); /* The number of sectors in the ROM disk */ + desc.nsectors = NSECTORS(romfs_img_len); /* The number of sectors in the ROM disk */ desc.sectsize = SECTORSIZE; /* The size of one sector in bytes */ - desc.image = (FAR uint8_t *)elf_romfs_img; /* File system image */ + desc.image = (FAR uint8_t *)romfs_img; /* File system image */ ret = boardctl(BOARDIOC_ROMDISK, (uintptr_t)&desc); if (ret < 0) @@ -239,13 +238,14 @@ int main(int argc, FAR char *argv[]) /* Mount the ROMFS file system */ message("Mounting ROMFS filesystem at target=%s with source=%s\n", - MOUNTPT, devname); + MOUNTPT, CONFIG_EXAMPLES_ELF_DEVPATH); - ret = mount(devname, MOUNTPT, "romfs", MS_RDONLY, NULL); + ret = mount(CONFIG_EXAMPLES_ELF_DEVPATH, MOUNTPT, "romfs", + MS_RDONLY, NULL); if (ret < 0) { errmsg("ERROR: mount(%s,%s,romfs) failed: %s\n", - devname, MOUNTPT, strerror(errno)); + CONFIG_EXAMPLES_ELF_DEVPATH, MOUNTPT, strerror(errno)); } #elif defined(CONFIG_EXAMPLES_ELF_CROMFS) @@ -268,26 +268,27 @@ int main(int argc, FAR char *argv[]) do { - ret = stat(devname, &buf); + ret = stat(CONFIG_EXAMPLES_ELF_DEVPATH, &buf); if (ret < 0) { int errcode = errno; if (errcode == ENOENT) { - printf("%s does not exist. Waiting...\n", devname); + printf("%s does not exist. Waiting...\n", + CONFIG_EXAMPLES_ELF_DEVPATH); sleep(1); } else { printf("ERROR: stat(%s) failed: %s Aborting...\n", - devname, strerror(errcode)); + CONFIG_EXAMPLES_ELF_DEVPATH, strerror(errcode)); exit(EXIT_FAILURE); } } else if (!S_ISBLK(buf.st_mode)) { printf("ERROR: stat(%s) exists but is not a block driver: %04x\n", - devname, buf.st_mode); + CONFIG_EXAMPLES_ELF_DEVPATH, buf.st_mode); exit(EXIT_FAILURE); } } @@ -299,11 +300,13 @@ int main(int argc, FAR char *argv[]) message("Mounting %s filesystem at target=%s\n", CONFIG_EXAMPLES_ELF_FSTYPE, MOUNTPT); - ret = mount(devname, MOUNTPT, CONFIG_EXAMPLES_ELF_FSTYPE, MS_RDONLY, NULL); + ret = mount(CONFIG_EXAMPLES_ELF_DEVPATH, MOUNTPT, + CONFIG_EXAMPLES_ELF_FSTYPE, MS_RDONLY, NULL); if (ret < 0) { - errmsg("ERROR: mount(%s, %s, %s) failed: %s\n", devname, - CONFIG_EXAMPLES_ELF_FSTYPE, MOUNTPT, strerror(errno)); + errmsg("ERROR: mount(%s, %s, %s) failed: %s\n", + CONFIG_EXAMPLES_ELF_DEVPATH, CONFIG_EXAMPLES_ELF_FSTYPE, + MOUNTPT, strerror(errno)); } #endif #else diff --git a/examples/elf/tests/Makefile b/examples/elf/tests/Makefile index b72020917..1ade3b106 100644 --- a/examples/elf/tests/Makefile +++ b/examples/elf/tests/Makefile @@ -85,8 +85,7 @@ $(ROMFS_IMG): install $(FSIMG_SRC): $(ROMFS_IMG) $(Q) (cd $(TESTS_DIR) && echo "#include " >$@ && \ - xxd -i romfs.img | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" | \ - sed -e "s/romfs_img/elf_romfs_img/g" >>$@) + xxd -i romfs.img | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" >>$@) else # Make sure that the NuttX gencromfs tool has been built diff --git a/examples/elf/tests/helloxx/hello++5.cxx b/examples/elf/tests/helloxx/hello++5.cxx index b087fdb00..bda7aaf9e 100644 --- a/examples/elf/tests/helloxx/hello++5.cxx +++ b/examples/elf/tests/helloxx/hello++5.cxx @@ -154,7 +154,7 @@ void CThingSayer::ThrowThing(void) void CThingSayer::ThrowMyThing(const char *czSayThis = NULL) { cout << "CThingSayer::ThrowMyThing: I am now throwing an MyException (with reason)." << endl; - throw MyException(tring(czSayThis)); + throw MyException(string(czSayThis)); } ///////////////////////////////////////////////////////////////////////////// diff --git a/examples/elf/tests/task/task.c b/examples/elf/tests/task/task.c index 8bbc819d9..dfaf9834a 100644 --- a/examples/elf/tests/task/task.c +++ b/examples/elf/tests/task/task.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/elf/tests/task/parent.c + * apps/examples/elf/tests/task/task.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -47,9 +47,11 @@ static char no_name[] = ""; * Privite Functions ****************************************************************************/ -/* NOTE: it is necessary for functions that are referred to by function pointers - * pointer to be declared with global scope (at least for ARM). Otherwise, - * a relocation type that is not supported by ELF is generated by GCC. +/* NOTE: it is necessary for functions that are referred to by + * function pointers pointer to be declared with global scope + * (at least for ARM). + * Otherwise, a relocation type that is not supported by ELF + * is generated by GCC. */ int child_task(int argc, char **argv) @@ -113,7 +115,8 @@ int main(int argc, char **argv) child_argv[0] = child_arg; child_argv[1] = 0; - child_pid = task_create(child_name, 50, 2048, child_task, (FAR char * const *)child_argv); + child_pid = task_create(child_name, 50, 2048, child_task, + (FAR char * const *)child_argv); if (child_pid < 0) { printf("Parent: task_create failed: %d\n", errno); diff --git a/examples/embedlog/CMakeLists.txt b/examples/embedlog/CMakeLists.txt index a5a598c13..055126498 100644 --- a/examples/embedlog/CMakeLists.txt +++ b/examples/embedlog/CMakeLists.txt @@ -19,6 +19,11 @@ # ############################################################################## if(CONFIG_EXAMPLES_EMBEDLOG) + + if(CONFIG_EXAMPLES_EMBEDLOG_STRIP_ALL_STRINGS) + list(APPEND CFLAGS -DDISABLE_ALL_EMBEDLOG) + endif() + nuttx_add_application( NAME ${CONFIG_EXAMPLES_EMBEDLOG_PROGNAME} diff --git a/examples/embedlog/Kconfig b/examples/embedlog/Kconfig index e258c3948..564823d50 100644 --- a/examples/embedlog/Kconfig +++ b/examples/embedlog/Kconfig @@ -23,6 +23,39 @@ config EXAMPLES_EMBEDLOG if EXAMPLES_EMBEDLOG +config EXAMPLES_EMBEDLOG_STRIP_ALL_STRINGS + bool "Disable embedlog (strip)" + default n + ---help--- + Enabled embedlog so you can disable it... sounds about right. + + Enable this to replace all embedlog function calls with stub + functions that always return OK. This will effectively strip + final binary from all log strings making code considerably + smaller. + + This may be useful in two cases (at least): + + 1) You develop your app on bigger version of target MCU, on + which you have a lot of memory. So on that version of the + build you can afford to enable good diagnostic logs. But + final image may be run on smaller version, on which logs + would not fit. In that case you can strip binary in final + production image. Thanks to that you will get logs in dev + env, but still maintain small footprint on production build. + + 2) You want to hide implementation details that could be + leaked with debug logs from final image. + + It only makes sense to enable this on production type builds. + Linker will optimize out embedlog and remove all unused + functions, just as if embedlog was never built. + + Enabling this will render embedlog example useless - it + will not print anything, but example will stil compile + and final image will be about 15kB smaller. But YMMV + depending how much strings you have in project. + config EXAMPLES_EMBEDLOG_PROGNAME string "Program name" default "embedlog" diff --git a/examples/embedlog/Makefile b/examples/embedlog/Makefile index f3476b3d7..6524a872f 100644 --- a/examples/embedlog/Makefile +++ b/examples/embedlog/Makefile @@ -27,6 +27,10 @@ PRIORITY = $(CONFIG_EXAMPLES_EMBEDLOG_PRIORITY) STACKSIZE = $(CONFIG_EXAMPLES_EMBEDLOG_STACKSIZE) MODULE = $(CONFIG_EXAMPLES_EMBEDLOG) +ifeq ($(CONFIG_EXAMPLES_EMBEDLOG_STRIP_ALL_STRINGS),y) + CFLAGS += -DDISABLE_ALL_EMBEDLOG +endif + # embedlog Example MAINSRC = embedlog_main.c diff --git a/examples/embedlog/embedlog_main.c b/examples/embedlog/embedlog_main.c index 97dbde77b..497fa1452 100644 --- a/examples/embedlog/embedlog_main.c +++ b/examples/embedlog/embedlog_main.c @@ -113,7 +113,6 @@ static void el_print_options(void) el_ooption(&g_el, EL_TS, EL_TS_LONG); el_ooption(&g_el, EL_TS, EL_TS_OFF); el_oprint(OELF, "no time information, if your heart desire it"); - el_ooption(&g_el, EL_TS_FRACT, EL_TS_FRACT_NS); el_ooption(&g_el, EL_FINFO, 1); el_oprint(OELF, "log location is very useful for debugging"); @@ -121,6 +120,10 @@ static void el_print_options(void) el_ooption(&g_el, EL_TS, EL_TS_LONG); el_ooption(&g_el, EL_TS_TM, EL_TS_TM_REALTIME); el_ooption(&g_el, EL_PRINT_LEVEL, 1); + + /* nuttx runs on rather slow cpus, so millisecond precision is enough */ + + el_ooption(&g_el, EL_TS_FRACT, EL_TS_FRACT_MS); el_oprint(OELF, "Different scenarios need different options"); el_oprint(OELA, "So we can mix options however we want"); @@ -188,6 +191,10 @@ static void el_print_memory(void) el_oprint(OELI, "print the same region but this time with nice ascii " "table"); el_opmemory_table(OELI, s, sizeof(s)); + + el_ooption(&g_el, EL_PMEMORY_SPACE, 1); + el_oprint(OELI, "print whole ASCII table with additional spacing"); + el_opmemory(OELI, ascii, sizeof(ascii)); } /**************************************************************************** @@ -221,51 +228,18 @@ static void el_print_file(const char *workdir) snprintf(log_path, sizeof(log_path), "%s/log-rotate", workdir); - /* Enable file rotation, maximum 5 files will be created, none of the log - * files size shall exceed 512 bytes. Rotate size is low to present how - * rotation works, in real life this should be much higher, unless you - * really know what you are doing and understand the consequences of low - * rotate size. - */ - - el_ooption(&g_el, EL_FROTATE_NUMBER, 5); - el_ooption(&g_el, EL_FROTATE_SIZE, 512); - - /* Tell embedlog to sync all buffers and metadata regarding log file. - * There are cases, when data (a lot of data) goes into block device, - * but metadata of the file are not updated when power loss occurs. This - * leads to data loss - even though they landed physically on block device - * like sdcard. To prevent losing too much data, you can define how often - * you want embedlog to call sync() functions. It basically translates to - * "how much data am I ready to loose?". In this example, we sync() once - * every 4096 bytes are stored into file. - */ - - el_ooption(&g_el, EL_FILE_SYNC_EVERY, 4096); - - /* Setting above value to too small value, will cause sync() to be called - * very often (depending on how much data you log) and that may criple - * performance greatly. And there are situations when you are willing to - * loose some info or debug data (up to configured sync every value), but - * when critical error shows up, you want data to be synced immediately to - * minimize chance of losing information about critical error. For that - * you can define which log level will be synced *every* time regardless - * of sync every value. Here we will instruct embedlog to log prints that - * have severity higher or equal to critical (so critial, alert and fatal) - */ - el_ooption(&g_el, EL_FILE_SYNC_LEVEL, EL_CRIT); - /* Print logs to both file and standard error */ - - el_ooption(&g_el, EL_OUT, EL_OUT_FILE | EL_OUT_STDERR); - - /* Register path to log file in embedlog. This will cause logger to look - * for next valid log file (when log rotate in enabled) and will try to - * open file for reading. + /* Enable logging to file with file rotation based on file size. + * Maximum 5 files will be created, none of the log files size shall + * exceed 512 bytes. Rotate size is low to present how rotation works, in + * real life this should be much higher, unless you really know what you + * are doing and understand the consequences of low rotate size. + * This function will also automatically enable file output without + * disabling any - already enabled - outputs. */ - if (el_ooption(&g_el, EL_FPATH, log_path) != 0) + if (el_oenable_file_log(&g_el, log_path, 5, 512)) { if (errno == ENAMETOOLONG || errno == EINVAL) { @@ -286,6 +260,29 @@ static void el_print_file(const char *workdir) return; } + /* Tell embedlog to sync all buffers and metadata regarding log file. + * + * There are cases, when data (a lot of data) goes into block device, + * but metadata of the file are not updated when power loss occurs. This + * leads to data loss - even though they landed physically on block device + * like sdcard. To prevent losing too much data, you can define how often + * you want embedlog to call sync() functions. It basically translates to + * "how much data am I ready to loose?". In this example, we sync() once + * every 4096 bytes are stored into file. + * + * Setting that value to too small value, will cause sync() to be called + * very often (depending on how much data you log) and that may criple + * performance greatly. And there are situations when you are willing to + * loose some info or debug data (up to configured sync every value), but + * when critical error shows up, you want data to be synced immediately to + * minimize chance of losing information about critical error. For that + * you can define which log level will be synced *every* time regardless + * of 'sync every' value. Here we will instruct embedlog to log prints that + * have severity higher or equal to critical (so critial, alert and fatal) + */ + + el_oset_file_sync(&g_el, 4096, EL_CRIT); + /* Now we can print messages */ el_oprint(OELI, "Now we enabled log rotation"); @@ -317,7 +314,21 @@ int main(int argc, FAR char *argv[]) el_oinit(&g_el); el_oprint(OELI, "Right after init, embedlog will print to stderr with " - "just log level information - these are default settings."); + "just log level information - these are default settings."); + + el_oprint(OELI, "You can enable most common and usefull options with just " + "a few special functions"); + + el_oset_timestamp(&g_el, EL_TS_LONG, EL_TS_TM_REALTIME, EL_TS_FRACT_US); + el_oprint_extra_info(&g_el, 1); + + el_oprint(OELI, "timestamp and information about log place in code is " + "most usefull for developer"); + el_oprint(OELI, "If these are not enough, you can always really fine"); + el_oprint(OELI, "tune embedlog behaviour with options"); + + el_oset_timestamp(&g_el, EL_TS_OFF, EL_TS_TM_REALTIME, EL_TS_FRACT_OFF); + el_oprint_extra_info(&g_el, 0); el_print_options(); el_print_memory(); diff --git a/examples/fb/fb_main.c b/examples/fb/fb_main.c index 2d3f998dc..bb80377ac 100644 --- a/examples/fb/fb_main.c +++ b/examples/fb/fb_main.c @@ -32,7 +32,6 @@ #include #include #include -#include #include #include @@ -56,9 +55,6 @@ struct fb_state_s struct fb_overlayinfo_s oinfo; #endif FAR void *fbmem; - FAR void *fbmem2; - FAR void *act_fbmem; - uint32_t mem2_yoffset; }; /**************************************************************************** @@ -91,166 +87,6 @@ static const uint8_t g_rgb8[NCOLORS] = * Private Functions ****************************************************************************/ -/**************************************************************************** - * sync_area - ****************************************************************************/ - -static void sync_area(FAR struct fb_state_s *state) -{ - if (state->fbmem2 == NULL) - { - return; - } - - if (state->act_fbmem == state->fbmem) - { - memcpy(state->fbmem, state->fbmem2, - state->vinfo.yres * state->pinfo.stride); - } - else - { - memcpy(state->fbmem2, state->fbmem, - state->vinfo.yres * state->pinfo.stride); - } -} - -/**************************************************************************** - * pan_display - ****************************************************************************/ - -static void pan_display(FAR struct fb_state_s *state) -{ - struct pollfd pfd; - int ret; - pfd.fd = state->fd; - pfd.events = POLLOUT; - - ret = poll(&pfd, 1, 0); - - if (ret > 0) - { - if (state->fbmem2 == NULL) - { - return; - } - - if (state->act_fbmem == state->fbmem) - { - state->pinfo.yoffset = 0; - } - else - { - state->pinfo.yoffset = state->mem2_yoffset; - } - - ioctl(state->fd, FBIOPAN_DISPLAY, - (unsigned long)(uintptr_t)&state->pinfo); - - state->act_fbmem = state->act_fbmem == state->fbmem ? - state->fbmem2 : state->fbmem; - } -} - -/**************************************************************************** - * fbdev_get_pinfo - ****************************************************************************/ - -static int fbdev_get_pinfo(int fd, FAR struct fb_planeinfo_s *pinfo) -{ - if (ioctl(fd, FBIOGET_PLANEINFO, (unsigned long)((uintptr_t)pinfo)) < 0) - { - int errcode = errno; - fprintf(stderr, "ERROR: ioctl(FBIOGET_PLANEINFO) failed: %d\n", - errcode); - return EXIT_FAILURE; - } - - printf("PlaneInfo (plane %d):\n", pinfo->display); - printf(" fbmem: %p\n", pinfo->fbmem); - printf(" fblen: %zu\n", pinfo->fblen); - printf(" stride: %u\n", pinfo->stride); - printf(" display: %u\n", pinfo->display); - printf(" bpp: %u\n", pinfo->bpp); - - /* Only these pixel depths are supported. viinfo.fmt is ignored, only - * certain color formats are supported. - */ - - if (pinfo->bpp != 32 && pinfo->bpp != 24 && - pinfo->bpp != 16 && pinfo->bpp != 8 && - pinfo->bpp != 1) - { - fprintf(stderr, "ERROR: bpp=%u not supported\n", pinfo->bpp); - return EXIT_FAILURE; - } - - return 0; -} - -/**************************************************************************** - * fb_init_mem2 - ****************************************************************************/ - -static int fb_init_mem2(FAR struct fb_state_s *state) -{ - int ret; - uintptr_t buf_offset; - struct fb_planeinfo_s pinfo; - - memset(&pinfo, 0, sizeof(pinfo)); - pinfo.display = state->pinfo.display + 1; - - if ((ret = fbdev_get_pinfo(state->fd, &pinfo)) < 0) - { - return EXIT_FAILURE; - } - - /* Check bpp */ - - if (pinfo.bpp != state->pinfo.bpp) - { - fprintf(stderr, "ERROR: fbmem2 is incorrect"); - return -EINVAL; - } - - /* Check the buffer address offset, - * It needs to be divisible by pinfo.stride - */ - - buf_offset = pinfo.fbmem - state->fbmem; - - if ((buf_offset % state->pinfo.stride) != 0) - { - fprintf(stderr, "ERROR: It is detected that buf_offset(%" PRIuPTR ") " - "and stride(%d) are not divisible, please ensure " - "that the driver handles the address offset by itself.\n", - buf_offset, state->pinfo.stride); - } - - /* Calculate the address and yoffset of fbmem2 */ - - if (buf_offset == 0) - { - /* Use consecutive fbmem2. */ - - state->mem2_yoffset = state->vinfo.yres; - state->fbmem2 = pinfo.fbmem + state->mem2_yoffset * pinfo.stride; - printf("Use consecutive fbmem2 = %p, yoffset = %" PRIu32"\n", - state->fbmem2, state->mem2_yoffset); - } - else - { - /* Use non-consecutive fbmem2. */ - - state->mem2_yoffset = buf_offset / state->pinfo.stride; - state->fbmem2 = pinfo.fbmem; - printf("Use non-consecutive fbmem2 = %p, yoffset = %" PRIu32"\n", - state->fbmem2, state->mem2_yoffset); - } - - return 0; -} - /**************************************************************************** * draw_rect ****************************************************************************/ @@ -263,7 +99,7 @@ static void draw_rect32(FAR struct fb_state_s *state, int x; int y; - row = (FAR uint8_t *)state->act_fbmem + state->pinfo.stride * area->y; + row = (FAR uint8_t *)state->fbmem + state->pinfo.stride * area->y; for (y = 0; y < area->h; y++) { dest = ((FAR uint32_t *)row) + area->x; @@ -276,29 +112,6 @@ static void draw_rect32(FAR struct fb_state_s *state, } } -static void draw_rect24(FAR struct fb_state_s *state, - FAR struct fb_area_s *area, int color) -{ - FAR uint8_t *dest; - FAR uint8_t *row; - int x; - int y; - - row = (FAR uint8_t *)state->fbmem + state->pinfo.stride * area->y; - for (y = 0; y < area->h; y++) - { - dest = ((FAR uint8_t *)row) + area->x * 3; - for (x = 0; x < area->w; x++) - { - *dest++ = g_rgb24[color] & 0xff; - *dest++ = (g_rgb24[color] >> 8) & 0xff; - *dest++ = (g_rgb24[color] >> 16) & 0xff; - } - - row += state->pinfo.stride; - } -} - static void draw_rect16(FAR struct fb_state_s *state, FAR struct fb_area_s *area, int color) { @@ -307,7 +120,7 @@ static void draw_rect16(FAR struct fb_state_s *state, int x; int y; - row = (FAR uint8_t *)state->act_fbmem + state->pinfo.stride * area->y; + row = (FAR uint8_t *)state->fbmem + state->pinfo.stride * area->y; for (y = 0; y < area->h; y++) { dest = ((FAR uint16_t *)row) + area->x; @@ -328,7 +141,7 @@ static void draw_rect8(FAR struct fb_state_s *state, int x; int y; - row = (FAR uint8_t *)state->act_fbmem + state->pinfo.stride * area->y; + row = (FAR uint8_t *)state->fbmem + state->pinfo.stride * area->y; for (y = 0; y < area->h; y++) { dest = row + area->x; @@ -358,7 +171,7 @@ static void draw_rect1(FAR struct fb_state_s *state, /* Calculate the framebuffer address of the first row to draw on */ - row = (FAR uint8_t *)state->act_fbmem + state->pinfo.stride * area->y; + row = (FAR uint8_t *)state->fbmem + state->pinfo.stride * area->y; /* Calculate the position of the first complete (with all bits) byte. * Then calculate the last byte with all the bits. @@ -435,10 +248,6 @@ static void draw_rect(FAR struct fb_state_s *state, draw_rect32(state, area, color); break; - case 24: - draw_rect24(state, area, color); - break; - case 16: draw_rect16(state, area, color); break; @@ -454,10 +263,6 @@ static void draw_rect(FAR struct fb_state_s *state, } #ifdef CONFIG_FB_UPDATE - int yoffset = state->act_fbmem == state->fbmem ? - 0 : state->mem2_yoffset; - area->y += yoffset; - ret = ioctl(state->fd, FBIO_UPDATE, (unsigned long)((uintptr_t)area)); if (ret < 0) @@ -467,11 +272,6 @@ static void draw_rect(FAR struct fb_state_s *state, errcode); } #endif - - if (state->pinfo.yres_virtual == (state->vinfo.yres * 2)) - { - pan_display(state); - } } /**************************************************************************** @@ -572,7 +372,7 @@ int main(int argc, FAR char *argv[]) printf("OverlayInfo (overlay 0):\n"); printf(" fbmem: %p\n", state.oinfo.fbmem); - printf(" fblen: %zu\n", state.oinfo.fblen); + printf(" fblen: %lu\n", (unsigned long)state.oinfo.fblen); printf(" stride: %u\n", state.oinfo.stride); printf(" overlay: %u\n", state.oinfo.overlay); printf(" bpp: %u\n", state.oinfo.bpp); @@ -586,22 +386,34 @@ int main(int argc, FAR char *argv[]) state.oinfo.sarea.w, state.oinfo.sarea.h); printf(" accl: %" PRIu32 "\n", state.oinfo.accl); - /* select default framebuffer layer */ +#endif - ret = ioctl(state.fd, FBIO_SELECT_OVERLAY, FB_NO_OVERLAY); + ret = ioctl(state.fd, FBIOGET_PLANEINFO, + (unsigned long)((uintptr_t)&state.pinfo)); if (ret < 0) { int errcode = errno; - fprintf(stderr, "ERROR: ioctl(FBIO_SELECT_OVERLAY) failed: %d\n", + fprintf(stderr, "ERROR: ioctl(FBIOGET_PLANEINFO) failed: %d\n", errcode); close(state.fd); return EXIT_FAILURE; } -#endif + printf("PlaneInfo (plane 0):\n"); + printf(" fbmem: %p\n", state.pinfo.fbmem); + printf(" fblen: %lu\n", (unsigned long)state.pinfo.fblen); + printf(" stride: %u\n", state.pinfo.stride); + printf(" display: %u\n", state.pinfo.display); + printf(" bpp: %u\n", state.pinfo.bpp); - if ((ret = fbdev_get_pinfo(state.fd, &state.pinfo)) < 0) + /* Only these pixel depths are supported. viinfo.fmt is ignored, only + * certain color formats are supported. + */ + + if (state.pinfo.bpp != 32 && state.pinfo.bpp != 16 && + state.pinfo.bpp != 8 && state.pinfo.bpp != 1) { + fprintf(stderr, "ERROR: bpp=%u not supported\n", state.pinfo.bpp); close(state.fd); return EXIT_FAILURE; } @@ -628,19 +440,8 @@ int main(int argc, FAR char *argv[]) printf("Mapped FB: %p\n", state.fbmem); - /* double buffer mode */ - - if (state.pinfo.yres_virtual == (state.vinfo.yres * 2)) - { - if ((ret = fb_init_mem2(&state)) < 0) - { - goto out; - } - } - /* Draw some rectangles */ - state.act_fbmem = state.fbmem; nsteps = 2 * (NCOLORS - 1) + 1; xstep = state.vinfo.xres / nsteps; ystep = state.vinfo.yres / nsteps; @@ -664,19 +465,10 @@ int main(int argc, FAR char *argv[]) width -= (2 * xstep); height -= (2 * ystep); - - /* double buffer mode */ - - if (state.pinfo.yres_virtual == (state.vinfo.yres * 2)) - { - sync_area(&state); - } } printf("Test finished\n"); - ret = EXIT_SUCCESS; -out: munmap(state.fbmem, state.pinfo.fblen); close(state.fd); - return ret; + return EXIT_SUCCESS; } diff --git a/examples/flash_test/README.md b/examples/flash_test/README.md deleted file mode 100644 index 9fb2fdf3f..000000000 --- a/examples/flash_test/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Examples / `flash_test` SMART Flash Device Test - -``` -Author: Ken Pettit - Date: April 24, 2013 -``` - -This application performs a SMART flash block device test. This test performs a -sector allocate, read, write, free and garbage collection test on a SMART MTD -block device. This test can be built only as an NSH command - -**Note**: This test uses internal OS interfaces and so is not available in the -NUTTX kernel build - -``` -Usage: - - flash_test mtdblock_device - -Additional options: - - --force to replace existing installation -``` diff --git a/examples/flowc/README.md b/examples/flowc/README.md deleted file mode 100644 index 6f3d23280..000000000 --- a/examples/flowc/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Examples / `flowc` - -General Usage Instructions: - -1. The receiver side enter, start the receiver program. The receiver is now - waiting to receive data on the configured serial port. -2. On the sender side start the sender program. This will send data to the - receiver which will verify that no data is lost. - -On Linux, you can alternatively do: - -```bash -$ stty -F /dev/ttyACM0 crtscts -$ cat testdata.dat >/dev/ttyACM0 -``` - -where you need to replace `/dev/ttyACM0` with your selected serial device. diff --git a/examples/fmsynth/keyboard_main.c b/examples/fmsynth/keyboard_main.c index 9c197eb70..1cbaba2a5 100644 --- a/examples/fmsynth/keyboard_main.c +++ b/examples/fmsynth/keyboard_main.c @@ -79,7 +79,6 @@ struct key_convert_s * Private Function Prototypes ****************************************************************************/ -extern int board_external_amp_mute_control(bool en); static void app_dequeue_cb(unsigned long arg, FAR struct ap_buffer_s *apb); static void app_complete_cb(unsigned long arg); @@ -91,6 +90,7 @@ static void app_user_cb(unsigned long arg, ****************************************************************************/ static struct kbd_s g_kbd; +static bool g_running = true; static struct nxaudio_callbacks_s cbs = { @@ -191,7 +191,10 @@ static void app_dequeue_cb(unsigned long arg, NULL, 0); } - nxaudio_enqbuffer(&kbd->nxaudio, apb); + if (g_running) + { + nxaudio_enqbuffer(&kbd->nxaudio, apb); + } } /**************************************************************************** @@ -373,11 +376,11 @@ int main(int argc, FAR char *argv[]) int i; int ret; int key; - bool running = true; pthread_t pid; struct app_options appopt; int key_idx; + g_running = true; if (configure_option(&appopt, argc, argv) != OK) { print_help(argv[0]); @@ -414,7 +417,7 @@ int main(int argc, FAR char *argv[]) printf("Start %s\n", argv[0]); print_keyusage(); - while (running) + while (g_running) { key = getchar(); if (key != EOF) @@ -422,7 +425,7 @@ int main(int argc, FAR char *argv[]) switch (key) { case 'q': - running = false; + g_running = false; break; default: @@ -438,8 +441,6 @@ int main(int argc, FAR char *argv[]) } } - board_external_amp_mute_control(true); - nxaudio_stop(&g_kbd.nxaudio); pthread_join(pid, NULL); diff --git a/examples/fmsynth/mmlplayer_main.c b/examples/fmsynth/mmlplayer_main.c index e24a0021e..88c849c02 100644 --- a/examples/fmsynth/mmlplayer_main.c +++ b/examples/fmsynth/mmlplayer_main.c @@ -98,6 +98,7 @@ static void app_user_cb(unsigned long arg, ****************************************************************************/ static struct mmlplayer_s g_mmlplayer; +static bool g_running = true; static struct nxaudio_callbacks_s cbs = { @@ -263,7 +264,11 @@ static void app_dequeue_cb(unsigned long arg, mmlplayer->nxaudio.chnum, tick_callback, (unsigned long)(uintptr_t)mmlplayer); - nxaudio_enqbuffer(&mmlplayer->nxaudio, apb); + + if (g_running) + { + nxaudio_enqbuffer(&mmlplayer->nxaudio, apb); + } } /**************************************************************************** @@ -503,12 +508,12 @@ int main(int argc, FAR char *argv[]) int i; int ret; int key; - bool running = true; pthread_t pid; struct app_options appopt; printf("Start %s\n", argv[0]); + g_running = true; if (configure_option(&appopt, argc, argv) != OK) { print_help(argv[0]); @@ -540,7 +545,7 @@ int main(int argc, FAR char *argv[]) pid = create_audio_thread(&g_mmlplayer); - while (running) + while (g_running) { key = getchar(); if (key != EOF) @@ -548,7 +553,7 @@ int main(int argc, FAR char *argv[]) switch (key) { case 'q': - running = false; + g_running = false; break; } } diff --git a/examples/foc/CMakeLists.txt b/examples/foc/CMakeLists.txt index 6ef888605..8cf8faa00 100644 --- a/examples/foc/CMakeLists.txt +++ b/examples/foc/CMakeLists.txt @@ -1,22 +1,22 @@ -############################################################################ +# ############################################################################## # apps/examples/foc/CMakeLists.txt # -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at +# Licensed to the Apache Software Foundation (ASF) under one or more contributor +# license agreements. See the NOTICE file distributed with this work for +# additional information regarding copyright ownership. The ASF licenses this +# file to you under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. +# License for the specific language governing permissions and limitations under +# the License. # -############################################################################ +# ############################################################################## if(CONFIG_EXAMPLES_FOC) nuttx_add_application( @@ -29,34 +29,36 @@ if(CONFIG_EXAMPLES_FOC) PRIORITY ${CONFIG_EXAMPLES_FOC_PRIORITY}) -set(CSRCS - foc_device.c - foc_mq.c - foc_thr.c - foc_intf.c) + set(CSRCS foc_device.c foc_mq.c foc_thr.c foc_intf.c) -if(CONFIG_BUILTIN) - list(APPEND CSRCS foc_parseargs.c) -endif() + if(CONFIG_BUILTIN) + list(APPEND CSRCS foc_parseargs.c) + endif() -# fixed16 support + # fixed16 support -if(CONFIG_INDUSTRY_FOC_FIXED16) - list(APPEND CSRCS foc_fixed16_thr.c foc_motor_b16.c) -endif() + if(CONFIG_INDUSTRY_FOC_FIXED16) + list(APPEND CSRCS foc_fixed16_thr.c foc_motor_b16.c) + endif() -# float32 support + # float32 support -if(CONFIG_INDUSTRY_FOC_FLOAT) - list(APPEND CSRCS foc_float_thr.c foc_motor_f32.c) -endif() + if(CONFIG_INDUSTRY_FOC_FLOAT) + list(APPEND CSRCS foc_float_thr.c foc_motor_f32.c) + endif() -# NxScope support + # NxScope support -if(CONFIG_EXAMPLES_FOC_NXSCOPE) - list(APPEND CSRCS foc_nxscope.c) -endif() + if(CONFIG_EXAMPLES_FOC_NXSCOPE) + list(APPEND CSRCS foc_nxscope.c) + endif() -target_sources(apps PRIVATE ${CSRCS}) + # perf support + + if(CONFIG_EXAMPLES_FOC_PERF) + list(APPEND CSRCS foc_perf.c) + endif() + + target_sources(apps PRIVATE ${CSRCS}) endif() diff --git a/examples/foc/Kconfig b/examples/foc/Kconfig index e5a8292fb..c2bc7e07f 100644 --- a/examples/foc/Kconfig +++ b/examples/foc/Kconfig @@ -43,6 +43,20 @@ config EXAMPLES_FOC_VERBOSE default 1 range 0 2 +config EXAMPLES_FOC_PERF + bool "Enable performance meassurements" + default n + +choice + prompt "FOC modulation selection" + default EXAMPLES_FOC_MODULATION_SVM3 + +config EXAMPLES_FOC_MODULATION_SVM3 + bool "FOC use SVM3" + select INDUSTRY_FOC_MODULATION_SVM3 + +endchoice # FOC modulation selection + choice prompt "FOC current controller selection" default EXAMPLES_FOC_CONTROL_PI @@ -65,12 +79,6 @@ config EXAMPLES_FOC_NOTIFIER_FREQ ---help--- Select the FOC notifier frequency -config EXAMPLES_FOC_IPHASE_ADC - int "FOC phase current scale [x100000]" - default 0 - ---help--- - This parameter is used to get real currents from ADC RAW values - config EXAMPLES_FOC_STATE_PRINT_FREQ int "FOC example data printer frequency" default 0 @@ -91,6 +99,7 @@ choice config EXAMPLES_FOC_SENSORLESS bool "FOC example sensorless configuration" + select EXAMPLES_FOC_ANGOBS config EXAMPLES_FOC_SENSORED bool "FOC example sensored configuration" @@ -98,6 +107,37 @@ config EXAMPLES_FOC_SENSORED endchoice # +menu "Motor phy" + +config EXAMPLES_FOC_MOTOR_POLES + int "FOC example motor poles pairs" + default 0 + +config EXAMPLES_FOC_MOTOR_RES + int "FOC example motor phase resistance (x1000000)" + default 0 + ---help--- + The unit is micro-ohm (1/1000000 ohm). + +config EXAMPLES_FOC_MOTOR_IND + int "FOC example motor phase inductance (x1000000)" + default 0 + ---help--- + The unit is micro micro-henry (1/1000000 henry). + +config EXAMPLES_FOC_MOTOR_FLUXLINK + int "FOC example motor flux linkage (x1000000)" + default 0 + ---help--- + The unit is micro-Vs (1/1000000 Vs). + Flux linkage can be obtained from the formula: + lambda_pm = (1 / sqrt(3)) * (60 / 2*PI) * (Ke / P) [Vs] + where: + Ke - motor voltage constant Ke [V/rpm] + P - motor pole pairs + +endmenu # Motor phy + if EXAMPLES_FOC_SENSORED choice @@ -115,10 +155,6 @@ endchoice # FOC sensored sensor selection if EXAMPLES_FOC_HAVE_QENCO -config EXAMPLES_FOC_MOTOR_POLES - int "FOC example motor poles pairs" - default 0 - config EXAMPLES_FOC_QENCO_POSMAX int "FOC example qencoder maximum position" default 0 @@ -148,19 +184,208 @@ endif # EXAMPLES_FOC_SENSORED config EXAMPLES_FOC_HAVE_OPENLOOP bool "FOC example have open-loop controller" select INDUSTRY_FOC_ANGLE_OPENLOOP + select EXAMPLES_FOC_HAVE_ALIGN default EXAMPLES_FOC_SENSORLESS config EXAMPLES_FOC_HAVE_TORQ bool "FOC example torque controller support" default n +if EXAMPLES_FOC_HAVE_TORQ + +config EXAMPLES_FOC_TORQ_MAX + int "FOC example torque maximum (x1000)" + default 1000 + ---help--- + The unit is mini-ampere (1/1000 ampere) for current mode. + The unit is mini-volt (1/1000 voltage) for voltage mode. + +endif # EXAMPLES_FOC_HAVE_TORQ + config EXAMPLES_FOC_HAVE_VEL bool "FOC example velocity controller support" default EXAMPLES_FOC_SENSORLESS + select EXAMPLES_FOC_HAVE_TORQ config EXAMPLES_FOC_HAVE_POS bool "FOC example position controller support" default n + select EXAMPLES_FOC_HAVE_VEL + +config EXAMPLES_FOC_VELOBS + bool "FOC example velocity observer support" + default n + +if EXAMPLES_FOC_HAVE_VEL + +config EXAMPLES_FOC_VELCTRL_FREQ + int "FOC example velocity controller frequency" + default 1000 + +config EXAMPLES_FOC_VELNOW_FILTER + int "FOC example velocity controller (x1000)" + default 990 + +config EXAMPLES_FOC_VEL_MAX + int "FOC example velocity maximum (x1)" + default 1000 + ---help--- + The unit is rad/s + +choice + prompt "FOC velocity controller selection" + default EXAMPLES_FOC_VELCTRL_PI + +config EXAMPLES_FOC_VELCTRL_PI + bool "FOC velocity PI controller" + +endchoice # FOC velocity controller + +if EXAMPLES_FOC_VELCTRL_PI + +config EXAMPLES_FOC_VELCTRL_PI_KP + int "FOC velocity PI Kp (1000000x)" + default 0 + ---help--- + The Kp coefficient used in controller is: + Kp = EXAMPLES_FOC_VELCTRL_PI_KP/1000000 + +config EXAMPLES_FOC_VELCTRL_PI_KI + int "FOC velocity PI Ki (1000000x)" + default 0 + ---help--- + The Ki coefficient used in controller is: + Ki = EXAMPLES_FOC_VELCTRL_PI_KI/1000000 + +endif # EXAMPLES_FOC_VELCTRL_PI + +endif # EXAMPLES_FOC_HAVE_VEL + +config EXAMPLES_FOC_ANGOBS + bool "FOC example phase angle observer support" + default n + +choice + prompt "FOC angle observer selection" + default EXAMPLES_FOC_ANGOBS_NFO + depends on EXAMPLES_FOC_ANGOBS + +config EXAMPLES_FOC_ANGOBS_SMO + bool "FOC angle SMO observer" + select INDUSTRY_FOC_ANGLE_OSMO + +config EXAMPLES_FOC_ANGOBS_NFO + bool "FOC angle NFO observer" + select INDUSTRY_FOC_ANGLE_ONFO + +endchoice # FOC angle observer + +if EXAMPLES_FOC_ANGOBS + +config EXAMPLES_FOC_ANGOBS_HYS + int "FOC angle observer hysteresis [x1]" + default 0 + ---help--- + Hysteresis added to the observer to open-loop transition. + +config EXAMPLES_FOC_ANGOBS_THR + int "FOC angle observer velocity threshold [x1]" + default 0 + ---help--- + Once the motor reaches this speed, we switch from the open-loop angle + to the observer angle. + +config EXAMPLES_FOC_ANGOBS_MERGE_RATIO + int "FOC angle observer merge ratio" + default 50 + range 0 50 + ---help--- + This parameter determines how quickly we make the transition from the + open-loop angle to the observer angle after reaching the observer threshold + velocity. The smaler the value, the smoother the transition. + If set to 0 - smooth transition is disabled. + +endif # EXAMPLES_FOC_ANGOBS + +if EXAMPLES_FOC_ANGOBS_SMO + +config EXAMPLES_FOC_ANGOBS_SMO_KSLIDE + int "FOC angle SMO observer Kslide (x1000)" + default 0 + ---help--- + The Kslide coefficient used in observer is: + Kslide = EXAMPLES_FOC_ANGOBS_SMO_KSLIDE/1000 + +config EXAMPLES_FOC_ANGOBS_SMO_ERRMAX + int "FOC angle SMO observer err_max (x1000)" + default 0 + ---help--- + The err_max coefficient used in observer is: + err_max = EXAMPLES_FOC_ANGOBS_SMO_ERRMAX/1000 + +endif # EXAMPLES_FOC_ANGOBS_SMO + +if EXAMPLES_FOC_ANGOBS_NFO + +config EXAMPLES_FOC_ANGOBS_NFO_GAIN + int "FOC angle NFO observer gain (x1)" + default 0 + ---help--- + The gain coefficient used in observer at maximum duty cycle. + +config EXAMPLES_FOC_ANGOBS_NFO_GAINSLOW + int "FOC angle NFO observer gain slow (x1)" + default 0 + ---help--- + The gain coefficient used in observer at minimum duty cycle. + +endif # EXAMPLES_FOC_ANGOBS_NFO + +config EXAMPLES_FOC_VELOBS + bool "FOC example velocity observer support" + default n + +if EXAMPLES_FOC_VELOBS + +choice + prompt "FOC example velocity observer selection" + default EXAMPLES_FOC_VELOBS_DIV + +config EXAMPLES_FOC_VELOBS_DIV + bool "FOC velocity DIV observer" + select INDUSTRY_FOC_VELOCITY_ODIV + +config EXAMPLES_FOC_VELOBS_PLL + bool "FOC velocity PLL observer" + select INDUSTRY_FOC_VELOCITY_OPLL + +endchoice # FOC example velocity observer selection + +if EXAMPLES_FOC_VELOBS_DIV + +config EXAMPLES_FOC_VELOBS_DIV_SAMPLES + int "FOC velocity DIV observer samples" + default 10 + +config EXAMPLES_FOC_VELOBS_DIV_FILTER + int "FOC velocity DIV observer filter (x1000)" + default 990 + +endif # INDUSTRY_FOC_VELOCITY_ODIV + +if EXAMPLES_FOC_VELOBS_PLL + +config EXAMPLES_FOC_VELOBS_PLL_KP + int "FOC velocity PLL observer Kp (x1)" + default 0 + +config EXAMPLES_FOC_VELOBS_PLL_KI + int "FOC velocity PLL observer Ki (x1)" + default 0 + +endif # EXAMPLES_FOC_VELOBS_PLL + +endif # EXAMPLES_FOC_VELOBS menu "FOC user input" @@ -321,11 +546,28 @@ config EXAMPLES_FOC_MMODE 4 - align only 5 - ident only +config EXAMPLES_FOC_STOP_CURRENT + int "FOC stop state Q voltage/current [x1000]" + default 0 + ---help--- + This current or voltage will be forced on the motor Q axis when + the application is in active break state. + config EXAMPLES_FOC_OPENLOOP_Q int "FOC open-loop Vq/Iq setting [x1000]" default 200 depends on EXAMPLES_FOC_HAVE_OPENLOOP +config EXAMPLES_FOC_FEEDFORWARD + bool "FOC use feedforward compensation for current controller" + select INDUSTRY_FOC_FEEDFORWARD + default n + ---help--- + This option enables feed-forward compensation for PI current controller + which can help achieve better performace of FOC. This option is not + recomended for sensorless operations and for current controllers that + already has high update frequency. + if EXAMPLES_FOC_CONTROL_PI config EXAMPLES_FOC_IDQ_KP @@ -347,15 +589,15 @@ config EXAMPLES_FOC_IDQ_KI endif #EXAMPLES_FOC_CONTROL_PI config EXAMPLES_FOC_RAMP_THR - int "FOC velocity ramp threshold [x1000]" + int "FOC velocity ramp threshold [x1]" default 0 config EXAMPLES_FOC_RAMP_ACC - int "FOC velocity ramp acc [x1000]" + int "FOC velocity ramp acc [x1]" default 0 config EXAMPLES_FOC_RAMP_DEC - int "FOC velocity ramp dec [x1000]" + int "FOC velocity ramp dec [x1]" default 0 config EXAMPLES_FOC_HAVE_ALIGN @@ -366,11 +608,11 @@ config EXAMPLES_FOC_HAVE_ALIGN if EXAMPLES_FOC_HAVE_ALIGN config EXAMPLES_FOC_ALIGN_VOLT - int "EXAMPLES_FOC_ALIGN_VOLT (x1000)" + int "FOC example motor alignment voltage (x1000)" default 0 config EXAMPLES_FOC_ALIGN_SEC - int "EXAMPLES_FOC_ALIGN_SEC (x1000)" + int "FOC example motor alignment time (x1000)" default 0 endif # EXAMPLES_FOC_HAVE_ALIGN @@ -484,12 +726,40 @@ config EXAMPLES_FOC_NXSCOPE_START frame from a NxScope master device. This allows us to capture controller data from the very beginning of its operation. +choice + prompt "FOC nxscope work caller" + default EXAMPLES_FOC_NXSCOPE_MAIN + +config EXAMPLES_FOC_NXSCOPE_MAIN + bool "FOC nxscope uses foc_main()" + ---help--- + Use foc_main() for NxScope communication. + +config EXAMPLES_FOC_NXSCOPE_CONTROL + bool "FOC nxscope uses control thread" + ---help--- + Use control thread for NxScope communication. + With this option enabled you should limit the number of nxscope channels. + Otherwise, handling incoming nxscope data may significantly delay the control + loop, and consequently, the control cycle may be missed. + config EXAMPLES_FOC_NXSCOPE_THREAD bool "FOC nxscope uses separate thread" - default n ---help--- Use a separate thread for NxScope communication. +endchoice # FOC nxscope work caller + +if EXAMPLES_FOC_NXSCOPE_CONTROL + +config EXAMPLES_FOC_NXSCOPE_WORK_PRESCALER + int "FOC nxscope work prescaler" + default 10 + ---help--- + This option allows you to reduce the frequency of calling nxscope worker. + +endif #EXAMPLES_FOC_NXSCOPE_CONTROL + if EXAMPLES_FOC_NXSCOPE_THREAD config EXAMPLES_FOC_NXSCOPE_PRIO @@ -506,4 +776,3 @@ endif # EXAMPLES_FOC_NXSCOPE endif # EXAMPLES_FOC - diff --git a/examples/foc/Makefile b/examples/foc/Makefile index 51f603577..cc81a3172 100644 --- a/examples/foc/Makefile +++ b/examples/foc/Makefile @@ -56,4 +56,10 @@ ifeq ($(CONFIG_EXAMPLES_FOC_NXSCOPE),y) CSRCS += foc_nxscope.c endif +# perf support + +ifeq ($(CONFIG_EXAMPLES_FOC_PERF),y) +CSRCS += foc_perf.c +endif + include $(APPDIR)/Application.mk diff --git a/examples/foc/README.md b/examples/foc/README.md deleted file mode 100644 index a3489bb2c..000000000 --- a/examples/foc/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# FOC example - -The main purpose of this example is to provide a universal template to -implement the motor controller based on the kernel-side FOC device and -the application-side FOC library. - -At the moment, this example implements a simple open-loop velocity controller. - -# Hardware setup - -This example has not yet implemented any mechanism to protect the -powered device. This means that there is no overtemeprature -protection, no overcurrent protection and no overvoltage protection. - -Make sure that you power the device properly and provide current -limits on your own so as not to break your hardware. - -# Configuration - -The FOC PI current controller parameters can be obtained from the given -equations: - -``` -Kp = ccb * Ls; -pp = Rs / Ls; -Ki = pp * Kp * T; -``` - -where: - Kp - PI proportional coefficient - Ki - PI integral coefficient - Rs - average phase serial resistance - Ls - average phase serial inductance - pp - pole plant - ccb - current control bandwidth - T - sampling period - -## Sample parameters for some commercially available motors - -* Odrive D6374 150KV - p = 7 - Rs = 0.0254 Ohm - Ls = 8.73 uH - i\_max = ? - v\_max = ? - - Example configuration for f\_PWM = 20kHz, f\_notifier = 10kHz, ccb=1000: - Kp = 0.0087 - Ki = 0.0025 - -* Linix 45ZWN24-40 (PMSM motor dedicated for NXP FRDM-MC-LVMTR kit) - p = 2 - Rs = 0.5 Ohm - Ls = 0.400 mH - i\_max = 2.34 A - v\_max = 24 V - - Example configuration for f\_PWM = 10kHz, f\_notifier = 5kHz, ccb=1000: - Kp = 0.4 - Ki = 0.1 - -* Bull-Running BR2804-1700 kV (motor provided with the ST P-NUCLEO-IHM07 kit) - p = 7 - Rs = 0.11 Ohm - Ls = 0.018 mH - i\_max = 1.2A - v\_max = 12V - - Example configuration for f\_PWM = 20kHz, f\_notifier = 10kHz, ccb=200: - Kp = 0.036 - Ki = 0.022 - -* iPower GBM2804H-100T (gimbal motor provided with the ST P-NUCLEO-IHM03 kit) - p = 7 - Rs = 5.29 Ohm - Ls = 1.05 mH - i\_max = 0.15A - v\_max = 12V - - Example configuration for f\_PWM = 10kHz, f\_notifier = 5kHz, ccb=TODO: - Kp = TODO - Ki = TODO diff --git a/examples/foc/foc_cfg.h b/examples/foc/foc_cfg.h index 44f46c4ab..3e03d3725 100644 --- a/examples/foc/foc_cfg.h +++ b/examples/foc/foc_cfg.h @@ -27,16 +27,15 @@ #include +#include + /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ -/* For now only torque mode supported for sensored */ - -#ifdef CONFIG_EXAMPLES_FOC_SENSORED -# ifndef CONFIG_EXAMPLES_FOC_HAVE_TORQ -# error -# endif +#if defined(CONFIG_EXAMPLES_FOC_SENSORLESS) && \ + defined(CONFIG_EXAMPLES_FOC_SENSORED) +# error Simultaneous support for sensorless and sensored mode not supported #endif /* For now only sensorless velocity control supported */ @@ -47,14 +46,28 @@ # endif #endif +/* Position controller needs velocity controller */ + +#if defined(CONFIG_EXAMPLES_FOC_HAVE_POS) && \ + !defined(CONFIG_EXAMPLES_FOC_HAVE_VEL) +# error Position controller needs velocity controller +#endif + +/* Velocity controller needs torque controller */ + +#if defined(CONFIG_EXAMPLES_FOC_HAVE_VEL) && \ + !defined(CONFIG_EXAMPLES_FOC_HAVE_TORQ) +# error Velocity controller needs torque controller +#endif + /* Open-loop configuration */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP # ifndef CONFIG_EXAMPLES_FOC_HAVE_VEL -# error +# error open-loop needs CONFIG_EXAMPLES_FOC_HAVE_VEL set # endif -# ifndef CONFIG_INDUSTRY_FOC_ANGLE_OPENLOOP -# error +# ifndef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP +# error open-loop needs CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP # endif #endif @@ -67,38 +80,32 @@ /* Velocity ramp must be configured */ #if (CONFIG_EXAMPLES_FOC_RAMP_THR == 0) -# error +# error CONFIG_EXAMPLES_FOC_RAMP_THR not configured #endif #if (CONFIG_EXAMPLES_FOC_RAMP_ACC == 0) -# error +# error CONFIG_EXAMPLES_FOC_RAMP_ACC not configured #endif #if (CONFIG_EXAMPLES_FOC_RAMP_DEC == 0) -# error -#endif - -/* ADC Iphase ratio must be provided */ - -#if (CONFIG_EXAMPLES_FOC_IPHASE_ADC == 0) -# error +# error CONFIG_EXAMPLES_FOC_RAMP_DEC not configured #endif /* Motor identification support */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_IDENT # if (CONFIG_EXAMPLES_FOC_IDENT_RES_CURRENT == 0) -# error +# error CONFIG_EXAMPLES_FOC_IDENT_RES_CURRENT not configured # endif # if (CONFIG_EXAMPLES_FOC_IDENT_RES_KI == 0) -# error +# error CONFIG_EXAMPLES_FOC_IDENT_RES_KI not configured # endif # if (CONFIG_EXAMPLES_FOC_IDENT_IND_VOLTAGE == 0) -# error +# error CONFIG_EXAMPLES_FOC_IDENT_IND_VOLTAGE not configured # endif # if (CONFIG_EXAMPLES_FOC_IDENT_RES_SEC == 0) -# error +# error CONFIG_EXAMPLES_FOC_IDENT_RES_SEC not configured # endif # if (CONFIG_EXAMPLES_FOC_IDENT_IND_SEC == 0) -# error +# error CONFIG_EXAMPLES_FOC_IDENT_IND_SEC not configured # endif #endif @@ -114,9 +121,7 @@ /* Velocity ramp configuration */ -#define RAMP_CFG_THR (CONFIG_EXAMPLES_FOC_RAMP_THR / 1000.0f) -#define RAMP_CFG_ACC (CONFIG_EXAMPLES_FOC_RAMP_ACC / 1000.0f) -#define RAMP_CFG_DEC (CONFIG_EXAMPLES_FOC_RAMP_DEC / 1000.0f) +#define RAMP_CFG_THR (CONFIG_EXAMPLES_FOC_RAMP_THR / 1.0f) #ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM @@ -132,25 +137,14 @@ # define FOC_MODEL_INDQ (0.0002f) #endif -/* Motor alignment configuration */ - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN -# if CONFIG_EXAMPLES_FOC_ALIGN_VOLT == 0 -# error -# endif -# if CONFIG_EXAMPLES_FOC_ALIGN_SEC == 0 -# error -# endif -#endif - /* Qenco configuration */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO # if CONFIG_EXAMPLES_FOC_MOTOR_POLES == 0 -# error +# error CONFIG_EXAMPLES_FOC_MOTOR_POLES must be defined # endif # if CONFIG_EXAMPLES_FOC_QENCO_POSMAX == 0 -# error +# error CONFIG_EXAMPLES_FOC_QENCO_POSMAX must be defined # endif #endif @@ -159,35 +153,35 @@ #if !defined(CONFIG_EXAMPLES_FOC_SETPOINT_CONST) && \ !defined(CONFIG_EXAMPLES_FOC_SETPOINT_ADC) && \ !defined(CONFIG_EXAMPLES_FOC_SETPOINT_CHAR) -# error +# error setpoint source not selected #endif /* Setpoint ADC scale factor */ #ifdef CONFIG_EXAMPLES_FOC_SETPOINT_ADC -# define SETPOINT_ADC_SCALE (1.0f / CONFIG_EXAMPLES_FOC_ADC_MAX) +# define SETPOINT_INTF_SCALE (1.0f / CONFIG_EXAMPLES_FOC_ADC_MAX) #endif /* If constant setpoint is selected, setpoint value must be provided */ #ifdef CONFIG_EXAMPLES_FOC_SETPOINT_CONST -# define SETPOINT_ADC_SCALE (1) +# define SETPOINT_INTF_SCALE (1) # if CONFIG_EXAMPLES_FOC_SETPOINT_CONST_VALUE == 0 -# error +# error CONFIG_EXAMPLES_FOC_SETPOINT_CONST_VALUE not configured # endif #endif /* CHARCTRL setpoint control */ #ifdef CONFIG_EXAMPLES_FOC_SETPOINT_CHAR -# define SETPOINT_ADC_SCALE (1 / 1000.0f) +# define SETPOINT_INTF_SCALE (1.0f / (CONFIG_EXAMPLES_FOC_SETPOINT_MAX / 1000.0f)) #endif /* VBUS source must be specified */ #if !defined(CONFIG_EXAMPLES_FOC_VBUS_CONST) && \ !defined(CONFIG_EXAMPLES_FOC_VBUS_ADC) -# error +# error no VBUS source selected ! #endif /* VBUS ADC scale factor */ @@ -206,7 +200,20 @@ # define VBUS_ADC_SCALE (1) # define VBUS_CONST_VALUE (CONFIG_EXAMPLES_FOC_VBUS_CONST_VALUE / 1000.0f) # if CONFIG_EXAMPLES_FOC_VBUS_CONST_VALUE == 0 -# error +# error CONFIG_EXAMPLES_FOC_VBUS_CONST_VALUE not configured +# endif +#endif + +/* Velocity controller prescaler */ + +#define VEL_CONTROL_PRESCALER (CONFIG_EXAMPLES_FOC_NOTIFIER_FREQ / \ + CONFIG_EXAMPLES_FOC_VELCTRL_FREQ) + +/* Open-loop to observer angle merge factor */ + +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS +# if CONFIG_EXAMPLES_FOC_ANGOBS_MERGE_RATIO > 0 +# define ANGLE_MERGE_FACTOR (CONFIG_EXAMPLES_FOC_ANGOBS_MERGE_RATIO / 100.0f) # endif #endif @@ -219,7 +226,12 @@ struct foc_thr_cfg_s int fmode; /* FOC control mode */ int mmode; /* Motor control mode */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - int qparam; /* Open-loop Q setting (x1000) */ + uint32_t qparam; /* Open-loop Q setting (x1000) */ + bool ol_force; /* Force open-loop */ +# ifdef CONFIG_EXAMPLES_FOC_ANGOBS + uint32_t ol_thr; /* Observer vel threshold [x1] */ + uint32_t ol_hys; /* Observer vel hysteresys [x1] */ +# endif #endif #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI @@ -232,6 +244,8 @@ struct foc_thr_cfg_s #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL uint32_t velmax; /* Velocity max (x1000) */ + uint32_t acc; /* Acceleration (x1) */ + uint32_t dec; /* Deceleration (x1) */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS uint32_t posmax; /* Position max (x1000) */ @@ -244,6 +258,28 @@ struct foc_thr_cfg_s uint32_t ident_ind_volt; /* Ident res voltage (x1000) */ uint32_t ident_ind_sec; /* Ident ind sec */ #endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + uint32_t vel_filter; /* Velocity filter (x1000) */ +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + uint32_t vel_pll_kp; /* Vel PLL observer Kp (x1000) */ + uint32_t vel_pll_ki; /* Vel PLL observer Ki (x1000) */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + uint32_t vel_div_samples; /* Vel DIV observer samples */ + uint32_t vel_div_filter; /* Vel DIV observer filter (x1000) */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + uint32_t vel_pi_kp; /* Vel controller PI Kp (x1000000) */ + uint32_t vel_pi_ki; /* Vel controller PI Ki (x1000000) */ +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + uint32_t ang_nfo_slow; /* Ang NFO slow gain (x1) */ + uint32_t ang_nfo_gain; /* Ang NFO gain (x1) */ +#endif }; #endif /* __APPS_EXAMPLES_FOC_FOC_CFG_H */ diff --git a/examples/foc/foc_device.c b/examples/foc/foc_device.c index 91ee1dbe9..5c39315be 100644 --- a/examples/foc/foc_device.c +++ b/examples/foc/foc_device.c @@ -90,6 +90,12 @@ int foc_device_init(FAR struct foc_device_s *dev, int id) goto errout; } +#ifdef CONFIG_EXAMPLES_FOC_PERF + /* Initialize perf */ + + foc_perf_init(&dev->perf); +#endif + errout: return ret; } @@ -172,6 +178,10 @@ int foc_dev_state_get(FAR struct foc_device_s *dev) goto errout; } +#ifdef CONFIG_EXAMPLES_FOC_PERF + foc_perf_start(&dev->perf); +#endif + errout: return ret; } @@ -195,6 +205,10 @@ int foc_dev_params_set(FAR struct foc_device_s *dev) goto errout; } +#ifdef CONFIG_EXAMPLES_FOC_PERF + foc_perf_end(&dev->perf); +#endif + errout: return ret; } diff --git a/examples/foc/foc_device.h b/examples/foc/foc_device.h index 1b46b9cab..8c57934cf 100644 --- a/examples/foc/foc_device.h +++ b/examples/foc/foc_device.h @@ -27,6 +27,8 @@ #include +#include "foc_perf.h" + #include "industry/foc/foc_utils.h" /**************************************************************************** @@ -41,6 +43,9 @@ struct foc_device_s struct foc_info_s info; /* FOC dev info */ struct foc_state_s state; /* FOC dev state */ struct foc_params_s params; /* FOC dev params */ +#ifdef CONFIG_EXAMPLES_FOC_PERF + struct foc_perf_s perf; /* FOC dev perf */ +#endif }; /**************************************************************************** diff --git a/examples/foc/foc_fixed16_thr.c b/examples/foc/foc_fixed16_thr.c index 87dc36ea1..6c5efe6a4 100644 --- a/examples/foc/foc_fixed16_thr.c +++ b/examples/foc/foc_fixed16_thr.c @@ -127,7 +127,9 @@ static int foc_handler_run(FAR struct foc_motor_b16_s *motor, /* Get FOC handler state */ - foc_handler_state_b16(&motor->handler, &motor->foc_state); + foc_handler_state_b16(&motor->handler, + &motor->foc_state, + &motor->mod_state); return ret; } @@ -226,12 +228,12 @@ static void foc_fixed16_nxscope(FAR struct foc_nxscope_s *nxs, nxscope_put_vb16(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VEL) -# warning not supported yet - i++; + ptr = (FAR b16_t *)&motor->vel_el; + nxscope_put_vb16(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VM) -# warning not supported yet - i++; + ptr = (FAR b16_t *)&motor->vel_mech; + nxscope_put_vb16(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VBUS) ptr = (FAR b16_t *)&motor->vbus; @@ -251,11 +253,29 @@ static void foc_fixed16_nxscope(FAR struct foc_nxscope_s *nxs, #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_DQREF) ptr = (FAR b16_t *)&motor->dq_ref; - nxscope_put_vb16_t(&nxs->nxs, i++, ptr, 2); + nxscope_put_vb16(&nxs->nxs, i++, ptr, 2); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VDQCOMP) ptr = (FAR b16_t *)&motor->vdq_comp; - nxscope_put_vb16_t(&nxs->nxs, i++, ptr, 2); + nxscope_put_vb16(&nxs->nxs, i++, ptr, 2); +#endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_SVM3) + b16_t svm3_tmp[4]; + + /* Convert sector to b16_t. + * Normally, a sector value is an integer in the range 1-6 but we convert + * it to b16_t and range to 0.1-0.6. This is to send the entire SVM3 state + * as b16_t array and scale the sector value closer to PWM duty values + * (range 0.0 to 0.5) which makes it easier to visualize the data later. + */ + + svm3_tmp[0] = b16mulb16(itob16(motor->mod_state.sector), ftob16(0.1f)); + svm3_tmp[1] = motor->mod_state.d_u; + svm3_tmp[2] = motor->mod_state.d_v; + svm3_tmp[3] = motor->mod_state.d_w; + + ptr = svm3_tmp; + nxscope_put_vb16(&nxs->nxs, i++, ptr, 4); #endif nxscope_unlock(&nxs->nxs); @@ -275,10 +295,8 @@ int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp) struct foc_mq_s handle; struct foc_motor_b16_s motor; struct foc_device_s dev; - int time = 0; int ret = OK; - UNUSED(time); DEBUGASSERT(envp); PRINTFV("foc_fixed_thr, id=%d\n", envp->id); @@ -305,9 +323,10 @@ int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp) goto errout; } - /* Get PWM max duty */ + /* Store data from device */ motor.pwm_duty_max = FOCDUTY_TO_FIXED16(dev.info.hw_cfg.pwm_max); + motor.iphase_adc = b16idiv(dev.info.hw_cfg.iphase_scale, 100000); /* Start with motor free */ @@ -321,7 +340,19 @@ int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp) while (motor.mq.quit == false) { - PRINTFV("foc_fixed16_thr %d %d\n", envp->id, time); + if (motor.mq.start == true) + { + /* Get FOC device state */ + + ret = foc_dev_state_get(&dev); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_state_get failed %d!\n", ret); + goto errout; + } + } + + PRINTFV("foc_fixed16_thr %d %d\n", envp->id, motor.time); /* Handle mqueue */ @@ -356,119 +387,129 @@ int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp) } motor.startstop = false; + + /* Start from the beginning of the control loop */ + + continue; } - /* Run control logic if controller started */ + /* Ignore control logic if controller not started yet */ - if (motor.mq.start == true) - { - /* Get FOC device state */ - - ret = foc_dev_state_get(&dev); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_state_get failed %d!\n", ret); - goto errout; - } - -#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM - /* Get model state */ - - ret = foc_model_state_get(&motor, &dev); - if (ret < 0) - { - PRINTF("ERROR: foc_model_state_get failed %d!\n", ret); - goto errout; - } -#endif - - /* Handle controller state */ - - ret = foc_dev_state_handle(&dev, &motor.fault); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_state_handle failed %d!\n", ret); - goto errout; - } - - /* Get motor state */ - - ret = foc_motor_get(&motor); - if (ret < 0) - { - PRINTF("ERROR: foc_motor_get failed %d!\n", ret); - goto errout; - } - - /* Motor control */ - - ret = foc_motor_control(&motor); - if (ret < 0) - { - PRINTF("ERROR: foc_motor_control failed %d!\n", ret); - goto errout; - } - - /* Run FOC */ - - ret = foc_handler_run(&motor, &dev); - if (ret < 0) - { - PRINTF("ERROR: foc_handler_run failed %d!\n", ret); - goto errout; - } - -#ifdef FOC_STATE_PRINT_PRE - /* Print state if configured */ - - if (time % FOC_STATE_PRINT_PRE == 0) - { - foc_state_print(&motor); - } -#endif - -#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM - /* Feed FOC model with data */ - - foc_model_run_b16(&motor.model, - ftob16(FOC_MODEL_LOAD), - &motor.foc_state.vab); -#endif - - /* Set FOC device parameters */ - - ret = foc_dev_params_set(&dev); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_params_set failed %d!\n", ret); - goto errout; - } - -#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE - /* Capture nxscope samples */ - - if (time % CONFIG_EXAMPLES_FOC_NXSCOPE_PRESCALER == 0) - { - foc_fixed16_nxscope(envp->nxs, &motor, &dev); - } -#endif - - /* Terminate control thread */ - - if (motor.ctrl_state == FOC_CTRL_STATE_TERMINATE) - { - PRINTF("TERMINATE CTRL THREAD\n"); - goto errout; - } - } - else + if (motor.mq.start == false) { usleep(1000); + continue; + } + +#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM + /* Get model state */ + + ret = foc_model_state_get(&motor, &dev); + if (ret < 0) + { + PRINTF("ERROR: foc_model_state_get failed %d!\n", ret); + goto errout; + } +#endif + + /* Handle controller state */ + + ret = foc_dev_state_handle(&dev, &motor.fault); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_state_handle failed %d!\n", ret); + goto errout; + } + + /* Get motor state */ + + ret = foc_motor_get(&motor); + if (ret < 0) + { + PRINTF("ERROR: foc_motor_get failed %d!\n", ret); + goto errout; + } + + /* Motor control */ + + ret = foc_motor_control(&motor); + if (ret < 0) + { + PRINTF("ERROR: foc_motor_control failed %d!\n", ret); + goto errout; + } + + /* Run FOC */ + + ret = foc_handler_run(&motor, &dev); + if (ret < 0) + { + PRINTF("ERROR: foc_handler_run failed %d!\n", ret); + goto errout; + } + +#ifdef FOC_STATE_PRINT_PRE + /* Print state if configured */ + + if (motor.time % FOC_STATE_PRINT_PRE == 0) + { + foc_state_print(&motor); + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM + /* Feed FOC model with data */ + + foc_model_run_b16(&motor.model, + ftob16(FOC_MODEL_LOAD), + &motor.foc_state.vab); +#endif + + /* Set FOC device parameters */ + + ret = foc_dev_params_set(&dev); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_params_set failed %d!\n", ret); + goto errout; + } + +#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE + /* Capture nxscope samples */ + + if (motor.time % CONFIG_EXAMPLES_FOC_NXSCOPE_PRESCALER == 0) + { + foc_fixed16_nxscope(envp->nxs, &motor, &dev); + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE_CONTROL + /* Handle nxscope work */ + + if (motor.time % CONFIG_EXAMPLES_FOC_NXSCOPE_WORK_PRESCALER == 0) + { + foc_nxscope_work(envp->nxs); + } +#endif + + /* Terminate control thread */ + + if (motor.ctrl_state == FOC_CTRL_STATE_TERMINATE) + { + PRINTF("TERMINATE CTRL THREAD\n"); + goto errout; } /* Increase counter */ - time += 1; + motor.time += 1; + +#ifdef CONFIG_EXAMPLES_FOC_PERF + if (dev.perf.max_changed) + { + PRINTF_PERF("max=%" PRId32 "\n", dev.perf.max); + } +#endif } errout: diff --git a/examples/foc/foc_float_thr.c b/examples/foc/foc_float_thr.c index 913162d84..05b4201ff 100644 --- a/examples/foc/foc_float_thr.c +++ b/examples/foc/foc_float_thr.c @@ -127,7 +127,9 @@ static int foc_handler_run(FAR struct foc_motor_f32_s *motor, /* Get FOC handler state */ - foc_handler_state_f32(&motor->handler, &motor->foc_state); + foc_handler_state_f32(&motor->handler, + &motor->foc_state, + &motor->mod_state); return ret; } @@ -192,7 +194,9 @@ static void foc_float_nxscope(FAR struct foc_nxscope_s *nxs, int i = nxs->ch_per_inst * motor->envp->id; #endif +#ifndef CONFIG_EXAMPLES_FOC_NXSCOPE_CONTROL nxscope_lock(&nxs->nxs); +#endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_IABC) ptr = (FAR float *)&motor->foc_state.curr; @@ -227,12 +231,12 @@ static void foc_float_nxscope(FAR struct foc_nxscope_s *nxs, nxscope_put_vfloat(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VEL) -# warning not supported yet - i++; + ptr = (FAR float *)&motor->vel_el; + nxscope_put_vfloat(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VM) -# warning not supported yet - i++; + ptr = (FAR float *)&motor->vel_mech; + nxscope_put_vfloat(&nxs->nxs, i++, ptr, 1); #endif #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VBUS) ptr = (FAR float *)&motor->vbus; @@ -258,8 +262,36 @@ static void foc_float_nxscope(FAR struct foc_nxscope_s *nxs, ptr = (FAR float *)&motor->vdq_comp; nxscope_put_vfloat(&nxs->nxs, i++, ptr, 2); #endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_SVM3) + float svm3_tmp[4]; + /* Convert sector to float. + * Normally, a sector value is an integer in the range 1-6 but we convert + * it to float and range to 0.1-0.6. This is to send the entire SVM3 state + * as float array and scale the sector value closer to PWM duty values + * (range 0.0 to 0.5) which makes it easier to visualize the data later. + */ + + svm3_tmp[0] = (float)motor->mod_state.sector * 0.1f; + svm3_tmp[1] = motor->mod_state.d_u; + svm3_tmp[2] = motor->mod_state.d_v; + svm3_tmp[3] = motor->mod_state.d_w; + + ptr = svm3_tmp; + nxscope_put_vfloat(&nxs->nxs, i++, ptr, 4); +#endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VOBS) + ptr = (FAR float *)&motor->vel_obs; + nxscope_put_vfloat(&nxs->nxs, i++, ptr, 1); +#endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_AOBS) + ptr = (FAR float *)&motor->angle_obs; + nxscope_put_vfloat(&nxs->nxs, i++, ptr, 1); +#endif + +#ifndef CONFIG_EXAMPLES_FOC_NXSCOPE_CONTROL nxscope_unlock(&nxs->nxs); +#endif } #endif @@ -276,10 +308,8 @@ int foc_float_thr(FAR struct foc_ctrl_env_s *envp) struct foc_mq_s handle; struct foc_motor_f32_s motor; struct foc_device_s dev; - int time = 0; int ret = OK; - UNUSED(time); DEBUGASSERT(envp); PRINTFV("foc_float_thr, id=%d\n", envp->id); @@ -306,9 +336,10 @@ int foc_float_thr(FAR struct foc_ctrl_env_s *envp) goto errout; } - /* Get PWM max duty */ + /* Store data from device */ motor.pwm_duty_max = FOCDUTY_TO_FLOAT(dev.info.hw_cfg.pwm_max); + motor.iphase_adc = dev.info.hw_cfg.iphase_scale / 100000.0f; /* Start with motor free */ @@ -322,7 +353,19 @@ int foc_float_thr(FAR struct foc_ctrl_env_s *envp) while (motor.mq.quit == false) { - PRINTFV("foc_float_thr %d %d\n", envp->id, time); + if (motor.mq.start == true) + { + /* Get FOC device state */ + + ret = foc_dev_state_get(&dev); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_state_get failed %d!\n", ret); + goto errout; + } + } + + PRINTFV("foc_float_thr %d %d\n", envp->id, motor.time); /* Handle mqueue */ @@ -357,119 +400,129 @@ int foc_float_thr(FAR struct foc_ctrl_env_s *envp) } motor.startstop = false; + + /* Start from the beginning of the control loop */ + + continue; } - /* Run control logic if controller started */ + /* Ignore control logic if controller not started yet */ - if (motor.mq.start == true) - { - /* Get FOC device state */ - - ret = foc_dev_state_get(&dev); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_state_get failed %d!\n", ret); - goto errout; - } - -#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM - /* Get model state */ - - ret = foc_model_state_get(&motor, &dev); - if (ret < 0) - { - PRINTF("ERROR: foc_model_state_get failed %d!\n", ret); - goto errout; - } -#endif - - /* Handle controller state */ - - ret = foc_dev_state_handle(&dev, &motor.fault); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_state_handle failed %d!\n", ret); - goto errout; - } - - /* Get motor state */ - - ret = foc_motor_get(&motor); - if (ret < 0) - { - PRINTF("ERROR: foc_motor_get failed %d!\n", ret); - goto errout; - } - - /* Motor control */ - - ret = foc_motor_control(&motor); - if (ret < 0) - { - PRINTF("ERROR: foc_motor_control failed %d!\n", ret); - goto errout; - } - - /* Run FOC */ - - ret = foc_handler_run(&motor, &dev); - if (ret < 0) - { - PRINTF("ERROR: foc_handler_run failed %d!\n", ret); - goto errout; - } - -#ifdef FOC_STATE_PRINT_PRE - /* Print state if configured */ - - if (time % FOC_STATE_PRINT_PRE == 0) - { - foc_state_print(&motor); - } -#endif - -#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE - /* Capture nxscope samples */ - - if (time % CONFIG_EXAMPLES_FOC_NXSCOPE_PRESCALER == 0) - { - foc_float_nxscope(envp->nxs, &motor, &dev); - } -#endif - -#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM - /* Feed FOC model with data */ - - foc_model_run_f32(&motor.model, - FOC_MODEL_LOAD, - &motor.foc_state.vab); -#endif - - /* Set FOC device parameters */ - - ret = foc_dev_params_set(&dev); - if (ret < 0) - { - PRINTF("ERROR: foc_dev_prams_set failed %d!\n", ret); - goto errout; - } - - /* Terminate control thread */ - - if (motor.ctrl_state == FOC_CTRL_STATE_TERMINATE) - { - PRINTF("TERMINATE CTRL THREAD\n"); - goto errout; - } - } - else + if (motor.mq.start == false) { usleep(1000); + continue; + } + +#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM + /* Get model state */ + + ret = foc_model_state_get(&motor, &dev); + if (ret < 0) + { + PRINTF("ERROR: foc_model_state_get failed %d!\n", ret); + goto errout; + } +#endif + + /* Handle controller state */ + + ret = foc_dev_state_handle(&dev, &motor.fault); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_state_handle failed %d!\n", ret); + goto errout; + } + + /* Get motor state */ + + ret = foc_motor_get(&motor); + if (ret < 0) + { + PRINTF("ERROR: foc_motor_get failed %d!\n", ret); + goto errout; + } + + /* Motor control */ + + ret = foc_motor_control(&motor); + if (ret < 0) + { + PRINTF("ERROR: foc_motor_control failed %d!\n", ret); + goto errout; + } + + /* Run FOC */ + + ret = foc_handler_run(&motor, &dev); + if (ret < 0) + { + PRINTF("ERROR: foc_handler_run failed %d!\n", ret); + goto errout; + } + +#ifdef FOC_STATE_PRINT_PRE + /* Print state if configured */ + + if (motor.time % FOC_STATE_PRINT_PRE == 0) + { + foc_state_print(&motor); + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM + /* Feed FOC model with data */ + + foc_model_run_f32(&motor.model, + FOC_MODEL_LOAD, + &motor.foc_state.vab); +#endif + + /* Set FOC device parameters */ + + ret = foc_dev_params_set(&dev); + if (ret < 0) + { + PRINTF("ERROR: foc_dev_prams_set failed %d!\n", ret); + goto errout; + } + +#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE + /* Capture nxscope samples */ + + if (motor.time % CONFIG_EXAMPLES_FOC_NXSCOPE_PRESCALER == 0) + { + foc_float_nxscope(envp->nxs, &motor, &dev); + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE_CONTROL + /* Handle nxscope work */ + + if (motor.time % CONFIG_EXAMPLES_FOC_NXSCOPE_WORK_PRESCALER == 0) + { + foc_nxscope_work(envp->nxs); + } +#endif + + /* Terminate control thread */ + + if (motor.ctrl_state == FOC_CTRL_STATE_TERMINATE) + { + PRINTF("TERMINATE CTRL THREAD\n"); + goto errout; } /* Increase counter */ - time += 1; + motor.time += 1; + +#ifdef CONFIG_EXAMPLES_FOC_PERF + if (dev.perf.max_changed) + { + PRINTF_PERF("max=%" PRId32 "\n", dev.perf.max); + } +#endif } errout: diff --git a/examples/foc/foc_main.c b/examples/foc/foc_main.c index f4d8f95d2..e4626baf6 100644 --- a/examples/foc/foc_main.c +++ b/examples/foc/foc_main.c @@ -75,7 +75,12 @@ struct args_s g_args = .fmode = CONFIG_EXAMPLES_FOC_FMODE, .mmode = CONFIG_EXAMPLES_FOC_MMODE, #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - .qparam = CONFIG_EXAMPLES_FOC_OPENLOOP_Q, + .qparam = CONFIG_EXAMPLES_FOC_OPENLOOP_Q, + .ol_force = false, +# ifdef CONFIG_EXAMPLES_FOC_ANGOBS + .ol_hys = CONFIG_EXAMPLES_FOC_ANGOBS_HYS, + .ol_thr = CONFIG_EXAMPLES_FOC_ANGOBS_THR, +# endif #endif #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI .foc_pi_kp = CONFIG_EXAMPLES_FOC_IDQ_KP, @@ -102,12 +107,35 @@ struct args_s g_args = .posmax = CONFIG_EXAMPLES_FOC_SETPOINT_MAX, # endif #endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + .acc = CONFIG_EXAMPLES_FOC_RAMP_ACC, + .dec = CONFIG_EXAMPLES_FOC_RAMP_DEC, +#endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_IDENT .ident_res_ki = CONFIG_EXAMPLES_FOC_IDENT_RES_KI, .ident_res_curr = CONFIG_EXAMPLES_FOC_IDENT_RES_CURRENT, .ident_res_sec = CONFIG_EXAMPLES_FOC_IDENT_RES_SEC, .ident_ind_volt = CONFIG_EXAMPLES_FOC_IDENT_IND_VOLTAGE, .ident_ind_sec = CONFIG_EXAMPLES_FOC_IDENT_IND_SEC, +#endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + .vel_filter = CONFIG_EXAMPLES_FOC_VELNOW_FILTER, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + .vel_pll_kp = CONFIG_EXAMPLES_FOC_VELOBS_PLL_KP, + .vel_pll_ki = CONFIG_EXAMPLES_FOC_VELOBS_PLL_KI, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + .vel_div_samples = CONFIG_EXAMPLES_FOC_VELOBS_DIV_SAMPLES, + .vel_div_filter = CONFIG_EXAMPLES_FOC_VELOBS_DIV_FILTER, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + .vel_pi_kp = CONFIG_EXAMPLES_FOC_VELCTRL_PI_KP, + .vel_pi_ki = CONFIG_EXAMPLES_FOC_VELCTRL_PI_KI, +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + .ang_nfo_slow = CONFIG_EXAMPLES_FOC_ANGOBS_NFO_GAINSLOW, + .ang_nfo_gain = CONFIG_EXAMPLES_FOC_ANGOBS_NFO_GAIN, #endif } }; @@ -368,8 +396,7 @@ int main(int argc, char *argv[]) { PRINTFV("foc_main loop %d\n", time); -#if defined(CONFIG_EXAMPLES_FOC_NXSCOPE) && \ - !defined(CONFIG_EXAMPLES_FOC_NXSCOPE_THREAD) +#ifdef CONFIG_EXAMPLES_FOC_NXSCOPE_MAIN foc_nxscope_work(&nxs); #endif diff --git a/examples/foc/foc_motor_b16.c b/examples/foc/foc_motor_b16.c index 2fe9dfd2c..91beaa060 100644 --- a/examples/foc/foc_motor_b16.c +++ b/examples/foc/foc_motor_b16.c @@ -26,10 +26,14 @@ #include #include +#include #include "foc_cfg.h" #include "foc_debug.h" #include "foc_motor_b16.h" +#ifdef CONFIG_EXAMPLES_FOC_FEEDFORWARD +# include "industry/foc/float/foc_feedforward.h" +#endif /**************************************************************************** * Pre-processor Definitions @@ -118,7 +122,9 @@ static int foc_motor_align(FAR struct foc_motor_b16_s *motor, FAR bool *done) } PRINTF("Aling results:\n"); +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR PRINTF(" dir = %.2f\n", b16tof(final.dir)); +#endif PRINTF(" offset = %.2f\n", b16tof(final.offset)); *done = true; @@ -264,7 +270,7 @@ static int foc_runmode_init(FAR struct foc_motor_b16_s *motor) #ifdef CONFIG_EXAMPLES_FOC_SENSORLESS # ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - motor->openloop_now = true; + motor->openloop_now = FOC_OPENLOOP_ENABLED; # else # error # endif @@ -286,7 +292,7 @@ static int foc_motor_configure(FAR struct foc_motor_b16_s *motor) #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI struct foc_initdata_b16_s ctrl_cfg; #endif -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 struct foc_mod_cfg_b16_s mod_cfg; #endif #ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM @@ -302,8 +308,8 @@ static int foc_motor_configure(FAR struct foc_motor_b16_s *motor) ret = foc_ramp_init_b16(&motor->ramp, motor->per, ftob16(RAMP_CFG_THR), - ftob16(RAMP_CFG_ACC), - ftob16(RAMP_CFG_ACC)); + ftob16((motor->envp->cfg->acc / 1.0f)), + ftob16((motor->envp->cfg->dec / 1.0f))); if (ret < 0) { PRINTF("ERROR: foc_ramp_init failed %d\n", ret); @@ -321,7 +327,7 @@ static int foc_motor_configure(FAR struct foc_motor_b16_s *motor) /* Get FOC modulation */ -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 foc_mod = &g_foc_mod_svm3_b16; #else # error FOC modulation not selected @@ -352,7 +358,7 @@ static int foc_motor_configure(FAR struct foc_motor_b16_s *motor) ctrl_cfg.iq_ki = ftob16(motor->envp->cfg->foc_pi_ki / 1000.0f); #endif -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 /* Get SVM3 modulation configuration */ mod_cfg.pwm_duty_max = motor->pwm_duty_max; @@ -362,11 +368,13 @@ static int foc_motor_configure(FAR struct foc_motor_b16_s *motor) foc_handler_cfg_b16(&motor->handler, &ctrl_cfg, &mod_cfg); -#ifdef CONFIG_EXAMPLES_FOC_MOTOR_POLES - /* Configure motor poles */ + /* Configure motor phy */ - motor->poles = CONFIG_EXAMPLES_FOC_MOTOR_POLES; -#endif + motor_phy_params_init_b16(&motor->phy, + CONFIG_EXAMPLES_FOC_MOTOR_POLES, + ftob16(CONFIG_EXAMPLES_FOC_MOTOR_RES / 1000000.0f), + ftob16(CONFIG_EXAMPLES_FOC_MOTOR_IND / 1000000.0f), + ftob16(CONFIG_EXAMPLES_FOC_MOTOR_FLUXLINK / 1000000.0f)); #ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM /* Initialize PMSM model */ @@ -432,9 +440,9 @@ static int foc_motor_torq(FAR struct foc_motor_b16_s *motor, uint32_t torq) */ tmp1 = itob16(motor->envp->cfg->torqmax / 1000); - tmp2 = b16mulb16(ftob16(SETPOINT_ADC_SCALE), tmp1); + tmp2 = b16mulb16(ftob16(SETPOINT_INTF_SCALE), tmp1); - motor->torq.des = b16muli(tmp2, torq); + motor->torq.des = b16mulb16(motor->dir, b16muli(tmp2, torq)); return OK; } @@ -457,9 +465,9 @@ static int foc_motor_vel(FAR struct foc_motor_b16_s *motor, uint32_t vel) */ tmp1 = itob16(motor->envp->cfg->velmax / 1000); - tmp2 = b16mulb16(ftob16(SETPOINT_ADC_SCALE), tmp1); + tmp2 = b16mulb16(ftob16(SETPOINT_INTF_SCALE), tmp1); - motor->vel.des = b16muli(tmp2, vel); + motor->vel.des = b16mulb16(motor->dir, b16muli(tmp2, vel)); return OK; } @@ -482,9 +490,9 @@ static int foc_motor_pos(FAR struct foc_motor_b16_s *motor, uint32_t pos) */ tmp1 = itob16(motor->envp->cfg->posmax / 1000); - tmp2 = b16mulb16(ftob16(SETPOINT_ADC_SCALE), tmp1); + tmp2 = b16mulb16(ftob16(SETPOINT_INTF_SCALE), tmp1); - motor->pos.des = b16muli(tmp2, pos); + motor->pos.des = b16mulb16(motor->dir, b16muli(tmp2, pos)); return OK; } @@ -573,6 +581,40 @@ errout: return ret; } +/**************************************************************************** + * Name: foc_motor_vel_reset + ****************************************************************************/ + +static int foc_motor_vel_reset(FAR struct foc_motor_b16_s *motor) +{ + int ret = OK; + + /* Reset velocity observer */ + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + ret = foc_velocity_zero_b16(&motor->vel_div); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_zero failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + ret = foc_velocity_zero_b16(&motor->vel_pll); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_zero failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + errout: +#endif + return ret; +} + /**************************************************************************** * Name: foc_motor_state ****************************************************************************/ @@ -583,7 +625,7 @@ static int foc_motor_state(FAR struct foc_motor_b16_s *motor, int state) DEBUGASSERT(motor); - /* Update motor state */ + /* Update motor state - this function is called every controller cycle */ switch (state) { @@ -601,10 +643,26 @@ static int foc_motor_state(FAR struct foc_motor_b16_s *motor, int state) case FOC_EXAMPLE_STATE_STOP: { +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + /* For sensorless we can just set Q reference to lock the motor */ + motor->dir = DIR_NONE_B16; /* DQ vector not zero - active brake */ + motor->dq_ref.q = ftob16(CONFIG_EXAMPLES_FOC_STOP_CURRENT / + 1000.0f); + motor->dq_ref.d = 0; +#else + /* For sensored mode we set requested velocity to 0 */ + +# ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + motor->vel.des = 0; +# else +# error STOP state for sensored mode requires velocity support +# endif +#endif + break; } @@ -629,6 +687,27 @@ static int foc_motor_state(FAR struct foc_motor_b16_s *motor, int state) } } +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + /* Re-align motor if we change mode from FREE/STOP to CW/CCW otherwise, + * the open-loop may fail because the rotor position at the start is + * random. + */ + + if ((motor->mq.app_state == FOC_EXAMPLE_STATE_FREE || + motor->mq.app_state == FOC_EXAMPLE_STATE_STOP) && + (state == FOC_EXAMPLE_STATE_CW || + state == FOC_EXAMPLE_STATE_CCW)) + { + motor->ctrl_state = FOC_CTRL_STATE_ALIGN; + motor->align_done = false; + motor->angle_now = 0; + + /* Reset velocity observer */ + + foc_motor_vel_reset(motor); + } +#endif + /* Reset current setpoint */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ @@ -696,23 +775,122 @@ errout: static int foc_motor_run_init(FAR struct foc_motor_b16_s *motor) { - /* Empty for now */ + int ret = OK; - return OK; +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + ret = foc_motor_vel_reset(motor); +#endif + + return ret; } +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS +/**************************************************************************** + * Name: foc_motor_openloop_trans + ****************************************************************************/ + +static void foc_motor_openloop_trans(FAR struct foc_motor_b16_s *motor) +{ +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* Set the intergral part of the velocity PI controller equal to the + * open-loop Q current value. + * + * REVISIT: this may casue a velocity overshoot when going from open-loop + * to closed-loop. We can either use part of the open-loop Q + * current here or gradually reduce the Q current during + * transition. + */ + + motor->vel_pi.part[1] = b16mulb16(motor->dir, motor->openloop_q); + motor->vel_pi.part[0] = 0; +#endif +} + +/**************************************************************************** + * Name: foc_motor_openloop_angobs + ****************************************************************************/ + +static void foc_motor_openloop_angobs(FAR struct foc_motor_b16_s *motor) +{ + b16_t vel_abs = 0; + + vel_abs = b16abs(motor->vel_el); + + /* Disable open-loop if velocity above threshold */ + + if (motor->openloop_now == FOC_OPENLOOP_ENABLED) + { + if (vel_abs >= motor->ol_thr) + { + /* Store angle error between the forced open-loop angle and + * observer output. The error will be gradually eliminated over + * the next controller cycles. + */ + +#ifdef ANGLE_MERGE_FACTOR + motor->angle_step = b16mulb16(motor->angle_err, + ftob16(ANGLE_MERGE_FACTOR)); + motor->angle_err = motor->angle_ol - motor->angle_obs; +#endif + + motor->openloop_now = FOC_OPENLOOP_TRANSITION; + } + } + + /* Handle transition end */ + + else if (motor->openloop_now == FOC_OPENLOOP_TRANSITION) + { + if (motor->angle_err == 0) + { + /* Call open-open loop transition handler */ + + foc_motor_openloop_trans(motor); + + motor->openloop_now = FOC_OPENLOOP_DISABLED; + } + } + + /* Enable open-loop if velocity below threshold with hysteresis */ + + else if (motor->openloop_now == FOC_OPENLOOP_DISABLED) + { + /* For better stability we add hysteresis from transition + * from closed-loop to open-loop. + */ + + if (vel_abs < (motor->ol_thr - motor->ol_hys)) + { + motor->openloop_now = FOC_OPENLOOP_ENABLED; + } + } +} +#endif + /**************************************************************************** * Name: foc_motor_run ****************************************************************************/ static int foc_motor_run(FAR struct foc_motor_b16_s *motor) { +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + b16_t vel_err = 0.0f; +#endif b16_t q_ref = 0; b16_t d_ref = 0; int ret = OK; DEBUGASSERT(motor); +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + if (motor->envp->cfg->ol_force == false) + { + /* Handle open-loop to observer transition */ + + foc_motor_openloop_angobs(motor); + } +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP /* Open-loop works only in velocity control mode */ @@ -734,35 +912,95 @@ static int foc_motor_run(FAR struct foc_motor_b16_s *motor) q_ref = motor->dq_ref.q; d_ref = motor->dq_ref.d; - /* Controller */ + /* Ignore controller if motor is free (sensorless and sensored mode) + * or stopped (only sensorless mode) + */ + + if (motor->mq.app_state == FOC_EXAMPLE_STATE_FREE +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + || motor->mq.app_state == FOC_EXAMPLE_STATE_STOP +#endif + ) + { + goto no_controller; + } + + /* Controller. + * + * The FOC motor controller is a cascade controller: + * + * 1. Position controller sets requested velocity, + * 2. Velocity controller sets requested torque, + * 3. Torque controller sets requested motor phase voltages. + * + * NOTE: the motor torque is directly proportional to the motor + * current which is proportional to the motor set voltage + */ switch (motor->envp->cfg->mmode) { -#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ - case FOC_MMODE_TORQ: - { - motor->torq.set = b16mulb16(motor->dir, motor->torq.des); - - q_ref = motor->torq.set; - d_ref = 0; - - break; - } -#endif - #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL case FOC_MMODE_VEL: { - /* Run velocity ramp controller */ + /* Saturate velocity */ - ret = foc_ramp_run_b16(&motor->ramp, motor->vel.des, - motor->vel.now, &motor->vel.set); - if (ret < 0) + f_saturate_b16(&motor->vel.des, -motor->vel_sat, + motor->vel_sat); + + /* Velocity controller */ + + if (motor->time % VEL_CONTROL_PRESCALER == 0) { - PRINTF("ERROR: foc_ramp_run failed %d\n", ret); - goto errout; + /* Run velocity ramp controller */ + + ret = foc_ramp_run_b16(&motor->ramp, + motor->vel.des, + motor->vel.now, + &motor->vel.set); + if (ret < 0) + { + PRINTF("ERROR: foc_ramp_run failed %d\n", ret); + goto errout; + } + + /* Run velocity controller if no in open-loop */ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + if (motor->openloop_now == false) +#endif + { + /* Get velocity error */ + + vel_err = motor->vel.set - motor->vel.now; + +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* PI velocit controller */ + + motor->torq.des = pi_controller_b16(&motor->vel_pi, + vel_err); +#else +# error Missing velocity controller +#endif + } } + /* Don't break here! pass to torque controller */ + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ + case FOC_MMODE_TORQ: + { + /* Saturate torque */ + + f_saturate_b16(&motor->torq.des, -motor->torq_sat, + motor->torq_sat); + + /* Torque setpoint */ + + motor->torq.set = motor->torq.des; + motor->torq.now = motor->foc_state.idq.q; + break; } #endif @@ -774,20 +1012,28 @@ static int foc_motor_run(FAR struct foc_motor_b16_s *motor) } } + /* Get dq ref */ + + q_ref = motor->torq.set; + d_ref = 0; + #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP /* Force open-loop current */ - if (motor->openloop_now == true) + if (motor->openloop_now == FOC_OPENLOOP_ENABLED || + motor->openloop_now == FOC_OPENLOOP_TRANSITION) { - /* Get open-loop currents - * NOTE: Id always set to 0 + /* Get open-loop currents. Positive for CW direction, negative for + * CCW direction. Id always set to 0. */ - q_ref = b16idiv(motor->envp->cfg->qparam, 1000); + q_ref = b16mulb16(motor->dir, motor->openloop_q); d_ref = 0; } #endif +no_controller: + /* Set DQ reference frame */ motor->dq_ref.q = q_ref; @@ -795,14 +1041,257 @@ static int foc_motor_run(FAR struct foc_motor_b16_s *motor) /* DQ compensation */ +#ifdef CONFIG_EXAMPLES_FOC_FEEDFORWARD + foc_feedforward_pmsm_b16(&motor->phy, &motor->foc_state.idq, + motor->vel.now, &motor->vdq_comp); +#else motor->vdq_comp.q = 0; motor->vdq_comp.d = 0; +#endif errout: return ret; } #endif +/**************************************************************************** + * Name: foc_motor_ang_get + ****************************************************************************/ + +static int foc_motor_ang_get(FAR struct foc_motor_b16_s *motor) +{ + struct foc_angle_in_b16_s ain; + struct foc_angle_out_b16_s aout; + int ret = OK; + + DEBUGASSERT(motor); + + /* Update open-loop angle handler */ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + ain.vel = motor->vel.set; +#endif + ain.angle = motor->angle_now; + ain.dir = motor->dir; + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + if (motor->openloop_now != FOC_OPENLOOP_DISABLED) + { + foc_angle_run_b16(&motor->openloop, &ain, &aout); + + /* Store open-loop angle */ + + motor->angle_ol = aout.angle; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO + ret = foc_angle_run_b16(&motor->qenco, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL + ret = foc_angle_run_b16(&motor->hall, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + ret = foc_angle_run_b16(&motor->ang_smo, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } + + motor->angle_obs = aout.angle; +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + ret = foc_angle_run_b16(&motor->ang_nfo, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } + + motor->angle_obs = aout.angle; +#endif + + /* Store electrical angle from sensor or observer */ + + if (aout.type == FOC_ANGLE_TYPE_ELE) + { + /* Store electrical angle */ + + motor->angle_el = aout.angle; + } + + else if (aout.type == FOC_ANGLE_TYPE_MECH) + { + /* Store mechanical angle */ + + motor->angle_m = aout.angle; + + /* Convert mechanical angle to electrical angle */ + + motor->angle_el = (b16muli(motor->angle_m, + motor->phy.p) % + MOTOR_ANGLE_E_MAX_B16); + } + + else + { + ASSERT(0); + } + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + /* Get open-loop phase angle */ + + if (motor->openloop_now == FOC_OPENLOOP_ENABLED) + { + motor->angle_now = motor->angle_ol; + motor->angle_el = motor->angle_ol; + } + else +#endif +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + /* Handle smooth open-loop to closed-loop transition */ + + if (motor->openloop_now == FOC_OPENLOOP_TRANSITION) + { +#ifdef ANGLE_MERGE_FACTOR + if (b16abs(motor->angle_err) > b16abs(motor->angle_step)) + { + motor->angle_now = motor->angle_obs + motor->angle_err; + + /* Update error */ + + motor->angle_err -= motor->angle_step; + } + else +#endif + { + motor->angle_now = motor->angle_obs; + motor->angle_err = 0; + } + } + + /* Get angle from observer if closed-loop now */ + + else + { + motor->angle_now = motor->angle_obs; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_SENSORED + /* Get phase angle from sensor */ + + motor->angle_now = motor->angle_el; +#endif + +#if defined(CONFIG_EXAMPLES_FOC_SENSORED) || defined(CONFIG_EXAMPLES_FOC_ANGOBS) + errout: +#endif + return ret; +} + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL +/**************************************************************************** + * Name: foc_motor_vel_get + ****************************************************************************/ + +static int foc_motor_vel_get(FAR struct foc_motor_b16_s *motor) +{ + struct foc_velocity_in_b16_s vin; + struct foc_velocity_out_b16_s vout; + int ret = OK; + + DEBUGASSERT(motor); + + /* Update velocity handler input data */ + + vin.state = &motor->foc_state; + vin.angle = motor->angle_now; + vin.vel = motor->vel.now; + vin.dir = motor->dir; + + /* Get velocity from observer */ + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + ret = foc_velocity_run_b16(&motor->vel_div, &vin, &vout); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_run failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + ret = foc_velocity_run_b16(&motor->vel_pll, &vin, &vout); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_run failed %d\n", ret); + goto errout; + } +#endif + + /* Get motor electrical velocity now */ + +#if defined(CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP) && \ + !defined(CONFIG_EXAMPLES_FOC_VELOBS) + /* No velocity feedback - assume that electical velocity is velocity set + * in a open-loop contorller. + */ + + UNUSED(vin); + UNUSED(vout); + + motor->vel_el = motor->vel.set; +#elif defined(CONFIG_EXAMPLES_FOC_VELOBS) && defined(CONFIG_EXAMPLES_FOC_SENSORLESS) + if (motor->openloop_now == FOC_OPENLOOP_DISABLED) + { + /* Get electrical velocity from observer if we are in closed-loop */ + + motor->vel_el = motor->vel_obs; + } + else + { + /* Otherwise use open-loop velocity */ + + motor->vel_el = motor->vel.set; + } +#elif defined(CONFIG_EXAMPLES_FOC_VELOBS) && defined(CONFIG_EXAMPLES_FOC_SENSORED) + /* Get electrical velocity from observer in sensored mode */ + + motor->vel_el = motor->vel_obs; +#else + /* Need electrical velocity source here - raise assertion */ + + ASSERT(0); +#endif + + LP_FILTER_B16(motor->vel.now, motor->vel_el, motor->vel_filter); + + /* Get mechanical velocity (rad/s) */ + + motor->vel_mech = b16mulb16(motor->vel_el, motor->phy.one_by_p); + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS +errout: +#endif + return ret; +} +#endif /* CONFIG_EXAMPLES_FOC_HAVE_VEL */ + /**************************************************************************** * Public Functions ****************************************************************************/ @@ -823,6 +1312,18 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, #ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL struct foc_hall_cfg_b16_s hl_cfg; #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + struct foc_angle_osmo_cfg_b16_s smo_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + struct foc_angle_onfo_cfg_b16_s nfo_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + struct foc_vel_div_b16_cfg_s odiv_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + struct foc_vel_pll_b16_cfg_s opll_cfg; +#endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN struct foc_routine_align_cfg_b16_s align_cfg; #endif @@ -845,7 +1346,16 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, /* Initialize motor data */ motor->per = b16divi(b16ONE, CONFIG_EXAMPLES_FOC_NOTIFIER_FREQ); - motor->iphase_adc = ftob16((CONFIG_EXAMPLES_FOC_IPHASE_ADC) / 100000.0f); +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + motor->ol_thr = ftob16(motor->envp->cfg->ol_thr / 1.0f); + motor->ol_hys = ftob16(motor->envp->cfg->ol_hys / 1.0f); +#endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ + motor->torq_sat = ftob16(CONFIG_EXAMPLES_FOC_TORQ_MAX / 1000.0f); +#endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + motor->vel_sat = ftob16(CONFIG_EXAMPLES_FOC_VEL_MAX / 1.0f); +#endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_RUN /* Initialize controller run mode */ @@ -872,6 +1382,10 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, ol_cfg.per = motor->per; foc_angle_cfg_b16(&motor->openloop, &ol_cfg); + + /* Store open-loop Q-param */ + + motor->openloop_q = ftob16(motor->envp->cfg->qparam / 1000.0f); #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO @@ -936,6 +1450,120 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, } #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + /* Initialzie SMO angle observer handler */ + + ret = foc_angle_init_b16(&motor->ang_smo, + &g_foc_angle_osmo_b16); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_b16 failed %d!\n", ret); + goto errout; + } + + /* Configure SMO angle handler */ + + smo_cfg.per = motor->per; + smo_cfg.k_slide = ftob16(CONFIG_EXAMPLES_FOC_ANGOBS_SMO_KSLIDE / 1000.0f); + smo_cfg.err_max = ftob16(CONFIG_EXAMPLES_FOC_ANGOBS_SMO_ERRMAX / 1000.0f); + memcpy(&smo_cfg.phy, &motor->phy, sizeof(struct motor_phy_params_b16_s)); + + ret = foc_angle_cfg_b16(&motor->ang_smo, &smo_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_cfg_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + /* Initialzie NFO angle observer handler */ + + ret = foc_angle_init_b16(&motor->ang_nfo, + &g_foc_angle_onfo_b16); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_b16 failed %d!\n", ret); + goto errout; + } + + /* Configure NFO angle handler */ + + nfo_cfg.per = motor->per; + nfo_cfg.gain = ftob16(motor->envp->cfg->ang_nfo_gain / 1.0f); + nfo_cfg.gain_slow = ftob16(motor->envp->cfg->ang_nfo_slow / 1.0f); + memcpy(&nfo_cfg.phy, &motor->phy, sizeof(struct motor_phy_params_b16_s)); + + ret = foc_angle_cfg_b16(&motor->ang_nfo, &nfo_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_cfg_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + /* Initialize velocity observer */ + + ret = foc_velocity_init_b16(&motor->vel_div, + &g_foc_velocity_odiv_b16); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_b16 failed %d!\n", ret); + goto errout; + } + + /* Configure velocity observer */ + + odiv_cfg.samples = (motor->envp->cfg->vel_div_samples); + odiv_cfg.filter = ftob16(motor->envp->cfg->vel_div_samples / 1000.0f); + odiv_cfg.per = motor->per; + + ret = foc_velocity_cfg_b16(&motor->vel_div, &odiv_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_cfg_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + /* Initialize velocity observer */ + + ret = foc_velocity_init_b16(&motor->vel_pll, + &g_foc_velocity_opll_b16); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_b16 failed %d!\n", ret); + goto errout; + } + + /* Configure velocity observer */ + + opll_cfg.kp = ftob16(motor->envp->cfg->vel_pll_kp / 1.0f); + opll_cfg.ki = ftob16(motor->envp->cfg->vel_pll_ki / 1.0f); + opll_cfg.per = motor->per; + + ret = foc_velocity_cfg_b16(&motor->vel_pll, &opll_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_cfg_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* Initialize velocity controller */ + + pi_controller_init_b16(&motor->vel_pi, + ftob16(motor->envp->cfg->vel_pi_kp / 1000000.0f), + ftob16(motor->envp->cfg->vel_pi_ki / 1000000.0f)); + + pi_saturation_set_b16(&motor->vel_pi, -motor->torq_sat, motor->torq_sat); + + pi_antiwindup_enable_b16(&motor->vel_pi, ftob16(0.99f), true); +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN /* Initialize motor alignment routine */ @@ -959,6 +1587,9 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, /* Connect align callbacks private data */ +# ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + align_cfg.cb.priv = &motor->openloop; +# endif # ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO align_cfg.cb.priv = &motor->qenco; # endif @@ -1008,6 +1639,12 @@ int foc_motor_init(FAR struct foc_motor_b16_s *motor, } #endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + /* Store velocity filter value */ + + motor->vel_filter = ftob16(motor->envp->cfg->vel_filter / 1000.0f); +#endif + /* Initialize controller state */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN @@ -1079,6 +1716,50 @@ int foc_motor_deinit(FAR struct foc_motor_b16_s *motor) } #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + /* Deinitialize SMO observer handler */ + + ret = foc_angle_deinit_b16(&motor->ang_smo); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_deinit_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + /* Deinitialize NFO observer handler */ + + ret = foc_angle_deinit_b16(&motor->ang_nfo); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_deinit_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + /* Deinitialize DIV observer handler */ + + ret = foc_velocity_deinit_b16(&motor->vel_div); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_deinit_b16 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + /* Deinitialize PLL observer handler */ + + ret = foc_velocity_deinit_b16(&motor->vel_pll); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_deinit_b16 failed %d!\n", ret); + goto errout; + } +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN /* Deinitialize motor alignment routine */ @@ -1135,105 +1816,29 @@ errout: int foc_motor_get(FAR struct foc_motor_b16_s *motor) { - struct foc_angle_in_b16_s ain; - struct foc_angle_out_b16_s aout; - int ret = OK; + int ret = OK; DEBUGASSERT(motor); - /* Update open-loop angle handler */ + /* Get motor angle */ + + ret = foc_motor_ang_get(motor); + if (ret < 0) + { + goto errout; + } #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL - ain.vel = motor->vel.set; -#endif - ain.angle = motor->angle_now; - ain.dir = motor->dir; + /* Get motor velocity */ -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - foc_angle_run_b16(&motor->openloop, &ain, &aout); - - /* Store open-loop angle */ - - motor->angle_ol = aout.angle; -#endif - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO - ret = foc_angle_run_b16(&motor->qenco, &ain, &aout); + ret = foc_motor_vel_get(motor); if (ret < 0) { - PRINTF("ERROR: foc_angle_run failed %d\n", ret); goto errout; } #endif -#ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL - ret = foc_angle_run_b16(&motor->hall, &ain, &aout); - if (ret < 0) - { - PRINTF("ERROR: foc_angle_run failed %d\n", ret); - goto errout; - } -#endif - -#ifdef CONFIG_EXAMPLES_FOC_SENSORED - /* Handle angle from sensor */ - - if (aout.type == FOC_ANGLE_TYPE_ELE) - { - /* Store electrical angle */ - - motor->angle_el = aout.angle; - } - - else if (aout.type == FOC_ANGLE_TYPE_MECH) - { - /* Store mechanical angle */ - - motor->angle_m = aout.angle; - - /* Convert mechanical angle to electrical angle */ - - motor->angle_el = (b16muli(motor->angle_m, - motor->poles) % MOTOR_ANGLE_E_MAX_B16); - } - - else - { - ASSERT(0); - } -#endif /* CONFIG_EXAMPLES_FOC_SENSORED */ - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - /* Get phase angle now */ - - if (motor->openloop_now == true) - { - motor->angle_now = motor->angle_ol; - } - else -#endif - { - /* Get phase angle from observer or sensor */ - - motor->angle_now = motor->angle_el; - } - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - if (motor->openloop_now == true) - { - /* No velocity feedback - assume that velocity now is velocity set */ - - motor->vel.now = motor->vel.set; - } - else -#endif - { - /* TODO: velocity observer or sensor */ - } - -#ifdef CONFIG_EXAMPLES_FOC_SENSORED errout: -#endif return ret; } diff --git a/examples/foc/foc_motor_b16.h b/examples/foc/foc_motor_b16.h index 5b660bf83..ee8c73a59 100644 --- a/examples/foc/foc_motor_b16.h +++ b/examples/foc/foc_motor_b16.h @@ -80,32 +80,67 @@ struct foc_motor_b16_s /* FOC data ***************************************************************/ struct foc_state_b16_s foc_state; /* FOC controller sate */ +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 + struct svm3_state_b16_s mod_state; /* Modulation state */ +#endif foc_handler_b16_t handler; /* FOC controller */ dq_frame_b16_t dq_ref; /* DQ reference */ dq_frame_b16_t vdq_comp; /* DQ voltage compensation */ int foc_mode; /* FOC mode */ + int time; /* Helper counter */ b16_t vbus; /* Power bus voltage */ b16_t per; /* Controller period in seconds */ +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + b16_t ol_thr; /* Angle observer threshold velocity */ + b16_t ol_hys; /* Angle observer hysteresis */ + b16_t angle_step; /* Open-loop transition step */ +#endif + + /* Data from FOC device ***************************************************/ + b16_t iphase_adc; /* Iphase ADC scaling factor */ b16_t pwm_duty_max; /* PWM duty max */ /* Velocity controller data ***********************************************/ struct foc_ramp_b16_s ramp; /* Velocity ramp data */ +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + pid_controller_b16_t vel_pi; /* Velocity controller */ +#endif - /* Motor state ************************************************************/ + /* Angle state ************************************************************/ b16_t angle_now; /* Phase angle now */ b16_t angle_m; /* Motor mechanical angle */ b16_t angle_el; /* Motor electrical angle */ +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + b16_t angle_ol; /* Phase angle open-loop */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + b16_t angle_obs; /* Angle observer output */ + b16_t angle_err; /* Open-loop to observer error */ +#endif + + /* Velocity state *********************************************************/ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + b16_t vel_el; /* Velocity - electrical */ + b16_t vel_mech; /* Velocity - mechanical */ + b16_t vel_filter; /* Velocity low-pass filter */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + b16_t vel_obs; /* Velocity observer output */ +#endif /* Motor setpoints ********************************************************/ #ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ struct foc_setpoint_b16_s torq; /* Torque setpoint */ + b16_t torq_sat; /* Torque saturation */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL struct foc_setpoint_b16_s vel; /* Velocity setpoint */ + b16_t vel_sat; /* Velocity saturation */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS struct foc_setpoint_b16_s pos; /* Position setpoint */ @@ -130,14 +165,14 @@ struct foc_motor_b16_s struct foc_model_b16_s model; /* Model handler */ struct foc_model_state_b16_s model_state; /* PMSM model state */ #endif - uint8_t poles; /* Motor poles */ + struct motor_phy_params_b16_s phy; /* Motor phy */ /* Motor velocity and angle handlers **************************************/ #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP foc_angle_b16_t openloop; /* Open-loop angle handler */ - bool openloop_now; /* Open-loop now */ - b16_t angle_ol; /* Phase angle open-loop */ + uint8_t openloop_now; /* Open-loop now */ + b16_t openloop_q; /* Open-loop Q parameter */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL foc_angle_b16_t hall; /* Hall angle handler */ @@ -147,6 +182,18 @@ struct foc_motor_b16_s foc_angle_b16_t qenco; /* Qenco angle handler */ char qedpath[32]; /* Qenco devpath */ #endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + foc_velocity_b16_t vel_div; /* DIV velocity observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + foc_velocity_b16_t vel_pll; /* PLL velocity observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + foc_angle_b16_t ang_smo; /* SMO angle observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + foc_angle_b16_t ang_nfo; /* NFO angle observer */ +#endif }; /**************************************************************************** diff --git a/examples/foc/foc_motor_f32.c b/examples/foc/foc_motor_f32.c index ead7e56b3..18d11648d 100644 --- a/examples/foc/foc_motor_f32.c +++ b/examples/foc/foc_motor_f32.c @@ -26,10 +26,14 @@ #include #include +#include #include "foc_cfg.h" #include "foc_debug.h" #include "foc_motor_f32.h" +#ifdef CONFIG_EXAMPLES_FOC_FEEDFORWARD +# include "industry/foc/float/foc_feedforward.h" +#endif /**************************************************************************** * Pre-processor Definitions @@ -118,7 +122,9 @@ static int foc_motor_align(FAR struct foc_motor_f32_s *motor, FAR bool *done) } PRINTF("Aling results:\n"); +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR PRINTF(" dir = %.2f\n", final.dir); +#endif PRINTF(" offset = %.2f\n", final.offset); *done = true; @@ -264,7 +270,7 @@ static int foc_runmode_init(FAR struct foc_motor_f32_s *motor) #ifdef CONFIG_EXAMPLES_FOC_SENSORLESS # ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - motor->openloop_now = true; + motor->openloop_now = FOC_OPENLOOP_ENABLED; # else # error # endif @@ -286,7 +292,7 @@ static int foc_motor_configure(FAR struct foc_motor_f32_s *motor) #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI struct foc_initdata_f32_s ctrl_cfg; #endif -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 struct foc_mod_cfg_f32_s mod_cfg; #endif #ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM @@ -302,8 +308,8 @@ static int foc_motor_configure(FAR struct foc_motor_f32_s *motor) ret = foc_ramp_init_f32(&motor->ramp, motor->per, RAMP_CFG_THR, - RAMP_CFG_ACC, - RAMP_CFG_ACC); + (motor->envp->cfg->acc / 1.0f), + (motor->envp->cfg->dec / 1.0f)); if (ret < 0) { PRINTF("ERROR: foc_ramp_init failed %d\n", ret); @@ -321,7 +327,7 @@ static int foc_motor_configure(FAR struct foc_motor_f32_s *motor) /* Get FOC modulation */ -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 foc_mod = &g_foc_mod_svm3_f32; #else # error FOC modulation not selected @@ -350,7 +356,7 @@ static int foc_motor_configure(FAR struct foc_motor_f32_s *motor) ctrl_cfg.iq_ki = (motor->envp->cfg->foc_pi_ki / 1000.0f); #endif -#ifdef CONFIG_INDUSTRY_FOC_MODULATION_SVM3 +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 /* Get SVM3 modulation configuration */ mod_cfg.pwm_duty_max = motor->pwm_duty_max; @@ -360,11 +366,13 @@ static int foc_motor_configure(FAR struct foc_motor_f32_s *motor) foc_handler_cfg_f32(&motor->handler, &ctrl_cfg, &mod_cfg); -#ifdef CONFIG_EXAMPLES_FOC_MOTOR_POLES - /* Configure motor poles */ + /* Configure motor phy */ - motor->poles = CONFIG_EXAMPLES_FOC_MOTOR_POLES; -#endif + motor_phy_params_init(&motor->phy, + CONFIG_EXAMPLES_FOC_MOTOR_POLES, + CONFIG_EXAMPLES_FOC_MOTOR_RES / 1000000.0f, + CONFIG_EXAMPLES_FOC_MOTOR_IND / 1000000.0f, + CONFIG_EXAMPLES_FOC_MOTOR_FLUXLINK / 1000000.0f); #ifdef CONFIG_EXAMPLES_FOC_STATE_USE_MODEL_PMSM /* Initialize PMSM model */ @@ -424,7 +432,7 @@ static int foc_motor_torq(FAR struct foc_motor_f32_s *motor, uint32_t torq) /* Update motor torque destination */ - motor->torq.des = (torq * SETPOINT_ADC_SCALE * + motor->torq.des = (motor->dir * torq * SETPOINT_INTF_SCALE * motor->envp->cfg->torqmax / 1000.0f); return OK; @@ -442,7 +450,7 @@ static int foc_motor_vel(FAR struct foc_motor_f32_s *motor, uint32_t vel) /* Update motor velocity destination */ - motor->vel.des = (vel * SETPOINT_ADC_SCALE * + motor->vel.des = (motor->dir * vel * SETPOINT_INTF_SCALE * motor->envp->cfg->velmax / 1000.0f); return OK; @@ -460,7 +468,7 @@ static int foc_motor_pos(FAR struct foc_motor_f32_s *motor, uint32_t pos) /* Update motor position destination */ - motor->pos.des = (pos * SETPOINT_ADC_SCALE * + motor->pos.des = (motor->dir * pos * SETPOINT_INTF_SCALE * motor->envp->cfg->posmax / 1000.0f); return OK; @@ -551,6 +559,40 @@ errout: return ret; } +/**************************************************************************** + * Name: foc_motor_vel_reset + ****************************************************************************/ + +static int foc_motor_vel_reset(FAR struct foc_motor_f32_s *motor) +{ + int ret = OK; + + /* Reset velocity observer */ + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + ret = foc_velocity_zero_f32(&motor->vel_div); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_zero failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + ret = foc_velocity_zero_f32(&motor->vel_pll); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_zero failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + errout: +#endif + return ret; +} + /**************************************************************************** * Name: foc_motor_state ****************************************************************************/ @@ -561,7 +603,7 @@ static int foc_motor_state(FAR struct foc_motor_f32_s *motor, int state) DEBUGASSERT(motor); - /* Update motor state */ + /* Update motor state - this function is called every controller cycle */ switch (state) { @@ -579,10 +621,25 @@ static int foc_motor_state(FAR struct foc_motor_f32_s *motor, int state) case FOC_EXAMPLE_STATE_STOP: { +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + /* For sensorless we can just set Q reference to lock the motor */ + motor->dir = DIR_NONE; /* DQ vector not zero - active brake */ + motor->dq_ref.q = CONFIG_EXAMPLES_FOC_STOP_CURRENT / 1000.0f; + motor->dq_ref.d = 0.0f; +#else + /* For sensored mode we set requested velocity to 0 */ + +# ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + motor->vel.des = 0.0f; +# else +# error STOP state for sensored mode requires velocity support +# endif +#endif + break; } @@ -607,6 +664,27 @@ static int foc_motor_state(FAR struct foc_motor_f32_s *motor, int state) } } +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + /* Re-align motor if we change mode from FREE/STOP to CW/CCW otherwise, + * the open-loop may fail because the rotor position at the start is + * random. + */ + + if ((motor->mq.app_state == FOC_EXAMPLE_STATE_FREE || + motor->mq.app_state == FOC_EXAMPLE_STATE_STOP) && + (state == FOC_EXAMPLE_STATE_CW || + state == FOC_EXAMPLE_STATE_CCW)) + { + motor->ctrl_state = FOC_CTRL_STATE_ALIGN; + motor->align_done = false; + motor->angle_now = 0.0f; + + /* Reset velocity observer */ + + foc_motor_vel_reset(motor); + } +#endif + /* Reset current setpoint */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ @@ -681,27 +759,125 @@ errout: static int foc_motor_run_init(FAR struct foc_motor_f32_s *motor) { - /* Empty for now */ + int ret = OK; - return OK; +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + ret = foc_motor_vel_reset(motor); +#endif + + return ret; } +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS +/**************************************************************************** + * Name: foc_motor_openloop_trans + ****************************************************************************/ + +static void foc_motor_openloop_trans(FAR struct foc_motor_f32_s *motor) +{ +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* Set the intergral part of the velocity PI controller equal to the + * open-loop Q current value. + * + * REVISIT: this may casue a velocity overshoot when going from open-loop + * to closed-loop. We can either use part of the open-loop Q + * current here or gradually reduce the Q current during + * transition. + */ + + motor->vel_pi.part[1] = motor->dir * motor->openloop_q; + motor->vel_pi.part[0] = 0.0f; +#endif +} + +/**************************************************************************** + * Name: foc_motor_openloop_angobs + ****************************************************************************/ + +static void foc_motor_openloop_angobs(FAR struct foc_motor_f32_s *motor) +{ + float vel_abs = 0.0f; + + vel_abs = fabsf(motor->vel_el); + + /* Disable open-loop if velocity above threshold */ + + if (motor->openloop_now == FOC_OPENLOOP_ENABLED) + { + if (vel_abs >= motor->ol_thr) + { + /* Store angle error between the forced open-loop angle and + * observer output. The error will be gradually eliminated over + * the next controller cycles. + */ + +#ifdef ANGLE_MERGE_FACTOR + motor->angle_err = motor->angle_ol - motor->angle_obs; + motor->angle_step = (motor->angle_err * ANGLE_MERGE_FACTOR); +#endif + + motor->openloop_now = FOC_OPENLOOP_TRANSITION; + } + } + + /* Handle transition end */ + + else if (motor->openloop_now == FOC_OPENLOOP_TRANSITION) + { + if (motor->angle_err == 0.0f) + { + /* Call open-open loop transition handler */ + + foc_motor_openloop_trans(motor); + + motor->openloop_now = FOC_OPENLOOP_DISABLED; + } + } + + /* Enable open-loop if velocity below threshold with hysteresis */ + + else if (motor->openloop_now == FOC_OPENLOOP_DISABLED) + { + /* For better stability we add hysteresis from transition + * from closed-loop to open-loop. + */ + + if (vel_abs < (motor->ol_thr - motor->ol_hys)) + { + motor->openloop_now = FOC_OPENLOOP_ENABLED; + } + } +} +#endif + /**************************************************************************** * Name: foc_motor_run ****************************************************************************/ static int foc_motor_run(FAR struct foc_motor_f32_s *motor) { +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + float vel_err = 0.0f; +#endif float q_ref = 0.0f; float d_ref = 0.0f; int ret = OK; DEBUGASSERT(motor); +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + if (motor->envp->cfg->ol_force == false) + { + /* Handle open-loop to observer transition */ + + foc_motor_openloop_angobs(motor); + } +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP /* Open-loop works only in velocity control mode */ - if (motor->openloop_now == true) + if (motor->openloop_now == FOC_OPENLOOP_ENABLED) { # ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL if (motor->envp->cfg->mmode != FOC_MMODE_VEL) @@ -719,35 +895,94 @@ static int foc_motor_run(FAR struct foc_motor_f32_s *motor) q_ref = motor->dq_ref.q; d_ref = motor->dq_ref.d; - /* Controller */ + /* Ignore controller if motor is free (sensorless and sensored mode) + * or stopped (only sensorless mode) + */ + + if (motor->mq.app_state == FOC_EXAMPLE_STATE_FREE +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + || motor->mq.app_state == FOC_EXAMPLE_STATE_STOP +#endif + ) + { + goto no_controller; + } + + /* Controller. + * + * The FOC motor controller is a cascade controller: + * + * 1. Position controller sets requested velocity, + * 2. Velocity controller sets requested torque, + * 3. Torque controller sets requested motor phase voltages. + * + * NOTE: the motor torque is directly proportional to the motor + * current which is proportional to the motor set voltage + */ switch (motor->envp->cfg->mmode) { -#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ - case FOC_MMODE_TORQ: - { - motor->torq.set = motor->dir * motor->torq.des; - - q_ref = motor->torq.set; - d_ref = 0.0f; - - break; - } -#endif - #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL case FOC_MMODE_VEL: { - /* Run velocity ramp controller */ + /* Saturate velocity */ - ret = foc_ramp_run_f32(&motor->ramp, motor->vel.des, - motor->vel.now, &motor->vel.set); - if (ret < 0) + f_saturate(&motor->vel.des, -motor->vel_sat, + motor->vel_sat); + + /* Velocity controller */ + + if (motor->time % VEL_CONTROL_PRESCALER == 0) { - PRINTF("ERROR: foc_ramp_run failed %d\n", ret); - goto errout; + /* Run velocity ramp controller */ + + ret = foc_ramp_run_f32(&motor->ramp, + motor->vel.des, + motor->vel.now, + &motor->vel.set); + if (ret < 0) + { + PRINTF("ERROR: foc_ramp_run failed %d\n", ret); + goto errout; + } + + /* Run velocity controller if no in open-loop */ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + if (motor->openloop_now == FOC_OPENLOOP_DISABLED) +#endif + { + /* Get velocity error */ + + vel_err = motor->vel.set - motor->vel.now; + +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* PI velocit controller */ + + motor->torq.des = pi_controller(&motor->vel_pi, + vel_err); +#else +# error Missing velocity controller +#endif + } } + /* Don't break here! pass to torque controller */ + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ + case FOC_MMODE_TORQ: + { + /* Saturate torque */ + + f_saturate(&motor->torq.des, -motor->torq_sat, + motor->torq_sat); + + /* Torque setpoint */ + + motor->torq.set = motor->torq.des; + break; } #endif @@ -759,20 +994,28 @@ static int foc_motor_run(FAR struct foc_motor_f32_s *motor) } } + /* Get dq ref */ + + q_ref = motor->torq.set; + d_ref = 0.0f; + #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP /* Force open-loop current */ - if (motor->openloop_now == true) + if (motor->openloop_now == FOC_OPENLOOP_ENABLED || + motor->openloop_now == FOC_OPENLOOP_TRANSITION) { - /* Get open-loop currents - * NOTE: Id always set to 0 + /* Get open-loop currents. Positive for CW direction, negative for + * CCW direction. Id always set to 0. */ - q_ref = (motor->envp->cfg->qparam / 1000.0f); + q_ref = motor->dir * motor->openloop_q; d_ref = 0.0f; } #endif +no_controller: + /* Set DQ reference frame */ motor->dq_ref.q = q_ref; @@ -780,14 +1023,263 @@ static int foc_motor_run(FAR struct foc_motor_f32_s *motor) /* DQ compensation */ +#ifdef CONFIG_EXAMPLES_FOC_FEEDFORWARD + foc_feedforward_pmsm_f32(&motor->phy, &motor->foc_state.idq, + motor->vel.now, &motor->vdq_comp); +#else motor->vdq_comp.q = 0.0f; motor->vdq_comp.d = 0.0f; +#endif errout: return ret; } #endif +/**************************************************************************** + * Name: foc_motor_ang_get + ****************************************************************************/ + +static int foc_motor_ang_get(FAR struct foc_motor_f32_s *motor) +{ + struct foc_angle_in_f32_s ain; + struct foc_angle_out_f32_s aout; + int ret = OK; + + DEBUGASSERT(motor); + + /* Update open-loop angle handler */ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + ain.vel = motor->vel.set; +#endif + ain.state = &motor->foc_state; + ain.angle = motor->angle_now; + ain.dir = motor->dir; + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + if (motor->openloop_now != FOC_OPENLOOP_DISABLED) + { + foc_angle_run_f32(&motor->openloop, &ain, &aout); + + /* Store open-loop angle */ + + motor->angle_ol = aout.angle; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO + ret = foc_angle_run_f32(&motor->qenco, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL + ret = foc_angle_run_f32(&motor->hall, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + ret = foc_angle_run_f32(&motor->ang_smo, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } + + motor->angle_obs = aout.angle; +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + ret = foc_angle_run_f32(&motor->ang_nfo, &ain, &aout); + if (ret < 0) + { + PRINTF("ERROR: foc_angle_run failed %d\n", ret); + goto errout; + } + + motor->angle_obs = aout.angle; +#endif + + /* Store electrical angle from sensor or observer */ + + if (aout.type == FOC_ANGLE_TYPE_ELE) + { + /* Store as electrical angle */ + + motor->angle_el = aout.angle; + } + + else if (aout.type == FOC_ANGLE_TYPE_MECH) + { + /* Store as mechanical angle */ + + motor->angle_m = aout.angle; + + /* Convert mechanical angle to electrical angle */ + + motor->angle_el = fmodf(motor->angle_m * motor->phy.p, + MOTOR_ANGLE_E_MAX); + } + + else + { + ASSERT(0); + } + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + /* Get open-loop phase angle */ + + if (motor->openloop_now == FOC_OPENLOOP_ENABLED) + { + motor->angle_now = motor->angle_ol; + motor->angle_el = motor->angle_ol; + } + else +#endif +#ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + /* Handle smooth open-loop to closed-loop transition */ + + if (motor->openloop_now == FOC_OPENLOOP_TRANSITION) + { +#ifdef ANGLE_MERGE_FACTOR + if (fabsf(motor->angle_err) > fabsf(motor->angle_step)) + { + motor->angle_now = motor->angle_obs + motor->angle_err; + + /* Update error */ + + motor->angle_err -= motor->angle_step; + } + else +#endif + { + motor->angle_now = motor->angle_obs; + motor->angle_err = 0.0f; + } + } + + /* Get angle from observer if closed-loop now */ + + else + { + motor->angle_now = motor->angle_obs; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_SENSORED + /* Get phase angle from sensor */ + + motor->angle_now = motor->angle_el; +#endif + +#if defined(CONFIG_EXAMPLES_FOC_SENSORED) || defined(CONFIG_EXAMPLES_FOC_ANGOBS) + errout: +#endif + return ret; +} + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL +/**************************************************************************** + * Name: foc_motor_vel_get + ****************************************************************************/ + +static int foc_motor_vel_get(FAR struct foc_motor_f32_s *motor) +{ + struct foc_velocity_in_f32_s vin; + struct foc_velocity_out_f32_s vout; + int ret = OK; + + DEBUGASSERT(motor); + + /* Update velocity handler input data */ + + vin.state = &motor->foc_state; + vin.angle = motor->angle_now; + vin.vel = motor->vel.now; + vin.dir = motor->dir; + + /* Get velocity */ + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + ret = foc_velocity_run_f32(&motor->vel_div, &vin, &vout); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_run failed %d\n", ret); + goto errout; + } + + motor->vel_obs = vout.velocity; +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + ret = foc_velocity_run_f32(&motor->vel_pll, &vin, &vout); + if (ret < 0) + { + PRINTF("ERROR: foc_velocity_run failed %d\n", ret); + goto errout; + } + + motor->vel_obs = vout.velocity; +#endif + + /* Get motor electrical velocity now */ + +#if defined(CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP) && \ + !defined(CONFIG_EXAMPLES_FOC_VELOBS) + /* No velocity feedback - assume that electical velocity is + * velocity set + */ + + UNUSED(vin); + UNUSED(vout); + + motor->vel_el = motor->vel.set; +#elif defined(CONFIG_EXAMPLES_FOC_VELOBS) && defined(CONFIG_EXAMPLES_FOC_SENSORLESS) + if (motor->openloop_now == FOC_OPENLOOP_DISABLED) + { + /* Get electrical velocity from observer if we are in closed-loop */ + + motor->vel_el = motor->vel_obs; + } + else + { + /* Otherwise use open-loop velocity */ + + motor->vel_el = motor->vel.set; + } +#elif defined(CONFIG_EXAMPLES_FOC_VELOBS) && defined(CONFIG_EXAMPLES_FOC_SENSORED) + /* Get electrical velocity from observer in sensored mode */ + + motor->vel_el = motor->vel_obs; +#else + /* Need electrical velocity source here - raise assertion */ + + ASSERT(0); +#endif + + /* Store filtered velocity */ + + LP_FILTER(motor->vel.now, motor->vel_el, motor->vel_filter); + + /* Get mechanical velocity (rad/s) */ + + motor->vel_mech = motor->vel_el * motor->phy.one_by_p; + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS +errout: +#endif + return ret; +} +#endif /* CONFIG_EXAMPLES_FOC_HAVE_VEL */ + /**************************************************************************** * Public Functions ****************************************************************************/ @@ -808,6 +1300,18 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, #ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL struct foc_hall_cfg_f32_s hl_cfg; #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + struct foc_angle_osmo_cfg_f32_s smo_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + struct foc_angle_onfo_cfg_f32_s nfo_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + struct foc_vel_div_f32_cfg_s odiv_cfg; +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + struct foc_vel_pll_f32_cfg_s opll_cfg; +#endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN struct foc_routine_align_cfg_f32_s align_cfg; #endif @@ -830,7 +1334,16 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, /* Initialize motor data */ motor->per = (float)(1.0f / CONFIG_EXAMPLES_FOC_NOTIFIER_FREQ); - motor->iphase_adc = ((CONFIG_EXAMPLES_FOC_IPHASE_ADC) / 100000.0f); +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + motor->ol_thr = (motor->envp->cfg->ol_thr / 1.0f); + motor->ol_hys = (motor->envp->cfg->ol_hys / 1.0f); +#endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ + motor->torq_sat = (CONFIG_EXAMPLES_FOC_TORQ_MAX / 1000.0f); +#endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + motor->vel_sat = (CONFIG_EXAMPLES_FOC_VEL_MAX / 1.0f); +#endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_RUN /* Initialize controller run mode */ @@ -857,6 +1370,10 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, ol_cfg.per = motor->per; foc_angle_cfg_f32(&motor->openloop, &ol_cfg); + + /* Store open-loop Q-param */ + + motor->openloop_q = motor->envp->cfg->qparam / 1000.0f; #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO @@ -921,6 +1438,120 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, } #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + /* Initialzie SMO angle observer handler */ + + ret = foc_angle_init_f32(&motor->ang_smo, + &g_foc_angle_osmo_f32); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_f32 failed %d!\n", ret); + goto errout; + } + + /* Configure SMO angle handler */ + + smo_cfg.per = motor->per; + smo_cfg.k_slide = (CONFIG_EXAMPLES_FOC_ANGOBS_SMO_KSLIDE / 1000.0f); + smo_cfg.err_max = (CONFIG_EXAMPLES_FOC_ANGOBS_SMO_ERRMAX / 1000.0f); + memcpy(&smo_cfg.phy, &motor->phy, sizeof(struct motor_phy_params_f32_s)); + + ret = foc_angle_cfg_f32(&motor->ang_smo, &smo_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_cfg_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + /* Initialzie NFO angle observer handler */ + + ret = foc_angle_init_f32(&motor->ang_nfo, + &g_foc_angle_onfo_f32); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_f32 failed %d!\n", ret); + goto errout; + } + + /* Configure NFO angle handler */ + + nfo_cfg.per = motor->per; + nfo_cfg.gain = (motor->envp->cfg->ang_nfo_gain / 1.0f); + nfo_cfg.gain_slow = (motor->envp->cfg->ang_nfo_slow / 1.0f); + memcpy(&nfo_cfg.phy, &motor->phy, sizeof(struct motor_phy_params_f32_s)); + + ret = foc_angle_cfg_f32(&motor->ang_nfo, &nfo_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_cfg_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + /* Initialize velocity observer */ + + ret = foc_velocity_init_f32(&motor->vel_div, + &g_foc_velocity_odiv_f32); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_f32 failed %d!\n", ret); + goto errout; + } + + /* Configure velocity observer */ + + odiv_cfg.samples = (motor->envp->cfg->vel_div_samples); + odiv_cfg.filter = (motor->envp->cfg->vel_div_samples / 1000.0f); + odiv_cfg.per = motor->per; + + ret = foc_velocity_cfg_f32(&motor->vel_div, &odiv_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_cfg_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + /* Initialize velocity observer */ + + ret = foc_velocity_init_f32(&motor->vel_pll, + &g_foc_velocity_opll_f32); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_init_f32 failed %d!\n", ret); + goto errout; + } + + /* Configure velocity observer */ + + opll_cfg.kp = (motor->envp->cfg->vel_pll_kp / 1.0f); + opll_cfg.ki = (motor->envp->cfg->vel_pll_ki / 1.0f); + opll_cfg.per = motor->per; + + ret = foc_velocity_cfg_f32(&motor->vel_pll, &opll_cfg); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_cfg_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + /* Initialize velocity controller */ + + pi_controller_init(&motor->vel_pi, + (motor->envp->cfg->vel_pi_kp / 1000000.0f), + (motor->envp->cfg->vel_pi_ki / 1000000.0f)); + + pi_saturation_set(&motor->vel_pi, -motor->torq_sat, motor->torq_sat); + + pi_antiwindup_enable(&motor->vel_pi, 0.99f, true); +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN /* Initialize motor alignment routine */ @@ -944,6 +1575,9 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, /* Connect align callbacks private data */ +# ifdef CONFIG_EXAMPLES_FOC_SENSORLESS + align_cfg.cb.priv = &motor->openloop; +# endif # ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO align_cfg.cb.priv = &motor->qenco; # endif @@ -990,6 +1624,12 @@ int foc_motor_init(FAR struct foc_motor_f32_s *motor, } #endif +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + /* Store velocity filter value */ + + motor->vel_filter = motor->envp->cfg->vel_filter / 1000.0f; +#endif + /* Initialize controller state */ #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN @@ -1066,6 +1706,50 @@ int foc_motor_deinit(FAR struct foc_motor_f32_s *motor) } #endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + /* Deinitialize SMO observer handler */ + + ret = foc_angle_deinit_f32(&motor->ang_smo); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_deinit_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + /* Deinitialize NFO observer handler */ + + ret = foc_angle_deinit_f32(&motor->ang_nfo); + if (ret < 0) + { + PRINTFV("ERROR: foc_angle_deinit_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + /* Deinitialize DIV observer handler */ + + ret = foc_velocity_deinit_f32(&motor->vel_div); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_deinit_f32 failed %d!\n", ret); + goto errout; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + /* Deinitialize PLL observer handler */ + + ret = foc_velocity_deinit_f32(&motor->vel_pll); + if (ret < 0) + { + PRINTFV("ERROR: foc_velocity_deinit_f32 failed %d!\n", ret); + goto errout; + } +#endif + #ifdef CONFIG_EXAMPLES_FOC_HAVE_ALIGN /* Deinitialize motor alignment routine */ @@ -1122,105 +1806,29 @@ errout: int foc_motor_get(FAR struct foc_motor_f32_s *motor) { - struct foc_angle_in_f32_s ain; - struct foc_angle_out_f32_s aout; - int ret = OK; + int ret = OK; DEBUGASSERT(motor); - /* Update open-loop angle handler */ + /* Get motor angle */ + + ret = foc_motor_ang_get(motor); + if (ret < 0) + { + goto errout; + } #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL - ain.vel = motor->vel.set; -#endif - ain.angle = motor->angle_now; - ain.dir = motor->dir; + /* Get motor velocity */ -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - foc_angle_run_f32(&motor->openloop, &ain, &aout); - - /* Store open-loop angle */ - - motor->angle_ol = aout.angle; -#endif - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_QENCO - ret = foc_angle_run_f32(&motor->qenco, &ain, &aout); + ret = foc_motor_vel_get(motor); if (ret < 0) { - PRINTF("ERROR: foc_angle_run failed %d\n", ret); goto errout; } #endif -#ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL - ret = foc_angle_run_f32(&motor->hall, &ain, &aout); - if (ret < 0) - { - PRINTF("ERROR: foc_angle_run failed %d\n", ret); - goto errout; - } -#endif - -#ifdef CONFIG_EXAMPLES_FOC_SENSORED - /* Handle angle from sensor */ - - if (aout.type == FOC_ANGLE_TYPE_ELE) - { - /* Store electrical angle */ - - motor->angle_el = aout.angle; - } - - else if (aout.type == FOC_ANGLE_TYPE_MECH) - { - /* Store mechanical angle */ - - motor->angle_m = aout.angle; - - /* Convert mechanical angle to electrical angle */ - - motor->angle_el = fmodf(motor->angle_m * motor->poles, - MOTOR_ANGLE_E_MAX); - } - - else - { - ASSERT(0); - } -#endif /* CONFIG_EXAMPLES_FOC_SENSORED */ - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - /* Get phase angle now */ - - if (motor->openloop_now == true) - { - motor->angle_now = motor->angle_ol; - } - else -#endif - { - /* Get phase angle from observer or sensor */ - - motor->angle_now = motor->angle_el; - } - -#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - if (motor->openloop_now == true) - { - /* No velocity feedback - assume that velocity now is velocity set */ - - motor->vel.now = motor->vel.set; - } - else -#endif - { - /* TODO: velocity observer or sensor */ - } - -#ifdef CONFIG_EXAMPLES_FOC_SENSORED errout: -#endif return ret; } diff --git a/examples/foc/foc_motor_f32.h b/examples/foc/foc_motor_f32.h index 0eb86a789..3a031282e 100644 --- a/examples/foc/foc_motor_f32.h +++ b/examples/foc/foc_motor_f32.h @@ -80,32 +80,67 @@ struct foc_motor_f32_s /* FOC data ***************************************************************/ struct foc_state_f32_s foc_state; /* FOC controller sate */ +#ifdef CONFIG_EXAMPLES_FOC_MODULATION_SVM3 + struct svm3_state_f32_s mod_state; /* Modulation state */ +#endif foc_handler_f32_t handler; /* FOC controller */ dq_frame_f32_t dq_ref; /* DQ reference */ dq_frame_f32_t vdq_comp; /* DQ voltage compensation */ int foc_mode; /* FOC mode */ + int time; /* Helper counter */ float vbus; /* Power bus voltage */ float per; /* Controller period in seconds */ +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + float ol_thr; /* Angle observer threshold velocity */ + float ol_hys; /* Angle observer hysteresis */ +#endif + + /* Data from FOC device ***************************************************/ + float iphase_adc; /* Iphase ADC scaling factor */ float pwm_duty_max; /* PWM duty max */ /* Velocity controller data ***********************************************/ struct foc_ramp_f32_s ramp; /* Velocity ramp data */ +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + pid_controller_f32_t vel_pi; /* Velocity controller */ +#endif - /* Motor state ************************************************************/ + /* Angle state ************************************************************/ float angle_now; /* Phase angle now */ float angle_m; /* Motor mechanical angle */ float angle_el; /* Motor electrical angle */ +#ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP + float angle_ol; /* Phase angle open-loop */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS + float angle_obs; /* Angle observer output */ + float angle_err; /* Open-loop to observer error */ + float angle_step; /* Open-loop transition step */ +#endif + + /* Velocity state *********************************************************/ + +#ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL + float vel_el; /* Velocity - electrical */ + float vel_mech; /* Velocity - mechanical */ + float vel_filter; /* Velocity low-pass filter */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS + float vel_obs; /* Velocity observer output */ +#endif /* Motor setpoints ********************************************************/ #ifdef CONFIG_EXAMPLES_FOC_HAVE_TORQ struct foc_setpoint_f32_s torq; /* Torque setpoint */ + float torq_sat; /* Torque saturation */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL struct foc_setpoint_f32_s vel; /* Velocity setpoint */ + float vel_sat; /* Velocity saturation */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS struct foc_setpoint_f32_s pos; /* Position setpoint */ @@ -130,14 +165,14 @@ struct foc_motor_f32_s struct foc_model_f32_s model; /* Model handler */ struct foc_model_state_f32_s model_state; /* PMSM model state */ #endif - uint8_t poles; /* Motor poles */ + struct motor_phy_params_f32_s phy; /* Motor phy */ /* Motor velocity and angle handlers **************************************/ #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP foc_angle_f32_t openloop; /* Open-loop angle handler */ - bool openloop_now; /* Open-loop now */ - float angle_ol; /* Phase angle open-loop */ + uint8_t openloop_now; /* Open-loop now */ + float openloop_q; /* Open-loop Q parameter */ #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_HALL foc_angle_f32_t hall; /* Hall angle handler */ @@ -147,6 +182,18 @@ struct foc_motor_f32_s foc_angle_f32_t qenco; /* Qenco angle handler */ char qedpath[32]; /* Qenco devpath */ #endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + foc_velocity_f32_t vel_div; /* DIV velocity observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + foc_velocity_f32_t vel_pll; /* PLL velocity observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_SMO + foc_angle_f32_t ang_smo; /* SMO angle observer */ +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + foc_angle_f32_t ang_nfo; /* NFO angle observer */ +#endif }; /**************************************************************************** diff --git a/examples/foc/foc_nxscope.c b/examples/foc/foc_nxscope.c index fef6ae239..f40297d51 100644 --- a/examples/foc/foc_nxscope.c +++ b/examples/foc/foc_nxscope.c @@ -42,7 +42,7 @@ # error CONFIG_LOGGING_NXSCOPE_DISABLE_PUTLOCK must be set to proper operation. #endif -#ifdef CONFIG_LOGGING_NXSCOPE_INTF_SERIAL +#if defined(CONFIG_LOGGING_NXSCOPE_INTF_SERIAL) && !defined(CONFIG_SERIAL_RTT) # ifndef CONFIG_SERIAL_TERMIOS # error CONFIG_SERIAL_TERMIOS must be set to proper operation. # endif @@ -158,7 +158,7 @@ int foc_nxscope_init(FAR struct foc_nxscope_s *nxs) switch (foc_thread_type(j)) { -#ifdef CONFIG_INDUSTRY_FOC_FLOAT +#if CONFIG_EXAMPLES_FOC_FLOAT_INST > 0 case FOC_NUMBER_TYPE_FLOAT: { u.s.dtype = NXSCOPE_TYPE_FLOAT; @@ -166,7 +166,7 @@ int foc_nxscope_init(FAR struct foc_nxscope_s *nxs) } #endif -#ifdef CONFIG_INDUSTRY_FOC_FIXED16 +#if CONFIG_EXAMPLES_FOC_FIXED16_INST > 0 case FOC_NUMBER_TYPE_FIXED16: { u.s.dtype = NXSCOPE_TYPE_B16; @@ -236,6 +236,15 @@ int foc_nxscope_init(FAR struct foc_nxscope_s *nxs) #if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VDQCOMP) nxscope_chan_init(&nxs->nxs, i++, "vdqcomp", u.u8, 2, 0); #endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_SVM3) + nxscope_chan_init(&nxs->nxs, i++, "svm3", u.u8, 4, 0); +#endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_VOBS) + nxscope_chan_init(&nxs->nxs, i++, "vobs", u.u8, 1, 0); +#endif +#if (CONFIG_EXAMPLES_FOC_NXSCOPE_CFG & FOC_NXSCOPE_AOBS) + nxscope_chan_init(&nxs->nxs, i++, "aobs", u.u8, 1, 0); +#endif if (i > CONFIG_EXAMPLES_FOC_NXSCOPE_CHANNELS) { diff --git a/examples/foc/foc_nxscope.h b/examples/foc/foc_nxscope.h index bfbdda833..911e0afdf 100644 --- a/examples/foc/foc_nxscope.h +++ b/examples/foc/foc_nxscope.h @@ -51,6 +51,9 @@ #define FOC_NXSCOPE_SPPOS (1 << 13) /* Position setpoint */ #define FOC_NXSCOPE_DQREF (1 << 14) /* DQ reference */ #define FOC_NXSCOPE_VDQCOMP (1 << 15) /* VDQ compensation */ +#define FOC_NXSCOPE_SVM3 (1 << 16) /* Space-vector modulation sector */ +#define FOC_NXSCOPE_VOBS (1 << 17) /* Output from velocity observer */ +#define FOC_NXSCOPE_AOBS (1 << 18) /* Output from angle observer */ /* Max 32-bit */ /**************************************************************************** diff --git a/examples/foc/foc_parseargs.c b/examples/foc/foc_parseargs.c index fa4de580e..cddd73b85 100644 --- a/examples/foc/foc_parseargs.c +++ b/examples/foc/foc_parseargs.c @@ -27,6 +27,7 @@ #include #include #include +#include #include "foc_debug.h" #include "foc_thr.h" @@ -45,6 +46,21 @@ #define OPT_IIV (SCHAR_MAX + 6) #define OPT_IIS (SCHAR_MAX + 7) +#define OPT_VOPLLKP (SCHAR_MAX + 8) +#define OPT_VOPLLKI (SCHAR_MAX + 9) +#define OPT_VODIVS (SCHAR_MAX + 10) +#define OPT_VODIVF (SCHAR_MAX + 11) + +#define OPT_VCPIKP (SCHAR_MAX + 12) +#define OPT_VCPIKI (SCHAR_MAX + 13) + +#define OPT_ANFOS (SCHAR_MAX + 14) +#define OPT_ANFOG (SCHAR_MAX + 15) + +#define OPT_OLFORCE (SCHAR_MAX + 16) +#define OPT_OLTHR (SCHAR_MAX + 17) +#define OPT_OLHYS (SCHAR_MAX + 18) + /**************************************************************************** * Private Data ****************************************************************************/ @@ -60,6 +76,8 @@ static struct option g_long_options[] = #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL { "vel", required_argument, 0, 'v' }, + { "acc", required_argument, 0, 'a' }, + { "dec", required_argument, 0, 'd' }, #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS { "pos", required_argument, 0, 'x' }, @@ -68,6 +86,11 @@ static struct option g_long_options[] = { "en", required_argument, 0, 'j' }, #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP { "oqset", required_argument, 0, 'o' }, + { "olforce", no_argument, 0, OPT_OLFORCE }, +# ifdef CONFIG_EXAMPLES_FOC_ANGOBS + { "olthr", required_argument, 0, OPT_OLTHR }, + { "olhys", required_argument, 0, OPT_OLHYS }, +# endif #endif #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI { "fkp", required_argument, 0, OPT_FKP }, @@ -79,6 +102,22 @@ static struct option g_long_options[] = { "irs", required_argument, 0, OPT_IRS }, { "iiv", required_argument, 0, OPT_IIV }, { "iis", required_argument, 0, OPT_IIS }, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + { "vopllkp", required_argument, 0, OPT_VOPLLKP }, + { "vopllki", required_argument, 0, OPT_VOPLLKI }, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + { "vodivs", required_argument, 0, OPT_VODIVS }, + { "vodivf", required_argument, 0, OPT_VODIVF }, +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + { "vcpikp", required_argument, 0, OPT_VCPIKP }, + { "vcpiki", required_argument, 0, OPT_VCPIKI }, +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + { "anfos", required_argument, 0, OPT_ANFOS }, + { "anfog", required_argument, 0, OPT_ANFOG }, #endif { 0, 0, 0, 0 } }; @@ -91,7 +130,7 @@ static struct option g_long_options[] = * Name: foc_help ****************************************************************************/ -static void foc_help(void) +static void foc_help(FAR struct args_s *args) { PRINTF("Usage: foc [OPTIONS]\n"); PRINTF(" [-t] run time (default: %d)\n", @@ -120,38 +159,73 @@ static void foc_help(void) #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_VEL PRINTF(" [-v] velocity [x1000]\n"); + PRINTF(" [-a] acceleration [x1000] (default: %" PRId32 ")\n", + args->cfg.acc); + PRINTF(" [-d] deceleration [x1000] (default: %" PRId32 ")\n", + args->cfg.dec); #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS PRINTF(" [-x] position [x1000]\n"); #endif PRINTF(" [-s] motor state init (default: %d)\n", - CONFIG_EXAMPLES_FOC_STATE_INIT); + args->state); PRINTF(" 1 - motor free\n"); PRINTF(" 2 - motor stop\n"); PRINTF(" 3 - motor CW\n"); PRINTF(" 4 - motor CCW\n"); PRINTF(" [-j] enable specific instances\n"); #ifdef CONFIG_EXAMPLES_FOC_HAVE_OPENLOOP - PRINTF(" [-o] openloop Vq/Iq setting [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_OPENLOOP_Q); + PRINTF(" [-o] openloop Vq/Iq setting [x1000] (default: %" PRId32 ")\n", + args->cfg.qparam); + PRINTF(" [--olforce] force openloop\n"); +# ifdef CONFIG_EXAMPLES_FOC_ANGOBS + PRINTF(" [--olthr] observer vel threshold [x1] (default: %d)\n", + CONFIG_EXAMPLES_FOC_ANGOBS_THR); + PRINTF(" [--olhys] observer vel hysteresys [x1] (default: %d)\n", + CONFIG_EXAMPLES_FOC_ANGOBS_THR); +# endif #endif #ifdef CONFIG_EXAMPLES_FOC_CONTROL_PI - PRINTF(" [--fki] PI Kp coefficient [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDQ_KP); - PRINTF(" [--fkp] PI Ki coefficient [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDQ_KI); + PRINTF(" [--fkp] PI Kp coefficient [x1000] (default: %" PRId32 ")\n", + args->cfg.foc_pi_kp); + PRINTF(" [--fki] PI Ki coefficient [x1000] (default: %" PRId32 ")\n", + args->cfg.foc_pi_ki); #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_IDENT - PRINTF(" [--irki] res Ki coefficient [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDENT_RES_KI); - PRINTF(" [--irc] res current [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDENT_RES_CURRENT); - PRINTF(" [--irs] res sec (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDENT_RES_SEC); - PRINTF(" [--iiv] ind voltage [x1000] (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDENT_IND_VOLTAGE); - PRINTF(" [--iis] ind sec (default: %d)\n", - CONFIG_EXAMPLES_FOC_IDENT_IND_SEC); + PRINTF(" [--irki] res Ki coefficient [x1000] (default: %" PRId32 ")\n", + args->cfg.ident_res_ki); + PRINTF(" [--irc] res current [x1000] (default: %" PRId32 ")\n", + args->cfg.ident_res_curr); + PRINTF(" [--irs] res sec (default: %" PRId32 ")\n", + args->cfg.ident_res_sec); + PRINTF(" [--iiv] ind voltage [x1000] (default: %" PRId32 ")\n", + args->cfg.ident_ind_volt); + PRINTF(" [--iis] ind sec (default: %" PRId32 ")\n", + args->cfg.ident_ind_sec); +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + PRINTF(" [--vopllkp] velobs PLL Kp [x1] (default: %" PRId32 ")\n", + args->cfg.vel_pll_kp); + PRINTF(" [--vopllki] velobs PLL Ki [x1] (default: %" PRId32 ")\n", + args->cfg.vel_pll_ki); +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + PRINTF(" [--vodivs] velobs DIV samples (default: %" PRId32 ")\n", + args->cfg.vel_div_samples); + PRINTF(" [--vodivf] velobs DIV filter (default: %" PRId32 ")\n", + args->cfg.vel_div_filter); +#endif +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + PRINTF(" [--vcpikp] velctrl PI Kp [x1000000] (default: %" PRId32 ")\n", + args->cfg.vel_pi_kp); + PRINTF(" [--vcpiki] velctrl PI Ki [x1000000] (default: %" PRId32 ")\n", + args->cfg.vel_pi_ki); +#endif +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + PRINTF(" [--anfos] angobs NFO Slow [x1] (default: %" PRId32 ")\n", + args->cfg.ang_nfo_slow); + PRINTF(" [--anfog] angobs NFO Gain [x1] (default: %" PRId32 ")\n", + args->cfg.ang_nfo_gain); #endif } @@ -170,7 +244,7 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) while (1) { - c = getopt_long(argc, argv, "ht:f:m:o:r:v:x:s:j:", g_long_options, + c = getopt_long(argc, argv, "ht:f:m:o:r:v:a:d:x:s:j:", g_long_options, &option_index); if (c == -1) @@ -226,6 +300,62 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) } #endif +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_PLL + case OPT_VOPLLKP: + { + args->cfg.vel_pll_kp = atoi(optarg); + break; + } + + case OPT_VOPLLKI: + { + args->cfg.vel_pll_ki = atoi(optarg); + break; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELOBS_DIV + case OPT_VODIVS: + { + args->cfg.vel_div_samples = atoi(optarg); + break; + } + + case OPT_VODIVF: + { + args->cfg.vel_div_filter = atoi(optarg); + break; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_VELCTRL_PI + case OPT_VCPIKP: + { + args->cfg.vel_pi_kp = atoi(optarg); + break; + } + + case OPT_VCPIKI: + { + args->cfg.vel_pi_ki = atoi(optarg); + break; + } +#endif + +#ifdef CONFIG_EXAMPLES_FOC_ANGOBS_NFO + case OPT_ANFOS: + { + args->cfg.ang_nfo_slow = atoi(optarg); + break; + } + + case OPT_ANFOG: + { + args->cfg.ang_nfo_gain = atoi(optarg); + break; + } +#endif + case 't': { args->time = atoi(optarg); @@ -234,7 +364,7 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) case 'h': { - foc_help(); + foc_help(args); exit(0); } @@ -264,6 +394,18 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) args->cfg.velmax = atoi(optarg); break; } + + case 'a': + { + args->cfg.acc = atoi(optarg); + break; + } + + case 'd': + { + args->cfg.dec = atoi(optarg); + break; + } #endif #ifdef CONFIG_EXAMPLES_FOC_HAVE_POS @@ -292,6 +434,26 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) args->cfg.qparam = atoi(optarg); break; } + + case OPT_OLFORCE: + { + args->cfg.ol_force = true; + break; + } + +# ifdef CONFIG_EXAMPLES_FOC_ANGOBS + case OPT_OLTHR: + { + args->cfg.ol_thr = atoi(optarg); + break; + } + + case OPT_OLHYS: + { + args->cfg.ol_hys = atoi(optarg); + break; + } +# endif #endif case '?': @@ -307,7 +469,7 @@ void parse_args(FAR struct args_s *args, int argc, FAR char **argv) PRINTF("ERROR: invalid option %s\n", argv[optind - 1]); } - foc_help(); + foc_help(args); exit(1); } } diff --git a/testing/gpu/gpu_log.c b/examples/foc/foc_perf.c similarity index 74% rename from testing/gpu/gpu_log.c rename to examples/foc/foc_perf.c index fc3ee24b2..74e378f2c 100644 --- a/testing/gpu/gpu_log.c +++ b/examples/foc/foc_perf.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/gpu_log.c + * apps/examples/foc/foc_perf.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -22,43 +22,53 @@ * Included Files ****************************************************************************/ -#include -#include -#include -#include "gpu_log.h" +#include -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ +#include +#include +#include -/**************************************************************************** - * Private Data - ****************************************************************************/ +#include + +#include "foc_perf.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** - * Name: gpu_log_printf + * Name: foc_perf_init ****************************************************************************/ -void gpu_log_printf(enum gpu_log_level_type_e level, - FAR const char *func, - FAR const char *fmt, - ...) +int foc_perf_init(struct foc_perf_s *p) { - struct va_format vaf; - va_list ap; + memset(p, 0, sizeof(struct foc_perf_s)); - static const int priority[_GPU_LOG_LEVEL_LAST] = - { - LOG_INFO, LOG_WARNING, LOG_ERR - }; - - va_start(ap, fmt); - vaf.fmt = fmt; - vaf.va = ≈ - syslog(priority[level], "[GPU] %s: %pV\n", func, &vaf); - va_end(ap); + return OK; +} + +/**************************************************************************** + * Name: foc_perf_start + ****************************************************************************/ + +void foc_perf_start(struct foc_perf_s *p) +{ + p->now = perf_gettime(); +} + +/**************************************************************************** + * Name: foc_perf_end + ****************************************************************************/ + +void foc_perf_end(struct foc_perf_s *p) +{ + p->now = perf_gettime() - p->now; + + p->max_changed = false; + + if (p->now > p->max) + { + p->max = p->now; + p->max_changed = true; + } } diff --git a/testing/gpu/vg_lite/vg_lite_test.h b/examples/foc/foc_perf.h similarity index 76% rename from testing/gpu/vg_lite/vg_lite_test.h rename to examples/foc/foc_perf.h index 32e1558bb..9303c2b9f 100644 --- a/testing/gpu/vg_lite/vg_lite_test.h +++ b/examples/foc/foc_perf.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/vg_lite/vg_lite_test.h + * apps/examples/foc/foc_perf.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -18,42 +18,38 @@ * ****************************************************************************/ -#ifndef __APPS_TESTING_GPU_VG_LITE_VG_LITE_TEST_H__ -#define __APPS_TESTING_GPU_VG_LITE_VG_LITE_TEST_H__ +#ifndef __APPS_EXAMPLES_FOC_FOC_PERF_H +#define __APPS_EXAMPLES_FOC_FOC_PERF_H /**************************************************************************** * Included Files ****************************************************************************/ -#include +#include /**************************************************************************** - * Public Types + * Pre-processor Definitions ****************************************************************************/ -struct gpu_test_context_s; +#define PRINTF_PERF(format, ...) printf(format, ##__VA_ARGS__) + +/**************************************************************************** + * Public Type Definition + ****************************************************************************/ + +struct foc_perf_s +{ + bool max_changed; + uint32_t max; + uint32_t now; +}; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ -#ifdef __cplusplus -#define EXTERN extern "C" -extern "C" -{ -#else -#define EXTERN extern -#endif +int foc_perf_init(struct foc_perf_s *p); +void foc_perf_start(struct foc_perf_s *p); +void foc_perf_end(struct foc_perf_s *p); -/**************************************************************************** - * Name: vg_lite_test - ****************************************************************************/ - -int vg_lite_test(FAR struct gpu_test_context_s *ctx); - -#undef EXTERN -#ifdef __cplusplus -} -#endif - -#endif /* __APPS_TESTING_GPU_VG_LITE_VG_LITE_TEST_H__ */ +#endif /* __APPS_EXAMPLES_FOC_FOC_PERF_H */ diff --git a/examples/foc/foc_thr.c b/examples/foc/foc_thr.c index a84efc2a7..a4bf87e33 100644 --- a/examples/foc/foc_thr.c +++ b/examples/foc/foc_thr.c @@ -46,15 +46,19 @@ # define CONFIG_EXAMPLES_FOC_FIXED16_INST (0) #endif +#if CONFIG_EXAMPLES_FOC_FLOAT_INST + CONFIG_EXAMPLES_FOC_FIXED16_INST == 0 +# warning no control thread enabled ! +#endif + /**************************************************************************** * Extern Functions Prototypes ****************************************************************************/ -#ifdef CONFIG_INDUSTRY_FOC_FLOAT +#if CONFIG_EXAMPLES_FOC_FLOAT_INST > 0 extern int foc_float_thr(FAR struct foc_ctrl_env_s *envp); #endif -#ifdef CONFIG_INDUSTRY_FOC_FIXED16 +#if CONFIG_EXAMPLES_FOC_FIXED16_INST > 0 extern int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp); #endif @@ -65,10 +69,10 @@ extern int foc_fixed16_thr(FAR struct foc_ctrl_env_s *envp); pthread_mutex_t g_cntr_lock; static uint32_t g_foc_thr = 0; -#ifdef CONFIG_INDUSTRY_FOC_FLOAT +#if CONFIG_EXAMPLES_FOC_FLOAT_INST > 0 static int g_float_thr_cntr = 0; #endif -#ifdef CONFIG_INDUSTRY_FOC_FIXED16 +#if CONFIG_EXAMPLES_FOC_FIXED16_INST > 0 static int g_fixed16_thr_cntr = 0; #endif @@ -138,7 +142,7 @@ static FAR void *foc_control_thr(FAR void *arg) switch (envp->type) { -#ifdef CONFIG_INDUSTRY_FOC_FLOAT +#if CONFIG_EXAMPLES_FOC_FLOAT_INST > 0 case FOC_NUMBER_TYPE_FLOAT: { pthread_mutex_lock(&g_cntr_lock); @@ -160,7 +164,7 @@ static FAR void *foc_control_thr(FAR void *arg) } #endif -#ifdef CONFIG_INDUSTRY_FOC_FIXED16 +#if CONFIG_EXAMPLES_FOC_FIXED16_INST > 0 case FOC_NUMBER_TYPE_FIXED16: { pthread_mutex_lock(&g_cntr_lock); @@ -286,14 +290,14 @@ int foc_thread_type(int id) { int ret = -1; -#ifdef CONFIG_INDUSTRY_FOC_FLOAT +#if CONFIG_EXAMPLES_FOC_FLOAT_INST > 0 if (id < CONFIG_EXAMPLES_FOC_FLOAT_INST) { ret = FOC_NUMBER_TYPE_FLOAT; } #endif -#ifdef CONFIG_INDUSTRY_FOC_FIXED16 +#if CONFIG_EXAMPLES_FOC_FIXED16_INST > 0 if (id < CONFIG_EXAMPLES_FOC_FLOAT_INST + CONFIG_EXAMPLES_FOC_FIXED16_INST) { ret = FOC_NUMBER_TYPE_FIXED16; diff --git a/examples/gpio/gpio_main.c b/examples/gpio/gpio_main.c index c097a265f..9793fbba4 100644 --- a/examples/gpio/gpio_main.c +++ b/examples/gpio/gpio_main.c @@ -67,12 +67,6 @@ static void show_usage(FAR const char *progname) fprintf(stderr, "\t 8: GPIO_INTERRUPT_RISING_PIN\n"); fprintf(stderr, "\t 9: GPIO_INTERRUPT_FALLING_PIN\n"); fprintf(stderr, "\t10: GPIO_INTERRUPT_BOTH_PIN\n"); - fprintf(stderr, "\t11: GPIO_INTERRUPT_PIN_WAKEUP\n"); - fprintf(stderr, "\t12: GPIO_INTERRUPT_HIGH_PIN_WAKEUP\n"); - fprintf(stderr, "\t13: GPIO_INTERRUPT_LOW_PIN_WAKEUP\n"); - fprintf(stderr, "\t14: GPIO_INTERRUPT_RISING_PIN_WAKEUP\n"); - fprintf(stderr, "\t15: GPIO_INTERRUPT_FALLING_PIN_WAKEUP\n"); - fprintf(stderr, "\t16: GPIO_INTERRUPT_BOTH_PIN_WAKEUP\n"); } /**************************************************************************** @@ -314,12 +308,6 @@ int main(int argc, FAR char *argv[]) case GPIO_INTERRUPT_RISING_PIN: case GPIO_INTERRUPT_FALLING_PIN: case GPIO_INTERRUPT_BOTH_PIN: - case GPIO_INTERRUPT_PIN_WAKEUP: - case GPIO_INTERRUPT_HIGH_PIN_WAKEUP: - case GPIO_INTERRUPT_LOW_PIN_WAKEUP: - case GPIO_INTERRUPT_RISING_PIN_WAKEUP: - case GPIO_INTERRUPT_FALLING_PIN_WAKEUP: - case GPIO_INTERRUPT_BOTH_PIN_WAKEUP: { printf(" Interrupt pin: Value=%u\n", invalue); diff --git a/examples/hdc1008_demo/CMakeLists.txt b/examples/hdc1008_demo/CMakeLists.txt index 3138f7da6..1bf7ce4da 100644 --- a/examples/hdc1008_demo/CMakeLists.txt +++ b/examples/hdc1008_demo/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/examples/hdc1008/CMakeLists.txt +# apps/examples/hdc1008_demo/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for diff --git a/examples/hello_d/Kconfig b/examples/hello_d/Kconfig new file mode 100644 index 000000000..04fb65a61 --- /dev/null +++ b/examples/hello_d/Kconfig @@ -0,0 +1,29 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config EXAMPLES_HELLO_D + tristate "\"Hello, D!\" D example" + default n + ---help--- + Enable the \"Hello, D!\" D example + +if EXAMPLES_HELLO_D + +config EXAMPLES_HELLO_D_PROGNAME + string "Program name" + default "hello_d" + ---help--- + This is the name of the program that will be used when the + program is installed. + +config EXAMPLES_HELLO_D_PRIORITY + int "Hello D task priority" + default 100 + +config EXAMPLES_HELLO_D_STACKSIZE + int "Hello D stack size" + default DEFAULT_TASK_STACKSIZE + +endif diff --git a/examples/hello_d/Make.defs b/examples/hello_d/Make.defs new file mode 100644 index 000000000..b267da14f --- /dev/null +++ b/examples/hello_d/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/examples/hello_d/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_EXAMPLES_HELLO_D),) +CONFIGURED_APPS += $(APPDIR)/examples/hello_d +endif diff --git a/system/nxcodec/Makefile b/examples/hello_d/Makefile similarity index 75% rename from system/nxcodec/Makefile rename to examples/hello_d/Makefile index 220e4f82c..a66e165c6 100644 --- a/system/nxcodec/Makefile +++ b/examples/hello_d/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/system/nxcodec/Makefile +# apps/examples/hello_d/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,17 +20,16 @@ include $(APPDIR)/Make.defs -CSRCS = nxcodec.c nxcodec_context.c +# Hello, World! D Example -# nxcodec test built-in application info +MAINSRC = hello_d_main.d -PROGNAME = $(CONFIG_SYSTEM_NXCODEC_PROGNAME) -PRIORITY = $(CONFIG_SYSTEM_NXCODEC_PRIORITY) -STACKSIZE = $(CONFIG_SYSTEM_NXCODEC_STACKSIZE) -MODULE = $(CONFIG_SYSTEM_NXCODEC) +# hello_d built-in application info -# nxcodec test - -MAINSRC = nxcodec_main.c +DFLAGS += -oq -betterC +PROGNAME = $(CONFIG_EXAMPLES_HELLO_D_PROGNAME) +PRIORITY = $(CONFIG_EXAMPLES_HELLO_D_PRIORITY) +STACKSIZE = $(CONFIG_EXAMPLES_HELLO_D_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_HELLO_D) include $(APPDIR)/Application.mk diff --git a/examples/hello_d/hello_d_main.d b/examples/hello_d/hello_d_main.d new file mode 100644 index 000000000..b679c4b30 --- /dev/null +++ b/examples/hello_d/hello_d_main.d @@ -0,0 +1,122 @@ +//*************************************************************************** +// apps/examples/hello_d/hello_d_main.d +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//*************************************************************************** +module examples.hello_d_main; + +//*************************************************************************** +// Imports module +//*************************************************************************** +/// Type issues, need make own D runtime (object.d file) +// import core.stdc.stdio : printf; +// import core.stdc.stdlib : malloc, free; + +/// +pragma(printf) +extern (C) int printf(scope const(char)* fmt, scope...) @nogc nothrow @trusted; +/// +extern (C) void* malloc(size_t size) @nogc nothrow @trusted; +/// +extern (C) void free(void* ptr) @nogc nothrow @trusted; + +//*************************************************************************** +// Private module content +//*************************************************************************** +private: + +// based heloxx class layout +extern (C++,class) +struct DHelloWorld +{ +@nogc nothrow: + + @disable this(); + @disable this(this); + this(int secret) @safe pure + { + mSecret = secret; + debug printf("Constructor\n"); + } + + ~this() @safe pure + { + debug printf("Destructor\n"); + } + + bool HelloWorld() @safe + { + debug printf("HelloWorld: mSecret=%d\n", mSecret); + + if (mSecret != 42) + { + printf("DHelloWorld.HelloWorld: CONSTRUCTION FAILED!\n"); + return false; + } + else + { + printf("DHelloWorld.HelloWorld: Hello, World!!\n"); + return true; + } + } + + private int mSecret; +} + +//*************************************************************************** +// Private Data +//*************************************************************************** + +// Define a statically constructed DHellowWorld instance if D static +// initializers are supported by the platform +// --d-version=D_Initialize +version (D_Initialize) +{ + static DHelloWorld g_HelloWorld; +} + +//*************************************************************************** +// Public Functions +//*************************************************************************** + +/**************************************************************************** + * Name: hello_d_main + ****************************************************************************/ +// betterC need main function no-mangle. +extern (C) +int hello_d_main(int argc, char*[] argv) nothrow @nogc +{ + version (LDC) + { + /// need LLVM targetinfo + printf("Hello World, [%s]!\n", __traits(targetCPU).ptr); + } + // Exercise an explicitly instantiated C++ object + auto pHelloWorld = cast(DHelloWorld*) malloc(DHelloWorld.sizeof); + scope (exit) + free(pHelloWorld); + + printf("hello_d_main: Saying hello from the dynamically constructed instance\n"); + pHelloWorld.HelloWorld(); + + // Exercise an D object instantiated on the stack + auto HelloWorld = DHelloWorld(42); + + printf("hello_d_main: Saying hello from the instance constructed on the stack\n"); + HelloWorld.HelloWorld(); + return 0; +} diff --git a/examples/hello_nim/Makefile b/examples/hello_nim/Makefile index 52d306d96..67e9bf9c9 100644 --- a/examples/hello_nim/Makefile +++ b/examples/hello_nim/Makefile @@ -30,8 +30,8 @@ MODULE = $(CONFIG_EXAMPLES_HELLO_NIM) # Hello, World! Example NIMPATH = $(shell choosenim show path) -CFLAGS += -I $(NIMPATH)/lib -I ./.nimcache -CSRCS += $(wildcard .nimcache/*.c) +CFLAGS += -I $(NIMPATH)/lib -I ../../.nimcache +CSRCS += $(wildcard ../../.nimcache/*.c) MAINSRC = hello_nim_main.c diff --git a/examples/hello_rust/Makefile b/examples/hello_rust/Makefile index 894de9cea..8415ff402 100644 --- a/examples/hello_rust/Makefile +++ b/examples/hello_rust/Makefile @@ -31,6 +31,6 @@ MODULE = $(CONFIG_EXAMPLES_HELLO_RUST) MAINSRC = hello_rust_main.rs -RUSTFLAGS += -C panic=abort +RUSTFLAGS += -C panic=abort -O include $(APPDIR)/Application.mk diff --git a/system/nxcamera/CMakeLists.txt b/examples/hello_wasm/CMakeLists.txt similarity index 72% rename from system/nxcamera/CMakeLists.txt rename to examples/hello_wasm/CMakeLists.txt index 4f7aad5dc..556aafd5b 100644 --- a/system/nxcamera/CMakeLists.txt +++ b/examples/hello_wasm/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/system/nxcamera/CMakeLists.txt +# apps/examples/hello_wasm/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,19 +18,19 @@ # # ############################################################################## -if(CONFIG_SYSTEM_NXCAMERA) +if(CONFIG_EXAMPLES_HELLO_WASM_BUILD_NATIVE) nuttx_add_application( NAME - nxcamera - PRIORITY - ${CONFIG_SCHED_PRIORITY_DEFAULT} - STACKSIZE - ${CONFIG_NXCAMERA_MAINTHREAD_STACKSIZE} - MODULE - ${CONFIG_SYSTEM_NXCAMERA} + ${CONFIG_EXAMPLES_HELLO_WASM_PROGNAME} SRCS - nxcamera_main.c) - - set(CSRCS nxcamera.c) - target_sources(apps PRIVATE ${CSRCS}) + hello_main.c + STACKSIZE + ${CONFIG_EXAMPLES_HELLO_WASM_STACKSIZE} + PRIORITY + ${CONFIG_EXAMPLES_HELLO_WASM_PRIORITY}) +endif() + +if(CONFIG_EXAMPLES_HELLO_WASM_BUILD_WASM) + wasm_add_application(NAME ${CONFIG_EXAMPLES_HELLO_WASM_PROGNAME} SRCS + hello_main.c) endif() diff --git a/examples/hello_wasm/Kconfig b/examples/hello_wasm/Kconfig index fedb8d828..d4ed93523 100644 --- a/examples/hello_wasm/Kconfig +++ b/examples/hello_wasm/Kconfig @@ -26,4 +26,16 @@ config EXAMPLES_HELLO_WASM_STACKSIZE int "Hello wasm stack size" default DEFAULT_TASK_STACKSIZE +config EXAMPLES_HELLO_WASM_BUILD_WASM + bool "Build as WebAssembly module" + default y + ---help--- + Build the WebAssembly binary from the C source code. + +config EXAMPLES_HELLO_WASM_BUILD_NATIVE + bool "Build as native program" + default n + ---help--- + Build the native binary from the C source code. + endif diff --git a/examples/hello_wasm/hello_main.c b/examples/hello_wasm/hello_main.c index a98dcf7e4..c351cf939 100644 --- a/examples/hello_wasm/hello_main.c +++ b/examples/hello_wasm/hello_main.c @@ -22,7 +22,6 @@ * Included Files ****************************************************************************/ -#include #include /**************************************************************************** diff --git a/examples/hello_zig/Makefile b/examples/hello_zig/Makefile index a1657034b..5413dc580 100644 --- a/examples/hello_zig/Makefile +++ b/examples/hello_zig/Makefile @@ -22,7 +22,7 @@ include $(APPDIR)/Make.defs # Hello, Zig! Example -MAINSRC = hello_zig_main.zig +MAINSRC = hello_zig.zig # Hello, Zig! built-in application info diff --git a/examples/hello_zig/hello_zig.zig b/examples/hello_zig/hello_zig.zig new file mode 100644 index 000000000..6d7f271eb --- /dev/null +++ b/examples/hello_zig/hello_zig.zig @@ -0,0 +1,40 @@ +//*************************************************************************** +// examples/hello_zig/hello_zig.zig +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//*************************************************************************** + +//*************************************************************************** +// Included Files +//*************************************************************************** +const std = @import("std"); + +//**************************************************************************** +//* Externs +//**************************************************************************** + +pub extern fn printf(_format: [*:0]const u8) c_int; + +//**************************************************************************** +//* hello_zig_main +//**************************************************************************** +pub export fn main(_argc: c_int, _argv: [*]const [*]const u8) u8 { + _ = _argc; + _ = _argv; + _ = printf("Hello, Zig!\n"); + return 0; +} diff --git a/system/telnetd/CMakeLists.txt b/examples/hx711/CMakeLists.txt similarity index 83% rename from system/telnetd/CMakeLists.txt rename to examples/hx711/CMakeLists.txt index 79b569677..aabe90ef6 100644 --- a/system/telnetd/CMakeLists.txt +++ b/examples/hx711/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/system/telnetd/CMakeLists.txt +# apps/examples/hx711/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,14 +18,14 @@ # # ############################################################################## -if(CONFIG_SYSTEM_TELNETD) +if(CONFIG_EXAMPLES_HX711) nuttx_add_application( NAME - ${CONFIG_SYSTEM_TELNETD_PROGNAME} + ${CONFIG_EXAMPLES_HX711_PROGNAME} SRCS - telnetd.c + hx711_main.c STACKSIZE - ${CONFIG_SYSTEM_TELNETD_STACKSIZE} + ${CONFIG_EXAMPLES_HX711_STACKSIZE} PRIORITY - ${CONFIG_SYSTEM_TELNETD_PRIORITY}) + ${CONFIG_EXAMPLES_HX711_PRIORITY}) endif() diff --git a/examples/hx711/Kconfig b/examples/hx711/Kconfig new file mode 100644 index 000000000..f68a26d12 --- /dev/null +++ b/examples/hx711/Kconfig @@ -0,0 +1,32 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config EXAMPLES_HX711 + tristate "HX711 driver example" + default n + select ADC_HX711 + ---help--- + Enable the HX711 example. This program is also useful during + development as it's possible to manipulate and dump hx711 + settings, as well as print conversions to terminal. + +if EXAMPLES_HX711 + +config EXAMPLES_HX711_PROGNAME + string "Program name" + default "hx711" + ---help--- + This is the name of the program that will be used when the NSH ELF + program is installed. + +config EXAMPLES_HX711_PRIORITY + int "hx711 task priority" + default 100 + +config EXAMPLES_HX711_STACKSIZE + int "hx711 stack size" + default DEFAULT_TASK_STACKSIZE + +endif diff --git a/math/kissfft/Make.defs b/examples/hx711/Make.defs similarity index 89% rename from math/kissfft/Make.defs rename to examples/hx711/Make.defs index 3da1486c9..7cffdda6f 100644 --- a/math/kissfft/Make.defs +++ b/examples/hx711/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/kissfft/Make.defs +# apps/examples/hx711/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,6 @@ # ############################################################################ -ifneq ($(CONFIG_MATH_KISSFFT),) -CONFIGURED_APPS += $(APPDIR)/math/kissfft +ifneq ($(CONFIG_EXAMPLES_HX711),) +CONFIGURED_APPS += $(APPDIR)/examples/hx711 endif diff --git a/testing/cachetest/Makefile b/examples/hx711/Makefile similarity index 78% rename from testing/cachetest/Makefile rename to examples/hx711/Makefile index 7d84880f9..4d2a84619 100644 --- a/testing/cachetest/Makefile +++ b/examples/hx711/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/testing/cachetest/Makefile +# apps/examples/hx711/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,13 +20,15 @@ include $(APPDIR)/Make.defs -# Cache test +# hx711 built-in application info -PROGNAME = $(CONFIG_TESTING_CACHETEST_PROGNAME) -PRIORITY = $(CONFIG_TESTING_CACHETEST_PRIORITY) -STACKSIZE = $(CONFIG_TESTING_CACHETEST_STACKSIZE) -MODULE = $(CONFIG_TESTING_CACHETEST) +PROGNAME = $(CONFIG_EXAMPLES_HX711_PROGNAME) +PRIORITY = $(CONFIG_EXAMPLES_HX711_PRIORITY) +STACKSIZE = $(CONFIG_EXAMPLES_HX711_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_HX711) -MAINSRC = cachetest_main.c +# hx711 example + +MAINSRC = hx711_main.c include $(APPDIR)/Application.mk diff --git a/examples/hx711/hx711_main.c b/examples/hx711/hx711_main.c new file mode 100644 index 000000000..fc7117469 --- /dev/null +++ b/examples/hx711/hx711_main.c @@ -0,0 +1,361 @@ +/**************************************************************************** + * apps/examples/hx711/hx711_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include + +#include +#include +#include +#include +#include +#include + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct hx711_config +{ + char dev[32]; + char dump; + char channel; + unsigned char gain; + unsigned average; + unsigned loops; + float precision; + int val_per_unit; + int sign; +} g_hx711_config; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: hx711_print_help + * + * Description: + * Prints help onto stdout. + * + ****************************************************************************/ + +static void hx711_print_help(const char *progname) +{ + printf("usage: %s [-d ] [options]\n" + "\n" + "\t-h print this help message\n" + "\t-d path to hx711 device, default: /dev/hx711_0\n" + "\t-t tares the scale with specified precision, might" + "take few seconds to complete.\n" + "\t If you set value per unit, precision is in units, " + "otherwise it's raw values.\n" + "\t If units are used, float can be passed like 0.1\n" + "\t-v value read that coresponds to one unit. This value " + "has to be\n" + "\t calibrated first before it's known\n" + "\t-s reverse sign, if values decreses when mass increases, " + "pass this\n" + "\t-D dumps current device settings (like, average, channel, " + "gain etc.)\n" + "\t-a set how many samples should be averaged before " + "returning value,\n" + "\t values [1..%d] are valid\n" + "\t-c set channel to read (either 'a' or 'b' is valid)\n" + "\t-g set adc gain, for channel 'a' 64 and 128 are valid,\n" + "\t for channel 'b', only 64 is valid\n" + "\t-r read this number of samples before exiting, samples " + "will be printed\n" + "\t on stdout as string, one sample per line\n" + "\n" + "Check documentation for full description\n", + progname, HX711_MAX_AVG_SAMPLES); +} + +/**************************************************************************** + * Name: hx711_parse_args + * + * Description: + * Parses command line arguments + * + ****************************************************************************/ + +static int hx711_parse_args(int argc, FAR char *argv[]) +{ + int opt; + + memset(&g_hx711_config, 0x00, sizeof(g_hx711_config)); + + while ((opt = getopt(argc, argv, "hd:Dt:a:c:g:r:v:s")) != -1) + { + switch (opt) + { + case 'h': + hx711_print_help(argv[0]); + return 1; + + case 'd': + strcpy(g_hx711_config.dev, optarg); + break; + + case 't': + g_hx711_config.precision = atof(optarg); + break; + + case 'D': + g_hx711_config.dump = 1; + break; + + case 'a': + g_hx711_config.average = atoi(optarg); + break; + + case 'c': + g_hx711_config.channel = optarg[0]; + break; + + case 'g': + g_hx711_config.gain = atoi(optarg); + break; + + case 'r': + g_hx711_config.loops = atoi(optarg); + break; + + case 's': + g_hx711_config.sign = -1; + break; + + case 'v': + g_hx711_config.val_per_unit = atoi(optarg); + break; + + default: + fprintf(stderr, "Invalid option, run with -h for help\n"); + return 1; + } + } + + if (g_hx711_config.dev[0] == '\0') + { + strcpy(g_hx711_config.dev, "/dev/hx711_0"); + } + + return 0; +} + +/**************************************************************************** + * Name: hx711_set_options + * + * Description: + * Set hx711 options if they were specified on command line + * + * Input Parameters: + * fd - opened hx711 instance + * + ****************************************************************************/ + +int hx711_set_options(int fd) +{ + int ret; + + /* Set channel to read */ + + if (g_hx711_config.channel > 0) + { + if ((ret = ioctl(fd, HX711_SET_CHANNEL, g_hx711_config.channel))) + { + fprintf(stderr, "Failed to set channel to %c, error: %s\n", + g_hx711_config.channel, strerror(errno)); + return -1; + } + } + + /* Set channel ADC gain */ + + if (g_hx711_config.gain > 0) + { + if ((ret = ioctl(fd, HX711_SET_GAIN, g_hx711_config.gain))) + { + fprintf(stderr, "Failed to set gain to %d, error: %s\n", + g_hx711_config.gain, strerror(errno)); + return -1; + } + } + + /* Set how many samples to average before printing value */ + + if (g_hx711_config.average > 0) + { + if ((ret = ioctl(fd, HX711_SET_AVERAGE, g_hx711_config.average))) + { + fprintf(stderr, "Failed to set average to %d, error: %s\n", + g_hx711_config.average, strerror(errno)); + return -1; + } + } + + /* Set if sign should be reversed or not */ + + if (g_hx711_config.sign) + { + if ((ret = ioctl(fd, HX711_SET_SIGN, &g_hx711_config.sign))) + { + fprintf(stderr, "Failed to set sign to %d, error: %s\n", + g_hx711_config.sign, strerror(errno)); + return -1; + } + } + + /* Set what value coresponds to 1 unit */ + + if (g_hx711_config.val_per_unit > 0) + { + if ((ret = ioctl(fd, HX711_SET_VAL_PER_UNIT, + g_hx711_config.val_per_unit))) + { + fprintf(stderr, "Failed to set val per unit to %d, error: %s\n", + g_hx711_config.val_per_unit, strerror(errno)); + return -1; + } + } + + return 0; +} + +/**************************************************************************** + * Name: hx711_dump_options + * + * Description: + * Reads current hx711 settings from kernel driver and dumps them on stdout + * + ****************************************************************************/ + +static void hx711_dump_options(int fd) +{ + unsigned average; + unsigned char gain; + char channel; + unsigned val_per_unit; + + ioctl(fd, HX711_GET_GAIN, &gain); + ioctl(fd, HX711_GET_CHANNEL, &channel); + ioctl(fd, HX711_GET_AVERAGE, &average); + ioctl(fd, HX711_GET_VAL_PER_UNIT, &val_per_unit); + + printf("Current settings for: %s\n", g_hx711_config.dev); + printf("average.............: %u\n", average); + printf("channel.............: %c\n", channel); + printf("gain................: %d\n", gain); + printf("value per unit......: %u\n", val_per_unit); +} + +/**************************************************************************** + * Name: hx711_read_and_dump + * + * Description: + * Reads configured number of samples, and dumps them to terminal. + * + ****************************************************************************/ + +static int hx711_read_and_dump(int fd) +{ + int32_t sample; + + while (g_hx711_config.loops--) + { + if (read(fd, &sample, sizeof(sample)) != sizeof(sample)) + { + fprintf(stderr, "Error reading from %s, error %s\n", + g_hx711_config.dev, strerror(errno)); + return -1; + } + + printf("%"PRId32"\n", sample); + } + + return 0; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * hx711 + ****************************************************************************/ + +int main(int argc, FAR char *argv[]) +{ + int fd; + + if (hx711_parse_args(argc, argv)) + { + return 1; + } + + fd = open(g_hx711_config.dev, O_RDONLY); + if (fd < 0) + { + fprintf(stderr, "Failed to open %s, error: %s\n", g_hx711_config.dev, + strerror(errno)); + return 1; + } + + if (hx711_set_options(fd)) + { + close(fd); + return 1; + } + + if (g_hx711_config.precision) + { + ioctl(fd, HX711_GET_VAL_PER_UNIT, &g_hx711_config.val_per_unit); + + if (g_hx711_config.val_per_unit) + { + printf("Taring with %fg precision\n", g_hx711_config.precision); + } + + if (ioctl(fd, HX711_TARE, &g_hx711_config.precision)) + { + perror("Failed to tare the scale"); + close(fd); + return 1; + } + } + + if (g_hx711_config.dump) + { + hx711_dump_options(fd); + } + + if (g_hx711_config.loops) + { + hx711_read_and_dump(fd); + } + + close(fd); + return 0; +} diff --git a/examples/json/README.md b/examples/json/README.md deleted file mode 100644 index 047b6c150..000000000 --- a/examples/json/README.md +++ /dev/null @@ -1,298 +0,0 @@ -# Examples / `json` cJSON JSON Parser - -This directory contains logic taken from the cJSON project: - -http://sourceforge.net/projects/cjson/ - -This corresponds to SVN revision `r42` (with lots of changes for NuttX coding -standards). As of `r42`, the SVN repository was last updated on `2011-10-10` so -I presume that the code is stable and there is no risk of maintaining duplicate -logic in the NuttX repository. - -# Contents - -- License -- Welcome to cJSON - -# License - -Copyright (c) 2009 Dave Gamble - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -# Welcome to cJSON - -cJSON aims to be the dumbest possible parser that you can get your job done -with. It's a single file of C, and a single header file. - -JSON is described best here: http://www.json.org/ It's like XML, but fat-free. -You use it to move data around, store things, or just generally represent your -program's state. - -First up, how do I build? Add `cJSON.c` to your project, and put `cJSON.h` -somewhere in the header search path. For example, to build the test app: - -```bash -gcc cJSON.c test.c -o test -lm -./test -``` - -As a library, cJSON exists to take away as much legwork as it can, but not get -in your way. As a point of pragmatism (i.e. ignoring the truth), I'm going to -say that you can use it in one of two modes: Auto and Manual. Let's have a quick -run-through. - -I lifted some JSON from this page: http://www.json.org/fatfree.html That page -inspired me to write cJSON, which is a parser that tries to share the same -philosophy as JSON itself. Simple, dumb, out of the way. - -Some JSON: - -```json -{ - "name": "Jack (\"Bee\") Nimble", - "format": { - "type": "rect", - "width": 1920, - "height": 1080, - "interlace": false, - "frame rate": 24 - } -} -``` - -Assume that you got this from a file, a webserver, or magic JSON elves, -whatever, you have a `char *` to it. Everything is a cJSON struct. - -Get it parsed: - -```c -cJSON *root = cJSON_Parse(my_json_string); -``` - -This is an object. We're in C. We don't have objects. But we do have structs. - -What's the framerate? - -```c -cJSON *format = cJSON_GetObjectItem(root,"format"); -int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint; -``` - -Want to change the framerate? - -```c -cJSON_GetObjectItem(format,"frame rate")->valueint = 25; -``` - -Back to disk? - -```c -char *rendered = cJSON_Print(root); -``` - -Finished? Delete the root (this takes care of everything else). - -```c -cJSON_Delete(root); -``` - -That's AUTO mode. If you're going to use Auto mode, you really ought to check -pointers before you dereference them. If you want to see how you'd build this -struct in code? - -```c -cJSON *root,*fmt; -root = cJSON_CreateObject(); - -cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble")); -cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject()); -cJSON_AddStringToObject(fmt,"type", "rect"); -cJSON_AddNumberToObject(fmt,"width", 1920); -cJSON_AddNumberToObject(fmt,"height", 1080); -cJSON_AddFalseToObject (fmt,"interlace"); -cJSON_AddNumberToObject(fmt,"frame rate", 24); -``` - -Hopefully we can agree that's not a lot of code? There's no overhead, no -unnecessary setup. Look at test.c for a bunch of nice examples, mostly all -ripped off the json.org site, and a few from elsewhere. - -What about manual mode? First up you need some detail. -Let's cover how the cJSON objects represent the JSON data. -cJSON doesn't distinguish arrays from objects in handling; just type. -Each cJSON has, potentially, a child, siblings, value, a name. - -The root object has: Object Type and a Child -The Child has name "name", with value "Jack ("Bee") Nimble", and a sibling: -Sibling has type Object, name "format", and a child. -That child has type String, name "type", value "rect", and a sibling: -Sibling has type Number, name "width", value 1920, and a sibling: -Sibling has type Number, name "height", value 1080, and a sibling: -Sibling hs type False, name "interlace", and a sibling: -Sibling has type Number, name "frame rate", value 24 - -Here's the structure: - -```c -typedef struct cJSON { - struct cJSON *next,*prev; - struct cJSON *child; - - int type; - - char *valuestring; - int valueint; - double valuedouble; - - char *string; -} cJSON; -``` - -By default all values are 0 unless set by virtue of being meaningful. - -next/prev is a doubly linked list of siblings. next takes you to your sibling, -prev takes you back from your sibling to you. Only objects and arrays have a -"child", and it's the head of the doubly linked list. A "child" entry will have -`prev==0`, but next potentially points on. The last sibling has `next=0`. The -type expresses Null/True/False/Number/String/Array/Object, all of which are -`#define`d in `cJSON.h`. - -A Number has `valueint` and `valuedouble`. If you're expecting an `int`, read -`valueint`, if not read `valuedouble`. - -Any entry which is in the linked list which is the child of an object will have -a "string" which is the "name" of the entry. When I said "name" in the above -example, that's "string". "string" is the JSON name for the 'variable name' if -you will. - -Now you can trivially walk the lists, recursively, and parse as you please. You -can invoke `cJSON_Parse` to get cJSON to parse for you, and then you can take -the root object, and traverse the structure (which is, formally, an N-tree), and -tokenise as you please. If you wanted to build a callback style parser, this is -how you'd do it (just an example, since these things are very specific): - -```c -void parse_and_callback(cJSON *item, const char *prefix) -{ - while (item) - { - size_t len = strlen(prefix) + strlen(item->name) + 2; - char *newprefix = malloc(len); - snprintf(newprefix, len, "%s/%s", prefix, item->name); - int dorecurse = callback(newprefix, item->type, item); - if (item->child && dorecurse) parse_and_callback(item->child, newprefix); - item = item->next; - free(newprefix); - } -} -``` - -The prefix process will build you a separated list, to simplify your callback -handling. The `dorecurse` flag would let the callback decide to handle -sub-arrays on it's own, or let you invoke it per-item. For the item above, your -callback might look like this: - -```c -int callback(const char *name,int type, cJSON *item) -{ - if (!strcmp(name,"name")) { /* populate name */ } - else if (!strcmp(name,"format/type") { /* handle "rect" */ } - else if (!strcmp(name,"format/width") { /* 800 */ } - else if (!strcmp(name,"format/height") { /* 600 */ } - else if (!strcmp(name,"format/interlace") { /* false */ } - else if (!strcmp(name,"format/frame rate") { /* 24 */ } - return 1; -} -``` - -Alternatively, you might like to parse iteratively. - -You'd use: - -```c -void parse_object(cJSON *item) -{ - int i; for (i=0; i < cJSON_GetArraySize(item); i++) - { - cJSON *subitem = cJSON_GetArrayItem(item, i); - // handle subitem. - } -} -``` - -Or, for PROPER manual mode: - -```c -void parse_object(cJSON *item) -{ - cJSON *subitem = item->child; - - while (subitem) - { - // handle subitem - if (subitem->child) parse_object(subitem->child); - - subitem = subitem->next; - } -} -``` - -Of course, this should look familiar, since this is just a stripped-down version -of the callback-parser. - -This should cover most uses you'll find for parsing. The rest should be possible -to infer.. and if in doubt, read the source! There's not a lot of it! ;) - -In terms of constructing JSON data, the example code above is the right way to -do it. You can, of course, hand your sub-objects to other functions to populate. -Also, if you find a use for it, you can manually build the objects. For -instance, suppose you wanted to build an array of objects? - -```c -cJSON *objects[24]; - -cJSON *Create_array_of_anything(cJSON **items,int num) -{ - int i;cJSON *prev, *root=cJSON_CreateArray(); - for (i=0;i<24;i++) - { - if (!i) root->child=objects[i]; - else prev->next=objects[i], objects[i]->prev=prev; - prev=objects[i]; - } - return root; -} -``` - -and simply: `Create_array_of_anything(objects,24)`; - -cJSON doesn't make any assumptions about what order you create things in. You -can attach the objects, as above, and later add children to each of those -objects. - -As soon as you call `cJSON_Print`, it renders the structure to text. - -The test.c code shows how to handle a bunch of typical cases. If you uncomment -the code, it'll load, parse and print a bunch of test files, also from json.org, -which are more complex than I'd care to try and stash into a `const char -array[]`. - -Enjoy cJSON! - -_Dave Gamble, Aug 2009_ diff --git a/examples/lp503x/Make.defs b/examples/lp503x/Make.defs old mode 100755 new mode 100644 diff --git a/examples/lp503x/Makefile b/examples/lp503x/Makefile old mode 100755 new mode 100644 diff --git a/examples/lvgldemo/Kconfig b/examples/lvgldemo/Kconfig index 68442e8f0..00f6b250f 100644 --- a/examples/lvgldemo/Kconfig +++ b/examples/lvgldemo/Kconfig @@ -18,44 +18,6 @@ config EXAMPLES_LVGLDEMO_PRIORITY config EXAMPLES_LVGLDEMO_STACKSIZE int "lvgldemo stack size" - default 32768 - -comment "Input configuration options" - depends on INPUT_TOUCHSCREEN || INPUT_MOUSE - -config EXAMPLES_LVGLDEMO_CALIBRATE - bool "Calibrate touchscreen" - default y - depends on INPUT_TOUCHSCREEN || INPUT_MOUSE - ---help--- - Calibrate touchscreen before demo start, but some touchscreen - don't need it, like capacitive touchscreen. - -if INPUT_TOUCHSCREEN - -config EXAMPLES_LVGLDEMO_MINOR - int "Touchscreen minor device number" - default 0 - ---help--- - The minor device number. Minor=N corresponds to touchscreen device - /dev/inputN. Note this value must with EXAMPLES_LVGLDEMO_DEVPATH. - Default 0. - -config EXAMPLES_LVGLDEMO_DEVPATH - string "Touchscreen device path" - default "/dev/input0" - ---help--- - The path to the touchscreen device. This must be consistent with - EXAMPLES_LVGLDEMO_MINOR. Default: "/dev/input0" - -endif # INPUT_TOUCHSCREEN - -config EXAMPLES_LVGLDEMO_MOUSE - bool "Mouse interface" - default n - depends on INPUT_MOUSE - ---help--- - The LittleVGL demo can also be configured to work with a mouse - driver by setting this option. + default 16384 endif # EXAMPLES_LVGLDEMO diff --git a/examples/lvgldemo/Make.defs b/examples/lvgldemo/Make.defs index cd8adf98d..1793bbd96 100644 --- a/examples/lvgldemo/Make.defs +++ b/examples/lvgldemo/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/lvgdemo/Make.defs +# apps/examples/lvgldemo/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/examples/lvgldemo/Makefile b/examples/lvgldemo/Makefile index 2c9fff971..65e0b5a95 100644 --- a/examples/lvgldemo/Makefile +++ b/examples/lvgldemo/Makefile @@ -25,10 +25,7 @@ PRIORITY = $(CONFIG_EXAMPLES_LVGLDEMO_PRIORITY) STACKSIZE = $(CONFIG_EXAMPLES_LVGLDEMO_STACKSIZE) MODULE = $(CONFIG_EXAMPLES_LVGLDEMO) -ifeq ($(CONFIG_ANIMATION_ENGINE_EXAMPLES), y) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/frameworks/graphics/animengine/examples -endif -# LittleVGL demo Example +# LVGL demo Example MAINSRC = lvgldemo.c diff --git a/examples/lvgldemo/lvgldemo.c b/examples/lvgldemo/lvgldemo.c index a13577819..b68bc0e93 100644 --- a/examples/lvgldemo/lvgldemo.c +++ b/examples/lvgldemo/lvgldemo.c @@ -111,7 +111,6 @@ int main(int argc, FAR char *argv[]) #ifdef CONFIG_LV_USE_NUTTX_LIBUV uv_loop_t ui_loop; - lv_memzero(&ui_loop, sizeof(ui_loop)); #endif #ifdef NEED_BOARDINIT @@ -129,10 +128,6 @@ int main(int argc, FAR char *argv[]) info.fb_path = "/dev/lcd0"; #endif -#ifdef CONFIG_INPUT_TOUCHSCREEN - info.input_path = CONFIG_EXAMPLES_LVGLDEMO_DEVPATH; -#endif - lv_nuttx_init(&info, &result); if (result.disp == NULL) @@ -155,8 +150,13 @@ int main(int argc, FAR char *argv[]) #else while (1) { - lv_timer_handler(); - usleep(10 * 1000); + uint32_t idle; + idle = lv_timer_handler(); + + /* Minimum sleep of 1ms */ + + idle = idle ? idle : 1; + usleep(idle * 1000); } #endif diff --git a/examples/lvglterm/lvglterm.c b/examples/lvglterm/lvglterm.c index 33cfcb0ac..8ee096f1b 100644 --- a/examples/lvglterm/lvglterm.c +++ b/examples/lvglterm/lvglterm.c @@ -38,7 +38,6 @@ #include #include #include -#include /* NSH Task requires posix_spawn() */ @@ -384,11 +383,11 @@ static void input_callback(lv_event_t *e) { /* Get the Button Index of the Keyboard Button Pressed */ - const uint16_t id = lv_keyboard_get_selected_btn(g_kb); + const uint16_t id = lv_keyboard_get_selected_button(g_kb); /* Get the Text of the Keyboard Button */ - const char *key = lv_keyboard_get_btn_text(g_kb, id); + const char *key = lv_keyboard_get_button_text(g_kb, id); if (key == NULL) { return; @@ -541,8 +540,14 @@ static void remove_escape_codes(char *buf, int len) int main(int argc, FAR char *argv[]) { + lv_nuttx_dsc_t info; + lv_nuttx_result_t result; int ret; +#ifdef CONFIG_LV_USE_NUTTX_LIBUV + uv_loop_t ui_loop; +#endif + #ifdef NEED_BOARDINIT /* Perform board-specific driver initialization */ @@ -559,9 +564,19 @@ int main(int argc, FAR char *argv[]) lv_init(); - /* LVGL port initialization */ + lv_nuttx_dsc_init(&info); - lv_port_init(); +#ifdef CONFIG_LV_USE_NUTTX_LCD + info.fb_path = "/dev/lcd0"; +#endif + + lv_nuttx_init(&info, &result); + + if (result.disp == NULL) + { + LV_LOG_ERROR("lv_demos initialization failure!"); + return 1; + } /* Create the LVGL Widgets */ @@ -573,6 +588,9 @@ int main(int argc, FAR char *argv[]) /* Handle LVGL tasks */ +#ifdef CONFIG_LV_USE_NUTTX_LIBUV + lv_nuttx_uv_loop(&ui_loop, &result); +#else while (1) { uint32_t idle; @@ -584,5 +602,6 @@ int main(int argc, FAR char *argv[]) usleep(idle * 1000); } +#endif return EXIT_SUCCESS; } diff --git a/examples/mcuboot/swap_test/README.md b/examples/mcuboot/swap_test/README.md deleted file mode 100644 index b78a3cd9f..000000000 --- a/examples/mcuboot/swap_test/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Examples / MCUboot / `swap_test` - -## Description - -MCUboot Swap Image is an application to demostrate firmware upgrade using -internal flash memory. It simulate MCUboot API steps to switch between two -valid images. - -This application add 3 Builtin Apps to NuttX NSH: version, set_img and confirm. -After application is build and `nuttx.bin` be generated, the binary must be -signed. Consult your board README file to get instructions how to do it. - -## How to build and flash - -First step is build your board configuraton using `mcuboot-loader` as target. -That create the bootloader itself. The `nuttx.bin` must be flash as usual. - -After that, clean up environment and set `mcuboot-swap-test` as target. The -build output will generate the `nuttx.bin` file. You should execute the MCUboot -script called `imgtool.py` and sign the binary file two times. - -The first time you will use `--version 1.0.0` and `signedv1.bin` as output file. -Then, the second sign you need change to `--version 2.0.0` and `signedv2.bin` -as output file. - -The `signedv1.bin` file must be at MCUboot Slot-0 partition and `signedv2.bin` -at Slot-1. - -More instructions about how to sign and flash can be found at board README file. - -## Running swap image test - -Open you terminal and reboot your board. You can see a similar output as below. -You can check builtin apps using command `?`. - -```bash -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> ? -help usage: help [-v] [] - - . cd echo hexdump mv rmdir true xd - [ cp exec kill printf set truncate - ? cmp exit ls ps sleep uname - basename dirname false mkdir pwd source umount - break dd free mkrd reboot test unset - cat df help mount rm time usleep - -Builtin Apps: - mcuboot_set_img mcuboot_confirm sh - mcuboot_version ramtest nsh -nsh> -``` - -First step (check version): - -```bash -nsh> mcuboot_version -Image version 1.0.0.0 -nsh> -``` - -Second step (mark image as good because it is running). This is an optional -step that must be executed if you ran `imgtool.py` without optional parameter -`--confirm`. - -```bash -nsh> mcuboot_confirm -Application Image successfully confirmed! -nsh> -``` - -Third step (let's reboot and see whats happen): - -```bash -nsh> reboot -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> mcuboot_version -Image version 1.0.0.0 -nsh> -``` - -Fourth step (let's switch image): - -```bash -nsh> mcuboot_set_img -Requested update for next boot. Restarting... -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> mcuboot_version -Image version 2.0.0.0 -nsh> -``` - -Now, we switched from image version 1.0.0 to image 2.0.0. However, we intentionaly -will not run `mcuboot_confirm` app. - -```bash -nsh> reboot -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> mcuboot_version -Image version 1.0.0.0 -nsh> -``` - -This means that if for any reason App reboot, have a malfunctioning or not boot, -MCUboot will switch back to old `good` image! Remember that we executed -`mcuboot_confirm` at step two. - -Fifth step (switch to image version 2 and mark as permanent): - -```bash -nsh> mcuboot_set_img -Requested update for next boot. Restarting... -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> mcuboot_confirm -Application Image successfully confirmed! -nsh> mcuboot_version -Image version 2.0.0.0 -nsh> -``` - -Sixth step (Reboot and confirm V2 image): - -```bash -nsh> reboot -*** Booting MCUboot build 7c890f4b075aed73e4c825ccf875b2fb9ebf2ded *** -NuttShell (NSH) NuttX-10.2.0 -nsh> mcuboot_version -Image version 2.0.0.0 -nsh> -``` - -Conclusion, once we boot a newer image and confirm it MCUboot always run that -image, unless you instruct it to swap again! diff --git a/examples/modbus/modbus_main.c b/examples/modbus/modbus_main.c index 14327766a..cefa94f90 100644 --- a/examples/modbus/modbus_main.c +++ b/examples/modbus/modbus_main.c @@ -123,7 +123,6 @@ struct modbus_state_s #endif pthread_t threadid; pthread_mutex_t lock; - volatile bool quit; }; /**************************************************************************** @@ -165,7 +164,7 @@ static inline int modbus_initialize(void) /* Verify that we are in the stopped state */ - if (g_modbus.threadstate != STOPPED) + if (g_modbus.threadstate == RUNNING) { fprintf(stderr, "modbus_main: " "ERROR: Bad state: %d\n", g_modbus.threadstate); @@ -379,7 +378,7 @@ static inline int modbus_create_pollthread(void) { int ret; - if (g_modbus.threadstate == STOPPED) + if (g_modbus.threadstate != RUNNING) { ret = pthread_create(&g_modbus.threadid, NULL, modbus_pollthread, NULL); @@ -427,25 +426,26 @@ static void modbus_showusage(FAR const char *progname, int exitcode) int main(int argc, FAR char *argv[]) { + bool quit = true; int option; int ret; /* Handle command line arguments */ - g_modbus.quit = false; - while ((option = getopt(argc, argv, "desqh")) != ERROR) { switch (option) { case 'd': /* Disable protocol stack */ - pthread_mutex_lock(&g_modbus.lock); g_modbus.threadstate = SHUTDOWN; - pthread_mutex_unlock(&g_modbus.lock); break; case 'e': /* Enable the protocol stack */ { + /* Keep running, otherwise the thread will die */ + + quit = false; + ret = modbus_create_pollthread(); if (ret != OK) { @@ -481,7 +481,6 @@ int main(int argc, FAR char *argv[]) break; case 'q': /* Quit application */ - g_modbus.quit = true; pthread_kill(g_modbus.threadid, 9); break; @@ -497,6 +496,13 @@ int main(int argc, FAR char *argv[]) } } + /* Don't exit until the thread finishes */ + + if (!quit) + { + pthread_join(g_modbus.threadid, NULL); + } + return EXIT_SUCCESS; } diff --git a/examples/modbusmaster/mbmaster_main.c b/examples/modbusmaster/mbmaster_main.c index 70e0aa239..4f80f1267 100644 --- a/examples/modbusmaster/mbmaster_main.c +++ b/examples/modbusmaster/mbmaster_main.c @@ -280,7 +280,7 @@ int main(int argc, FAR char *argv[]) if (ret != OK) { - fprintf(stderr, "mbmaster_main: ", + fprintf(stderr, "mbmaster_main: " "ERROR: mbmaster_initialize failed: %d\n", ret); goto errout; } @@ -292,11 +292,15 @@ int main(int argc, FAR char *argv[]) if (ret != OK) { - fprintf(stderr, "mbmaster_main: ", + fprintf(stderr, "mbmaster_main: " "ERROR: mbmaster_pollthread create failed: %d\n", ret); goto errout_with_initialize; } + /* Work around to give time to pthread_create run the modbus poller */ + + usleep(100000); + printf("Sending %d requests to slave %d\n", MBMASTER_REQUESTS_COUNT, SLAVE_ID); diff --git a/examples/module/main/CMakeLists.txt b/examples/module/CMakeLists.txt similarity index 95% rename from examples/module/main/CMakeLists.txt rename to examples/module/CMakeLists.txt index 57f3f4f01..0b6a68e82 100644 --- a/examples/module/main/CMakeLists.txt +++ b/examples/module/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/examples/module/main/CMakeLists.txt +# apps/examples/module/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for diff --git a/examples/module/main/Kconfig b/examples/module/Kconfig similarity index 100% rename from examples/module/main/Kconfig rename to examples/module/Kconfig diff --git a/examples/module/Make.defs b/examples/module/Make.defs index 57b758ed1..6729d9c24 100644 --- a/examples/module/Make.defs +++ b/examples/module/Make.defs @@ -18,4 +18,6 @@ # ############################################################################ -include $(wildcard $(APPDIR)/examples/module/*/Make.defs) +ifneq ($(CONFIG_EXAMPLES_MODULE),) +CONFIGURED_APPS += $(APPDIR)/examples/module +endif diff --git a/examples/module/Makefile b/examples/module/Makefile index 802434271..1a3c51356 100644 --- a/examples/module/Makefile +++ b/examples/module/Makefile @@ -18,6 +18,46 @@ # ############################################################################ -MENUDESC = "Module example" +include $(APPDIR)/Make.defs -include $(APPDIR)/Directory.mk +# Module example built-in application info + +PROGNAME = module +PRIORITY = SCHED_PRIORITY_DEFAULT +STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_MODULE) + +# Module Example + +ifeq ($(CONFIG_EXAMPLES_MODULE_ROMFS),y) +CSRCS = romfs.c +endif +ifeq ($(CONFIG_EXAMPLES_MODULE_CROMFS),y) +CSRCS = cromfs.c +endif +CSRCS += mod_symtab.c +drivers$(DELIM)mod_symtab.c_CFLAGS = -fno-builtin +drivers$(DELIM)mod_symtab.c_CELFFLAGS = -fno-builtin +MAINSRC = module_main.c + +VPATH += drivers +DEPPATH += --dep-path drivers + +# Build targets + +ifeq ($(CONFIG_EXAMPLES_MODULE_ROMFS),y) +drivers/romfs.c: build +endif +ifeq ($(CONFIG_EXAMPLES_MODULE_CROMFS),y) +drivers/cromfs.c: build +endif +drivers/mod_symtab.c: build + +.PHONY: build +build: + +$(Q) $(MAKE) -C drivers TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" CROSSDEV=$(CROSSDEV) + +clean:: + +$(Q) $(MAKE) -C drivers TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" CROSSDEV=$(CROSSDEV) clean + +include $(APPDIR)/Application.mk diff --git a/examples/module/drivers/.gitignore b/examples/module/drivers/.gitignore new file mode 100644 index 000000000..922cf8961 --- /dev/null +++ b/examples/module/drivers/.gitignore @@ -0,0 +1,5 @@ +/fsroot +/romfs.c +/cromfs.c +/romfs.img +/mod_symtab.c diff --git a/examples/module/drivers/Makefile b/examples/module/drivers/Makefile new file mode 100644 index 000000000..248067f18 --- /dev/null +++ b/examples/module/drivers/Makefile @@ -0,0 +1,110 @@ +############################################################################ +# apps/examples/module/drivers/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +ALL_SUBDIRS = chardev +BUILD_SUBDIRS = chardev +FSIMG_SUBDIR = fsroot + +MODULE_DIR = $(APPDIR)/examples/module +DRIVER_DIR = $(MODULE_DIR)/drivers +FSROOT_DIR = $(DRIVER_DIR)/fsroot +SYMTAB_SRC = $(DRIVER_DIR)/mod_symtab.c + +ifneq ($(CONFIG_BUILD_FLAT),y) + PASS1_SYMTAB = $(TOPDIR)/pass1/mod_symtab.c +endif + +ifeq ($(CONFIG_EXAMPLES_MODULE_BUILTINFS),y) +ifeq ($(CONFIG_EXAMPLES_MODULE_ROMFS),y) + ROMFS_IMG = $(DRIVER_DIR)/romfs.img + FSIMG_SRC = $(DRIVER_DIR)/romfs.c +else ifeq ($(CONFIG_EXAMPLES_MODULE_CROMFS),y) + NXTOOLDIR = $(TOPDIR)/tools + GENCROMFSSRC = gencromfs.c + GENCROMFSEXE = gencromfs$(HOSTEXEEXT) + + FSIMG_SRC = $(DRIVER_DIR)/cromfs.c +endif +endif + +define DIR_template +$(1)_$(2): + +$(Q) $(MAKE) -C $(1) $(2) TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" FSROOT_DIR="$(FSROOT_DIR)" CROSSDEV=$(CROSSDEV) +endef + +all: $(FSIMG_SRC) $(SYMTAB_SRC) $(PASS1_SYMTAB) +.PHONY: all clean install + +$(foreach DIR, $(ALL_SUBDIRS), $(eval $(call DIR_template,$(DIR),clean))) +$(foreach DIR, $(BUILD_SUBDIRS), $(eval $(call DIR_template,$(DIR),install))) + +# Install each program in the fsroot directory + +install: $(foreach DIR, $(BUILD_SUBDIRS), $(DIR)_install) + +ifeq ($(CONFIG_EXAMPLES_MODULE_BUILTINFS),y) +ifeq ($(CONFIG_EXAMPLES_MODULE_ROMFS),y) +# Create the romfs.img file from the populated fsroot directory + +$(ROMFS_IMG): install + $(Q) genromfs -f $@.tmp -d $(FSROOT_DIR) -V "MODULETEST" + $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) + +# Create the romfs.c file from the romfs.img file + +$(FSIMG_SRC): $(ROMFS_IMG) + $(Q) (cd $(DRIVER_DIR) && echo "#include " >$@ && \ + xxd -i romfs.img | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" >>$@) + +else ifeq ($(CONFIG_EXAMPLES_MODULE_CROMFS),y) +# Make sure that the NuttX gencromfs tool has been built + +$(NXTOOLDIR)/$(GENCROMFSEXE): $(NXTOOLDIR)/$(GENCROMFSSRC) + $(Q) $(MAKE) -C $(NXTOOLDIR) -f Makefile.host $(GENCROMFSEXE) + +# Create the cromfs.c file from the populated cromfs directory + +$(FSIMG_SRC): install $(NXTOOLDIR)/$(GENCROMFSEXE) + $(Q) $(NXTOOLDIR)/$(GENCROMFSEXE) $(FSIMG_DIR) $@.tmp + $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) + +endif +endif + +# Create the exported symbol table + +$(SYMTAB_SRC): install + $(Q) $(APPDIR)$(DELIM)tools$(DELIM)mksymtab.sh $(FSROOT_DIR) g_mod >$@.tmp + $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) + +# Copy the symbol table into the kernel pass1/ build directory + +ifneq ($(CONFIG_BUILD_FLAT),y) +$(PASS1_SYMTAB): $(SYMTAB_SRC) + $(Q) install -m 0644 $(SYMTAB_SRC) $(PASS1_SYMTAB) +endif + +# Clean each subdirectory + +clean: $(foreach DIR, $(ALL_SUBDIRS), $(DIR)_clean) + $(Q) rm -f $(FSIMG_SRC) $(ROMFS_IMG) $(SYMTAB_SRC) + $(Q) rm -rf $(FSROOT_DIR) diff --git a/examples/module/drivers/chardev/.gitignore b/examples/module/drivers/chardev/.gitignore new file mode 100644 index 000000000..c28dc954f --- /dev/null +++ b/examples/module/drivers/chardev/.gitignore @@ -0,0 +1 @@ +/chardev diff --git a/examples/module/drivers/chardev/Makefile b/examples/module/drivers/chardev/Makefile new file mode 100644 index 000000000..abf530f58 --- /dev/null +++ b/examples/module/drivers/chardev/Makefile @@ -0,0 +1,73 @@ +############################################################################ +# apps/examples/module/drivers/chardev/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +CMODULEFLAGS += $(KDEFINE) + +ifeq ($(CONFIG_EXAMPLES_MODULE_LIBGCC),y) +LIBGCC = "${shell $(CC) $(ARCHCPUFLAGS) -print-libgcc-file-name 2>/dev/null}" +ifneq ($(LIBGCC),) + LDLIBPATH += -L "${shell dirname $(LIBGCC)}" + LDLIBS += -lgcc +endif +endif + +ifeq ($(CONFIG_EXAMPLES_MODULE_LIBC),y) +LDMODULEFLAGS += -Bstatic +LDLIBPATH += -L $(NUTTXLIB) +endif + +ifeq ($(CONFIG_EXAMPLES_MODULE_LIBC),y) +ifneq ($(CONFIG_BUILD_FLAT),y) +LDLIBS += -lkc +else +LDLIBS += -lc +endif +endif + +BIN = chardev + +SRCS = $(BIN).c +OBJS = $(SRCS:.c=$(OBJEXT)) + +all: $(BIN) +.PHONY: all clean install + +$(OBJS): %$(OBJEXT): %.c + @echo "MODULECC: $<" + $(Q) $(MODULECC) -c $(CMODULEFLAGS) $< -o $@ + +$(BIN): $(OBJS) + @echo "MODULELD: $<" + $(Q) $(MODULELD) $(LDMODULEFLAGS) $(LDLIBPATH) -o $@ $(ARCHCRT0OBJ) $^ $(LDLIBS) + +$(FSROOT_DIR)/$(BIN): $(BIN) + $(Q) mkdir -p $(FSROOT_DIR) + $(Q) install $(BIN) $(FSROOT_DIR)/$(BIN) +ifneq ($(CONFIG_DEBUG_SYMBOLS),y) + $(Q) $(MODULESTRIP) $(FSROOT_DIR)/$(BIN) +endif + +install: $(FSROOT_DIR)/$(BIN) + +clean: + $(call DELFILE, $(BIN)) + $(call CLEAN) diff --git a/examples/module/chardev/chardev.c b/examples/module/drivers/chardev/chardev.c similarity index 89% rename from examples/module/chardev/chardev.c rename to examples/module/drivers/chardev/chardev.c index aaf9f4911..a96f397df 100644 --- a/examples/module/chardev/chardev.c +++ b/examples/module/drivers/chardev/chardev.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/module/chardev/chardev.c + * apps/examples/module/drivers/chardev/chardev.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -101,13 +101,12 @@ static ssize_t chardev_write(FAR struct file *filep, FAR const char *buffer, * Name: module_uninitialize ****************************************************************************/ -__attribute__((destructor)) -void module_uninitialize(void) +static int module_uninitialize(FAR void *arg) { /* TODO: Check if there are any open references to the driver */ - syslog(LOG_INFO, "module_uninitialize\n"); - unregister_driver("/dev/chardev"); + syslog(LOG_INFO, "module_uninitialize: arg=%p\n", arg); + return unregister_driver("/dev/chardev"); } /**************************************************************************** @@ -122,9 +121,14 @@ void module_uninitialize(void) * ****************************************************************************/ -__attribute__((constructor)) -void module_initialize(void) +int module_initialize(FAR struct mod_info_s *modinfo) { - syslog(LOG_INFO, "module_initialize\n"); - register_driver("/dev/chardev", &g_chardev_fops, 0666, NULL); + syslog(LOG_INFO, "module_initialize:\n"); + + modinfo->uninitializer = module_uninitialize; + modinfo->arg = NULL; + modinfo->exports = NULL; + modinfo->nexports = 0; + + return register_driver("/dev/chardev", &g_chardev_fops, 0666, NULL); } diff --git a/examples/module/main/.gitignore b/examples/module/main/.gitignore deleted file mode 100644 index 03d6e064e..000000000 --- a/examples/module/main/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/chardev_romfs.c -/chardev_romfs.img -/cromfs.c -/chardev_mod_symtab.c -/mod_symtab.c diff --git a/examples/module/main/Makefile b/examples/module/main/Makefile deleted file mode 100644 index c731bade5..000000000 --- a/examples/module/main/Makefile +++ /dev/null @@ -1,89 +0,0 @@ -############################################################################ -# apps/examples/module/main/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -# Module example built-in application info - -PROGNAME = module -PRIORITY = SCHED_PRIORITY_DEFAULT -STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) -MODULE = $(CONFIG_EXAMPLES_MODULE) - -MAINSRC = module_main.c - -SYMTABSRC = mod_symtab.c -SYMTABOBJ = $(SYMTABSRC:.c=$(OBJEXT)) - -$(SYMTABSRC): - $(Q) $(APPDIR)$(DELIM)tools$(DELIM)mksymtab.sh $(BINDIR) g_mod >$@.tmp - $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) - - -$(SYMTABOBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@, -fno-lto -fno-builtin) - -ifeq ($(CONFIG_EXAMPLES_MODULE_BUILTINFS),y) -ifeq ($(CONFIG_EXAMPLES_MODULE_ROMFS),y) - -ROMFSIMG = chardev_romfs.img -ROMFSSRC = chardev_romfs.c -ROMFSOBJ = $(ROMFSSRC:.c=$(OBJEXT)) - -$(ROMFSIMG): - $(Q) genromfs -d $(BINDIR) -f $@ - -$(ROMFSSRC): $(ROMFSIMG) - $(Q) (echo "#include " >$@ && \ - xxd -i $(ROMFSIMG) | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" >>$@) - -$(ROMFSOBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@, -fno-lto -fno-builtin) - -else ifeq ($(CONFIG_EXAMPLES_MODULE_CROMFS),y) - NXTOOLDIR = $(TOPDIR)/tools - GENCROMFSSRC = gencromfs.c - GENCROMFSEXE = gencromfs$(HOSTEXEEXT) - - FSIMG_SRC = cromfs.c - FSIMG_OBJ = $(FSIMG_SRC:.c=$(OBJEXT)) - -$(NXTOOLDIR)/$(GENCROMFSEXE): $(NXTOOLDIR)/$(GENCROMFSSRC) - $(Q) $(MAKE) -C $(NXTOOLDIR) -f Makefile.host $(GENCROMFSEXE) - -# Create the cromfs.c file from the populated cromfs directory - -$(FSIMG_SRC):$(NXTOOLDIR)/$(GENCROMFSEXE) - $(Q) $(NXTOOLDIR)/$(GENCROMFSEXE) $(BINDIR) $@.tmp - $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) - -$(FSIMG_OBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@, -fno-lto -fno-builtin) - -endif - -endif - -postinstall:: $(ROMFSOBJ) $(SYMTABOBJ) $(FSIMG_OBJ) - $(call ARLOCK, $(call CONVERT_PATH,$(BIN)), $^) - -distclean:: - $(Q) $(call DELFILE, $(SYMTABSRC) $(SYMTABOBJ) $(ROMFSSRC) $(ROMFSIMG) $(ROMFSOBJ)) - - -include $(APPDIR)/Application.mk diff --git a/examples/module/main/module_main.c b/examples/module/module_main.c similarity index 97% rename from examples/module/main/module_main.c rename to examples/module/module_main.c index 903aced65..3c72f5aa3 100644 --- a/examples/module/main/module_main.c +++ b/examples/module/module_main.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/module/main/module_main.c + * apps/examples/module/module_main.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -114,8 +114,8 @@ static const char g_write_string[] = "Hi there installed driver\n"; ****************************************************************************/ #if defined(CONFIG_EXAMPLES_MODULE_ROMFS) || defined(CONFIG_EXAMPLES_MODULE_CROMFS) -extern const unsigned char chardev_romfs_img[]; -extern const unsigned int chardev_romfs_img_len; +extern const unsigned char romfs_img[]; +extern const unsigned int romfs_img_len; #endif #ifdef CONFIG_BUILD_FLAT @@ -172,9 +172,9 @@ int main(int argc, FAR char *argv[]) CONFIG_EXAMPLES_MODULE_DEVMINOR); desc.minor = CONFIG_EXAMPLES_MODULE_DEVMINOR; /* Minor device number of the ROM disk. */ - desc.nsectors = NSECTORS(chardev_romfs_img_len); /* The number of sectors in the ROM disk */ + desc.nsectors = NSECTORS(romfs_img_len); /* The number of sectors in the ROM disk */ desc.sectsize = SECTORSIZE; /* The size of one sector in bytes */ - desc.image = (FAR uint8_t *)chardev_romfs_img; /* File system image */ + desc.image = (FAR uint8_t *)romfs_img; /* File system image */ ret = boardctl(BOARDIOC_ROMDISK, (uintptr_t)&desc); if (ret < 0) diff --git a/examples/mqttc/README.md b/examples/mqttc/README.md deleted file mode 100644 index 28f562a0f..000000000 --- a/examples/mqttc/README.md +++ /dev/null @@ -1,25 +0,0 @@ -This is a simple MQTT publisher example using MQTT-C - -By default it publishes to the "test" topic and exits. Default behaviour -including, host, port, topic, message and loop count can be changed through -different arguments. - -To test: -From the host start an MQTT broker and subscribe to the "test" topic. Here -mosquitto is used: - -``` -mosquitto& -mosquitto_sub -t test -``` -Make sure that mosquitto is not configured in local mode only. - -From the nsh: - -Launch the built-in app `mqttc_pub` specifying the host: - -``` -mqttc_pub -h HOST -``` - -The target will publish the message "test". diff --git a/examples/mqttc/mqttc_pub.c b/examples/mqttc/mqttc_pub.c index c22fc569e..ac06944db 100644 --- a/examples/mqttc/mqttc_pub.c +++ b/examples/mqttc/mqttc_pub.c @@ -100,7 +100,7 @@ static void parsearg(int argc, FAR char *argv[], { int opt; - while ((opt = getopt(argc, argv, "h:p:m:t:n:")) != ERROR) + while ((opt = getopt(argc, argv, "h:p:m:t:n:q:")) != ERROR) { switch (opt) { @@ -124,6 +124,21 @@ static void parsearg(int argc, FAR char *argv[], *n = strtol(optarg, NULL, 10); break; + case 'q': + switch (strtol(optarg, NULL, 10)) + { + case '0': + cfg->qos = MQTT_PUBLISH_QOS_0; + break; + case '1': + cfg->qos = MQTT_PUBLISH_QOS_1; + break; + case '2': + cfg->qos = MQTT_PUBLISH_QOS_2; + break; + } + break; + default: fprintf(stderr, "ERROR: Unrecognized option\n"); break; diff --git a/examples/netloop/lo_listener.c b/examples/netloop/lo_listener.c index 84b057290..6e85c35a9 100644 --- a/examples/netloop/lo_listener.c +++ b/examples/netloop/lo_listener.c @@ -182,7 +182,7 @@ static inline bool net_connection(struct net_listener_s *nls) printf("lo_listener: Accepting new connection on sd=%d\n", nls->listensd); - sd = accept4(nls->listensd, NULL, NULL, SOCK_CLOEXEC); + sd = accept(nls->listensd, NULL, NULL); if (sd < 0) { printf("lo_listener: accept failed: %d\n", errno); diff --git a/examples/nettest/nettest_cmdline.c b/examples/nettest/nettest_cmdline.c index 76736d79d..af8ed5e69 100644 --- a/examples/nettest/nettest_cmdline.c +++ b/examples/nettest/nettest_cmdline.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/nettest/netest_cmdline.c + * apps/examples/nettest/nettest_cmdline.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with diff --git a/examples/nettest/nettest_server.c b/examples/nettest/nettest_server.c index ef686e2d1..4ce399f15 100644 --- a/examples/nettest/nettest_server.c +++ b/examples/nettest/nettest_server.c @@ -145,8 +145,7 @@ void nettest_server(void) printf("server: Accepting connections on port %d\n", CONFIG_EXAMPLES_NETTEST_SERVER_PORTNO); - acceptsd = accept4(listensd, (struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (struct sockaddr *)&myaddr, &addrlen); if (acceptsd < 0) { printf("server: accept failure: %d\n", errno); diff --git a/examples/nxdemo/nxdemo_listener.c b/examples/nxdemo/nxdemo_listener.c index a5042a077..430b90039 100644 --- a/examples/nxdemo/nxdemo_listener.c +++ b/examples/nxdemo/nxdemo_listener.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/nxterm/nxdemo_listener.c + * apps/examples/nxdemo/nxdemo_listener.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -46,7 +46,7 @@ FAR void *nxdemo_listener(FAR void *arg) /* Process events forever */ - for (;;) + for (; ; ) { /* Handle the next event. If we were configured blocking, then * we will stay right here until the next event is received. Since diff --git a/examples/nxflat/tests/task/task.c b/examples/nxflat/tests/task/task.c index f543dc19b..e77dc8875 100644 --- a/examples/nxflat/tests/task/task.c +++ b/examples/nxflat/tests/task/task.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/nxflat/tests/task/parent.c + * apps/examples/nxflat/tests/task/task.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -47,9 +47,10 @@ static char no_name[] = ""; * Privite Functions ****************************************************************************/ -/* NOTE: it is necessary for functions that are referred to by function pointers - * pointer to be declared with global scope (at least for ARM). Otherwise, - * a relocation type that is not supported by NXFLAT is generated by GCC. +/* NOTE: it is necessary for functions that are referred to by function + * pointers pointer to be declared with global scope (at least for ARM). + * Otherwise, a relocation type that is not supported by + * NXFLAT is generated by GCC. */ int child_task(int argc, char **argv) @@ -113,7 +114,8 @@ int main(int argc, char **argv) child_argv[0] = child_arg; child_argv[1] = 0; - child_pid = task_create(child_name, 50, 512, child_task, (FAR char * const *)child_argv); + child_pid = task_create(child_name, 50, 512, + child_task, (FAR char * const *)child_argv); if (child_pid < 0) { printf("Parent: task_create failed: %d\n", errno); diff --git a/examples/nximage/nximage_listener.c b/examples/nximage/nximage_listener.c index 84d4e47ca..f92f10b87 100644 --- a/examples/nximage/nximage_listener.c +++ b/examples/nximage/nximage_listener.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/nxterm/nximage_listener.c + * apps/examples/nximage/nximage_listener.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -46,7 +46,7 @@ FAR void *nximage_listener(FAR void *arg) /* Process events forever */ - for (;;) + for (; ; ) { /* Handle the next event. If we were configured blocking, then * we will stay right here until the next event is received. Since diff --git a/examples/nxlines/nxlines_listener.c b/examples/nxlines/nxlines_listener.c index 8bb4d9d94..452e2b658 100644 --- a/examples/nxlines/nxlines_listener.c +++ b/examples/nxlines/nxlines_listener.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/nxterm/nxlines_listener.c + * apps/examples/nxlines/nxlines_listener.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -46,7 +46,7 @@ FAR void *nxlines_listener(FAR void *arg) /* Process events forever */ - for (;;) + for (; ; ) { /* Handle the next event. If we were configured blocking, then * we will stay right here until the next event is received. Since diff --git a/examples/nxscope/Kconfig b/examples/nxscope/Kconfig index 33cabeb61..b29f97f26 100644 --- a/examples/nxscope/Kconfig +++ b/examples/nxscope/Kconfig @@ -33,6 +33,8 @@ config EXAMPLES_NXSCOPE_SERIAL_PATH config EXAMPLES_NXSCOPE_SERIAL_BAUD int "nxscope serial baud" default 115200 + ---help--- + Ignored if set to 0 (for example for RTT interface) config EXAMPLES_NXSCOPE_CDCACM bool "nxscope CDCACM device support" @@ -53,6 +55,10 @@ config EXAMPLES_NXSCOPE_RXBUF_LEN int "nxscope RX buffer length" default 32 +config EXAMPLES_NXSCOPE_CHARLOG + bool "nxscope send text message over channel 19" + default n + config EXAMPLES_NXSCOPE_CRIBUF_LEN int "nxscope critical channels buffer length" default 32 @@ -66,6 +72,13 @@ config EXAMPLES_NXSCOPE_TIMER bool "nxscope use timer to wake up samples thread" default n +config EXAMPLES_NXSCOPE_MAIN_INTERVAL + int "nxscope main interval (microseconds)" + default 100000 + ---help--- + This value is responsible for the frequency at which stream + frames will be sent and incoming frames will be received. + if EXAMPLES_NXSCOPE_TIMER config EXAMPLES_NXSCOPE_TIMER_PATH diff --git a/examples/nxscope/nxscope_main.c b/examples/nxscope/nxscope_main.c index 6a63e2c69..bfdfadcbc 100644 --- a/examples/nxscope/nxscope_main.c +++ b/examples/nxscope/nxscope_main.c @@ -30,6 +30,7 @@ #include #include #include +#include #ifdef CONFIG_EXAMPLES_NXSCOPE_TIMER # include @@ -41,6 +42,16 @@ #include "logging/nxscope/nxscope.h" +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifdef CONFIG_LIBM_NONE +# error "math library must be selected for this example" +#endif + +#define SIN_DT (0.01f) + /**************************************************************************** * Private Type Definition ****************************************************************************/ @@ -58,7 +69,7 @@ struct nxscope_thr_env_s * Name: nxscope_cb_userid ****************************************************************************/ -int nxscope_cb_userid(FAR void *priv, uint8_t id, FAR uint8_t *buff) +static int nxscope_cb_userid(FAR void *priv, uint8_t id, FAR uint8_t *buff) { UNUSED(priv); @@ -71,7 +82,7 @@ int nxscope_cb_userid(FAR void *priv, uint8_t id, FAR uint8_t *buff) * Name: nxscope_cb_start ****************************************************************************/ -int nxscope_cb_start(FAR void *priv, bool start) +static int nxscope_cb_start(FAR void *priv, bool start) { UNUSED(priv); @@ -197,14 +208,14 @@ static FAR void *nxscope_samples_thr(FAR void *arg) sigaddset(&set, CONFIG_EXAMPLES_NXSCOPE_TIMER_SIGNO); #endif - /* Initialize float vector */ - - v[0] = -1.0f; - v[1] = 0.0f; - v[2] = 1.0f; - while (1) { + /* Float vector - tree-phase sine waveform */ + + v[0] = sinf(i * SIN_DT); + v[1] = sinf(i * SIN_DT + (2.0f / 3.0f) * M_PI); + v[2] = sinf(i * SIN_DT + (4.0f / 3.0f) * M_PI); + /* Channel 0 */ nxscope_put_uint8(envp->nxs, 0, i); @@ -309,6 +320,7 @@ errout: return NULL; } +#ifdef CONFIG_EXAMPLES_NXSCOPE_CHARLOG /**************************************************************************** * Name: nxscope_charlog_thr ****************************************************************************/ @@ -336,6 +348,7 @@ static FAR void *nxscope_charlog_thr(FAR void *arg) return NULL; } +#endif #ifdef CONFIG_LOGGING_NXSCOPE_CRICHANNELS /**************************************************************************** @@ -621,12 +634,14 @@ int main(int argc, FAR char *argv[]) u.s.cri = 0; nxscope_chan_init(&nxs, 18, "chan18", u.u8, 0, 4); +#ifdef CONFIG_EXAMPLES_NXSCOPE_CHARLOG /* Char channel with metadata */ u.s.dtype = NXSCOPE_TYPE_CHAR; u.s._res = 0; u.s.cri = 0; nxscope_chan_init(&nxs, 19, "chan19", u.u8, 64, 4); +#endif #ifdef CONFIG_LOGGING_NXSCOPE_CRICHANNELS /* Critical channel */ @@ -649,6 +664,7 @@ int main(int argc, FAR char *argv[]) goto errout; } +#ifdef CONFIG_EXAMPLES_NXSCOPE_CHARLOG /* Create char log thread */ env.nxs = &nxs; @@ -658,6 +674,7 @@ int main(int argc, FAR char *argv[]) printf("ERROR: pthread_create failed %d\n", ret); goto errout; } +#endif #ifdef CONFIG_LOGGING_NXSCOPE_CRICHANNELS /* Create critical channel thread */ @@ -698,7 +715,7 @@ int main(int argc, FAR char *argv[]) printf("ERROR: nxscope_recv failed %d\n", ret); } - usleep(100000); + usleep(CONFIG_EXAMPLES_NXSCOPE_MAIN_INTERVAL); } errout: diff --git a/examples/pdcurses/README.md b/examples/pdcurses/README.md deleted file mode 100644 index 2bce03f9c..000000000 --- a/examples/pdcurses/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Examples / `pdcurses` PDCurses Demos - -This directory contains demonstration programs to show and test the capabilities -of `pdcurses` libraries. Some of them predate PDCurses, PCcurses or even -`pcurses`/`ncurses`. Although some PDCurses-specific code has been added, all -programs remain portable to other implementations (at a minimum, to `ncurses`). - -## Building - -The demos are built by the platform-specific makefiles, in the platform -directories. There are no dependencies besides curses and the standard C -library, and no configuration is needed. - -## Distribution Status - -Public Domain, except for `rain_main.c` and `worm_main.c`, which are under the -ncurses license (MIT-like). diff --git a/examples/pdcurses/tui.h b/examples/pdcurses/tui.h index f7abba784..c15db5610 100644 --- a/examples/pdcurses/tui.h +++ b/examples/pdcurses/tui.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/pdcurses/tui.c + * apps/examples/pdcurses/tui.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with diff --git a/examples/pipe/pipe.h b/examples/pipe/pipe.h index 14931607a..304fb8e16 100644 --- a/examples/pipe/pipe.h +++ b/examples/pipe/pipe.h @@ -48,8 +48,7 @@ * Public Function Prototypes ****************************************************************************/ -extern int transfer_test(int fdin, int fdout, - int boost_reader, int boost_writer); +extern int transfer_test(int fdin, int fdout); extern int interlock_test(void); extern int redirection_test(void); diff --git a/examples/pipe/pipe_main.c b/examples/pipe/pipe_main.c index 8d70d158c..697afe5f9 100644 --- a/examples/pipe/pipe_main.c +++ b/examples/pipe/pipe_main.c @@ -137,37 +137,7 @@ int main(int argc, FAR char *argv[]) /* Then perform the test using those file descriptors */ - ret = transfer_test(fd[0], fd[1], 0, 0); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: FIFO test FAILED (00) (%d)\n", ret); - return 6; - } - - ret = transfer_test(fd[0], fd[1], 1, 0); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: FIFO test FAILED (10) (%d)\n", ret); - return 6; - } - - ret = transfer_test(fd[0], fd[1], 0, 1); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: FIFO test FAILED (01)(%d)\n", ret); - return 6; - } - - ret = transfer_test(fd[0], fd[1], 1, 1); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: FIFO test FAILED (11) (%d)\n", ret); - return 6; - } + ret = transfer_test(fd[0], fd[1]); if (close(fd[0]) != 0) { @@ -179,6 +149,20 @@ int main(int argc, FAR char *argv[]) fprintf(stderr, "pipe_main: close failed: %d\n", errno); } + /* unlink(FIFO_PATH1); fails */ + + if (ret != 0) + { + fprintf(stderr, "pipe_main: FIFO test FAILED (%d)\n", ret); + return 6; + } + + ret = remove(FIFO_PATH1); + if (ret != 0) + { + fprintf(stderr, "pipe_main: remove failed with errno=%d\n", errno); + } + /* Perform the FIFO interlock test */ fprintf(stderr, "\npipe_main: Performing pipe interlock test\n"); @@ -212,37 +196,7 @@ int main(int argc, FAR char *argv[]) /* Then perform the test using those file descriptors */ - ret = transfer_test(fd[0], fd[1], 0, 0); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: PIPE test FAILED (00) (%d)\n", ret); - return 9; - } - - ret = transfer_test(fd[0], fd[1], 1, 0); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: PIPE test FAILED (10) (%d)\n", ret); - return 9; - } - - ret = transfer_test(fd[0], fd[1], 0, 1); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: PIPE test FAILED (01) (%d)\n", ret); - return 9; - } - - ret = transfer_test(fd[0], fd[1], 1, 1); - - if (ret != 0) - { - fprintf(stderr, "pipe_main: PIPE test FAILED (11) (%d)\n", ret); - return 9; - } + ret = transfer_test(fd[0], fd[1]); if (close(fd[0]) != 0) { @@ -254,6 +208,12 @@ int main(int argc, FAR char *argv[]) fprintf(stderr, "pipe_main: close failed: %d\n", errno); } + if (ret != 0) + { + fprintf(stderr, "pipe_main: PIPE test FAILED (%d)\n", ret); + return 9; + } + /* Perform the pipe redirection test */ fprintf(stderr, "\npipe_main: Performing redirection test\n"); diff --git a/examples/pipe/transfer_test.c b/examples/pipe/transfer_test.c index a7ae26d11..fcba4413b 100644 --- a/examples/pipe/transfer_test.c +++ b/examples/pipe/transfer_test.c @@ -176,34 +176,21 @@ static void *transfer_writer(pthread_addr_t pvarg) * Name: transfer_test ****************************************************************************/ -int transfer_test(int fdin, int fdout, int boost_reader, int boost_writer) +int transfer_test(int fdin, int fdout) { pthread_t readerid; pthread_t writerid; - pthread_attr_t rattr; - pthread_attr_t wattr; void *value; int tmp; int ret; printf("transfer_test: fdin=%d fdout=%d\n", fdin, fdout); - /* Boost the priority of reader or writer on need */ - - pthread_attr_init(&rattr); - if (boost_reader) - { - rattr.priority += 1; - printf("transfer_test: Boost priority of transfer_reader" - "thread to %d\n", rattr.priority); - } - /* Start transfer_reader thread */ printf("transfer_test: Starting transfer_reader thread\n"); - ret = pthread_create(&readerid, &rattr, + ret = pthread_create(&readerid, NULL, \ transfer_reader, (void *)(intptr_t)fdin); - pthread_attr_destroy(&rattr); if (ret != 0) { fprintf(stderr, \ @@ -212,22 +199,11 @@ int transfer_test(int fdin, int fdout, int boost_reader, int boost_writer) return 1; } - /* Boost the priority of reader or writer on need */ - - pthread_attr_init(&wattr); - if (boost_writer) - { - wattr.priority += 1; - printf("transfer_test: Boost priority of transfer_writer" - "thread to %d\n", wattr.priority); - } - /* Start transfer_writer thread */ printf("transfer_test: Starting transfer_writer thread\n"); - ret = pthread_create(&writerid, &wattr, - transfer_writer, (void *)(intptr_t)fdout); - pthread_attr_destroy(&wattr); + ret = pthread_create(&writerid, \ + NULL, transfer_writer, (void *)(intptr_t)fdout); if (ret != 0) { fprintf(stderr, \ diff --git a/examples/poll/net_listener.c b/examples/poll/net_listener.c index 3f04ea771..136b19e43 100644 --- a/examples/poll/net_listener.c +++ b/examples/poll/net_listener.c @@ -182,7 +182,7 @@ static inline bool net_connection(struct net_listener_s *nls) printf("net_listener: Accepting new connection on sd=%d\n", nls->listensd); - sd = accept4(nls->listensd, NULL, NULL, SOCK_CLOEXEC); + sd = accept(nls->listensd, NULL, NULL); if (sd < 0) { printf("net_listener: accept failed: %d\n", errno); diff --git a/examples/poll/net_reader.c b/examples/poll/net_reader.c index c60de4700..16dd676ca 100644 --- a/examples/poll/net_reader.c +++ b/examples/poll/net_reader.c @@ -278,8 +278,7 @@ void *net_reader(pthread_addr_t pvarg) printf("net_reader: Accepting new connections on port %d\n", LISTENER_PORT); addrlen = sizeof(struct sockaddr_in); - acceptsd = accept4(listensd, (struct sockaddr *)&addr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (struct sockaddr *)&addr, &addrlen); if (acceptsd < 0) { printf("net_reader: accept failure: %d\n", errno); diff --git a/system/nxcodec/CMakeLists.txt b/examples/rmtchar/CMakeLists.txt similarity index 72% rename from system/nxcodec/CMakeLists.txt rename to examples/rmtchar/CMakeLists.txt index fcb19d80e..0adae0913 100644 --- a/system/nxcodec/CMakeLists.txt +++ b/examples/rmtchar/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/system/nxcodec/CMakeLists.txt +# apps/examples/rmtchar/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,19 +18,21 @@ # # ############################################################################## -if(CONFIG_SYSTEM_NXCODEC) +if(CONFIG_EXAMPLES_RMTCHAR) nuttx_add_application( NAME - ${CONFIG_SYSTEM_NXCODEC_PROGNAME} - PRIORITY - ${CONFIG_SYSTEM_NXCODEC_PRIORITY} + rmtchar STACKSIZE - ${CONFIG_SYSTEM_NXCODEC_STACKSIZE} + ${CONFIG_DEFAULT_TASK_STACKSIZE} MODULE - ${CONFIG_SYSTEM_NXCODEC} + ${CONFIG_EXAMPLES_RMTCHAR} SRCS - nxcodec_main.c) - - set(CSRCS nxcodec.c nxcodec_context.c) - target_sources(apps PRIVATE ${CSRCS}) + rmtchar_common.c + rmtchar_main.c) + if(CONFIG_EXAMPLES_RMTCHAR_TX) + target_sources(apps PRIVATE rmtchar_transmitter.c) + endif() + if(CONFIG_EXAMPLES_RMTCHAR_RX) + target_sources(apps PRIVATE rmtchar_receiver.c) + endif() endif() diff --git a/examples/rmtchar/Kconfig b/examples/rmtchar/Kconfig new file mode 100644 index 000000000..8831f56a2 --- /dev/null +++ b/examples/rmtchar/Kconfig @@ -0,0 +1,68 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config EXAMPLES_RMTCHAR + tristate "RMT character driver test" + default n + depends on RMT + ---help--- + Enable the RMT character driver test + +if EXAMPLES_RMTCHAR + +config EXAMPLES_RMTCHAR_TX + bool "Use RMT transmitter" + default n + ---help--- + This should be set if the RMT device supports a transmitter. + +if EXAMPLES_RMTCHAR_TX + +config EXAMPLES_RMTCHAR_TX_DEVPATH + string "RMT transmitter character device path" + default "/dev/rmt0" + ---help--- + The default path to the RMT transmitter character device. + Default: /dev/rmt0 + +config EXAMPLES_RMTCHAR_TXSTACKSIZE + int "Transmitter thread stack size" + default DEFAULT_TASK_STACKSIZE + ---help--- + This is the stack size to use when starting the transmitter thread. + +endif # EXAMPLES_RMTCHAR_TX + +config EXAMPLES_RMTCHAR_RX + bool "Use RMT receiver" + default n + ---help--- + This should be set if the RMT device supports a receiver. + +if EXAMPLES_RMTCHAR_RX + +config EXAMPLES_RMTCHAR_RX_DEVPATH + string "RMT receiver character device path" + default "/dev/rmt1" + ---help--- + The default path to the RMT receiver character device. + Default: /dev/rmt1 + +config EXAMPLES_RMTCHAR_RXSTACKSIZE + int "Receiver thread stack size" + default DEFAULT_TASK_STACKSIZE + ---help--- + This is the stack size to use when starting the receiver thread. + +endif # EXAMPLES_RMTCHAR_RX + +config EXAMPLES_RMTCHAR_ITEMS + int "Number of words to transmit or receive" + default 64 + ---help--- + This is the total amount of words to be transmitted or + received by the RMT RX device. + +endif diff --git a/examples/rmtchar/Make.defs b/examples/rmtchar/Make.defs new file mode 100644 index 000000000..e6550150c --- /dev/null +++ b/examples/rmtchar/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/examples/rmtchar/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_EXAMPLES_RMTCHAR),) +CONFIGURED_APPS += $(APPDIR)/examples/rmtchar +endif diff --git a/examples/rmtchar/Makefile b/examples/rmtchar/Makefile new file mode 100644 index 000000000..342cb6ec4 --- /dev/null +++ b/examples/rmtchar/Makefile @@ -0,0 +1,41 @@ +############################################################################ +# apps/examples/rmtchar/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +# rmt character driver test + +ifeq ($(CONFIG_EXAMPLES_RMTCHAR_TX),y) +CSRCS += rmtchar_transmitter.c +endif +ifeq ($(CONFIG_EXAMPLES_RMTCHAR_RX),y) +CSRCS += rmtchar_receiver.c +endif +CSRCS += rmtchar_common.c +MAINSRC = rmtchar_main.c + +# Touchscreen built-in application info + +PROGNAME = rmtchar +PRIORITY = SCHED_PRIORITY_DEFAULT +STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_RMTCHAR) + +include $(APPDIR)/Application.mk diff --git a/examples/rmtchar/rmtchar.h b/examples/rmtchar/rmtchar.h new file mode 100644 index 000000000..2d89479bf --- /dev/null +++ b/examples/rmtchar/rmtchar.h @@ -0,0 +1,127 @@ +/**************************************************************************** + * apps/examples/rmtchar/rmtchar.h + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +#ifndef __APPS_EXAMPLES_RMTCHAR_RMTCHAR_H +#define __APPS_EXAMPLES_RMTCHAR_RMTCHAR_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* Configuration */ + +#ifndef CONFIG_EXAMPLES_RMTCHAR_TX_DEVPATH +# define CONFIG_EXAMPLES_RMTCHAR_TX_DEVPATH "/dev/rmt0" +#endif + +#ifndef CONFIG_EXAMPLES_RMTCHAR_RX_DEVPATH +# define CONFIG_EXAMPLES_RMTCHAR_RX_DEVPATH "/dev/rmt1" +#endif + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +struct rmtchar_state_s +{ + bool initialized; + int rmtchar_items; +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + FAR char *txdevpath; +#endif +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + FAR char *rxdevpath; +#endif +}; + +struct rmt_item32_s +{ + union + { + struct + { + uint32_t duration0 : 15; /* Duration of level0 */ + uint32_t level0 : 1; /* Level of the first part */ + uint32_t duration1 : 15; /* Duration of level1 */ + uint32_t level1 : 1; /* Level of the second part */ + }; + uint32_t val; /* Equivalent unsigned value for the RMT item */ + }; +}; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Name: rmtchar_transmitter() + * + * Description: + * This is the entry point for the transmitter thread. + * + ****************************************************************************/ + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX +pthread_addr_t rmtchar_transmitter(pthread_addr_t arg); +#endif + +/**************************************************************************** + * Name: rmtchar_receiver() + * + * Description: + * This is the entry point for the receiver thread. + * + ****************************************************************************/ + +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX +pthread_addr_t rmtchar_receiver(pthread_addr_t arg); +#endif + +/**************************************************************************** + * Name: print_items + * + * Description: + * This function prints the level and duration of RMT items stored in a + * buffer. It iterates over the buffer, printing the level and duration of + * each item in a formatted manner. + * + * Input Parameters: + * buf - Pointer to the buffer containing the RMT items. + * len - The number of RMT items in the buffer. + * + * Returned Value: + * None. + * + ****************************************************************************/ + +void print_items(struct rmt_item32_s *buf, int len); + +#endif /* __APPS_EXAMPLES_RMTCHAR_RMTCHAR_H */ diff --git a/testing/gpu/gpu_recorder.c b/examples/rmtchar/rmtchar_common.c similarity index 59% rename from testing/gpu/gpu_recorder.c rename to examples/rmtchar/rmtchar_common.c index 72efd159f..f7d1a4d9d 100644 --- a/testing/gpu/gpu_recorder.c +++ b/examples/rmtchar/rmtchar_common.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/gpu_recorder.c + * apps/examples/rmtchar/rmtchar_common.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -22,13 +22,17 @@ * Included Files ****************************************************************************/ -#include "gpu_recorder.h" -#include "gpu_test.h" -#include -#include -#include +#include + +#include #include -#include +#include +#include +#include +#include +#include + +#include "rmtchar.h" /**************************************************************************** * Pre-processor Definitions @@ -38,88 +42,50 @@ * Private Types ****************************************************************************/ -struct gpu_recorder_s -{ - FAR struct gpu_test_context_s *ctx; - int fd; -}; +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** - * Name: gpu_recorder_create + * Name: print_items + * + * Description: + * This function prints the level and duration of RMT items stored in a + * buffer. It iterates over the buffer, printing the level and duration of + * each item in a formatted manner. + * + * Input Parameters: + * buf - Pointer to the buffer containing the RMT items. + * len - The number of RMT items in the buffer. + * + * Returned Value: + * None. + * ****************************************************************************/ -FAR struct gpu_recorder_s *gpu_recorder_create( - FAR struct gpu_test_context_s *ctx, - const char *name) +void print_items(struct rmt_item32_s *buf, int len) { - FAR struct gpu_recorder_s *recorder; - char path[PATH_MAX]; - char filename[64]; - gpu_get_localtime_str(filename, sizeof(filename)); + int i; - snprintf(path, sizeof(path), "%s/report_%s_%s.csv", - ctx->param.output_dir, name, filename); - - int fd = open(path, O_CREAT | O_WRONLY | O_CLOEXEC, 0666); - - if (fd < 0) + for (i = 0; i < len; i++, buf++) { - GPU_LOG_ERROR("open %s failed", path); - return NULL; + printf("\t[%d]:\tL %d\tD %d\t", i, buf->level0, buf->duration0); + printf("L %d\t D %d\n", buf->level1, buf->duration1); } - - recorder = calloc(1, sizeof(struct gpu_recorder_s)); - GPU_ASSERT_NULL(recorder); - recorder->fd = fd; - recorder->ctx = ctx; - GPU_LOG_WARN("recorder file: %s created, fd = %d", path, fd); - return recorder; -} - -/**************************************************************************** - * Name: gpu_recorder_delete - ****************************************************************************/ - -void gpu_recorder_delete(FAR struct gpu_recorder_s *recorder) -{ - GPU_ASSERT_NULL(recorder); - close(recorder->fd); - free(recorder); - GPU_LOG_WARN("recorder deleted"); -} - -/**************************************************************************** - * Name: gpu_recorder_write_string - ****************************************************************************/ - -int gpu_recorder_write_string(FAR struct gpu_recorder_s *recorder, - FAR const char *str) -{ - GPU_ASSERT_NULL(recorder); - GPU_ASSERT_NULL(str); - size_t len = strlen(str); - size_t written = 0; - - while (written < len) - { - ssize_t ret = write(recorder->fd, str + written, len - written); - - if (ret < 0) - { - GPU_LOG_ERROR("write failed: %d", errno); - return ERROR; - } - - written += ret; - } - - return OK; } diff --git a/examples/rmtchar/rmtchar_main.c b/examples/rmtchar/rmtchar_main.c new file mode 100644 index 000000000..d57c815be --- /dev/null +++ b/examples/rmtchar/rmtchar_main.c @@ -0,0 +1,360 @@ +/**************************************************************************** + * apps/examples/rmtchar/rmtchar_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "rmtchar.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#if !defined(CONFIG_EXAMPLES_RMTCHAR_RX) && \ + !defined(CONFIG_EXAMPLES_RMTCHAR_TX) +# error "At least one of CONFIG_EXAMPLES_RMTCHAR_RX or \ + CONFIG_EXAMPLES_RMTCHAR_TX must be defined" +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static struct rmtchar_state_s g_rmtchar; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: rmtchar_devpath + ****************************************************************************/ + +static void rmtchar_devpath(FAR struct rmtchar_state_s *rmtchar, + FAR const char *devpath, + bool is_tx) +{ + /* Get rid of any old device path */ + + if (is_tx) + { + if (rmtchar->txdevpath) + { + free(rmtchar->txdevpath); + } + + /* Then set-up the new device path by copying the string */ + + rmtchar->txdevpath = strdup(devpath); + } + else + { + if (rmtchar->rxdevpath) + { + free(rmtchar->rxdevpath); + } + + /* Then set-up the new device path by copying the string */ + + rmtchar->rxdevpath = strdup(devpath); + } +} + +/**************************************************************************** + * Name: rmtchar_help + ****************************************************************************/ + +static void rmtchar_help(FAR struct rmtchar_state_s *rmtchar) +{ + printf("Usage: rmtchar [OPTIONS]\n"); + printf("\nArguments are \"sticky\".\n"); + printf("For example, once the RMT character device is\n"); + printf("specified, that device will be re-used until it is changed.\n"); + printf("\n\"sticky\" OPTIONS include:\n"); + printf(" [-i items] selects the number of words (items) to be transmitted" + " or received by the RMT character device. " + "Default: %d Current: %d\n", + CONFIG_EXAMPLES_RMTCHAR_ITEMS, + rmtchar->rmtchar_items ? rmtchar->rmtchar_items : + CONFIG_EXAMPLES_RMTCHAR_ITEMS); +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + printf(" [-t devpath] selects the RMT transmitter character device path. " + "Default: %s Current: %s\n", + CONFIG_EXAMPLES_RMTCHAR_TX_DEVPATH, + rmtchar->txdevpath ? rmtchar->txdevpath : "NONE"); +#endif +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + printf(" [-r devpath] selects the RMT receiver character device path. " + "Default: %s Current: %s\n", + CONFIG_EXAMPLES_RMTCHAR_RX_DEVPATH, + rmtchar->rxdevpath ? rmtchar->rxdevpath : "NONE"); +#endif + printf(" [-h] shows this message and exits\n"); +} + +/**************************************************************************** + * Name: arg_string + ****************************************************************************/ + +static int arg_string(FAR char **arg, FAR char **value) +{ + FAR char *ptr = *arg; + + if (ptr[2] == '\0') + { + *value = arg[1]; + return 2; + } + else + { + *value = &ptr[2]; + return 1; + } +} + +/**************************************************************************** + * Name: arg_decimal + ****************************************************************************/ + +static int arg_decimal(FAR char **arg, FAR int *value) +{ + FAR char *string; + int ret; + + ret = arg_string(arg, &string); + *value = strtol(string, NULL, 10); + return ret; +} + +/**************************************************************************** + * Name: parse_args + ****************************************************************************/ + +static void parse_args(FAR struct rmtchar_state_s *rmtchar, + int argc, + FAR char **argv) +{ + FAR char *ptr; + FAR char *str; + int value; + int index; + int nargs; + + for (index = 1; index < argc; ) + { + ptr = argv[index]; + if (ptr[0] != '-') + { + printf("Invalid options format: %s\n", ptr); + exit(0); + } + + switch (ptr[1]) + { + case 'i': + nargs = arg_decimal(&argv[index], &value); + if (value < 0) + { + printf("Count must be non-negative: %d\n", value); + exit(1); + } + + rmtchar->rmtchar_items = value; + index += nargs; + break; +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + case 't': + nargs = arg_string(&argv[index], &str); + rmtchar_devpath(rmtchar, str, true); + index += nargs; + break; +#endif + +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + case 'r': + nargs = arg_string(&argv[index], &str); + rmtchar_devpath(rmtchar, str, false); + index += nargs; + break; +#endif + case 'h': + rmtchar_help(rmtchar); + exit(0); + + default: + printf("Unsupported option: %s\n", ptr); + rmtchar_help(rmtchar); + exit(1); + } + } +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: rmtchar_main + ****************************************************************************/ + +int main(int argc, FAR char *argv[]) +{ + pthread_attr_t attr; + pthread_addr_t result; +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + pthread_t transmitter; +#endif +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + pthread_t receiver; +#endif +#if defined(CONFIG_EXAMPLES_RMTCHAR_RX) && defined(CONFIG_EXAMPLES_RMTCHAR_TX) + struct sched_param param; +#endif + int ret; + + UNUSED(ret); + + /* Check if we have initialized */ + + if (!g_rmtchar.initialized) + { + /* Set the default values */ + + g_rmtchar.rmtchar_items = CONFIG_EXAMPLES_RMTCHAR_ITEMS; + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + rmtchar_devpath(&g_rmtchar, CONFIG_EXAMPLES_RMTCHAR_TX_DEVPATH, true); +#endif +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + rmtchar_devpath(&g_rmtchar, CONFIG_EXAMPLES_RMTCHAR_RX_DEVPATH, false); +#endif + + g_rmtchar.initialized = true; + } + + /* Parse the command line */ + + parse_args(&g_rmtchar, argc, argv); + +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + /* Start the receiver thread */ + + printf("rmtchar_main: Start receiver thread\n"); + pthread_attr_init(&attr); + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + /* Bump the receiver priority from the default so that it will be above + * the priority of transmitter. This is important if a loopback test is + * being performed. + */ + + pthread_attr_getschedparam(&attr, ¶m); + param.sched_priority++; + pthread_attr_setschedparam(&attr, ¶m); +#endif + + /* Set the receiver stack size */ + + pthread_attr_setstacksize(&attr, CONFIG_EXAMPLES_RMTCHAR_RXSTACKSIZE); + + /* Start the receiver */ + + ret = pthread_create(&receiver, &attr, rmtchar_receiver, &g_rmtchar); + if (ret != OK) + { + printf("rmtchar_main: ERROR: failed to Start receiver thread: %d\n", + ret); + return EXIT_FAILURE; + } + + pthread_setname_np(receiver, "receiver"); +#endif + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + /* Start the transmitter thread */ + + printf("rmtchar_main: Start transmitter thread\n"); + pthread_attr_init(&attr); + + /* Set the transmitter stack size */ + + pthread_attr_setstacksize(&attr, CONFIG_EXAMPLES_RMTCHAR_TXSTACKSIZE); + + /* Start the transmitter */ + + ret = pthread_create(&transmitter, &attr, rmtchar_transmitter, &g_rmtchar); + if (ret != OK) + { + printf("rmtchar_main: ERROR: failed to Start transmitter thread: %d\n", + ret); +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + printf("rmtchar_main: Waiting for the receiver thread\n"); + pthread_join(receiver, &result); +#endif + return EXIT_FAILURE; + } + + pthread_setname_np(transmitter, "transmitter"); +#endif + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + printf("rmtchar_main: Waiting for the transmitter thread\n"); + ret = pthread_join(transmitter, &result); + if (ret != OK) + { + printf("rmtchar_main: ERROR: pthread_join failed: %d\n", ret); + } +#endif + +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX + printf("rmtchar_main: Waiting for the receiver thread\n"); + ret = pthread_join(receiver, &result); + if (ret != OK) + { + printf("rmtchar_main: ERROR: pthread_join failed: %d\n", ret); + } +#endif + + return EXIT_SUCCESS; +} diff --git a/testing/gpu/vg_lite/vg_lite_test_case_path_glyph.c b/examples/rmtchar/rmtchar_receiver.c similarity index 53% rename from testing/gpu/vg_lite/vg_lite_test_case_path_glyph.c rename to examples/rmtchar/rmtchar_receiver.c index ccbced01b..1f1e16a5f 100644 --- a/testing/gpu/vg_lite/vg_lite_test_case_path_glyph.c +++ b/examples/rmtchar/rmtchar_receiver.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/vg_lite/vg_lite_test_case_path_glyph.c + * apps/examples/rmtchar/rmtchar_receiver.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -22,8 +22,19 @@ * Included Files ****************************************************************************/ -#include "vg_lite_test_utils.h" -#include "resource/glphy_paths.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "rmtchar.h" + +#ifdef CONFIG_EXAMPLES_RMTCHAR_RX /**************************************************************************** * Pre-processor Definitions @@ -41,6 +52,10 @@ * Private Data ****************************************************************************/ +/**************************************************************************** + * Public Data + ****************************************************************************/ + /**************************************************************************** * Private Functions ****************************************************************************/ @@ -50,107 +65,74 @@ ****************************************************************************/ /**************************************************************************** - * Name: vg_lite_test_path_glyph + * Name: rmtchar_receiver() + * + * Description: + * This is the entry point for the receiver thread. + * ****************************************************************************/ -vg_lite_error_t vg_lite_test_path_glyph( - FAR struct gpu_test_context_s *ctx) +pthread_addr_t rmtchar_receiver(pthread_addr_t arg) { - vg_lite_error_t error = VG_LITE_SUCCESS; - vg_lite_matrix_t matrix; + FAR struct rmtchar_state_s *rmtchar = (FAR struct rmtchar_state_s *)arg; + struct rmt_item32_s buf[rmtchar->rmtchar_items]; + int nread; + int fd; - vg_lite_path_t path; - vg_lite_init_path( - &path, - VG_LITE_S16, - VG_LITE_HIGH, - sizeof(glphy_u9f8d_path_data), - (FAR void *)glphy_u9f8d_path_data, 0, 0, 4000, 4000); + /* Open the RMT character device */ - vg_lite_identity(&matrix); - vg_lite_scale(0.05, 0.05, &matrix); + fd = open(rmtchar->rxdevpath, O_RDONLY); + if (fd < 0) + { + int errcode = errno; + printf("rmtchar_receiver: ERROR: failed to open %s: %d\n", + rmtchar->rxdevpath, errcode); + pthread_exit(NULL); + } - VG_LITE_CHECK_ERROR(vg_lite_draw( - VG_LITE_DEST_BUF, - &path, - VG_LITE_FILL_EVEN_ODD, - &matrix, - VG_LITE_BLEND_SRC_OVER, - 0xff0a59f7)); + /* Flush any output before reading */ - GPU_PERF_RENDER_START(); - VG_LITE_CHECK_ERROR(vg_lite_finish()); - GPU_PERF_RENDER_STOP(); + fflush(stdout); -error_handler: - return error; + /* Read the buffer to the RMT character driver */ + + nread = read(fd, (char *)buf, rmtchar->rmtchar_items * + sizeof(struct rmt_item32_s)); + if (nread < 0) + { + int errcode = errno; + if (errcode != EINTR) + { + printf("rmtchar_receiver: ERROR: read failed: %d\n", + errcode); + close(fd); + pthread_exit(NULL); + } + } + else + { + if (nread != (rmtchar->rmtchar_items * sizeof(struct rmt_item32_s))) + { + printf("rmtchar_receiver: ERROR: partial read: %d\n", + nread); + printf("rmtchar_receiver: Received buffer:\n"); + print_items(buf, nread / sizeof(struct rmt_item32_s)); + close(fd); + pthread_exit(NULL); + } + else + { + printf("rmtchar_receiver: Received buffer:\n"); + print_items(buf, nread / sizeof(struct rmt_item32_s)); + } + } + + /* Make sure that the transmitter thread has a chance to run */ + + pthread_yield(); + + close(fd); + return NULL; } -/**************************************************************************** - * Name: vg_lite_test_path_glyph_random - ****************************************************************************/ - -vg_lite_error_t vg_lite_test_path_glyph_random( - FAR struct gpu_test_context_s *ctx) -{ - vg_lite_error_t error = VG_LITE_SUCCESS; - vg_lite_matrix_t matrix; - vg_lite_path_t path; - float scale_val = 0.01; - int16_t bounding = 5000 + (rand() % 3000); - - vg_lite_init_path( - &path, - VG_LITE_S16, - VG_LITE_MEDIUM, - sizeof(glphy_u663e_path_data), - (FAR void *)glphy_u663e_path_data, -300, -300, bounding, bounding); - - vg_lite_identity(&matrix); - vg_lite_scale(scale_val, scale_val, &matrix); - - matrix.m[1][1] = -matrix.m[1][1]; - - float offset = (float)(rand() % 100); - vg_lite_translate( - offset / scale_val, -(offset + 200) / scale_val, &matrix - ); - - VG_LITE_CHECK_ERROR(vg_lite_draw( - VG_LITE_DEST_BUF, - &path, - VG_LITE_FILL_EVEN_ODD, - &matrix, - VG_LITE_BLEND_SRC_OVER, - 0xff0a59f7 - )); - - vg_lite_translate(80 / scale_val, 0, &matrix); - - VG_LITE_CHECK_ERROR(vg_lite_draw( - VG_LITE_DEST_BUF, - &path, - VG_LITE_FILL_EVEN_ODD, - &matrix, - VG_LITE_BLEND_SRC_OVER, - 0xff0a00f7 - )); - - vg_lite_translate(80 / scale_val, 0, &matrix); - - VG_LITE_CHECK_ERROR(vg_lite_draw( - VG_LITE_DEST_BUF, - &path, - VG_LITE_FILL_EVEN_ODD, - &matrix, - VG_LITE_BLEND_SRC_OVER, - 0xffff00f7 - )); - - GPU_PERF_RENDER_START(); - VG_LITE_CHECK_ERROR(vg_lite_finish()); - GPU_PERF_RENDER_STOP(); - -error_handler: - return error; -} +#endif /* CONFIG_EXAMPLES_RMTCHAR_RX */ diff --git a/examples/rmtchar/rmtchar_transmitter.c b/examples/rmtchar/rmtchar_transmitter.c new file mode 100644 index 000000000..249f877ae --- /dev/null +++ b/examples/rmtchar/rmtchar_transmitter.c @@ -0,0 +1,156 @@ +/**************************************************************************** + * apps/examples/rmtchar/rmtchar_transmitter.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "rmtchar.h" + +#ifdef CONFIG_EXAMPLES_RMTCHAR_TX + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: rmtchar_transmitter() + * + * Description: + * This is the entry point for the transmitter thread. + * + ****************************************************************************/ + +pthread_addr_t rmtchar_transmitter(pthread_addr_t arg) +{ + FAR struct rmtchar_state_s *rmtchar = (FAR struct rmtchar_state_s *)arg; + struct rmt_item32_s buf[rmtchar->rmtchar_items]; + int duration = 1000; + int nwritten; + int fd; + int i; + + /* Open the RMT character device */ + + fd = open(rmtchar->txdevpath, O_WRONLY); + if (fd < 0) + { + int errcode = errno; + printf("rmtchar_transmitter: ERROR: failed to open %s: %d\n", + rmtchar->txdevpath, errcode); + pthread_exit(NULL); + } + + /* Fill the transmitter buffer with known items */ + + for (i = 0; i < rmtchar->rmtchar_items; i++) + { + buf[i].level0 = 1; + buf[i].duration0 = duration; + buf[i].level1 = 0; + buf[i].duration1 = duration; + + duration += 10; + } + + /* Flush any output before writing */ + + fflush(stdout); + + /* Print the buffer to be sent */ + + print_items(buf, rmtchar->rmtchar_items); + + /* Then send the buffer */ + + /* Write the buffer to the RMT character driver */ + + nwritten = write(fd, (char *)buf, rmtchar->rmtchar_items * + sizeof(struct rmt_item32_s)); + if (nwritten < 0) + { + int errcode = errno; + if (errcode != EINTR) + { + printf("rmtchar_transmitter: ERROR: write failed: %d\n", + errcode); + close(fd); + pthread_exit(NULL); + } + } + else if (nwritten != (rmtchar->rmtchar_items * + sizeof(struct rmt_item32_s))) + { + printf("rmtchar_transmitter: ERROR: partial write: %d\n", + nwritten); + close(fd); + pthread_exit(NULL); + } + else + { + printf("rmtchar_transmitter: Send buffer with %d bytes\n", + rmtchar->rmtchar_items * sizeof(struct rmt_item32_s)); + } + + /* Make sure that the receiver thread has a chance to run */ + + pthread_yield(); + + close(fd); + return NULL; +} + +#endif /* CONFIG_EXAMPLES_RMTCHAR_TX */ diff --git a/examples/romfs/Kconfig b/examples/romfs/Kconfig index 6284a2013..e4a2308a4 100644 --- a/examples/romfs/Kconfig +++ b/examples/romfs/Kconfig @@ -6,7 +6,7 @@ config EXAMPLES_ROMFS tristate "ROMFS example" default n - depends on FS_ROMFS && BUILD_FLAT && BOARDCTL_ROMDISK + depends on FS_ROMFS && BUILD_FLAT ---help--- Enable the ROMFS example diff --git a/examples/rpmsgsocket/Android.bp b/examples/rpmsgsocket/Android.bp deleted file mode 100644 index 6dce807ea..000000000 --- a/examples/rpmsgsocket/Android.bp +++ /dev/null @@ -1,10 +0,0 @@ -cc_binary { - name: "rpsock_client", - srcs: ["rpsock_client.c"], - shared_libs: ["libcutils"], -} -cc_binary { - name: "rpsock_server", - srcs: ["rpsock_server.c"], - shared_libs: ["libcutils"], -} diff --git a/examples/rpmsgsocket/rpsock_client.c b/examples/rpmsgsocket/rpsock_client.c index 8db8b1647..9415dbffd 100644 --- a/examples/rpmsgsocket/rpsock_client.c +++ b/examples/rpmsgsocket/rpsock_client.c @@ -22,24 +22,25 @@ * Included Files ****************************************************************************/ +#include + +#include #include +#include #include #include #include #include -#include #include #include -#include #include -#include /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define ALIGN_UP(a) (((a) + 0x3) & ~0x3) -#define SYNCSIZE 1024 +#define SYNCSIZE CONFIG_NET_RPMSG_RXBUF_SIZE #define BUFSIZE SYNCSIZE * 2 #define BUFHEAD 64 @@ -58,10 +59,10 @@ struct rpsock_arg_s }; /**************************************************************************** - * Private Functions + * Public Functions ****************************************************************************/ -static void *rpsock_send_thread(void *pvarg) +static void *rpsock_send_thread(pthread_addr_t pvarg) { struct rpsock_arg_s *args = pvarg; int bufsize = args->bufsize; @@ -148,7 +149,8 @@ static int rpsock_unsync_test(struct rpsock_arg_s *args) pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 10 * 1024); - ret = pthread_create(&thread, &attr, rpsock_send_thread, args); + ret = pthread_create(&thread, &attr, rpsock_send_thread, + (pthread_addr_t)args); if (ret < 0) { return ret; @@ -223,7 +225,7 @@ static int rpsock_unsync_test(struct rpsock_arg_s *args) return 0; } -static int rpsock_stream_client(char *argv[]) +static int rpsock_stream_client(int argc, char *argv[]) { struct sockaddr_rpmsg myaddr; struct rpsock_arg_s args; @@ -418,7 +420,7 @@ errout_with_buffers: return -errno; } -static int rpsock_dgram_client(char *argv[]) +static int rpsock_dgram_client(int argc, char *argv[]) { struct sockaddr_rpmsg myaddr; struct rpsock_arg_s args; @@ -513,18 +515,6 @@ errout_with_buffers: return -errno; } -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/**************************************************************************** - * Name: rpsock_client_main - * - * Description: - * Main entry point for the rpsock_client example. - * - ****************************************************************************/ - int main(int argc, char *argv[]) { if (argc < 4) @@ -536,11 +526,11 @@ int main(int argc, char *argv[]) if (!strcmp(argv[1], "stream")) { - return rpsock_stream_client(argv); + return rpsock_stream_client(argc, argv); } else if (!strcmp(argv[1], "dgram")) { - return rpsock_dgram_client(argv); + return rpsock_dgram_client(argc, argv); } return -EINVAL; diff --git a/examples/rpmsgsocket/rpsock_server.c b/examples/rpmsgsocket/rpsock_server.c index 26e158361..66b04e1a8 100644 --- a/examples/rpmsgsocket/rpsock_server.c +++ b/examples/rpmsgsocket/rpsock_server.c @@ -22,18 +22,18 @@ * Included Files ****************************************************************************/ +#include + #include #include +#include #include #include #include #include -#include #include #include -#include #include -#include /**************************************************************************** * Private types @@ -46,10 +46,10 @@ struct rpsock_arg_s }; /**************************************************************************** - * Private Functions + * Public Functions ****************************************************************************/ -static void *rpsock_thread(void *pvarg) +static void *rpsock_thread(pthread_addr_t pvarg) { struct rpsock_arg_s *args = pvarg; struct pollfd pfd; @@ -238,8 +238,7 @@ static int rpsock_stream_server(int argc, char *argv[]) } printf("server: try accept ...\n"); - new = accept4(listensd, (struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + new = accept(listensd, (struct sockaddr *)&myaddr, &addrlen); if (new < 0) break; @@ -251,7 +250,8 @@ static int rpsock_stream_server(int argc, char *argv[]) args->fd = new; args->nonblock = nonblock; - pthread_create(&thread, NULL, rpsock_thread, args); + pthread_create(&thread, NULL, rpsock_thread, + (pthread_addr_t)args); pthread_detach(thread); } @@ -348,21 +348,9 @@ static int rpsock_dgram_server(int argc, char *argv[]) return 0; } -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/**************************************************************************** - * Name: rpsock_server_main - * - * Description: - * Main entry point for the rpsock_server example. - * - ****************************************************************************/ - int main(int argc, char *argv[]) { - if (argc < 4) + if (argc != 4 && argc != 5) { printf("Usage: rpsock_server stream/dgram" " block/nonblock rp_name [rp_cpu]\n"); diff --git a/examples/sensor_fusion/Kconfig b/examples/sensor_fusion/Kconfig new file mode 100644 index 000000000..ba1fd6674 --- /dev/null +++ b/examples/sensor_fusion/Kconfig @@ -0,0 +1,38 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config EXAMPLES_SENSOR_FUSION + bool "Sensor Fusion Example" + default n + ---help--- + Sensor fusion example that combines gyro and accelerometer data + using the Madgwick algorithm to provide yaw, pitch and roll angles. + +if EXAMPLES_SENSOR_FUSION + +config EXAMPLES_SENSOR_FUSION_SAMPLES + int "Number of samples to acquire" + default 100 + +config EXAMPLES_SENSOR_FUSION_SAMPLE_RATE + int "Sample rate in ms" + default 100 + +config EXAMPLES_SENSOR_FUSION_PROGNAME + string "Program name" + default "sensor_fusion" + ---help--- + This is the name of the program that will be used when the NSH ELF + program is installed. + +config EXAMPLES_SENSOR_FUSION_PRIORITY + int "Sensor Fusion task priority" + default 100 + +config EXAMPLES_SENSOR_FUSION_STACKSIZE + int "Sensor Fusion stack size" + default DEFAULT_TASK_STACKSIZE + +endif diff --git a/examples/sotest/modprint/Make.defs b/examples/sensor_fusion/Make.defs similarity index 87% rename from examples/sotest/modprint/Make.defs rename to examples/sensor_fusion/Make.defs index 2d6ae226b..f7499a972 100644 --- a/examples/sotest/modprint/Make.defs +++ b/examples/sensor_fusion/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/sotest/modprint/Make.defs +# apps/examples/sensor_fusion/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,7 @@ # ############################################################################ -ifneq ($(CONFIG_EXAMPLES_SOTEST),) -CONFIGURED_APPS += $(APPDIR)/examples/sotest/modprint +ifneq ($(CONFIG_EXAMPLES_SENSOR_FUSION),) +CONFIGURED_APPS += $(APPDIR)/examples/sensor_fusion + endif diff --git a/games/shift/Makefile b/examples/sensor_fusion/Makefile similarity index 78% rename from games/shift/Makefile rename to examples/sensor_fusion/Makefile index 6bda408e9..ce17e69df 100644 --- a/games/shift/Makefile +++ b/examples/sensor_fusion/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/games/shift/Makefile +# apps/examples/sensor_fusion/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,15 +20,11 @@ include $(APPDIR)/Make.defs -# Shift game info +PROGNAME = $(CONFIG_EXAMPLES_SENSOR_FUSION_PROGNAME) +PRIORITY = $(CONFIG_EXAMPLES_SENSOR_FUSION_PRIORITY) +STACKSIZE = $(CONFIG_EXAMPLES_SENSOR_FUSION_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_SENSOR_FUSION) -PROGNAME = $(CONFIG_GAMES_SHIFT_PROGNAME) -PRIORITY = $(CONFIG_GAMES_SHIFT_PRIORITY) -STACKSIZE = $(CONFIG_GAMES_SHIFT_STACKSIZE) -MODULE = $(CONFIG_GAMES_SHIFT) - -# Shift game application - -MAINSRC = shift_main.c +MAINSRC = sensor_fusion_main.c include $(APPDIR)/Application.mk diff --git a/examples/sensor_fusion/sensor_fusion_main.c b/examples/sensor_fusion/sensor_fusion_main.c new file mode 100644 index 000000000..a603c3c82 --- /dev/null +++ b/examples/sensor_fusion/sensor_fusion_main.c @@ -0,0 +1,162 @@ +/**************************************************************************** + * apps/examples/sensor_fusion/sensor_fusion_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include "Fusion/Fusion.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define REG_LOW_MASK 0xFF00 +#define REG_HIGH_MASK 0x00FF +#define MPU6050_FS_SEL 32.8f +#define MPU6050_AFS_SEL 4096.0f + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct mpu6050_imu_msg +{ + int16_t acc_x; + int16_t acc_y; + int16_t acc_z; + int16_t temp; + int16_t gyro_x; + int16_t gyro_y; + int16_t gyro_z; +}; + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void read_mpu6050(int fd, struct sensor_accel *acc_data, + struct sensor_gyro *gyro_data); + +/**************************************************************************** + * sensor_fusion_main + ****************************************************************************/ + +int main(int argc, char *argv[]) +{ + int fd; + int iterations = CONFIG_EXAMPLES_SENSOR_FUSION_SAMPLES; + float acq_period = CONFIG_EXAMPLES_SENSOR_FUSION_SAMPLE_RATE / 1000.0f; + + /* Minimal required data for Fusion library. Use of magnetometer data + * is optional and can improve performance. + */ + + struct sensor_accel imu_acc_data; + struct sensor_gyro imu_gyro_data; + FusionVector accelerometer; + FusionVector gyroscope; + FusionEuler euler; + FusionAhrs ahrs; + + FusionAhrsInitialise(&ahrs); + + printf("Sensor Fusion example\n"); + printf("Sample Rate: %.2f Hz\n", 1.0 / acq_period); + + fd = open("/dev/imu0", O_RDONLY); + if (fd < 0) + { + printf("Failed to open imu0\n"); + return EXIT_FAILURE; + } + + for (int i = 0; i < iterations; i++) + { + read_mpu6050(fd, &imu_acc_data, &imu_gyro_data); + + accelerometer.axis.x = imu_acc_data.x; + accelerometer.axis.y = imu_acc_data.y; + accelerometer.axis.z = imu_acc_data.z; + + gyroscope.axis.x = imu_gyro_data.x; + gyroscope.axis.y = imu_gyro_data.y; + gyroscope.axis.z = imu_gyro_data.z; + + FusionAhrsUpdateNoMagnetometer(&ahrs, + gyroscope, + accelerometer, + acq_period); + euler = FusionQuaternionToEuler(FusionAhrsGetQuaternion(&ahrs)); + + printf("Yaw: %.3f | Pitch: %.3f | Roll: %.3f\n", + euler.angle.yaw, euler.angle.pitch, euler.angle.roll); + usleep(CONFIG_EXAMPLES_SENSOR_FUSION_SAMPLE_RATE * 1000); + } + + close(fd); + + return EXIT_SUCCESS; +} + +void read_mpu6050(int fd, + struct sensor_accel *acc_data, + struct sensor_gyro *gyro_data) +{ + struct mpu6050_imu_msg raw_imu; + int16_t raw_data[7]; + memset(&raw_imu, 0, sizeof(raw_imu)); + + int ret = read(fd, &raw_data, sizeof(raw_data)); + if (ret != sizeof(raw_data)) + { + printf("Failed to read accelerometer data\n"); + } + else + { + raw_imu.acc_x = ((raw_data[0] & REG_HIGH_MASK) << 8) + + ((raw_data[0] & REG_LOW_MASK) >> 8); + raw_imu.acc_y = ((raw_data[1] & REG_HIGH_MASK) << 8) + + ((raw_data[1] & REG_LOW_MASK) >> 8); + raw_imu.acc_z = ((raw_data[2] & REG_HIGH_MASK) << 8) + + ((raw_data[2] & REG_LOW_MASK) >> 8); + raw_imu.gyro_x = ((raw_data[4] & REG_HIGH_MASK) << 8) + + ((raw_data[4] & REG_LOW_MASK) >> 8); + raw_imu.gyro_y = ((raw_data[5] & REG_HIGH_MASK) << 8) + + ((raw_data[5] & REG_LOW_MASK) >> 8); + raw_imu.gyro_z = ((raw_data[6] & REG_HIGH_MASK) << 8) + + ((raw_data[6] & REG_LOW_MASK) >> 8); + } + + acc_data->x = raw_imu.acc_x / MPU6050_AFS_SEL; + acc_data->y = raw_imu.acc_y / MPU6050_AFS_SEL; + acc_data->z = raw_imu.acc_z / MPU6050_AFS_SEL; + + /* Gyro data in º/s (degrees per second) */ + + gyro_data->x = raw_imu.gyro_x / MPU6050_FS_SEL; + gyro_data->y = raw_imu.gyro_y / MPU6050_FS_SEL; + gyro_data->z = raw_imu.gyro_z / MPU6050_FS_SEL; +} diff --git a/examples/serialrx/serialrx_main.c b/examples/serialrx/serialrx_main.c index a64515b78..0864805ce 100644 --- a/examples/serialrx/serialrx_main.c +++ b/examples/serialrx/serialrx_main.c @@ -52,7 +52,7 @@ int main(int argc, FAR char *argv[]) #else int fd; int cnt; - int bytecount = 0; + #endif #ifdef CONFIG_EXAMPLES_SERIALRX_PRINTHYPHEN int count = 0; @@ -64,6 +64,7 @@ int main(int argc, FAR char *argv[]) bool eof = false; FAR char *buf; FAR char *devpath; + int bytecount = 0; if (argc == 1) { diff --git a/examples/settings/Kconfig b/examples/settings/Kconfig new file mode 100644 index 000000000..81bf1e93d --- /dev/null +++ b/examples/settings/Kconfig @@ -0,0 +1,61 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config EXAMPLES_SETTINGS + tristate "Settings example" + default n + ---help--- + Enable the "settings" example. This uses the functions provided in + system/settings to test the storage and retrieval of various + configurable parameters + +if EXAMPLES_SETTINGS + +config EXAMPLES_SETTINGS_PROGNAME + string "Program name" + default "settings" + ---help--- + This is the name of the program that will be used when the NSH ELF + program is installed. + +config EXAMPLES_SETTINGS_PRIORITY + int "settings task priority" + default 100 + +config EXAMPLES_SETTINGS_STACKSIZE + int "settings stack size" + default DEFAULT_TASK_STACKSIZE + +choice + prompt "Select settings storage location" + default EXAMPLES_SETTINGS_USE_TMPFS + +config EXAMPLES_SETTINGS_USE_TMPFS + bool "Use TMPFS" + select FS_TMPFS + ---help--- + TMPFS will be enabled and used + +config EXAMPLES_SETTINGS_USE_OTHER + bool "Use existing/other storage media" + +endchoice # Select settings storage location + +if EXAMPLES_SETTINGS_USE_OTHER + +config EXAMPLES_SETTINGS_EXISTING_STORAGE + string "Path to existing storage media" + default "/mnt/mmcsd0" + +endif # EXAMPLES_SETTINGS_USE_OTHER + +config EXAMPLES_SETTINGS_FILENAME + string "Filename" + default "settings" + ---help--- + filename to be used. This append will append .txt and .bin + to this name to use/create two settings files. + +endif # EXAMPLES_SETTINGS diff --git a/examples/settings/Make.defs b/examples/settings/Make.defs new file mode 100644 index 000000000..8198e28a3 --- /dev/null +++ b/examples/settings/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/examples/settings/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_EXAMPLES_SETTINGS),) +CONFIGURED_APPS += $(APPDIR)/examples/settings +endif diff --git a/examples/settings/Makefile b/examples/settings/Makefile new file mode 100644 index 000000000..53bf1f22d --- /dev/null +++ b/examples/settings/Makefile @@ -0,0 +1,34 @@ +############################################################################ +# apps/examples/settings/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +# settings built-in application info + +PROGNAME = $(CONFIG_EXAMPLES_SETTINGS_PROGNAME) +PRIORITY = $(CONFIG_EXAMPLES_SETTINGS_PRIORITY) +STACKSIZE = $(CONFIG_EXAMPLES_SETTINGS_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_SETTINGS) + +# Settings Example + +MAINSRC = settings_main.c + +include $(APPDIR)/Application.mk diff --git a/examples/settings/settings_main.c b/examples/settings/settings_main.c new file mode 100644 index 000000000..931260836 --- /dev/null +++ b/examples/settings/settings_main.c @@ -0,0 +1,301 @@ +/**************************************************************************** + * apps/examples/settings/settings_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include + +#include "system/settings.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * settings_main + ****************************************************************************/ + +int settings_main(int argc, FAR char *argv[]) +{ + int ret; + int fd; + enum settings_type_e stype; + char text_path[CONFIG_PATH_MAX]; + char bin_path[CONFIG_PATH_MAX]; + const char teststr[] = "I'm a string"; + int testval = 0x5aa5; + char readstr[CONFIG_SYSTEM_SETTINGS_VALUE_SIZE]; +#ifdef CONFIG_EXAMPLES_SETTINGS_USE_TMPFS + struct stat sbuf; + +# ifndef CONFIG_FS_TMPFS +# error TMPFS must be enabled +# endif +# ifndef CONFIG_LIBC_TMPDIR +# error LIBC_TMPDIR must be defined +# endif + if (stat(CONFIG_LIBC_TMPDIR, &sbuf)) + { + ret = nx_mount(NULL, CONFIG_LIBC_TMPDIR, "tmpfs", 0, NULL); + if (ret < 0) + { + printf("ERROR: Failed to mount tmpfs at %s: %d\n", + CONFIG_LIBC_TMPDIR, ret); + goto end; + } + } + + strcpy(bin_path, CONFIG_LIBC_TMPDIR); +#else + strcpy(bin_path, CONFIG_EXAMPLES_SETTINGS_EXISTING_STORAGE); + if (bin_path == NULL) + { + printf("Settings filepath is empty!"); + goto end; + } +#endif + + strcat(bin_path, "/"); + strcat(bin_path, CONFIG_EXAMPLES_SETTINGS_FILENAME); + strcpy(text_path, bin_path); + strcat(bin_path, ".bin"); + strcat(text_path, ".txt"); + + printf("Example of settings usage to file: %s and %s:", + bin_path, text_path); + printf("--------------------------------------------------------------\n"); + + settings_init(); + + ret = settings_setstorage(bin_path, STORAGE_BINARY); + if (ret == -ENOENT) + { + printf("No existing binary storage file found. Creating it.\n"); + fd = open(bin_path, O_CREAT); + if (fd < 0) + { + printf("Failed to create settings file\n"); + goto end; + } + + close(fd); + } + else if (ret < 0) + { + printf("settings setstorage failed: %d\n", ret); + goto end; + } + else + { + printf("existing bin settings storage file found\n"); + } + + ret = settings_setstorage(text_path, STORAGE_TEXT); + if (ret == -ENOENT) + { + printf("No existing text storage file found. Creating it.\n"); + fd = open(text_path, O_CREAT); + if (fd < 0) + { + printf("Failed to create settings file\n"); + goto end; + } + + close(fd); + } + else if (ret < 0) + { + printf("settings setstorage failed: %d\n", ret); + goto end; + } + else + { + printf("existing text settings storage file found\n"); + } + + ret = settings_create("v1", SETTING_STRING, "default value"); + if (ret < 0) + { + printf("settings create failed: %d\n", ret); + goto end; + } + + /* if this app has been run before, the setting type is likely changed */ + + ret = settings_type("v1", &stype); + if (ret < 0) + { + printf("Failed to get settings type: %d\n", ret); + goto end; + } + + if (stype == SETTING_STRING) + { + ret = settings_get("v1", SETTING_STRING, &readstr, sizeof(readstr)); + if (ret < 0) + { + printf("settings retrieve failed: %d\n", ret); + goto end; + } + + printf("Retrieved settings value (v1) with value:%s\n", readstr); + } + else + { + ret = settings_get("v1", SETTING_INT, &testval, + CONFIG_SYSTEM_SETTINGS_VALUE_SIZE); + if (ret < 0) + { + printf("settings retrieve failed: %d\n", ret); + goto end; + } + + printf("Retrieved settings value (v1) with value:%d\n", testval); + } + + printf("Trying to (re)create a setting that already exists (v1)\n"); + + testval = 0xa5a5; + ret = settings_create("v1", SETTING_INT, testval); + if (ret == -EACCES) + { + printf("Deliberate fail: setting exists! Error: %d\n", ret); + } + else if (ret < 0) + { + printf("settings create failed: %d\n", ret); + goto end; + } + + ret = settings_type("v1", &stype); + if (ret < 0) + { + printf("failed to read settings type: %d\n", ret); + goto end; + } + + printf("Retrieved setting type is: %d\n", stype); + + printf("Trying to change setting (v1) to integer type\n"); + ret = settings_set("v1", SETTING_INT, &testval); + if (ret < 0) + { + printf("Deliberate fail: settings change invalid: %d\n", ret); + } + + ret = settings_get("v2", SETTING_INT, &testval); + if (ret < 0) + { + printf("Deliberate fail: non-existent setting requested. Error:%d\n", + ret); + } + + printf("Trying to change setting (v1) from int to string: %s\n", teststr); + ret = settings_set("v1", SETTING_STRING, &teststr); + if (ret < 0) + { + printf("Deliberate fail: settings change invalid: %d\n", ret); + } + + printf("Creating a string settings value (s1):%s\n", teststr); + ret = settings_create("s1", SETTING_STRING, teststr); + if (ret < 0) + { + printf("settings changed failed: %d\n", ret); + goto end; + } + + ret = settings_get("s1", SETTING_STRING, &readstr, sizeof(readstr)); + if (ret < 0) + { + printf("settings retrieve failed: %d\n", ret); + goto end; + } + + printf("Retrieved string settings value (s1) with value:%s\n", + readstr); + + FAR struct in_addr save_ip; + FAR struct in_addr load_ip; + save_ip.s_addr = 0xc0a86401; + + printf("Changing setting to an IP value (s1) with value:%d.%d.%d.%d\n", + (int)(save_ip.s_addr >> 24) & 0xff, + (int)(save_ip.s_addr >> 16) & 0xff, + (int)(save_ip.s_addr >> 8) & 0xff, + (int)(save_ip.s_addr >> 0) & 0xff); + ret = settings_set("s1", SETTING_IP_ADDR, &save_ip); + if (ret < 0) + { + printf("IP address settings create failed: %d\n", ret); + goto end; + } + + ret = settings_get("s1", SETTING_IP_ADDR, &load_ip); + if (ret < 0) + { + printf("IP address settings retrieve failed: %d\n", ret); + goto end; + } + + printf("Retrieved IP address settings value (s1) with value:0x%08lx\n", + load_ip.s_addr); + + printf("syncing storages\n"); + ret = settings_sync(true); /* wait for cached saves to complete + * (will only be done if caching enabled). + */ + if (ret < 0) + { + printf("Failed to sync storages: %d\n", ret); + goto end; + } + +end: + printf("exiting settings example app\n"); + fflush(stdout); + + return ret; +} diff --git a/testing/cpuload/CMakeLists.txt b/examples/shm_test/CMakeLists.txt similarity index 84% rename from testing/cpuload/CMakeLists.txt rename to examples/shm_test/CMakeLists.txt index 43e776cf6..1985986d5 100644 --- a/testing/cpuload/CMakeLists.txt +++ b/examples/shm_test/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/testing/cpuload/CMakeLists.txt +# apps/examples/shm_test/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,16 +18,14 @@ # # ############################################################################## -if(CONFIG_TESTING_CPULOAD) +if(CONFIG_EXAMPLES_SHM) nuttx_add_application( NAME - cpuload - PRIORITY - 100 - STACKSIZE - ${CONFIG_DEFAULT_TASK_STACKSIZE} - MODULE - ${CONFIG_TESTING_CPULOAD} + ${CONFIG_EXAMPLES_SHM_PROGNAME} SRCS - cpuload_main.c) + shm_main.c + STACKSIZE + ${CONFIG_EXAMPLES_SHM_STACKSIZE} + PRIORITY + ${CONFIG_EXAMPLES_SHM_PRIORITY}) endif() diff --git a/testing/cachetest/Kconfig b/examples/shm_test/Kconfig similarity index 53% rename from testing/cachetest/Kconfig rename to examples/shm_test/Kconfig index e127d918e..85c9957ec 100644 --- a/testing/cachetest/Kconfig +++ b/examples/shm_test/Kconfig @@ -3,27 +3,28 @@ # see the file kconfig-language.txt in the NuttX tools repository. # -config TESTING_CACHETEST - tristate "Cache Test" +config EXAMPLES_SHM + tristate "SHM example" default n + depends on FS_SHMFS ---help--- - Enable a simple Cache test. + Enable the SHM example which has an shm producer and consumer -if TESTING_CACHETEST +if EXAMPLES_SHM -config TESTING_CACHETEST_PROGNAME +config EXAMPLES_SHM_PROGNAME string "Program name" - default "cachetest" + default "shm_test" ---help--- This is the name of the program that will be used when the NSH ELF program is installed. -config TESTING_CACHETEST_PRIORITY - int "Cache test task priority" +config EXAMPLES_SHM_PRIORITY + int "SHM task priority" default 100 -config TESTING_CACHETEST_STACKSIZE - int "Cache test stack size" +config EXAMPLES_SHM_STACKSIZE + int "SHM stack size" default DEFAULT_TASK_STACKSIZE endif diff --git a/examples/shm_test/Make.defs b/examples/shm_test/Make.defs new file mode 100644 index 000000000..5248c3f6e --- /dev/null +++ b/examples/shm_test/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/examples/shm_test/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_EXAMPLES_SHM),) +CONFIGURED_APPS += $(APPDIR)/examples/shm_test +endif diff --git a/examples/shm_test/Makefile b/examples/shm_test/Makefile new file mode 100644 index 000000000..1f3346868 --- /dev/null +++ b/examples/shm_test/Makefile @@ -0,0 +1,42 @@ +############################################################################ +# apps/examples/shm_test/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +# SHM test built-in application info + +PROGNAME = $(CONFIG_EXAMPLES_SHM_PROGNAME) +PRIORITY = $(CONFIG_EXAMPLES_SHM_PRIORITY) +STACKSIZE = $(CONFIG_EXAMPLES_SHM_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_SHM) + +# SHM test Example + +MAINSRC = shm_main.c + +# Build with WebAssembly when CONFIG_INTERPRETERS_WAMR is enabled + +WASM_BUILD = both + +# Mode of WebAssembly Micro Runtime + +WAMR_MODE = AOT + +include $(APPDIR)/Application.mk diff --git a/examples/shm_test/shm_main.c b/examples/shm_test/shm_main.c new file mode 100644 index 000000000..1fb1d0b0d --- /dev/null +++ b/examples/shm_test/shm_main.c @@ -0,0 +1,116 @@ +/**************************************************************************** + * apps/examples/shm_test/shm_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void shm_producer(const int shm_size, const char *shm_name) +{ + /* Write Hello World! to shared memory */ + + const char *message_0 = "Hello"; + const char *message_1 = "World!"; + + /* Shared memory file descriptor */ + + int shm_fd; + + /* Pointer to shared memory object */ + + void *ptr; + + /* Create the shared memory object */ + + shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666); + + /* Configure the size of the shared memory object */ + + ftruncate(shm_fd, shm_size); + + /* Memory map the shared memory object */ + + ptr = mmap(0, shm_size, PROT_WRITE, MAP_SHARED, shm_fd, 0); + + /* Write to the shared memory object */ + + sprintf(ptr, "%s", message_0); + + ptr += strlen(message_0); + sprintf(ptr, "%s", message_1); + ptr += strlen(message_1); + + printf("Producer Wrote to SHM: %s%s\n", message_0, message_1); +} + +void shm_consumer(const int shm_size, const char *shm_name) +{ + /* Shared memory file descriptor */ + + int shm_fd; + + /* Pointer to shared memory object */ + + void *ptr; + + /* Open the shared memory object */ + + shm_fd = shm_open(shm_name, O_RDONLY, 0666); + + /* Memory map the shared memory object */ + + ptr = mmap(0, shm_size, PROT_READ, MAP_SHARED, shm_fd, 0); + + /* Read from the shared memory object */ + + printf("Consumer Read from SHM: %s\n", (char *)ptr); + + /* Remove the shared memory object */ + + shm_unlink(shm_name); +} + +/**************************************************************************** + * shm_main + ****************************************************************************/ + +int main(int argc, FAR char *argv[]) +{ + const int shm_size = 2048; + const char *shm_name = "OS"; + + shm_producer(shm_size, shm_name); + shm_consumer(shm_size, shm_name); + return 0; +} diff --git a/examples/sotest/main/CMakeLists.txt b/examples/sotest/CMakeLists.txt similarity index 95% rename from examples/sotest/main/CMakeLists.txt rename to examples/sotest/CMakeLists.txt index 3e059d984..f677d8d8b 100644 --- a/examples/sotest/main/CMakeLists.txt +++ b/examples/sotest/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/examples/sotest/main/CMakeLists.txt +# apps/examples/sotest/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for diff --git a/examples/sotest/main/Kconfig b/examples/sotest/Kconfig similarity index 100% rename from examples/sotest/main/Kconfig rename to examples/sotest/Kconfig diff --git a/examples/sotest/Make.defs b/examples/sotest/Make.defs index 6f9fbe6f5..1f732f9ec 100644 --- a/examples/sotest/Make.defs +++ b/examples/sotest/Make.defs @@ -18,4 +18,6 @@ # ############################################################################ -include $(wildcard $(APPDIR)/examples/sotest/*/Make.defs) +ifneq ($(CONFIG_EXAMPLES_SOTEST),) +CONFIGURED_APPS += $(APPDIR)/examples/sotest +endif diff --git a/examples/sotest/Makefile b/examples/sotest/Makefile index 6e7bb3af7..f7a0690e8 100644 --- a/examples/sotest/Makefile +++ b/examples/sotest/Makefile @@ -18,6 +18,41 @@ # ############################################################################ -MENUDESC = "sotest example" +include $(APPDIR)/Make.defs -include $(APPDIR)/Directory.mk +# Shared library example built-in application info + +PROGNAME = sotest +PRIORITY = SCHED_PRIORITY_DEFAULT +STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) +MODULE = $(CONFIG_EXAMPLES_SOTEST) + +# Shared Library Example + +ifeq ($(CONFIG_EXAMPLES_SOTEST_BUILTINFS),y) +CSRCS = romfs.c +endif +CSRCS += sot_symtab.c +lib$(DELIM)sot_symtab.c_CFLAGS = -fno-builtin +lib$(DELIM)sot_symtab.c_CELFFLAGS = -fno-builtin +MAINSRC = sotest_main.c + +DEPPATH += --dep-path lib + +# Build targets + +VPATH = lib + +ifeq ($(CONFIG_EXAMPLES_SOTEST_BUILTINFS),y) +lib/romfs.c: build +endif +lib/sot_symtab.c: build + +.PHONY: build +build: + +$(Q) $(MAKE) -C lib TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" CROSSDEV=$(CROSSDEV) + +clean:: + +$(Q) $(MAKE) -C lib TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" CROSSDEV=$(CROSSDEV) clean + +include $(APPDIR)/Application.mk diff --git a/examples/sotest/lib/.gitignore b/examples/sotest/lib/.gitignore new file mode 100644 index 000000000..f41ef9224 --- /dev/null +++ b/examples/sotest/lib/.gitignore @@ -0,0 +1,4 @@ +/fsroot +/romfs.c +/romfs.img +/sot_symtab.c diff --git a/examples/sotest/lib/Makefile b/examples/sotest/lib/Makefile new file mode 100644 index 000000000..734944203 --- /dev/null +++ b/examples/sotest/lib/Makefile @@ -0,0 +1,80 @@ +############################################################################ +# apps/examples/sotest/lib/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +ALL_SUBDIRS = sotest +BUILD_SUBDIRS = sotest + +ifneq ($(CONFIG_MODLIB_MAXDEPEND),0) +ALL_SUBDIRS += modprint +BUILD_SUBDIRS += modprint +endif + +SOTEST_DIR = $(APPDIR)/examples/sotest +LIB_DIR = $(SOTEST_DIR)/lib +FSROOT_DIR = $(LIB_DIR)/fsroot +SYMTAB_SRC = $(LIB_DIR)/sot_symtab.c + +ifeq ($(CONFIG_EXAMPLES_SOTEST_BUILTINFS),y) + ROMFS_IMG = $(LIB_DIR)/romfs.img + ROMFS_SRC = $(LIB_DIR)/romfs.c +endif + +define DIR_template +$(1)_$(2): + +$(Q) $(MAKE) -C $(1) $(2) TOPDIR="$(TOPDIR)" APPDIR="$(APPDIR)" FSROOT_DIR="$(FSROOT_DIR)" CROSSDEV=$(CROSSDEV) +endef + +all: $(ROMFS_SRC) $(SYMTAB_SRC) +.PHONY: all clean install + +$(foreach DIR, $(ALL_SUBDIRS), $(eval $(call DIR_template,$(DIR),clean))) +$(foreach DIR, $(BUILD_SUBDIRS), $(eval $(call DIR_template,$(DIR),install))) + +# Install each program in the fsroot directory + +install: $(foreach DIR, $(BUILD_SUBDIRS), $(DIR)_install) + +ifeq ($(CONFIG_EXAMPLES_SOTEST_BUILTINFS),y) +# Create the romfs.img file from the populated fsroot directory + +$(ROMFS_IMG): install + $(Q) genromfs -f $@.tmp -d $(FSROOT_DIR) -V "SOTESTTEST" + $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) + +# Create the romfs.c file from the romfs.img file + +$(ROMFS_SRC): $(ROMFS_IMG) + $(Q) (cd $(LIB_DIR) && echo "#include " >$@ && \ + xxd -i romfs.img | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" >>$@) +endif + +# Create the exported symbol table + +$(SYMTAB_SRC): install + $(Q) $(APPDIR)$(DELIM)tools$(DELIM)mksymtab.sh $(FSROOT_DIR) g_sot | sed "/modprint/d" >$@.tmp + $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) + +# Clean each subdirectory + +clean: $(foreach DIR, $(ALL_SUBDIRS), $(DIR)_clean) + $(Q) rm -f $(ROMFS_SRC) $(ROMFS_IMG) $(SYMTAB_SRC) + $(Q) rm -rf $(FSROOT_DIR) diff --git a/examples/sotest/lib/modprint/.gitignore b/examples/sotest/lib/modprint/.gitignore new file mode 100644 index 000000000..791ac9ac0 --- /dev/null +++ b/examples/sotest/lib/modprint/.gitignore @@ -0,0 +1 @@ +/modprint diff --git a/math/ruy/Makefile b/examples/sotest/lib/modprint/Makefile similarity index 51% rename from math/ruy/Makefile rename to examples/sotest/lib/modprint/Makefile index aa9b2be5e..b755b8d54 100644 --- a/math/ruy/Makefile +++ b/examples/sotest/lib/modprint/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/ruy/Makefile +# apps/examples/sotest/lib/modprint/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,23 +20,45 @@ include $(APPDIR)/Make.defs -RUY_VER = d37128311b445e758136b8602d1bbd2a755e115d - -ruy.zip: - $(Q) curl -L https://github.com/google/ruy/archive/$(RUY_VER).zip -o ruy.zip - $(Q) unzip -o ruy.zip - $(Q) mv ruy-$(RUY_VER) ruy - -# Download and unpack tarball if no git repo found -ifeq ($(wildcard ruy/.git),) -context:: ruy.zip - -distclean:: - $(call DELDIR, ruy) - $(call DELFILE, ruy.zip) +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBGCC),y) +LIBGCC = "${shell $(CC) $(ARCHCPUFLAGS) -print-libgcc-file-name 2>/dev/null}" +ifneq ($(LIBGCC),) + LDLIBPATH += -L "${shell dirname $(LIBGCC)}" + LDLIBS += -lgcc +endif endif -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/ruy/ruy -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/ruy/ruy +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBC),y) +LDMODULEFLAGS += -Bstatic +LDLIBPATH += -L $(NUTTXLIB) +endif -include $(APPDIR)/Application.mk \ No newline at end of file +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBC),y) +LDLIBS += -lc +endif + +BIN = modprint + +SRCS = $(BIN).c +OBJS = $(SRCS:.c=$(OBJEXT)) + +all: $(BIN) +.PHONY: all clean install + +$(OBJS): %$(OBJEXT): %.c + @echo "MODULECC: $<" + $(Q) $(MODULECC) -c $(CMODULEFLAGS) $< -o $@ + +$(BIN): $(OBJS) + @echo "MODULELD: $<" + $(Q) $(MODULELD) $(LDMODULEFLAGS) $(LDLIBPATH) -o $@ $(ARCHCRT0OBJ) $^ $(LDLIBS) + +$(FSROOT_DIR)/$(BIN): $(BIN) + $(Q) mkdir -p $(FSROOT_DIR) + $(Q) install $(BIN) $(FSROOT_DIR)/$(BIN) + +install: $(FSROOT_DIR)/$(BIN) + +clean: + $(call DELFILE, $(BIN)) + $(call CLEAN) diff --git a/testing/gpu/gpu_recorder.h b/examples/sotest/lib/modprint/modprint.c similarity index 62% rename from testing/gpu/gpu_recorder.h rename to examples/sotest/lib/modprint/modprint.c index 5b60e6959..bb2793ef1 100644 --- a/testing/gpu/gpu_recorder.h +++ b/examples/sotest/lib/modprint/modprint.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/gpu_recorder.h + * apps/examples/sotest/lib/modprint/modprint.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -18,63 +18,84 @@ * ****************************************************************************/ -#ifndef __APPS_TESTING_GPU_RECORDER_H -#define __APPS_TESTING_GPU_RECORDER_H - /**************************************************************************** * Included Files ****************************************************************************/ #include -#include + +#include +#include +#include +#include + +#include +#include /**************************************************************************** - * Pre-processor Definitions + * Private Function Prototypes ****************************************************************************/ +static void modprint(FAR const char *fmt, ...) printf_like(1, 2); + /**************************************************************************** - * Public Types + * Private Data ****************************************************************************/ -struct gpu_test_context_s; -struct gpu_recorder_s; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -#ifdef __cplusplus -#define EXTERN extern "C" -extern "C" +static const struct symtab_s g_modprint_exports[1] = { -#else -#define EXTERN extern -#endif + { + "modprint", (FAR const void *)modprint, + } +}; /**************************************************************************** - * Name: gpu_recoder_create + * Private Functions ****************************************************************************/ -FAR struct gpu_recorder_s *gpu_recorder_create( - FAR struct gpu_test_context_s *ctx, - const char *name); - /**************************************************************************** - * Name: gpu_recoder_delete + * Name: modprint ****************************************************************************/ -void gpu_recorder_delete(FAR struct gpu_recorder_s *recorder); +static void modprint(FAR const char *fmt, ...) +{ + va_list ap; -/**************************************************************************** - * Name: gpu_recorder_write_string - ****************************************************************************/ - -int gpu_recorder_write_string(FAR struct gpu_recorder_s *recorder, - FAR const char *str); - -#undef EXTERN -#ifdef __cplusplus + va_start(ap, fmt); + vsyslog(LOG_INFO, fmt, ap); + va_end(ap); } -#endif -#endif /* __APPS_TESTING_GPU_VGLITE_H */ +/**************************************************************************** + * Name: module_uninitialize + ****************************************************************************/ + +static int module_uninitialize(FAR void *arg) +{ + syslog(LOG_INFO, "module_uninitialize: arg=%p\n", arg); + return OK; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: module_initialize + * + * Description: + * Register /dev/sotest + * + ****************************************************************************/ + +int module_initialize(FAR struct mod_info_s *modinfo) +{ + syslog(LOG_INFO, "module_initialize:\n"); + + modinfo->uninitializer = module_uninitialize; + modinfo->arg = NULL; + modinfo->exports = g_modprint_exports; + modinfo->nexports = 1; + + return OK; +} diff --git a/examples/sotest/lib/sotest/.gitignore b/examples/sotest/lib/sotest/.gitignore new file mode 100644 index 000000000..256c42b57 --- /dev/null +++ b/examples/sotest/lib/sotest/.gitignore @@ -0,0 +1 @@ +/sotest diff --git a/testing/gpu/Makefile b/examples/sotest/lib/sotest/Makefile similarity index 52% rename from testing/gpu/Makefile rename to examples/sotest/lib/sotest/Makefile index 2984049b8..55338e1da 100644 --- a/testing/gpu/Makefile +++ b/examples/sotest/lib/sotest/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# aapps/testing/gpu/Makefile +# apps/examples/sotest/lib/sotest/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,23 +20,45 @@ include $(APPDIR)/Make.defs -PROGNAME = gpu_test -PRIORITY = $(CONFIG_TESTING_GPU_PRIORITY) -STACKSIZE = $(CONFIG_TESTING_GPU_STACKSIZE) -MODULE = $(CONFIG_TESTING_GPU) - -MAINSRC = gpu_main.c - -ifneq ($(CONFIG_TESTING_GPU_VG_LITE_INCLUDE), "") -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/../$(CONFIG_TESTING_GPU_VG_LITE_INCLUDE) +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBGCC),y) +LIBGCC = "${shell $(CC) $(ARCHCPUFLAGS) -print-libgcc-file-name 2>/dev/null}" +ifneq ($(LIBGCC),) + LDLIBPATH += -L "${shell dirname $(LIBGCC)}" + LDLIBS += -lgcc +endif endif -ifneq ($(CONFIG_LIB_PNG),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/../external/libpng -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/../external/libpng/libpng +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBC),y) +LDMODULEFLAGS += -Bstatic +LDLIBPATH += -L $(NUTTXLIB) endif -CSRCS += $(wildcard vg_lite/*.c) -CSRCS += $(filter-out gpu_main.c, $(wildcard *.c)) +ifeq ($(CONFIG_EXAMPLES_SOTEST_LIBC),y) +LDLIBS += -lc +endif -include $(APPDIR)/Application.mk +BIN = sotest + +SRCS = $(BIN).c +OBJS = $(SRCS:.c=$(OBJEXT)) + +all: $(BIN) +.PHONY: all clean install + +$(OBJS): %$(OBJEXT): %.c + @echo "MODULECC: $<" + $(Q) $(MODULECC) -c $(CMODULEFLAGS) $< -o $@ + +$(BIN): $(OBJS) + @echo "MODULELD: $<" + $(Q) $(MODULELD) $(LDMODULEFLAGS) $(LDLIBPATH) -o $@ $(ARCHCRT0OBJ) $^ $(LDLIBS) + +$(FSROOT_DIR)/$(BIN): $(BIN) + $(Q) mkdir -p $(FSROOT_DIR) + $(Q) install $(BIN) $(FSROOT_DIR)/$(BIN) + +install: $(FSROOT_DIR)/$(BIN) + +clean: + $(call DELFILE, $(BIN)) + $(call CLEAN) diff --git a/examples/sotest/sotest/sotest.c b/examples/sotest/lib/sotest/sotest.c similarity index 75% rename from examples/sotest/sotest/sotest.c rename to examples/sotest/lib/sotest/sotest.c index 83c575ff0..da09bf9a7 100644 --- a/examples/sotest/sotest/sotest.c +++ b/examples/sotest/lib/sotest/sotest.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/sotest/sotest/sotest.c + * apps/examples/sotest/lib/sotest/sotest.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -44,16 +44,40 @@ void modprint(FAR const char *fmt, ...) printf_like(1, 2); * Private Function Prototypes ****************************************************************************/ +static void testfunc1(FAR const char *msg); +static void testfunc2(FAR const char *msg); +static void testfunc3(FAR const char *msg); +static int module_uninitialize(FAR void *arg); + /**************************************************************************** * Private Data ****************************************************************************/ -__attribute__((visibility("default"))) -const char g_msg1[] = "Hello to you too!"; -__attribute__((visibility("default"))) -const char g_msg2[] = "Not so bad so far."; -__attribute__((visibility("default"))) -const char g_msg3[] = "Yes, don't be a stranger!"; +static const char g_msg1[] = "Hello to you too!"; +static const char g_msg2[] = "Not so bad so far."; +static const char g_msg3[] = "Yes, don't be a stranger!"; + +static const struct symtab_s g_sotest_exports[6] = +{ + { + "testfunc1", (FAR const void *)testfunc1, + }, + { + "testfunc2", (FAR const void *)testfunc2, + }, + { + "testfunc3", (FAR const void *)testfunc3, + }, + { + "g_msg1", (FAR const void *)g_msg1, + }, + { + "g_msg2", (FAR const void *)g_msg2, + }, + { + "g_msg3", (FAR const void *)g_msg3, + }, +}; /**************************************************************************** * Private Functions @@ -78,8 +102,7 @@ static void modprint(FAR const char *fmt, ...) * Name: testfunc1 ****************************************************************************/ -__attribute__((visibility("default"))) -void testfunc1(FAR const char *msg) +static void testfunc1(FAR const char *msg) { modprint("testfunc1: Hello, everyone!\n"); modprint(" caller: %s\n", msg); @@ -89,8 +112,7 @@ void testfunc1(FAR const char *msg) * Name: testfunc2 ****************************************************************************/ -__attribute__((visibility("default"))) -void testfunc2(FAR const char *msg) +static void testfunc2(FAR const char *msg) { modprint("testfunc2: Hope you are having a great day!\n"); modprint(" caller: %s\n", msg); @@ -100,8 +122,7 @@ void testfunc2(FAR const char *msg) * Name: testfunc3 ****************************************************************************/ -__attribute__((visibility("default"))) -void testfunc3(FAR const char *msg) +static void testfunc3(FAR const char *msg) { modprint("testfunc3: Let's talk again very soon\n"); modprint(" caller: %s\n", msg); @@ -111,10 +132,10 @@ void testfunc3(FAR const char *msg) * Name: module_uninitialize ****************************************************************************/ -__attribute__((destructor)) -static void module_uninitialize(void) +static int module_uninitialize(FAR void *arg) { - modprint("module_uninitialize\n"); + modprint("module_uninitialize: arg=%p\n", arg); + return OK; } /**************************************************************************** @@ -129,8 +150,14 @@ static void module_uninitialize(void) * ****************************************************************************/ -__attribute__((constructor)) -static void module_initialize(void) +int module_initialize(FAR struct mod_info_s *modinfo) { - modprint("module_initialize\n"); + modprint("module_initialize:\n"); + + modinfo->uninitializer = module_uninitialize; + modinfo->arg = NULL; + modinfo->exports = g_sotest_exports; + modinfo->nexports = 6; + + return OK; } diff --git a/examples/sotest/main/.gitignore b/examples/sotest/main/.gitignore deleted file mode 100644 index cb2478b33..000000000 --- a/examples/sotest/main/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/sotest_symtab.c -/sotest_romfs.c -/sotest_romfs.img diff --git a/examples/sotest/main/Makefile b/examples/sotest/main/Makefile deleted file mode 100644 index 17c905703..000000000 --- a/examples/sotest/main/Makefile +++ /dev/null @@ -1,70 +0,0 @@ -############################################################################ -# apps/examples/sotest/main/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -# Shared library example built-in application info - -PROGNAME = sotest -PRIORITY = SCHED_PRIORITY_DEFAULT -STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) -MODULE = $(CONFIG_EXAMPLES_SOTEST) - -# Shared Library Example - -MAINSRC = sotest_main.c - -SYMTABSRC = sotest_symtab.c -SYMTABOBJ = $(SYMTABSRC:.c=$(OBJEXT)) - -$(SYMTABSRC): - $(Q) $(APPDIR)$(DELIM)tools$(DELIM)mksymtab.sh $(BINDIR) g_sot >$@.tmp - $(Q) $(call TESTANDREPLACEFILE, $@.tmp, $@) - - -$(SYMTABOBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@, -fno-lto -fno-builtin) - - -ifeq ($(CONFIG_EXAMPLES_SOTEST_BUILTINFS),y) - -ROMFSIMG = sotest_romfs.img -ROMFSSRC = sotest_romfs.c -ROMFSOBJ = $(ROMFSSRC:.c=$(OBJEXT)) - -$(ROMFSIMG): - $(Q) genromfs -d $(BINDIR) -f $@ - -$(ROMFSSRC): $(ROMFSIMG) - $(Q) (echo "#include " >$@ && \ - xxd -i $(ROMFSIMG) | sed -e "s/^unsigned char/const unsigned char aligned_data(4)/g" >>$@) - -$(ROMFSOBJ): %$(OBJEXT): %.c - $(call COMPILE, $<, $@, -fno-lto -fno-builtin) - -endif - -postinstall:: $(ROMFSOBJ) $(SYMTABOBJ) $(FSIMG_OBJ) - $(call ARLOCK, $(call CONVERT_PATH,$(BIN)), $^) - -distclean:: - $(Q) $(call DELFILE, $(SYMTABSRC) $(SYMTABOBJ) $(ROMFSSRC) $(ROMFSIMG) $(ROMFSOBJ)) - -include $(APPDIR)/Application.mk diff --git a/examples/sotest/modprint/Kconfig b/examples/sotest/modprint/Kconfig deleted file mode 100644 index f72f3c094..000000000 --- a/examples/sotest/modprint/Kconfig +++ /dev/null @@ -1,4 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# diff --git a/examples/sotest/sotest/Kconfig b/examples/sotest/sotest/Kconfig deleted file mode 100644 index f72f3c094..000000000 --- a/examples/sotest/sotest/Kconfig +++ /dev/null @@ -1,4 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# diff --git a/examples/sotest/sotest/Make.defs b/examples/sotest/sotest/Make.defs deleted file mode 100644 index 08c4edce1..000000000 --- a/examples/sotest/sotest/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/examples/sotest/sotest/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_EXAMPLES_SOTEST),) -CONFIGURED_APPS += $(APPDIR)/examples/sotest/sotest -endif diff --git a/examples/sotest/main/sotest_main.c b/examples/sotest/sotest_main.c similarity index 95% rename from examples/sotest/main/sotest_main.c rename to examples/sotest/sotest_main.c index 030717e0c..5c1568e59 100644 --- a/examples/sotest/main/sotest_main.c +++ b/examples/sotest/sotest_main.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/sotest/main/sotest_main.c + * apps/examples/sotest/sotest_main.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -69,7 +69,7 @@ # define SECTORSIZE 64 # define NSECTORS(b) (((b)+SECTORSIZE-1)/SECTORSIZE) -# define BINDIR "/mnt/sotest/romfs" +# define BINDIR "/mnt/romfs" # ifndef CONFIG_EXAMPLES_SOTEST_DEVMINOR # define CONFIG_EXAMPLES_SOTEST_DEVMINOR 0 @@ -85,8 +85,8 @@ ****************************************************************************/ #ifdef CONFIG_EXAMPLES_SOTEST_BUILTINFS -extern const unsigned char sotest_romfs_img[]; -extern const unsigned int sotest_romfs_img_len; +extern const unsigned char romfs_img[]; +extern const unsigned int romfs_img_len; #endif extern const struct symtab_s g_sot_exports[]; @@ -102,9 +102,7 @@ extern const int g_sot_nexports; int main(int argc, FAR char *argv[]) { -#ifdef CONFIG_EXAMPLES_SOTEST_BUILTINFS char devname[32]; -#endif #if CONFIG_MODLIB_MAXDEPEND > 0 FAR void *handle1; #endif @@ -128,9 +126,9 @@ int main(int argc, FAR char *argv[]) /* Create a ROM disk for the ROMFS filesystem */ desc.minor = CONFIG_EXAMPLES_SOTEST_DEVMINOR; /* Minor device number of the ROM disk. */ - desc.nsectors = NSECTORS(sotest_romfs_img_len); /* The number of sectors in the ROM disk */ + desc.nsectors = NSECTORS(romfs_img_len); /* The number of sectors in the ROM disk */ desc.sectsize = SECTORSIZE; /* The size of one sector in bytes */ - desc.image = (FAR uint8_t *)sotest_romfs_img; /* File system image */ + desc.image = (FAR uint8_t *)romfs_img; /* File system image */ printf("main: Registering romdisk at /dev/ram%d\n", CONFIG_EXAMPLES_SOTEST_DEVMINOR); diff --git a/testing/cxxtest/CMakeLists.txt b/examples/stepper/CMakeLists.txt similarity index 89% rename from testing/cxxtest/CMakeLists.txt rename to examples/stepper/CMakeLists.txt index b191a01cf..a86573c92 100644 --- a/testing/cxxtest/CMakeLists.txt +++ b/examples/stepper/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/testing/cxxtest/CMakeLists.txt +# apps/examples/stepper/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,14 +18,14 @@ # # ############################################################################## -if(CONFIG_TESTING_CXXTEST) +if(CONFIG_EXAMPLES_STEPPER) nuttx_add_application( NAME - cxxtest + stepper STACKSIZE ${CONFIG_DEFAULT_TASK_STACKSIZE} MODULE - ${CONFIG_TESTING_CXXTEST} + ${CONFIG_EXAMPLES_STEPPER} SRCS - cxxtest_main.cxx) + stepper.c) endif() diff --git a/testing/kasantest/Kconfig b/examples/stepper/Kconfig similarity index 61% rename from testing/kasantest/Kconfig rename to examples/stepper/Kconfig index 16c7b237e..6294b96b1 100644 --- a/testing/kasantest/Kconfig +++ b/examples/stepper/Kconfig @@ -3,8 +3,8 @@ # see the file kconfig-language.txt in the NuttX tools repository. # -config TESTING_KASAN - tristate "KASan validity test" +config EXAMPLES_STEPPER + tristate "Stepper controller test" default n ---help--- - Enable the KASan validity test + Enable the stepper controller test diff --git a/examples/stepper/Make.defs b/examples/stepper/Make.defs new file mode 100644 index 000000000..e98fa345c --- /dev/null +++ b/examples/stepper/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/examples/stepper/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_EXAMPLES_STEPPER),) +CONFIGURED_APPS += $(APPDIR)/examples/stepper +endif diff --git a/testing/kasantest/Makefile b/examples/stepper/Makefile similarity index 84% rename from testing/kasantest/Makefile rename to examples/stepper/Makefile index 1a80c2ac8..00fb19999 100644 --- a/testing/kasantest/Makefile +++ b/examples/stepper/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/testing/kasantest/Makefile +# apps/examples/stepper/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,13 +20,15 @@ include $(APPDIR)/Make.defs -# KASan validity test +# Stepper example -MAINSRC = kasantest.c -PROGNAME = kasantest -PRIORITY = SCHED_PRIORITY_DEFAULT +MAINSRC = stepper.c + +# stepper built-in application info + +PROGNAME = stepper +PRIORITY = SCHED_PRIORITY_DEFAULT STACKSIZE = $(CONFIG_DEFAULT_TASK_STACKSIZE) - -CFLAGS += -Wno-error -Wno-use-after-free +MODULE = $(CONFIG_EXAMPLES_STEPPER) include $(APPDIR)/Application.mk diff --git a/examples/stepper/stepper.c b/examples/stepper/stepper.c new file mode 100644 index 000000000..13b727c6d --- /dev/null +++ b/examples/stepper/stepper.c @@ -0,0 +1,163 @@ +/**************************************************************************** + * apps/examples/stepper/stepper.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include + +#include + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +struct stepper_args +{ + FAR const char *path; + int microstep; + int speed; + int steps; +}; + +static int parse_args(int argc, FAR char *argv[], + FAR struct stepper_args *args) +{ + int i; + + if (argc < 3) + { + return -1; + } + + args->path = argv[1]; + args->microstep = -1; + args->speed = 200; + + for (i i = 2; i < argc; ++i) + { + if (strncmp("-m", argv[i], 2) == 0) + { + i++; + if (i >= argc) + { + return -1; + } + + args->microstep = atoi(argv[i]); + i++; + } + + if (strncmp("-s", argv[i], 2) == 0) + { + i++; + if (i >= argc) + { + return -1; + } + + args->speed = atoi(argv[i]); + i++; + } + } + + args->steps = atoi(argv[argc - 1]); + return 0; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int main(int argc, FAR char *argv[]) +{ + struct stepper_args args; + struct stepper_status_s status; + struct stepper_job_s job; + int fd; + int rc; + + if (parse_args(argc, argv, &args) < 0) + { + printf("usage:\n" + "stepper path\n" + " [-m microstep (sticky)]\n" + " [-s speed in steps/s (default 200)]\n" + " steps (positive: CW, negative: CCW)\n"); + return 1; + } + + fd = open(args.path, O_RDWR); + if (fd < 0) + { + printf("Oops: %s\n", strerror(errno)); + exit(1); + } + + if (args.microstep > 0) + { + printf("Set microstepping to %d\n", args.microstep); + rc = ioctl(fd, STEPIOC_MICROSTEPPING, args.microstep); + if (rc < 0) + { + printf("STEPIOC_MICROSTEPPING: %s\n", strerror(errno)); + exit(2); + } + } + + job.steps = args.steps; + job.speed = args.speed; + + /* Retrieve the absolute position - before movement */ + + rc = read(fd, &status, sizeof(struct stepper_status_s)); + if (rc != sizeof(struct stepper_status_s)) + { + printf("read: %s\n", strerror(errno)); + } + + printf("Position before stepper motor moving: %ld\n", status.position); + + /* Move the stepper */ + + printf("GO -> %ld @ %ld steps/s\n", job.steps, job.speed); + + rc = write(fd, &job, sizeof(struct stepper_job_s)); /* blocking */ + if (rc != sizeof(struct stepper_job_s)) + { + printf("write: %s\n", strerror(errno)); + } + + /* Retrieve the absolute position - after movement */ + + rc = read(fd, &status, sizeof(struct stepper_status_s)); + if (rc != sizeof(struct stepper_status_s)) + { + printf("read: %s\n", strerror(errno)); + } + + printf("Position after stepper motor moving: %ld\n", status.position); + + return 0; +} diff --git a/examples/tcp_ipc_client/README.md b/examples/tcp_ipc_client/README.md deleted file mode 100644 index 70dc8c149..000000000 --- a/examples/tcp_ipc_client/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Client TCP - -## What's this? - -This program consists of a client socket & custom messages that send data (hex-string formatted data) to a server (tcp_ipc_server). -Then, tcp_ipc_server send this data over LoraWAN (using Radioenge LoRaWAN module). It means using TCP/IP sockets as IPC channel to ensure controlled access to LoRaWAN connectivity. -The goals of using this approach to send LoRaWAN data are: - -* Having a solid and reliable infrastructure to ensure IPC works fine for multiple applications simultaneously -* Having the possibility to host different IoT projects and solutions that use LPWAN in a single ESP32 -* Having the possibility to validate, test and debug multiple IoT projects and solutions at the same time, under the same connectivity conditions (same signal strength, same antenna, same modem/transceiver, etc.) - -Both client and server work on local network scope. - - -## How do I use this? - -In order to test tcp_ipc_client & tcp_ipc_server together, there are two ways to proceed: - -1) Init server manually (command: SERVER &), and after successfull server init, also init client manually (CLIENT 127.0.0.1) -2) init server automatically after boot using NuttShell start up scripts (check: https://nuttx.apache.org/docs/latest/applications/nsh/installation.html#nuttshell-start-up-scripts ) - -## Additional info - -Both tcp_ipc_client and tcp_ipc_server examples have been full covered in NuttX International Workshop 2022. You can watch the full presentation here: https://www.youtube.com/watch?v=hr0OfTt1KeY -The tcp_ipc_server and tcp_ipc_client examples have been developed by Flavio Ipirranga and Pedro Bertoleti from Instituto de Pesquisas Eldorado (IPE) in Brazil. \ No newline at end of file diff --git a/examples/tcp_ipc_client/protocol.h b/examples/tcp_ipc_client/protocol.h index 3173b6113..ecd546bc0 100644 --- a/examples/tcp_ipc_client/protocol.h +++ b/examples/tcp_ipc_client/protocol.h @@ -38,4 +38,4 @@ typedef struct void send_msg_to_lpwan (unsigned char *msg, protocolo_ipc *pt_protocol); -#endif /* __APPS_EXAMPLES_TCP_IPC_CLIENT_PROTOCOL_H */ +#endif /* __APPS_EXAMPLES_TCP_IPC_CLIENT_PROTOCOL_H */ \ No newline at end of file diff --git a/examples/tcp_ipc_server/README.md b/examples/tcp_ipc_server/README.md deleted file mode 100644 index 73019242e..000000000 --- a/examples/tcp_ipc_server/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Server TCP - -## What's this? - -This program consists of a server socket & custom messages to establish IPC for multiple applications (client_tcp) and one process that controls LoRaWAN connectivity (server_tcp). -For more details about client side, please see client_tcp example. - -This approach using TCP/IP sockets as IPC channel ensures controlled access to LoRaWAN connectivity. -The goals of using this approach are: - -* Having a solid and reliable infrastructure to ensure IPC works fine for multiple applications simultaneously -* Having the possibility to host different IoT projects and solutions that use LPWAN in a single ESP32 -* Having the possibility to validate, test and debug multiple IoT projects and solutions at the same time, under the same connectivity conditions (same signal strength, same antenna, same modem/transceiver, etc.) - -Both client and server work on local network scope. - - -## How do I use this? - -In order to test client_tcp & server_tcp together, there are two ways to proceed: - -1) Init server manually (command: SERVER &), and after successfull server init, also init client manually (CLIENT 127.0.0.1) -2) init server automatically after boot using NuttShell start up scripts (check: https://nuttx.apache.org/docs/latest/applications/nsh/installation.html#nuttshell-start-up-scripts ) - -## Additional info - -Both client_tcp and server_tcp examples have been full covered in NuttX International Workshop 2022. You can watch the full presentation here: https://www.youtube.com/watch?v=hr0OfTt1KeY -The server_tcp and client_tcp examples have been developed by Flavio Ipirranga and Pedro Bertoleti from Instituto de Pesquisas Eldorado (IPE) in Brazil. \ No newline at end of file diff --git a/examples/tcp_ipc_server/protocol.h b/examples/tcp_ipc_server/protocol.h index c0541a9d6..a49cae10e 100644 --- a/examples/tcp_ipc_server/protocol.h +++ b/examples/tcp_ipc_server/protocol.h @@ -38,4 +38,4 @@ typedef struct void send_msg_to_lpwan (unsigned char *msg, protocolo_ipc *pt_protocol); -#endif /* __APPS_EXAMPLES_SERVER_TCP_PROTOCOL_H */ +#endif /* __APPS_EXAMPLES_SERVER_TCP_PROTOCOL_H */ \ No newline at end of file diff --git a/examples/tcp_ipc_server/tcp_ipc_server_main.c b/examples/tcp_ipc_server/tcp_ipc_server_main.c index e7d0b50b0..7f00715c2 100644 --- a/examples/tcp_ipc_server/tcp_ipc_server_main.c +++ b/examples/tcp_ipc_server/tcp_ipc_server_main.c @@ -243,9 +243,9 @@ int main(int argc, char *argv[]) /* Wait for a new client socket connection */ addr_size = sizeof server_storage; - new_socket_client_fd = accept4(socket_server_fd, - (struct sockaddr *)&server_storage, - &addr_size, SOCK_CLOEXEC); + new_socket_client_fd = accept(socket_server_fd, + (struct sockaddr *)&server_storage, + &addr_size); if (new_socket_client_fd < 0) { diff --git a/examples/tcpblaster/README.md b/examples/tcpblaster/README.md deleted file mode 100644 index 1ad0e3f3d..000000000 --- a/examples/tcpblaster/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Examples / `tcpblaster` TCP Performance Test - -To set up, do `make menuconfig` and select the _Apps_ → _Examples_ → -_tcpblaster_. By default, nuttx will the be the client which sends data; and the -host computer (Linux, macOS, or Windows) will be the server. - -Set up networking so the nuttx computer can ping the host, and the host can ping -nuttx. Now you are ready to run the test. - -On host: - -``` -$ ./tcpserver -Binding to IPv4 Address: 00000000 -server: Accepting connections on port 5471 -``` - -On nuttx: - -``` -nsh> tcpclient -Connecting to IPv4 Address: 0100000a -client: Connected -[2014-07-31 00:16:15.000] 0: Sent 200 4096-byte buffers: 800.0 KB (avg 4.0 KB) in 0.18 seconds (4444.4 KB/second) -``` - -Now on the host you should see something like: - -``` -$ ./tcpserver -Binding to IPv4 Address: 00000000 -server: Accepting connections on port 5471 -server: Connection accepted -- receiving -[2020-02-22 16:17:07.000] 0: Received 200 buffers: 502.9 KB (buffer average size: 2.5 KB) in 0.12 seconds (4194.8 KB/second) -[2020-02-22 16:17:07.000] 1: Received 200 buffers: 393.1 KB (buffer average size: 2.0 KB) in 0.09 seconds (4299.4 KB/second) -``` - -This will tell you the link speed in KB/sec – kilobytes per second. If you want -kilobits, multiply by `8`. - -You can use the `make menuconfig` to reverse the setup, and have nuttx be the -server, and the host be the client. If you do that, start the server first -(nuttx), then start the client (host). diff --git a/examples/tcpblaster/tcpblaster_server.c b/examples/tcpblaster/tcpblaster_server.c index c1a576965..ea7311d2a 100644 --- a/examples/tcpblaster/tcpblaster_server.c +++ b/examples/tcpblaster/tcpblaster_server.c @@ -153,8 +153,7 @@ void tcpblaster_server(void) printf("server: Accepting connections on port %d\n", CONFIG_EXAMPLES_TCPBLASTER_SERVER_PORTNO); - acceptsd = accept4(listensd, (FAR struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (FAR struct sockaddr *)&myaddr, &addrlen); if (acceptsd < 0) { printf("server: accept failure: %d\n", errno); diff --git a/examples/tcpecho/tcpecho_main.c b/examples/tcpecho/tcpecho_main.c index 6ad687679..6524048b0 100644 --- a/examples/tcpecho/tcpecho_main.c +++ b/examples/tcpecho/tcpecho_main.c @@ -244,8 +244,7 @@ static int tcpecho_server(void) /* new client connection */ clilen = sizeof(cliaddr); - connfd = accept4(listenfd, (struct sockaddr *)&cliaddr, &clilen, - SOCK_CLOEXEC); + connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); ninfo("new client: %s\n", inet_ntoa_r(cliaddr.sin_addr, inetaddr, sizeof(inetaddr))); diff --git a/examples/telnetd/CMakeLists.txt b/examples/telnetd/CMakeLists.txt index 941b53524..737d8bb76 100644 --- a/examples/telnetd/CMakeLists.txt +++ b/examples/telnetd/CMakeLists.txt @@ -21,7 +21,7 @@ if(CONFIG_EXAMPLES_TELNETD) nuttx_add_application( NAME - example_telnetd + telnetd PRIORITY ${CONFIG_EXAMPLES_TELNETD_DAEMONPRIO} STACKSIZE diff --git a/examples/telnetd/Makefile b/examples/telnetd/Makefile index 35ebef77c..f12fec619 100644 --- a/examples/telnetd/Makefile +++ b/examples/telnetd/Makefile @@ -26,7 +26,7 @@ MAINSRC = telnetd.c # Buttons built-in application info -PROGNAME = example_telnetd +PROGNAME = telnetd PRIORITY = $(CONFIG_EXAMPLES_TELNETD_DAEMONPRIO) STACKSIZE = $(CONFIG_EXAMPLES_TELNETD_DAEMONSTACKSIZE) MODULE = $(CONFIG_EXAMPLES_TELNETD) diff --git a/examples/telnetd/README.md b/examples/telnetd/README.md deleted file mode 100644 index 28cd2e12e..000000000 --- a/examples/telnetd/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Examples / `telnetd` Telnet Daemon - -This directory contains a functional port of the tiny uIP shell. In the NuttX -environment, the NuttShell (at `apps/nshlib`) supersedes this tiny shell and -also supports telnetd. - -This example is retained here for reference purposes only. diff --git a/examples/tiff/tiff_main.c b/examples/tiff/tiff_main.c index f511e9791..72d5afb16 100644 --- a/examples/tiff/tiff_main.c +++ b/examples/tiff/tiff_main.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/graphics/tiff/tiff_main.c + * apps/examples/tiff/tiff_main.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -33,10 +33,13 @@ /**************************************************************************** * Pre-Processor Definitions ****************************************************************************/ + /* Configuration ************************************************************/ -/* This is a simple unit test for the TIFF creation library at apps/graphic/tiff. - * It is configured to work in the Linux user-mode simulation and has not been - * tested in any other environment. + +/* This is a simple unit test for the TIFF creation library at + * apps/graphic/tiff. + * It is configured to work in the Linux user-mode simulation and + * has not been tested in any other environment. * * Other configuration options: * @@ -88,7 +91,7 @@ int main(int argc, FAR char *argv[]) { struct tiff_info_s info; - uint8_t strip[3*256]; + uint8_t strip[3 * 256]; uint8_t *ptr; int green; int blue; @@ -144,5 +147,6 @@ int main(int argc, FAR char *argv[]) printf("tiff_finalize() failed: %d\n", ret); exit(1); } + return 0; } diff --git a/examples/tlpi/.gitignore b/examples/tlpi/.gitignore deleted file mode 100644 index 2f57dd394..000000000 --- a/examples/tlpi/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/tlpi diff --git a/examples/tlpi/Kconfig b/examples/tlpi/Kconfig deleted file mode 100644 index 1f366b701..000000000 --- a/examples/tlpi/Kconfig +++ /dev/null @@ -1,22 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config EXAMPLES_TLPI - tristate "The Linux Programming Interface Example" - default n - ---help--- - Enable the tlpi - -if EXAMPLES_TLPI - -config EXAMPLES_TLPI_PRIORITY - int "Task priority" - default 100 - -config EXAMPLES_TLPI_STACKSIZE - int "Stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/examples/tlpi/Makefile b/examples/tlpi/Makefile deleted file mode 100644 index 6b2fef4ce..000000000 --- a/examples/tlpi/Makefile +++ /dev/null @@ -1,455 +0,0 @@ -############################################################################ -# apps/examples/tlpi/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -PRIORITY = $(CONFIG_EXAMPLES_TLPI_PRIORITY) -STACKSIZE = $(CONFIG_EXAMPLES_TLPI_STACKSIZE) -MODULE = $(CONFIG_EXAMPLES_TLPI) -TLPIDIR = $(APPDIR)/examples/tlpi/tlpi - -#CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/cap -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/daemons -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/filelock -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/files -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/lib -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/namespaces -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/pipes -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/procexec -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/procres -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/pty -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/seccomp -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/signals -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/sockets -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/svmsg -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/svsem -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/time -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/timers -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/tty -CFLAGS += ${INCDIR_PREFIX}$(TLPIDIR)/users_groups -CFLAGS += -Wno-strict-prototypes -Wno-unused-variable -Wno-unused-but-set-variable - -#CSRCS += $(TLPIDIR)/cap/cap_functions.c \ -# $(TLPIDIR)/daemons/become_daemon.c -CSRCS += $(TLPIDIR)/filelock/create_pid_file.c \ - $(TLPIDIR)/filelock/region_locking.c \ - $(TLPIDIR)/files/file_perms.c \ - $(TLPIDIR)/lib/alt_functions.c \ - $(TLPIDIR)/lib/error_functions.c \ - $(TLPIDIR)/lib/get_num.c -# $(TLPIDIR)/namespaces/userns_functions.c -CSRCS += $(TLPIDIR)/procexec/execlp.c \ - $(TLPIDIR)/procexec/print_wait_status.c \ - $(TLPIDIR)/procexec/simple_system.c \ - $(TLPIDIR)/procexec/system.c \ - $(TLPIDIR)/procres/print_rlimit.c -# $(TLPIDIR)/procres/print_rusage.c \ -# $(TLPIDIR)/pty/pty_fork.c -CSRCS += $(TLPIDIR)/pty/pty_master_open.c -# $(TLPIDIR)/pty/pty_master_open_bsd.c \ -# $(TLPIDIR)/seccomp/seccomp_functions.c -CSRCS += $(TLPIDIR)/signals/siginterrupt.c \ - $(TLPIDIR)/signals/signal.c \ - $(TLPIDIR)/signals/signal_functions.c \ - $(TLPIDIR)/sockets/inet_sockets.c \ - $(TLPIDIR)/sockets/rdwrn.c \ - $(TLPIDIR)/sockets/read_line.c \ - $(TLPIDIR)/sockets/read_line_buf.c \ - $(TLPIDIR)/sockets/scm_functions.c \ - $(TLPIDIR)/sockets/sendfile.c \ - $(TLPIDIR)/sockets/unix_sockets.c -# $(TLPIDIR)/svsem/binary_sems.c \ -# $(TLPIDIR)/svsem/event_flags.c \ -# $(TLPIDIR)/threads/strerror.c \ -# $(TLPIDIR)/threads/strerror_tls.c \ -# $(TLPIDIR)/threads/strerror_tsd.c -CSRCS += $(TLPIDIR)/time/curr_time.c \ - $(TLPIDIR)/timers/itimerspec_from_str.c \ - $(TLPIDIR)/tty/tty_functions.c \ - $(TLPIDIR)/tty/ttyname.c \ - $(TLPIDIR)/users_groups/ugid_functions.c - -# acl -#MAINSRC += $(TLPIDIR)/acl/acl_update.c \ -# $(TLPIDIR)/acl/acl_view.c -# altio -MAINSRC += $(TLPIDIR)/altio/demo_sigio.c \ - $(TLPIDIR)/altio/epoll_flags_fork.c \ - $(TLPIDIR)/altio/epoll_input.c \ - $(TLPIDIR)/altio/multithread_epoll_wait.c \ - $(TLPIDIR)/altio/poll_pipes.c \ - $(TLPIDIR)/altio/select_mq.c \ - $(TLPIDIR)/altio/self_pipe.c \ - $(TLPIDIR)/altio/t_select.c -# cap -#MAINSRC += $(TLPIDIR)/cap/cap_launcher.c \ -# $(TLPIDIR)/cap/cap_text.c \ -# $(TLPIDIR)/cap/check_password_caps.c \ -# $(TLPIDIR)/cap/demo_file_caps.c \ -# $(TLPIDIR)/cap/show_secbits.c \ -# $(TLPIDIR)/cap/t_cap_get_file.c \ -# $(TLPIDIR)/cap/t_cap_get_pid.c \ -# $(TLPIDIR)/cap/t_cap_set_file.c \ -# $(TLPIDIR)/cap/view_cap_xattr.c -# cgroups -#MAINSRC += $(TLPIDIR)/cgroups/alloc_mem.c -MAINSRC += $(TLPIDIR)/cgroups/fork_bomb.c -# $(TLPIDIR)/cgroups/fork_bomb_simple.c - -# daemons -#MAINSRC += $(TLPIDIR)/daemons/daemon_SIGHUP.c -MAINSRC += $(TLPIDIR)/daemons/t_syslog.c -# $(TLPIDIR)/daemons/test_become_daemon.c -# dirs_links -MAINSRC += $(TLPIDIR)/dirs_links/bad_symlink.c \ - $(TLPIDIR)/dirs_links/file_type_stats.c \ - $(TLPIDIR)/dirs_links/list_files.c \ - $(TLPIDIR)/dirs_links/list_files_readdir_r.c \ - $(TLPIDIR)/dirs_links/nftw_dir_tree.c \ - $(TLPIDIR)/dirs_links/t_unlink.c \ - $(TLPIDIR)/dirs_links/t_dirbasename.c \ - $(TLPIDIR)/dirs_links/view_symlink.c -# filebuff -MAINSRC += $(TLPIDIR)/filebuff/direct_read.c \ - $(TLPIDIR)/filebuff/mix23_linebuff.c \ - $(TLPIDIR)/filebuff/mix23io.c \ - $(TLPIDIR)/filebuff/write_bytes.c -# fileio -MAINSRC += $(TLPIDIR)/fileio/atomic_append.c \ - $(TLPIDIR)/fileio/bad_exclusive_open.c \ - $(TLPIDIR)/fileio/copy.c \ - $(TLPIDIR)/fileio/large_file.c \ - $(TLPIDIR)/fileio/multi_descriptors.c \ - $(TLPIDIR)/fileio/seek_io.c \ - $(TLPIDIR)/fileio/t_readv.c \ - $(TLPIDIR)/fileio/t_truncate.c -# filelock -MAINSRC += $(TLPIDIR)/filelock/i_fcntl_locking.c -# $(TLPIDIR)/filelock/t_flock.c -# files -MAINSRC += $(TLPIDIR)/files/chiflag.c \ - $(TLPIDIR)/files/t_chown.c \ - $(TLPIDIR)/files/t_stat.c \ - $(TLPIDIR)/files/t_umask.c \ - $(TLPIDIR)/files/t_utime.c \ - $(TLPIDIR)/files/t_utimes.c -# filesys -#MAINSRC += $(TLPIDIR)/filesys/t_mount.c \ -# $(TLPIDIR)/filesys/t_statfs.c -MAINSRC += $(TLPIDIR)/filesys/t_statvfs.c \ - $(TLPIDIR)/filesys/t_umount.c -# getopt -MAINSRC += $(TLPIDIR)/getopt/t_getopt.c -# inotify -MAINSRC += $(TLPIDIR)/inotify/demo_inotify.c -# $(TLPIDIR)/inotify/dnotify.c \ -# $(TLPIDIR)/inotify/inotify_dtree.c -MAINSRC += $(TLPIDIR)/inotify/rand_dtree.c -# loginacct -#MAINSRC += $(TLPIDIR)/loginacct/dump_utmpx.c \ -# $(TLPIDIR)/loginacct/utmpx_login.c \ -# $(TLPIDIR)/loginacct/view_lastlog.c -# memalloc -ifneq ($(CONFIG_BUILD_KERNEL),) -MAINSRC += $(TLPIDIR)/memalloc/free_and_sbrk.c -endif -# mmap -MAINSRC += $(TLPIDIR)/mmap/anon_mmap.c \ - $(TLPIDIR)/mmap/mmcat.c \ - $(TLPIDIR)/mmap/mmcopy.c \ - $(TLPIDIR)/mmap/t_mmap.c -# $(TLPIDIR)/mmap/t_remap_file_pages.c -# namespaces -#MAINSRC += $(TLPIDIR)/namespaces/cred_launcher.c \ -# $(TLPIDIR)/namespaces/demo_userns.c \ -# $(TLPIDIR)/namespaces/demo_uts_namespaces.c -MAINSRC += $(TLPIDIR)/namespaces/hostname.c -# $(TLPIDIR)/namespaces/make_orphans.c \ -# $(TLPIDIR)/namespaces/multi_pidns.c \ -# $(TLPIDIR)/namespaces/ns_capable.c \ -# $(TLPIDIR)/namespaces/ns_child_exec.c \ -# $(TLPIDIR)/namespaces/ns_exec.c \ -# $(TLPIDIR)/namespaces/ns_run.c \ -# $(TLPIDIR)/namespaces/orphan.c \ -# $(TLPIDIR)/namespaces/pidns_init_sleep.c \ -# $(TLPIDIR)/namespaces/show_creds.c \ -# $(TLPIDIR)/namespaces/simple_init.c \ -# $(TLPIDIR)/namespaces/t_setns_userns.c \ -# $(TLPIDIR)/namespaces/unshare.c \ -# $(TLPIDIR)/namespaces/userns_child_exec.c \ -# $(TLPIDIR)/namespaces/userns_setns_test.c -# pgsjc -#MAINSRC += $(TLPIDIR)/pgsjc/catch_SIGHUP.c \ -# $(TLPIDIR)/pgsjc/disc_SIGHUP.c -MAINSRC += $(TLPIDIR)/pgsjc/handling_SIGTSTP.c -# $(TLPIDIR)/pgsjc/job_mon.c \ -# $(TLPIDIR)/pgsjc/orphaned_pgrp_SIGHUP.c \ -# $(TLPIDIR)/pgsjc/t_setsid.c -# pipes -MAINSRC += $(TLPIDIR)/pipes/change_case.c \ - $(TLPIDIR)/pipes/fifo_seqnum_client.c \ - $(TLPIDIR)/pipes/fifo_seqnum_server.c -# $(TLPIDIR)/pipes/popen_glob.c -MAINSRC += $(TLPIDIR)/pipes/pipe_ls_wc.c \ - $(TLPIDIR)/pipes/pipe_sync.c \ - $(TLPIDIR)/pipes/simple_pipe.c -# pmsg -MAINSRC += $(TLPIDIR)/pmsg/mq_notify_sig.c \ - $(TLPIDIR)/pmsg/mq_notify_siginfo.c -# $(TLPIDIR)/pmsg/mq_notify_sigwaitinfo.c \ -# $(TLPIDIR)/pmsg/mq_notify_thread.c -MAINSRC += $(TLPIDIR)/pmsg/mq_notify_via_signal.c -# $(TLPIDIR)/pmsg/mq_notify_via_thread.c -MAINSRC += $(TLPIDIR)/pmsg/pmsg_create.c -# $(TLPIDIR)/pmsg/pmsg_getattr.c -MAINSRC += $(TLPIDIR)/pmsg/pmsg_receive.c \ - $(TLPIDIR)/pmsg/pmsg_send.c \ - $(TLPIDIR)/pmsg/pmsg_unlink.c -# proc -MAINSRC += $(TLPIDIR)/proc/bad_longjmp.c \ - $(TLPIDIR)/proc/display_env.c \ - $(TLPIDIR)/proc/longjmp.c \ - $(TLPIDIR)/proc/mem_segments.c \ - $(TLPIDIR)/proc/modify_env.c \ - $(TLPIDIR)/proc/necho.c -# $(TLPIDIR)/proc/setenv.c -MAINSRC += $(TLPIDIR)/proc/setjmp_vars.c \ - $(TLPIDIR)/proc/t_getenv.c -# proccred -#MAINSRC += $(TLPIDIR)/proccred/idshow.c -# procexec -#MAINSRC += $(TLPIDIR)/procexec/acct_on.c \ -# $(TLPIDIR)/procexec/acct_view.c \ -# $(TLPIDIR)/procexec/acct_v3_view.c -MAINSRC += $(TLPIDIR)/procexec/child_status.c \ - $(TLPIDIR)/procexec/closeonexec.c -# $(TLPIDIR)/procexec/demo_clone.c -MAINSRC += $(TLPIDIR)/procexec/envargs.c \ - $(TLPIDIR)/procexec/exit_handlers.c -ifneq ($(CONFIG_BUILD_KERNEL),) -MAINSRC += $(TLPIDIR)/procexec/footprint.c -endif -MAINSRC += $(TLPIDIR)/procexec/fork_file_sharing.c \ - $(TLPIDIR)/procexec/fork_stdio_buf.c \ - $(TLPIDIR)/procexec/fork_sig_sync.c \ - $(TLPIDIR)/procexec/fork_whos_on_first.c \ - $(TLPIDIR)/procexec/make_zombie.c \ - $(TLPIDIR)/procexec/multi_SIGCHLD.c \ - $(TLPIDIR)/procexec/multi_wait.c \ - $(TLPIDIR)/procexec/orphan.c -# $(TLPIDIR)/procexec/pdeath_signal.c -# $(TLPIDIR)/procexec/t_clone.c -MAINSRC += $(TLPIDIR)/procexec/t_execl.c \ - $(TLPIDIR)/procexec/t_execle.c \ - $(TLPIDIR)/procexec/t_execlp.c \ - $(TLPIDIR)/procexec/t_execve.c \ - $(TLPIDIR)/procexec/t_fork.c \ - $(TLPIDIR)/procexec/t_system.c \ - $(TLPIDIR)/procexec/t_vfork.c \ - $(TLPIDIR)/procexec/vfork_fd_test.c -# procpri -MAINSRC += $(TLPIDIR)/procpri/demo_sched_fifo.c \ - $(TLPIDIR)/procpri/sched_set.c \ - $(TLPIDIR)/procpri/sched_view.c -# $(TLPIDIR)/procpri/t_sched_getaffinity.c -MAINSRC += $(TLPIDIR)/procpri/t_sched_setaffinity.c \ - $(TLPIDIR)/procpri/t_setpriority.c -# procres -#MAINSRC += $(TLPIDIR)/procres/rlimit_nproc.c \ -# $(TLPIDIR)/procres/rusage.c -MAINSRC += $(TLPIDIR)/procres/rusage_wait.c -# progconc -MAINSRC += $(TLPIDIR)/progconc/syscall_speed.c -# psem -MAINSRC += $(TLPIDIR)/psem/psem_create.c \ - $(TLPIDIR)/psem/psem_getvalue.c \ - $(TLPIDIR)/psem/psem_timedwait.c \ - $(TLPIDIR)/psem/psem_trywait.c \ - $(TLPIDIR)/psem/psem_post.c \ - $(TLPIDIR)/psem/psem_unlink.c \ - $(TLPIDIR)/psem/psem_wait.c \ - $(TLPIDIR)/psem/thread_incr_psem.c -# pshm -MAINSRC += $(TLPIDIR)/pshm/pshm_create.c \ - $(TLPIDIR)/pshm/pshm_read.c \ - $(TLPIDIR)/pshm/pshm_unlink.c \ - $(TLPIDIR)/pshm/pshm_write.c -# pty -#MAINSRC += $(TLPIDIR)/pty/script.c \ -# $(TLPIDIR)/pty/unbuffer.c -# shlibs -#MAINSRC += $(TLPIDIR)/seccomp/dump_seccomp_filter.c \ -# $(TLPIDIR)/seccomp/libseccomp_demo.c \ -# $(TLPIDIR)/seccomp/seccomp_arg64.c \ -# $(TLPIDIR)/seccomp/seccomp_bench.c \ -# $(TLPIDIR)/seccomp/seccomp_control_open.c \ -# $(TLPIDIR)/seccomp/seccomp_deny_open.c \ -# $(TLPIDIR)/seccomp/seccomp_deny_syscall.c \ -# $(TLPIDIR)/seccomp/seccomp_launch.c \ -# $(TLPIDIR)/seccomp/seccomp_logging.c \ -# $(TLPIDIR)/seccomp/seccomp_multiarch.c \ -# $(TLPIDIR)/seccomp/seccomp_perf.c \ -# $(TLPIDIR)/seccomp/seccomp_trap_sigsys.c \ -# $(TLPIDIR)/seccomp/seccomp_unotify_mkdir.c \ -# $(TLPIDIR)/seccomp/seccomp_unotify_openat.c -# shlibs -MAINSRC += $(TLPIDIR)/shlibs/dynload.c -# signals -#MAINSRC += $(TLPIDIR)/signals/catch_rtsigs.c -MAINSRC += $(TLPIDIR)/signals/demo_SIGFPE.c \ - $(TLPIDIR)/signals/ignore_pending_sig.c \ - $(TLPIDIR)/signals/intquit.c -# $(TLPIDIR)/signals/nonreentrant.c -MAINSRC += $(TLPIDIR)/signals/ouch.c \ - $(TLPIDIR)/signals/sig_receiver.c \ - $(TLPIDIR)/signals/sig_sender.c \ - $(TLPIDIR)/signals/sig_speed_sigsuspend.c \ - $(TLPIDIR)/signals/sigmask_longjmp.c \ - $(TLPIDIR)/signals/signalfd_sigval.c \ - $(TLPIDIR)/signals/t_kill.c -# $(TLPIDIR)/signals/t_sigaltstack.c -MAINSRC += $(TLPIDIR)/signals/t_sigqueue.c \ - $(TLPIDIR)/signals/t_sigsuspend.c -# $(TLPIDIR)/signals/t_sigwaitinfo.c -# sockets -MAINSRC += $(TLPIDIR)/sockets/id_echo_cl.c -# $(TLPIDIR)/sockets/id_echo_sv.c -MAINSRC += $(TLPIDIR)/sockets/is_echo_cl.c \ - $(TLPIDIR)/sockets/is_echo_inetd_sv.c -# $(TLPIDIR)/sockets/is_echo_sv.c \ -# $(TLPIDIR)/sockets/is_echo_v2_sv.c -MAINSRC += $(TLPIDIR)/sockets/is_seqnum_cl.c \ - $(TLPIDIR)/sockets/is_seqnum_sv.c \ - $(TLPIDIR)/sockets/is_seqnum_v2_cl.c \ - $(TLPIDIR)/sockets/is_seqnum_v2_sv.c \ - $(TLPIDIR)/sockets/i6d_ucase_cl.c \ - $(TLPIDIR)/sockets/i6d_ucase_sv.c \ - $(TLPIDIR)/sockets/list_host_addresses.c -# $(TLPIDIR)/sockets/scm_cred_recv.c -MAINSRC += $(TLPIDIR)/sockets/scm_cred_send.c -# $(TLPIDIR)/sockets/scm_multi_recv.c -MAINSRC += $(TLPIDIR)/sockets/scm_multi_send.c \ - $(TLPIDIR)/sockets/scm_rights_recv.c \ - $(TLPIDIR)/sockets/scm_rights_send.c \ - $(TLPIDIR)/sockets/socknames.c -# $(TLPIDIR)/sockets/t_gethostbyname.c -MAINSRC += $(TLPIDIR)/sockets/t_getservbyname.c \ - $(TLPIDIR)/sockets/ud_ucase_cl.c \ - $(TLPIDIR)/sockets/ud_ucase_sv.c \ - $(TLPIDIR)/sockets/us_abstract_bind.c \ - $(TLPIDIR)/sockets/us_xfr_cl.c \ - $(TLPIDIR)/sockets/us_xfr_sv.c \ - $(TLPIDIR)/sockets/us_xfr_v2_cl.c \ - $(TLPIDIR)/sockets/us_xfr_v2_sv.c -# sysinfo -MAINSRC += $(TLPIDIR)/sysinfo/procfs_pidmax.c \ - $(TLPIDIR)/sysinfo/procfs_user_exe.c \ - $(TLPIDIR)/sysinfo/t_uname.c -# svipc -MAINSRC += $(TLPIDIR)/svipc/svmsg_demo_server.c \ - $(TLPIDIR)/svipc/t_ftok.c -# svmsg -MAINSRC += $(TLPIDIR)/svmsg/svmsg_chqbytes.c \ - $(TLPIDIR)/svmsg/svmsg_create.c \ - $(TLPIDIR)/svmsg/svmsg_file_client.c \ - $(TLPIDIR)/svmsg/svmsg_file_server.c -# $(TLPIDIR)/svmsg/svmsg_info.c \ -# $(TLPIDIR)/svmsg/svmsg_ls.c -MAINSRC += $(TLPIDIR)/svmsg/svmsg_receive.c \ - $(TLPIDIR)/svmsg/svmsg_rm.c \ - $(TLPIDIR)/svmsg/svmsg_send.c -# svsem -#MAINSRC += $(TLPIDIR)/svsem/svsem_bad_init.c \ -# $(TLPIDIR)/svsem/svsem_create.c \ -# $(TLPIDIR)/svsem/svsem_demo.c \ -# $(TLPIDIR)/svsem/svsem_good_init.c \ -# $(TLPIDIR)/svsem/svsem_info.c \ -# $(TLPIDIR)/svsem/svsem_mon.c \ -# $(TLPIDIR)/svsem/svsem_op.c \ -# $(TLPIDIR)/svsem/svsem_rm.c \ -# $(TLPIDIR)/svsem/svsem_setall.c -# svshm -MAINSRC += $(TLPIDIR)/svshm/svshm_attach.c \ - $(TLPIDIR)/svshm/svshm_create.c -# $(TLPIDIR)/svshm/svshm_info.c \ -# $(TLPIDIR)/svshm/svshm_lock.c -MAINSRC += $(TLPIDIR)/svshm/svshm_mon.c \ - $(TLPIDIR)/svshm/svshm_rm.c -# $(TLPIDIR)/svshm/svshm_unlock.c \ -# $(TLPIDIR)/svshm/svshm_xfr_reader.c \ -# $(TLPIDIR)/svshm/svshm_xfr_writer.c -# syslim -MAINSRC += $(TLPIDIR)/syslim/t_fpathconf.c -# $(TLPIDIR)/syslim/t_sysconf.c -# threads -MAINSRC += $(TLPIDIR)/threads/detached_attrib.c \ - $(TLPIDIR)/threads/one_time_init.c \ - $(TLPIDIR)/threads/prod_condvar.c \ - $(TLPIDIR)/threads/prod_no_condvar.c \ - $(TLPIDIR)/threads/pthread_barrier_demo.c \ - $(TLPIDIR)/threads/simple_thread.c \ - $(TLPIDIR)/threads/strerror_test.c \ - $(TLPIDIR)/threads/thread_cancel.c \ - $(TLPIDIR)/threads/thread_cleanup.c \ - $(TLPIDIR)/threads/thread_incr.c \ - $(TLPIDIR)/threads/thread_incr_mutex.c \ - $(TLPIDIR)/threads/thread_incr_rwlock.c \ - $(TLPIDIR)/threads/thread_incr_spinlock.c \ - $(TLPIDIR)/threads/thread_lock_speed.c \ - $(TLPIDIR)/threads/thread_multijoin.c -# time -MAINSRC += $(TLPIDIR)/time/calendar_time.c \ - $(TLPIDIR)/time/process_time.c \ - $(TLPIDIR)/time/show_time.c \ - $(TLPIDIR)/time/strtime.c -# timers -MAINSRC += $(TLPIDIR)/timers/cpu_burner.c \ - $(TLPIDIR)/timers/cpu_multi_burner.c -# $(TLPIDIR)/timers/cpu_multithread_burner.c -MAINSRC += $(TLPIDIR)/timers/demo_timerfd.c \ - $(TLPIDIR)/timers/ptmr_null_evp.c \ - $(TLPIDIR)/timers/ptmr_sigev_signal.c \ - $(TLPIDIR)/timers/ptmr_sigev_thread.c \ - $(TLPIDIR)/timers/real_timer.c \ - $(TLPIDIR)/timers/timed_read.c \ - $(TLPIDIR)/timers/t_clock_nanosleep.c \ - $(TLPIDIR)/timers/t_nanosleep.c -# tty -MAINSRC += $(TLPIDIR)/tty/demo_SIGWINCH.c \ - $(TLPIDIR)/tty/new_intr.c \ - $(TLPIDIR)/tty/no_echo.c \ - $(TLPIDIR)/tty/test_tty_functions.c -# users_groups -MAINSRC += $(TLPIDIR)/users_groups/check_password.c \ - $(TLPIDIR)/users_groups/t_getpwent.c \ - $(TLPIDIR)/users_groups/t_getpwnam_r.c -# vdso -MAINSRC += $(TLPIDIR)/vdso/gettimeofday.c -# vmem -MAINSRC += $(TLPIDIR)/vmem/madvise_dontneed.c -# $(TLPIDIR)/vmem/memlock.c -MAINSRC += $(TLPIDIR)/vmem/t_mprotect.c -# xattr -MAINSRC += $(TLPIDIR)/xattr/t_setxattr.c \ - $(TLPIDIR)/xattr/xattr_view.c - -PROGNAME := $(notdir $(patsubst %.c,%, $(MAINSRC))) - -include $(APPDIR)/Application.mk diff --git a/examples/unpv13e/.gitignore b/examples/unpv13e/.gitignore deleted file mode 100644 index c9b5f5bcb..000000000 --- a/examples/unpv13e/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/unpv13e diff --git a/examples/usrsocktest/usrsocktest_basic_connect.c b/examples/usrsocktest/usrsocktest_basic_connect.c index fbdf87610..0f639856a 100644 --- a/examples/usrsocktest/usrsocktest_basic_connect.c +++ b/examples/usrsocktest/usrsocktest_basic_connect.c @@ -109,18 +109,18 @@ static void setup(FAR struct usrsocktest_daemon_conf_s *dconf) static void teardown(void) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(OK, ret); } } diff --git a/examples/usrsocktest/usrsocktest_basic_daemon.c b/examples/usrsocktest/usrsocktest_basic_daemon.c index a9b6340e5..29b86f84a 100644 --- a/examples/usrsocktest/usrsocktest_basic_daemon.c +++ b/examples/usrsocktest/usrsocktest_basic_daemon.c @@ -502,29 +502,29 @@ TEST_SETUP(basic_daemon) TEST_TEAR_DOWN(basic_daemon) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (sd2 >= 0) { ret = close(sd2); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (sd3 >= 0) { ret = close(sd3); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_basic_getsockname.c b/examples/usrsocktest/usrsocktest_basic_getsockname.c index 61f8a7730..fd7810a03 100644 --- a/examples/usrsocktest/usrsocktest_basic_getsockname.c +++ b/examples/usrsocktest/usrsocktest_basic_getsockname.c @@ -235,17 +235,17 @@ TEST_SETUP(basic_getsockname) TEST_TEAR_DOWN(basic_getsockname) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_basic_getsockopt.c b/examples/usrsocktest/usrsocktest_basic_getsockopt.c index b6d997abb..2d1cf7c78 100644 --- a/examples/usrsocktest/usrsocktest_basic_getsockopt.c +++ b/examples/usrsocktest/usrsocktest_basic_getsockopt.c @@ -214,17 +214,17 @@ TEST_SETUP(basic_getsockopt) TEST_TEAR_DOWN(basic_getsockopt) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_basic_send.c b/examples/usrsocktest/usrsocktest_basic_send.c index 45391094c..9c87df59f 100644 --- a/examples/usrsocktest/usrsocktest_basic_send.c +++ b/examples/usrsocktest/usrsocktest_basic_send.c @@ -291,17 +291,17 @@ TEST_SETUP(basic_send) TEST_TEAR_DOWN(basic_send) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_basic_setsockopt.c b/examples/usrsocktest/usrsocktest_basic_setsockopt.c index 47a67caf4..7798050e1 100644 --- a/examples/usrsocktest/usrsocktest_basic_setsockopt.c +++ b/examples/usrsocktest/usrsocktest_basic_setsockopt.c @@ -182,17 +182,17 @@ TEST_SETUP(basic_setsockopt) TEST_TEAR_DOWN(basic_setsockopt) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_block_recv.c b/examples/usrsocktest/usrsocktest_block_recv.c index 2ce6d82f8..b2b10db8d 100644 --- a/examples/usrsocktest/usrsocktest_block_recv.c +++ b/examples/usrsocktest/usrsocktest_block_recv.c @@ -558,18 +558,18 @@ TEST_SETUP(block_recv) TEST_TEAR_DOWN(block_recv) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_block_send.c b/examples/usrsocktest/usrsocktest_block_send.c index 232c6d4c0..84ad4e024 100644 --- a/examples/usrsocktest/usrsocktest_block_send.c +++ b/examples/usrsocktest/usrsocktest_block_send.c @@ -358,17 +358,17 @@ TEST_SETUP(block_send) TEST_TEAR_DOWN(block_send) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_chardev.c b/examples/usrsocktest/usrsocktest_chardev.c index a9e74a5b9..3377c744d 100644 --- a/examples/usrsocktest/usrsocktest_chardev.c +++ b/examples/usrsocktest/usrsocktest_chardev.c @@ -97,18 +97,18 @@ TEST_SETUP(char_dev) TEST_TEAR_DOWN(char_dev) { - int unused_data ret; + int ret; if (us_fd >= 0) { ret = close(us_fd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (us_fd_two >= 0) { ret = close(us_fd_two); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } } diff --git a/examples/usrsocktest/usrsocktest_daemon.c b/examples/usrsocktest/usrsocktest_daemon.c index 032eed50b..74ba8ebd4 100644 --- a/examples/usrsocktest/usrsocktest_daemon.c +++ b/examples/usrsocktest/usrsocktest_daemon.c @@ -274,17 +274,17 @@ static FAR void *find_endpoint(FAR struct daemon_priv_s *priv, in_addr_t ipaddr) { FAR struct sockaddr_in *endpaddr; - int unused_data ok; + int ok; endpaddr = malloc(sizeof(*endpaddr)); usrsocktest_endp_malloc_cnt++; - assert(endpaddr); + DEBUGASSERT(endpaddr != NULL); ok = inet_pton(AF_INET, priv->conf->endpoint_addr, &endpaddr->sin_addr.s_addr); endpaddr->sin_family = AF_INET; endpaddr->sin_port = htons(priv->conf->endpoint_port); - assert(ok); + DEBUGASSERT(ok); if (endpaddr->sin_addr.s_addr == ipaddr) { @@ -1600,8 +1600,8 @@ static int handle_usrsock_request(int fd, FAR struct daemon_priv_s *priv) return -EIO; } - assert(handlers[common_hdr->reqid].hdrlen < - (sizeof(hdrbuf) - sizeof(*common_hdr))); + DEBUGASSERT(handlers[common_hdr->reqid].hdrlen < + sizeof(hdrbuf) - sizeof(*common_hdr)); rlen = read_req(fd, common_hdr, hdrbuf, handlers[common_hdr->reqid].hdrlen); diff --git a/examples/usrsocktest/usrsocktest_multi_thread.c b/examples/usrsocktest/usrsocktest_multi_thread.c index 586413961..8291ada2e 100644 --- a/examples/usrsocktest/usrsocktest_multi_thread.c +++ b/examples/usrsocktest/usrsocktest_multi_thread.c @@ -144,7 +144,7 @@ TEST_SETUP(multithread) TEST_TEAR_DOWN(multithread) { - int unused_data ret; + int ret; int i; for (i = 0; i < nitems(tids); i++) @@ -152,9 +152,9 @@ TEST_TEAR_DOWN(multithread) if (tids[i] != -1) { ret = pthread_cancel(tids[i]); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); ret = pthread_join(tids[i], NULL); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } @@ -163,14 +163,14 @@ TEST_TEAR_DOWN(multithread) if (sds[i] != -1) { ret = close(sds[i]); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_noblock_connect.c b/examples/usrsocktest/usrsocktest_noblock_connect.c index 3365136b4..758bd08c8 100644 --- a/examples/usrsocktest/usrsocktest_noblock_connect.c +++ b/examples/usrsocktest/usrsocktest_noblock_connect.c @@ -72,24 +72,24 @@ TEST_SETUP(no_block_connect) TEST_TEAR_DOWN(no_block_connect) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret == 0); + TEST_ASSERT_EQUAL(ret, 0); } if (sd2 >= 0) { ret = close(sd2); - assert(ret == 0); + TEST_ASSERT_EQUAL(ret, 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_noblock_recv.c b/examples/usrsocktest/usrsocktest_noblock_recv.c index c6f1e06ff..b75cf374d 100644 --- a/examples/usrsocktest/usrsocktest_noblock_recv.c +++ b/examples/usrsocktest/usrsocktest_noblock_recv.c @@ -461,17 +461,17 @@ TEST_SETUP(no_block_recv) TEST_TEAR_DOWN(no_block_recv) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_noblock_send.c b/examples/usrsocktest/usrsocktest_noblock_send.c index b23112ec7..140a6d563 100644 --- a/examples/usrsocktest/usrsocktest_noblock_send.c +++ b/examples/usrsocktest/usrsocktest_noblock_send.c @@ -351,17 +351,17 @@ TEST_SETUP(no_block_send) TEST_TEAR_DOWN(no_block_send) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_nodaemon.c b/examples/usrsocktest/usrsocktest_nodaemon.c index a0c4f0901..3fd45f546 100644 --- a/examples/usrsocktest/usrsocktest_nodaemon.c +++ b/examples/usrsocktest/usrsocktest_nodaemon.c @@ -95,12 +95,12 @@ TEST_SETUP(no_daemon) TEST_TEAR_DOWN(no_daemon) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } } diff --git a/examples/usrsocktest/usrsocktest_poll.c b/examples/usrsocktest/usrsocktest_poll.c index aac135af0..d45691b59 100644 --- a/examples/usrsocktest/usrsocktest_poll.c +++ b/examples/usrsocktest/usrsocktest_poll.c @@ -570,17 +570,17 @@ TEST_SETUP(poll) TEST_TEAR_DOWN(poll) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_remote_disconnect.c b/examples/usrsocktest/usrsocktest_remote_disconnect.c index 47cbb0ab4..2e55a75e9 100644 --- a/examples/usrsocktest/usrsocktest_remote_disconnect.c +++ b/examples/usrsocktest/usrsocktest_remote_disconnect.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/usrsocktest/usrsocktest_remote_disconnect.c + * apps/examples/usrsocktest/usrsocktest_remote_disconnect.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -972,18 +972,18 @@ TEST_SETUP(remote_disconnect) TEST_TEAR_DOWN(remote_disconnect) { - int unused_data ret; + int ret; if (sd >= 0) { ret = close(sd); - assert(ret >= 0); + TEST_ASSERT_TRUE(ret >= 0); } if (started) { ret = usrsocktest_daemon_stop(); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } } diff --git a/examples/usrsocktest/usrsocktest_wake_with_signal.c b/examples/usrsocktest/usrsocktest_wake_with_signal.c index c77180f61..bf59e559b 100644 --- a/examples/usrsocktest/usrsocktest_wake_with_signal.c +++ b/examples/usrsocktest/usrsocktest_wake_with_signal.c @@ -648,7 +648,7 @@ TEST_SETUP(wake_with_signal) TEST_TEAR_DOWN(wake_with_signal) { - int unused_data ret; + int ret; int i; for (i = 0; i < MAX_THREADS; i++) @@ -656,9 +656,9 @@ TEST_TEAR_DOWN(wake_with_signal) if (tid[i] != -1) { ret = pthread_cancel(tid[i]); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); ret = pthread_join(tid[i], NULL); - assert(ret == OK); + TEST_ASSERT_EQUAL(ret, OK); } if (test_sd[i] != -1) diff --git a/examples/ustream/ustream_server.c b/examples/ustream/ustream_server.c index b1744a339..8ed5f0cea 100644 --- a/examples/ustream/ustream_server.c +++ b/examples/ustream/ustream_server.c @@ -132,8 +132,7 @@ int main(int argc, char *argv[]) } #endif - acceptsd = accept4(listensd, (struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (struct sockaddr *)&myaddr, &addrlen); if (acceptsd < 0) { printf("server: accept failure: %d\n", errno); diff --git a/examples/watchdog/watchdog.h b/examples/watchdog/watchdog.h index 4ab44dd5a..7c90ca6ff 100644 --- a/examples/watchdog/watchdog.h +++ b/examples/watchdog/watchdog.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/examples/watchdog/watchdog.h + * apps/examples/watchdog/watchdog.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -30,7 +30,9 @@ /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ + /* Configuration ************************************************************/ + /* CONFIG_NSH_BUILTIN_APPS - Build the WATCHDOG test as an NSH built-in * function. * CONFIG_EXAMPLES_WATCHDOG_DEVPATH - The path to the Watchdog device. diff --git a/examples/wiegand/Makefile b/examples/wiegand/Makefile index b07019653..50c7a24e0 100644 --- a/examples/wiegand/Makefile +++ b/examples/wiegand/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/wiegand/Make.defs +# apps/examples/wiegand/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/examples/ws2812esp32rmt/Make.defs b/examples/ws2812esp32rmt/Make.defs index 6d98a56af..ddb06ef58 100644 --- a/examples/ws2812esp32rmt/Make.defs +++ b/examples/ws2812esp32rmt/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/ws2812/Make.defs +# apps/examples/ws2812esp32rmt/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/examples/ws2812esp32rmt/Makefile b/examples/ws2812esp32rmt/Makefile index 8f34feee0..fe1656cf8 100644 --- a/examples/ws2812esp32rmt/Makefile +++ b/examples/ws2812esp32rmt/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/ws2812/Makefile +# apps/examples/ws2812esp32rmt/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/examples/xmlrpc/xmlrpc_main.c b/examples/xmlrpc/xmlrpc_main.c index 9f9df54f4..dbd807353 100644 --- a/examples/xmlrpc/xmlrpc_main.c +++ b/examples/xmlrpc/xmlrpc_main.c @@ -410,8 +410,7 @@ int main(int argc, FAR char *argv[]) for (; ; ) { clilen = sizeof(cliaddr); - connfd = accept4(listenfd, (struct sockaddr *)&cliaddr, &clilen, - SOCK_CLOEXEC); + connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen); if (connfd <= 0) { break; diff --git a/external b/external deleted file mode 120000 index 2e7469e1d..000000000 --- a/external +++ /dev/null @@ -1 +0,0 @@ -../external/ \ No newline at end of file diff --git a/frameworks b/frameworks deleted file mode 120000 index cd29c103a..000000000 --- a/frameworks +++ /dev/null @@ -1 +0,0 @@ -../frameworks/ \ No newline at end of file diff --git a/fsutils/inifile/README.md b/fsutils/inifile/README.md deleted file mode 100644 index 86590cbcb..000000000 --- a/fsutils/inifile/README.md +++ /dev/null @@ -1,144 +0,0 @@ -# File System Utilities / `inifile` INI File - -## Syntax - -This directory contains a very simple INI file parser. An INI file consists of a -sequence of lines up to the end of file. A line may be one of the following: - -1. A blank line. - -2. A comment line. Any line beginning with `;` - -3. A section header. Definitions are divided into sections. Each section begins - with a line containing the section name enclosed in square brackets. For - example, `[section1]`. The left bracket must be the first character on the - line. Section names are case insensitive, i.e., `SECTION1` and `Section1` - refer to the same section. - -4. Variable assignments. A variable assignment is a variable name followed by - the `=` sign and then the value of the variable. For example, `A=B`: `A` is - the variable name; `B` is the variable value. All variables following the - section header belong in the section. - - Variable names may be preceded with white space. Whitespace is not permitted - before the `=` sign. Variable names are case insensitive, i.e., `A` and `a` - refer to the same variable name. - - Variable values may be numeric (any base) or a string. The case of string - arguments is preserved. - -## Programming Interfaces - -See `apps/include/fsutils/inifile.h` for interfaces supported by the INI file -parser. - -## Test Program - -Below is a simple test program: - -```c -int main(int argc, char *argv[]) -{ - INIHANDLE handle; - FILE *stream; - FAR char *ptr; - long value; - - stream = fopen("/tmp/file.ini", "w"); - fprintf(stream, "; Test INI file\n"); - fprintf(stream, "[section1]\n"); - fprintf(stream, " VAR1=1\n"); - fprintf(stream, " VAR2=2\n"); - fprintf(stream, " VAR3=3\n"); - fprintf(stream, "\n"); - fprintf(stream, "[section2]\n"); - fprintf(stream, " VAR4=4\n"); - fprintf(stream, " VAR5=5\n"); - fprintf(stream, "VAR6=6\n"); - fprintf(stream, "\n"); - fclose(stream); - - handle = inifile_initialize("/tmp/file.ini"); - - ptr = inifile_read_string(handle, "section2", "VAR5", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section2", "VAR5", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section1", "VAR2", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section1", "VAR2", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section3", "VAR3", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section3", "VAR3", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section1", "VAR3", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section1", "VAR3", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section1", "VAR1", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section1", "VAR1", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section1", "VAR42", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section1", "VAR42", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section2", "VAR6", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section2", "VAR6", ptr); - inifile_free_string(ptr); - - ptr = inifile_read_string(handle, "section2", "VAR4", "OOPS"); - printf("Section: %s Variable: %s String: %s\n", "section2", "VAR4", ptr); - inifile_free_string(ptr); - - value = inifile_read_integer(handle, "section1", "VAR3", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section1", "VAR3", value); - - value = inifile_read_integer(handle, "section3", "VAR3", 0); - printf("Section: %s Variable: %s String: %ld\n", "section3", "VAR3", value); - - value = inifile_read_integer(handle, "section1", "VAR1", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section1", "VAR1", value); - - value = inifile_read_integer(handle, "section2", "VAR5", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section2", "VAR5", value); - - value = inifile_read_integer(handle, "section2", "VAR6", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section2", "VAR6", value); - - value = inifile_read_integer(handle, "section1", "VAR42", 0); - printf("Section: %s Variable: %s String: %ld\n", "section1", "VAR42", value); - - value = inifile_read_integer(handle, "section1", "VAR2", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section1", "VAR2", value); - - value = inifile_read_integer(handle, "section2", "VAR4", 0); - printf("Section: %s Variable: %s Value: %ld\n", "section2", "VAR4", value); - - inifile_uninitialize(handle); - return 0; -} -``` - -Test program output: - -``` -Section: section2 Variable: VAR5 String: 5 -Section: section1 Variable: VAR2 String: 2 -Section: section3 Variable: VAR3 String: OOPS -Section: section1 Variable: VAR3 String: 3 -Section: section1 Variable: VAR1 String: 1 -Section: section1 Variable: VAR42 String: OOPS -Section: section2 Variable: VAR6 String: 6 -Section: section2 Variable: VAR4 String: 4 - -Section: section1 Variable: VAR3 Value: 3 -Section: section3 Variable: VAR3 Value: 0 -Section: section1 Variable: VAR1 Value: 1 -Section: section2 Variable: VAR5 Value: 5 -Section: section2 Variable: VAR6 Value: 6 -Section: section1 Variable: VAR42 String: 0 -Section: section1 Variable: VAR2 Value: 2 -Section: section2 Variable: VAR4 Value: 4 -``` diff --git a/fsutils/inifile/inifile.c b/fsutils/inifile/inifile.c index 9bd903185..afd105785 100644 --- a/fsutils/inifile/inifile.c +++ b/fsutils/inifile/inifile.c @@ -603,7 +603,7 @@ long inifile_read_integer(INIHANDLE handle, /* Assume failure to find the requested value */ - iniinfo("section=\"%s\" variable=\"%s\" defvalue=%ld\n", + iniinfo("section=\"%s\" variable=\"%s\" defvalue=%d\n", section, variable, defvalue); /* Get the value as a string first */ @@ -624,7 +624,7 @@ long inifile_read_integer(INIHANDLE handle, /* Return the value that we found. */ - iniinfo("Returning %ld\n", ret); + iniinfo("Returning %d\n", ret); return ret; } diff --git a/fsutils/mkgpt/Makefile b/fsutils/mkgpt/Makefile index 1379ac488..39daffe15 100644 --- a/fsutils/mkgpt/Makefile +++ b/fsutils/mkgpt/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/fsutils/mkgpt/Make.defs +# apps/fsutils/mkgpt/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/games/shift/Kconfig b/games/brickmatch/Kconfig similarity index 68% rename from games/shift/Kconfig rename to games/brickmatch/Kconfig index 8aec0d167..9d2d7d5c1 100644 --- a/games/shift/Kconfig +++ b/games/brickmatch/Kconfig @@ -3,11 +3,11 @@ # see the file kconfig-language.txt in the NuttX tools repository. # -config GAMES_SHIFT - bool "Shift Game" +config GAMES_BRICKMATCH + bool "Brickmatch Game" default n ---help--- - Enable Shift games. Shift is a brick game, like a mix + Enable Brickmatch games. Brickmatch is like a mix between Tetris and Crush Candy. The inspiration came from a Shift game that was available for Android in the F-Droid store. The original game source code still here: @@ -16,21 +16,21 @@ config GAMES_SHIFT NOTE: The source code here is not based on that code from above github. -if GAMES_SHIFT +if GAMES_BRICKMATCH -config GAMES_SHIFT_PROGNAME +config GAMES_BRICKMATCH_PROGNAME string "Program name" - default "shift" + default "brick" ---help--- This is the name of the program that will be used when the NSH ELF program is installed. -config GAMES_SHIFT_PRIORITY - int "Shift Game task priority" +config GAMES_BRICKMATCH_PRIORITY + int "Brickmatch Game task priority" default 100 -config GAMES_SHIFT_STACKSIZE - int "Shift Game stack size" +config GAMES_BRICKMATCH_STACKSIZE + int "Brickmatch Game stack size" default DEFAULT_TASK_STACKSIZE # @@ -39,17 +39,17 @@ config GAMES_SHIFT_STACKSIZE choice prompt "Input Device (Joystick, Gesture Sensor, etc)" - default GAMES_SHIFT_USE_CONSOLEKEY + default GAMES_BRICKMATCH_USE_CONSOLEKEY -config GAMES_SHIFT_USE_CONSOLEKEY +config GAMES_BRICKMATCH_USE_CONSOLEKEY bool "Serial Console as Input" depends on !INPUT_DJOYSTICK && !SENSORS_APDS9960 -config GAMES_SHIFT_USE_DJOYSTICK +config GAMES_BRICKMATCH_USE_DJOYSTICK bool "Discrete Joystick as Input" depends on INPUT_DJOYSTICK -config GAMES_SHIFT_USE_GESTURE +config GAMES_BRICKMATCH_USE_GESTURE bool "Gesture Sensor APDS-9960 as Input" depends on SENSORS_APDS9960 diff --git a/games/brickmatch/Make.defs b/games/brickmatch/Make.defs new file mode 100644 index 000000000..659bcf052 --- /dev/null +++ b/games/brickmatch/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/games/brickmatch/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_GAMES_BRICKMATCH),) +CONFIGURED_APPS += $(APPDIR)/games/brickmatch +endif diff --git a/games/brickmatch/Makefile b/games/brickmatch/Makefile new file mode 100644 index 000000000..b327e1b36 --- /dev/null +++ b/games/brickmatch/Makefile @@ -0,0 +1,34 @@ +############################################################################ +# apps/games/brickmatch/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +# Brickmatch game info + +PROGNAME = $(CONFIG_GAMES_BRICKMATCH_PROGNAME) +PRIORITY = $(CONFIG_GAMES_BRICKMATCH_PRIORITY) +STACKSIZE = $(CONFIG_GAMES_BRICKMATCH_STACKSIZE) +MODULE = $(CONFIG_GAMES_BRICKMATCH) + +# Brickmatch game application + +MAINSRC = bm_main.c + +include $(APPDIR)/Application.mk diff --git a/games/shift/shift_input_console.h b/games/brickmatch/bm_input_console.h similarity index 98% rename from games/shift/shift_input_console.h rename to games/brickmatch/bm_input_console.h index d2f974d25..cb5e45b0a 100644 --- a/games/shift/shift_input_console.h +++ b/games/brickmatch/bm_input_console.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/games/shift/shift_input_console.h + * apps/games/brickmatch/bm_input_console.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -25,7 +25,7 @@ #include #include -#include "shift_inputs.h" +#include "bm_inputs.h" /**************************************************************************** * Preprocessor Definitions diff --git a/games/shift/shift_input_gesture.h b/games/brickmatch/bm_input_gesture.h similarity index 97% rename from games/shift/shift_input_gesture.h rename to games/brickmatch/bm_input_gesture.h index 54feb71c1..eaf74ca3a 100644 --- a/games/shift/shift_input_gesture.h +++ b/games/brickmatch/bm_input_gesture.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/games/shift/shift_input_gesture.h + * apps/games/brickmatch/bm_input_gesture.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -26,7 +26,7 @@ #include -#include "shift_inputs.h" +#include "bm_inputs.h" /**************************************************************************** * Preprocessor Definitions diff --git a/games/shift/shift_input_joystick.h b/games/brickmatch/bm_input_joystick.h similarity index 98% rename from games/shift/shift_input_joystick.h rename to games/brickmatch/bm_input_joystick.h index 2bd3a625c..ef5146cac 100644 --- a/games/shift/shift_input_joystick.h +++ b/games/brickmatch/bm_input_joystick.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/games/shift/shift_input_joystick.h + * apps/games/brickmatch/bm_input_joystick.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -26,7 +26,7 @@ #include -#include "shift_inputs.h" +#include "bm_inputs.h" /**************************************************************************** * Preprocessor Definitions diff --git a/games/shift/shift_inputs.h b/games/brickmatch/bm_inputs.h similarity index 91% rename from games/shift/shift_inputs.h rename to games/brickmatch/bm_inputs.h index c2141d6d3..a78f03601 100644 --- a/games/shift/shift_inputs.h +++ b/games/brickmatch/bm_inputs.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/games/shift/shift_inputs.h + * apps/games/brickmatch/bm_inputs.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -50,13 +50,13 @@ struct input_state_s { -#ifdef CONFIG_GAMES_SHIFT_USE_CONSOLEKEY +#ifdef CONFIG_GAMES_BRICKMATCH_USE_CONSOLEKEY int fd_con; #endif -#ifdef CONFIG_GAMES_SHIFT_USE_DJOYSTICK +#ifdef CONFIG_GAMES_BRICKMATCH_USE_DJOYSTICK int fd_joy; #endif -#ifdef CONFIG_GAMES_SHIFT_USE_GESTURE +#ifdef CONFIG_GAMES_BRICKMATCH_USE_GESTURE int fd_gest; #endif int dir; /* Direction to move the blocks */ diff --git a/games/shift/shift_main.c b/games/brickmatch/bm_main.c similarity index 98% rename from games/shift/shift_main.c rename to games/brickmatch/bm_main.c index 0e60f56a1..187ce2683 100644 --- a/games/shift/shift_main.c +++ b/games/brickmatch/bm_main.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/games/shift/shift_main.c + * apps/games/brickmatch/bm_main.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -36,16 +36,16 @@ #include #include -#ifdef CONFIG_GAMES_SHIFT_USE_CONSOLEKEY -#include "shift_input_console.h" +#ifdef CONFIG_GAMES_BRICKMATCH_USE_CONSOLEKEY +#include "bm_input_console.h" #endif -#ifdef CONFIG_GAMES_SHIFT_USE_DJOYSTICK -#include "shift_input_joystick.h" +#ifdef CONFIG_GAMES_BRICKMATCH_USE_DJOYSTICK +#include "bm_input_joystick.h" #endif -#ifdef CONFIG_GAMES_SHIFT_USE_GESTURE -#include "shift_input_gesture.h" +#ifdef CONFIG_GAMES_BRICKMATCH_USE_GESTURE +#include "bm_input_gesture.h" #endif /**************************************************************************** @@ -302,7 +302,7 @@ void draw_board(FAR struct screen_state_s *state, * Draw the board including the user non-visible border for debugging. ****************************************************************************/ -#ifdef DEBUG_SHIFT_GAME +#ifdef DEBUG_BRICKMATCH_GAME void print_board(void) { int row; @@ -750,7 +750,7 @@ int check_board(void) ****************************************************************************/ /**************************************************************************** - * shift_main + * brick_main ****************************************************************************/ int main(int argc, FAR char *argv[]) @@ -854,7 +854,7 @@ int main(int argc, FAR char *argv[]) screen.dir = input.dir; -#ifdef DEBUG_SHIFT_GAME +#ifdef DEBUG_BRICKMATCH_GAME printf("Before moving:\n"); print_board(); usleep(2000000); @@ -868,7 +868,7 @@ int main(int argc, FAR char *argv[]) draw_board(&state, &area, &screen); -#ifdef DEBUG_SHIFT_GAME +#ifdef DEBUG_BRICKMATCH_GAME printf("After moving:\n"); print_board(); usleep(1000000); @@ -907,7 +907,7 @@ int main(int argc, FAR char *argv[]) usleep(500000); } -#ifdef DEBUG_SHIFT_GAME +#ifdef DEBUG_BRICKMATCH_GAME printf("After checking:\n"); print_board(); usleep(1000000); diff --git a/graphics/libyuv/CMakeLists.txt b/graphics/libyuv/CMakeLists.txt deleted file mode 100644 index bae355fd9..000000000 --- a/graphics/libyuv/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# ############################################################################## -# apps/graphics/libyuv/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_LIBYUV) - get_property(TARGET_SUPPORTS_SHARED_ORIG GLOBAL - PROPERTY TARGET_SUPPORTS_SHARED_LIBS) - set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS TRUE) - add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/libyuv) - nuttx_add_external_library(yuv) - set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS - ${TARGET_SUPPORTS_SHARED_ORIG}) - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES - ${CMAKE_CURRENT_SOURCE_DIR}/libyuv/include) -endif() diff --git a/graphics/lvgl/.gitignore b/graphics/lvgl/.gitignore index 413ad4ffc..11da3994b 100644 --- a/graphics/lvgl/.gitignore +++ b/graphics/lvgl/.gitignore @@ -1,3 +1,2 @@ /lvgl /*.zip -/ext \ No newline at end of file diff --git a/graphics/lvgl/0001-fix-demo-fix-compile-warning.patch b/graphics/lvgl/0001-fix-demo-fix-compile-warning.patch new file mode 100644 index 000000000..ca99d3a6e --- /dev/null +++ b/graphics/lvgl/0001-fix-demo-fix-compile-warning.patch @@ -0,0 +1,46 @@ +From d1576c890e8a8622c95dc4a782c457ab3884e7fa Mon Sep 17 00:00:00 2001 +From: Xu Xingliang +Date: Mon, 22 Apr 2024 12:26:35 +0800 +Subject: [PATCH] fix(demo): fix compile warning + +In file included from /home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/../../lvgl.h:30, + from /home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/../lv_demos.h:16, + from /home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/lv_demo_stress.h:16, + from /home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/lv_demo_stress.c:9: +/home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/lv_demo_stress.c: In function 'obj_test_task_cb': +/home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/lv_demo_stress.c:81:29: warning: format '%zu' expects argument of type 'size_t', but argument 6 has type 'long unsigned int' [-Wformat=] + 81 | LV_LOG_USER("mem leak since start: %zu, frag: %3d %%", mem_free_start - mon.free_size, mon.frag_pct); + | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + | | + | long unsigned int +/home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/../../src/misc/lv_log.h:132:97: note: in definition of macro 'LV_LOG_USER' + 132 | # define LV_LOG_USER(...) _lv_log_add(LV_LOG_LEVEL_USER, LV_LOG_FILE, LV_LOG_LINE, __func__, __VA_ARGS__) + | ^~~~~~~~~~~ +/home/neo/projects/nuttx/apps/graphics/lvgl/lvgl/demos/stress/lv_demo_stress.c:81:54: note: format string is defined here + 81 | LV_LOG_USER("mem leak since start: %zu, frag: %3d %%", mem_free_start - mon.free_size, mon.frag_pct); + | ~~^ + | | + | unsigned int + | %lu + +Signed-off-by: Xu Xingliang +--- + demos/stress/lv_demo_stress.c | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/demos/stress/lv_demo_stress.c b/demos/stress/lv_demo_stress.c +index 65728519c..b76c1f655 100644 +--- a/demos/stress/lv_demo_stress.c ++++ b/demos/stress/lv_demo_stress.c +@@ -32,7 +32,7 @@ static void obj_test_task_cb(lv_timer_t * tmr); + **********************/ + static lv_obj_t * main_page; + static lv_obj_t * ta; +-static uint32_t mem_free_start = 0; ++static size_t mem_free_start = 0; + static int16_t g_state = -1; + + /********************** +-- +2.34.1 + diff --git a/graphics/lvgl/CMakeLists.txt b/graphics/lvgl/CMakeLists.txt index ebfffe0dc..ae0bf3da4 100644 --- a/graphics/lvgl/CMakeLists.txt +++ b/graphics/lvgl/CMakeLists.txt @@ -42,6 +42,9 @@ if(CONFIG_GRAPHICS_LVGL) "" TEST_COMMAND "" + PATCH_COMMAND + patch -p1 -s -d ${CMAKE_CURRENT_LIST_DIR}/lvgl < + ${CMAKE_CURRENT_LIST_DIR}/0001-fix-demo-fix-compile-warning.patch DOWNLOAD_NO_PROGRESS true TIMEOUT 30) @@ -71,52 +74,6 @@ if(CONFIG_GRAPHICS_LVGL) target_compile_definitions(lvgl PRIVATE "LV_ASSERT_HANDLER=ASSERT(0)\;") endif() - if(CONFIG_LV_USE_FREETYPE) - if(NOT CONFIG_LIB_FREETYPE) - message(WARNING "LIB_FREETYPE is not enabled") - endif() - target_link_libraries(lvgl PRIVATE freetype) - nuttx_add_dependencies(TARGET lvgl DEPENDS freetype) - endif() - - if(CONFIG_LV_USE_LIBPNG) - if(NOT CONFIG_LIB_PNG) - message(WARNING "LIB_PNG is not enabled") - endif() - target_link_libraries(lvgl PRIVATE png_static) - nuttx_add_dependencies(TARGET lvgl DEPENDS png_static) - endif() - - if(CONFIG_LV_USE_LIBWEBP) - if(NOT CONFIG_LIB_WEBP) - message(WARNING "LIB_WEBP is not enabled") - endif() - target_link_libraries(lvgl PRIVATE webpdecoder) - nuttx_add_dependencies(TARGET lvgl DEPENDS webpdecoder) - endif() - - if(CONFIG_LV_USE_FFMPEG) - message(FATAL_ERROR "FFMPEG is not supported yet") - endif() - - if(CONFIG_LV_USE_RLOTTIE) - message(FATAL_ERROR "RLOTTIE is not supported yet") - endif() - - if(CONFIG_LV_USE_LIBJPEG_TURBO) - if(NOT CONFIG_LIB_JPEG_TURBO) - message(WARNING "LIB_JPEG_TURBO is not enabled") - endif() - target_link_libraries(lvgl PRIVATE turbojpeg-static) - nuttx_add_dependencies(TARGET lvgl DEPENDS turbojpeg-static) - endif() - - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_LIST_DIR} - ${CMAKE_CURRENT_LIST_DIR}/lvgl) - - add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/ext) - + # allow to include via lvgl/lvgl.h + target_include_directories(lvgl PUBLIC ${CMAKE_CURRENT_LIST_DIR}) endif() diff --git a/graphics/lvgl/Kconfig b/graphics/lvgl/Kconfig index 6e95801c3..5c11cb6af 100644 --- a/graphics/lvgl/Kconfig +++ b/graphics/lvgl/Kconfig @@ -11,21 +11,1634 @@ menuconfig GRAPHICS_LVGL if GRAPHICS_LVGL -config LVGL_VERSION - string "LVGL Version" - default "9.1.0" +# Below options are copied directly from lvgl/Kconfig, do not edit +# Kconfig file for LVGL v9.1.0 -osource "$APPSDIR/graphics/lvgl/lvgl/Kconfig" -osource "$APPSDIR/graphics/lvgl/ext/Kconfig" +menu "LVGL configuration" -config LV_DRAW_VG_LITE_INCLUDE - string "VG-Lite API header include path" - depends on LV_USE_DRAW_VG_LITE - default "" + # Define CONFIG_LV_CONF_SKIP so we can use LVGL + # without lv_conf.h file, the lv_conf_internal.h and + # lv_conf_kconfig.h files are used instead. + config LV_CONF_SKIP + bool "Check this to not use custom lv_conf.h" + default y -config LV_GPU_G2D_INCLUDE_PATH - string "include path of G2D header" - depends on LV_USE_DRAW_G2D - default "" + config LV_CONF_MINIMAL + bool "LVGL minimal configuration" + + menu "Color Settings" + choice LV_COLOR_DEPTH + prompt "Color depth" + default LV_COLOR_DEPTH_16 + help + Color depth to be used. + + config LV_COLOR_DEPTH_32 + bool "32: XRGB8888" + config LV_COLOR_DEPTH_24 + bool "24: RGB888" + config LV_COLOR_DEPTH_16 + bool "16: RGB565" + config LV_COLOR_DEPTH_8 + bool "8: RGB232" + config LV_COLOR_DEPTH_1 + bool "1: 1 byte per pixel" + endchoice + + config LV_COLOR_DEPTH + int + default 1 if LV_COLOR_DEPTH_1 + default 8 if LV_COLOR_DEPTH_8 + default 16 if LV_COLOR_DEPTH_16 + default 24 if LV_COLOR_DEPTH_24 + default 32 if LV_COLOR_DEPTH_32 + endmenu + + menu "Memory Settings" + choice + prompt "Malloc functions source" + default LV_USE_BUILTIN_MALLOC + + config LV_USE_BUILTIN_MALLOC + bool "LVGL's built in implementation" + + config LV_USE_CLIB_MALLOC + bool "Standard C functions malloc/realloc/free" + + config LV_USE_MICROPYTHON_MALLOC + bool "MicroPython functions malloc/realloc/free" + + config LV_USE_RTTHREAD_MALLOC + bool "RTThread functions malloc/realloc/free" + + config LV_USE_CUSTOM_MALLOC + bool "Implement the functions externally" + + endchoice # "Malloc functions" + + choice + prompt "String functions source" + default LV_USE_BUILTIN_STRING + + config LV_USE_BUILTIN_STRING + bool "LVGL's built in implementation" + + config LV_USE_CLIB_STRING + bool "Standard C functions memcpy/memset/strlen/strcpy" + + config LV_USE_CUSTOM_STRING + bool "Implement the functions externally" + + endchoice # "String functions" + + choice + prompt "Sprintf functions source" + default LV_USE_BUILTIN_SPRINTF + + config LV_USE_BUILTIN_SPRINTF + bool "LVGL's built in implementation" + + config LV_USE_CLIB_SPRINTF + bool "Standard C functions vsnprintf" + + config LV_USE_CUSTOM_SPRINTF + bool "Implement the functions externally" + + endchoice # "Sprintf functions" + + config LV_MEM_SIZE_KILOBYTES + int "Size of the memory used by `lv_malloc()` in kilobytes (>= 2kB)" + default 64 + depends on LV_USE_BUILTIN_MALLOC + + config LV_MEM_POOL_EXPAND_SIZE_KILOBYTES + int "Size of the memory expand for `lv_malloc()` in kilobytes" + default 0 + depends on LV_USE_BUILTIN_MALLOC + + config LV_MEM_ADR + hex "Address for the memory pool instead of allocating it as a normal array" + default 0x0 + depends on LV_USE_BUILTIN_MALLOC + + endmenu + + menu "HAL Settings" + config LV_DEF_REFR_PERIOD + int "Default refresh period (ms)" + default 33 + help + Default display refresh, input device read and animation step period. + + config LV_DPI_DEF + int "Default Dots Per Inch (in px/inch)" + default 130 + help + Used to initialize default sizes such as widgets sized, style paddings. + (Not so important, you can adjust it to modify default sizes and spaces) + endmenu + + menu "Operating System (OS)" + choice LV_USE_OS + prompt "Default operating system to use" + default LV_OS_NONE + + config LV_OS_NONE + bool "0: NONE" + config LV_OS_PTHREAD + bool "1: PTHREAD" + config LV_OS_FREERTOS + bool "2: FREERTOS" + config LV_OS_CMSIS_RTOS2 + bool "3: CMSIS_RTOS2" + config LV_OS_RTTHREAD + bool "4: RTTHREAD" + config LV_OS_WINDOWS + bool "5: WINDOWS" + config LV_OS_CUSTOM + bool "255: CUSTOM" + endchoice + + config LV_USE_OS + int + default 0 if LV_OS_NONE + default 1 if LV_OS_PTHREAD + default 2 if LV_OS_FREERTOS + default 3 if LV_OS_CMSIS_RTOS2 + default 4 if LV_OS_RTTHREAD + default 5 if LV_OS_WINDOWS + default 255 if LV_OS_CUSTOM + + config LV_OS_CUSTOM_INCLUDE + string "Custom OS include header" + default "stdint.h" + depends on LV_OS_CUSTOM + endmenu + + menu "Rendering Configuration" + config LV_DRAW_BUF_STRIDE_ALIGN + int "Buffer stride alignment" + default 1 + help + Align the stride of all layers and images to this bytes. + + config LV_DRAW_BUF_ALIGN + int "Buffer address alignment" + default 4 + help + Align the start address of draw_buf addresses to this bytes. + + config LV_DRAW_LAYER_SIMPLE_BUF_SIZE + int "Optimal size to buffer the widget with opacity" + default 24576 + depends on LV_USE_DRAW_SW + help + If a widget has `style_opa < 255` (not `bg_opa`, `text_opa` etc) or not NORMAL blend mode + it is buffered into a "simple" layer before rendering. The widget can be buffered in smaller chunks. + "Transformed layers" (if `transform_angle/zoom` are set) use larger buffers and can't be drawn in chunks. + + config LV_USE_DRAW_SW + bool "Enable software rendering" + default y + help + Required to draw anything on the screen. + + config LV_DRAW_SW_DRAW_UNIT_CNT + int "Number of draw units" + default 1 + depends on LV_USE_DRAW_SW + help + > 1 requires an operating system enabled in `LV_USE_OS` + > 1 means multiply threads will render the screen in parallel + + config LV_USE_DRAW_ARM2D_SYNC + bool "Enable Arm's 2D image processing library (Arm-2D) for all Cortex-M processors" + default n + depends on LV_USE_DRAW_SW + help + Must deploy arm-2d library to your project and add include PATH for "arm_2d.h". + + config LV_USE_NATIVE_HELIUM_ASM + bool "Enable native helium assembly" + default y + depends on LV_USE_DRAW_SW + help + Disabling this allows arm2d to work on its own (for testing only) + + config LV_DRAW_SW_COMPLEX + bool "Enable complex draw engine" + default y + depends on LV_USE_DRAW_SW + help + 0: use a simple renderer capable of drawing only simple rectangles with gradient, images, texts, and straight lines only, + 1: use a complex renderer capable of drawing rounded corners, shadow, skew lines, and arcs too. + + config LV_DRAW_SW_SHADOW_CACHE_SIZE + int "Allow buffering some shadow calculation" + depends on LV_DRAW_SW_COMPLEX + default 0 + help + LV_DRAW_SW_SHADOW_CACHE_SIZE is the max shadow size to buffer, where + shadow size is `shadow_width + radius`. + Caching has LV_DRAW_SW_SHADOW_CACHE_SIZE^2 RAM cost. + + config LV_DRAW_SW_CIRCLE_CACHE_SIZE + int "Set number of maximally cached circle data" + depends on LV_DRAW_SW_COMPLEX + default 4 + help + The circumference of 1/4 circle are saved for anti-aliasing + radius * 4 bytes are used per circle (the most often used + radiuses are saved). + Set to 0 to disable caching. + + choice LV_USE_DRAW_SW_ASM + prompt "Asm mode in sw draw" + default LV_DRAW_SW_ASM_NONE + depends on LV_USE_DRAW_SW + help + ASM mode to be used + + config LV_DRAW_SW_ASM_NONE + bool "0: NONE" + config LV_DRAW_SW_ASM_NEON + bool "1: NEON" + config LV_DRAW_SW_ASM_HELIUM + bool "2: HELIUM" + config LV_DRAW_SW_ASM_CUSTOM + bool "255: CUSTOM" + endchoice + + config LV_USE_DRAW_SW_ASM + int + default 0 if LV_DRAW_SW_ASM_NONE + default 1 if LV_DRAW_SW_ASM_NEON + default 2 if LV_DRAW_SW_ASM_HELIUM + default 255 if LV_DRAW_SW_ASM_CUSTOM + + config LV_DRAW_SW_ASM_CUSTOM_INCLUDE + string "Set the custom asm include file" + default "" + depends on LV_DRAW_SW_ASM_CUSTOM + + config LV_USE_DRAW_VGLITE + bool "Use NXP's VG-Lite GPU on iMX RTxxx platforms" + default n + + config LV_USE_VGLITE_BLIT_SPLIT + bool "Enable blit quality degradation workaround recommended for screen's dimension > 352 pixels" + depends on LV_USE_DRAW_VGLITE + default n + + config LV_USE_VGLITE_DRAW_ASYNC + bool "Enable VGLite draw async" + depends on LV_USE_DRAW_VGLITE && LV_USE_OS > 0 + default y + help + Queue multiple tasks and flash them once to the GPU. + + config LV_USE_VGLITE_ASSERT + bool "Enable VGLite asserts" + default n + depends on LV_USE_DRAW_VGLITE + + config LV_USE_DRAW_PXP + bool "Use NXP's PXP on iMX RTxxx platforms" + default n + + config LV_USE_PXP_ASSERT + bool "Enable PXP asserts" + default n + depends on LV_USE_DRAW_PXP + + config LV_USE_DRAW_DAVE2D + bool "Use Renesas Dave2D on RA platforms" + default n + + config LV_USE_DRAW_SDL + bool "Draw using cached SDL textures" + default n + help + Uses SDL renderer API + + config LV_USE_DRAW_VG_LITE + bool "Use VG-Lite GPU" + + config LV_VG_LITE_USE_GPU_INIT + bool "Enable VG-Lite custom external 'gpu_init()' function" + default n + depends on LV_USE_DRAW_VG_LITE + + config LV_VG_LITE_USE_ASSERT + bool "Enable VG-Lite assert" + default n + depends on LV_USE_DRAW_VG_LITE + + config LV_VG_LITE_FLUSH_MAX_COUNT + int "VG-Lite flush commit trigger threshold" + default 8 + depends on LV_USE_DRAW_VG_LITE + help + GPU will try to batch these many draw tasks + + config LV_VG_LITE_USE_BOX_SHADOW + bool "Enable border to simulate shadow" + default n + depends on LV_USE_DRAW_VG_LITE + help + which usually improves performance, + but does not guarantee the same rendering quality as the software. + + config LV_USE_VECTOR_GRAPHIC + bool "Use Vector Graphic APIs" + default n + help + Enable drawing support vector graphic APIs. + endmenu + + menu "Feature Configuration" + menu "Logging" + config LV_USE_LOG + bool "Enable the log module" + + choice + bool "Default log verbosity" if LV_USE_LOG + default LV_LOG_LEVEL_WARN + help + Specify how important log should be added. + + config LV_LOG_LEVEL_TRACE + bool "A lot of logs to give detailed information" + config LV_LOG_LEVEL_INFO + bool "Log important events" + config LV_LOG_LEVEL_WARN + bool "Log if something unwanted happened but didn't cause a problem" + config LV_LOG_LEVEL_ERROR + bool "Only critical issues, when the system may fail" + config LV_LOG_LEVEL_USER + bool "Only logs added by the user" + config LV_LOG_LEVEL_NONE + bool "Do not log anything" + endchoice + + config LV_LOG_LEVEL + int + default 0 if LV_LOG_LEVEL_TRACE + default 1 if LV_LOG_LEVEL_INFO + default 2 if LV_LOG_LEVEL_WARN + default 3 if LV_LOG_LEVEL_ERROR + default 4 if LV_LOG_LEVEL_USER + default 5 if LV_LOG_LEVEL_NONE + + config LV_LOG_PRINTF + bool "Print the log with 'printf'" if LV_USE_LOG + help + Use printf for log output. + If not set the user needs to register a callback with `lv_log_register_print_cb`. + + config LV_LOG_USE_TIMESTAMP + bool "Enable print timestamp" + default y + depends on LV_USE_LOG + + config LV_LOG_USE_FILE_LINE + bool "Enable print file and line number" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_MEM + bool "Enable/Disable LV_LOG_TRACE in mem module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_TIMER + bool "Enable/Disable LV_LOG_TRACE in timer module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_INDEV + bool "Enable/Disable LV_LOG_TRACE in indev module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_DISP_REFR + bool "Enable/Disable LV_LOG_TRACE in disp refr module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_EVENT + bool "Enable/Disable LV_LOG_TRACE in event module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_OBJ_CREATE + bool "Enable/Disable LV_LOG_TRACE in obj create module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_LAYOUT + bool "Enable/Disable LV_LOG_TRACE in layout module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_ANIM + bool "Enable/Disable LV_LOG_TRACE in anim module" + default y + depends on LV_USE_LOG + + config LV_LOG_TRACE_CACHE + bool "Enable/Disable LV_LOG_TRACE in cache module" + default y + depends on LV_USE_LOG + endmenu + + menu "Asserts" + config LV_USE_ASSERT_NULL + bool "Check if the parameter is NULL. (Very fast, recommended)" + default y if !LV_CONF_MINIMAL + + config LV_USE_ASSERT_MALLOC + bool "Checks if the memory is successfully allocated or no. (Very fast, recommended)" + default y if !LV_CONF_MINIMAL + + config LV_USE_ASSERT_STYLE + bool "Check if the styles are properly initialized. (Very fast, recommended)" + + config LV_USE_ASSERT_MEM_INTEGRITY + bool "Check the integrity of `lv_mem` after critical operations. (Slow)" + + config LV_USE_ASSERT_OBJ + bool "Check NULL, the object's type and existence (e.g. not deleted). (Slow)" + + config LV_ASSERT_HANDLER_INCLUDE + string "Header to include for the custom assert function" + default "assert.h" + help + Add a custom handler when assert happens e.g. to restart the MCU + endmenu + + menu "Debug" + config LV_USE_REFR_DEBUG + bool "Draw random colored rectangles over the redrawn areas" + + config LV_USE_LAYER_DEBUG + bool "Draw a red overlay for ARGB layers and a green overlay for RGB layers" + + config LV_USE_PARALLEL_DRAW_DEBUG + bool "Draw overlays with different colors for each draw_unit's tasks" + help + Also add the index number of the draw unit on white background. + For layers add the index number of the draw unit on black background. + endmenu + + menu "Others" + config LV_ENABLE_GLOBAL_CUSTOM + bool "Enable 'lv_global' customization" + + config LV_GLOBAL_CUSTOM_INCLUDE + string "Header to include for the custom 'lv_global' function" + depends on LV_ENABLE_GLOBAL_CUSTOM + default "lv_global.h" + + config LV_CACHE_DEF_SIZE + int "Default image cache size. 0 to disable caching" + default 0 + depends on LV_USE_DRAW_SW + help + If only the built-in image formats are used there is no real advantage of caching. + (I.e. no new image decoder is added). + + With complex image decoders (e.g. PNG or JPG) caching can + save the continuous open/decode of images. + However the opened images might consume additional RAM. + + config LV_IMAGE_HEADER_CACHE_DEF_CNT + int "Default image header cache count. 0 to disable caching" + default 0 + depends on LV_USE_DRAW_SW + help + If only the built-in image formats are used there is no real advantage of caching. + (I.e. no new image decoder is added). + + With complex image decoders (e.g. PNG or JPG) caching can + save the continuous getting header information of images. + However the records of opened images headers might consume additional RAM. + + config LV_GRADIENT_MAX_STOPS + int "Number of stops allowed per gradient" + default 2 + depends on LV_USE_DRAW_SW + help + Increase this to allow more stops. + This adds (sizeof(lv_color_t) + 1) bytes per additional stop + + config LV_COLOR_MIX_ROUND_OFS + int "Adjust color mix functions rounding" + default 128 if !LV_COLOR_DEPTH_32 + default 0 if LV_COLOR_DEPTH_32 + range 0 254 + help + 0: no adjustment, get the integer part of the result (round down) + 64: round up from x.75 + 128: round up from half + 192: round up from x.25 + 254: round up + + config LV_OBJ_STYLE_CACHE + bool "Use cache to speed up getting object style properties" + default n + help + Add 2 x 32 bit variables to each lv_obj_t to speed up getting style properties + + config LV_USE_OBJ_ID + bool "Add id field to obj" + default n + + config LV_USE_OBJ_ID_BUILTIN + bool "Use builtin method to deal with obj ID" + default n + + config LV_USE_OBJ_PROPERTY + bool "Use obj property set/get API" + default n + + config LV_USE_VG_LITE_THORVG + bool "VG-Lite Simulator" + default n + depends on LV_USE_THORVG + help + Use thorvg to simulate VG-Lite hardware behavior, it's useful + for debugging and testing on PC simulator. Enable LV_USE_THORVG, + Either internal ThorVG or external ThorVG library is required. + + config LV_VG_LITE_THORVG_LVGL_BLEND_SUPPORT + bool "Enable LVGL blend mode support" + default n + depends on LV_USE_VG_LITE_THORVG + + config LV_VG_LITE_THORVG_YUV_SUPPORT + bool "Enable YUV color format support" + default n + depends on LV_USE_VG_LITE_THORVG + + config LV_VG_LITE_THORVG_16PIXELS_ALIGN + bool "Enable 16 pixels alignment" + default y + depends on LV_USE_VG_LITE_THORVG + + config LV_VG_LITE_THORVG_BUF_ADDR_ALIGN + int "Buffer address alignment" + default 64 + depends on LV_USE_VG_LITE_THORVG + + config LV_VG_LITE_THORVG_THREAD_RENDER + bool "Enable multi-thread render" + default n + depends on LV_USE_VG_LITE_THORVG + endmenu + endmenu + + menu "Compiler Settings" + config LV_BIG_ENDIAN_SYSTEM + bool "For big endian systems set to 1" + + config LV_ATTRIBUTE_MEM_ALIGN_SIZE + int "Required alignment size for buffers" + default 1 + + config LV_ATTRIBUTE_FAST_MEM_USE_IRAM + bool "Set IRAM as LV_ATTRIBUTE_FAST_MEM" + help + Set this option to configure IRAM as LV_ATTRIBUTE_FAST_MEM + + config LV_USE_FLOAT + bool "Use float as lv_value_precise_t" + default n + endmenu + + menu "Font Usage" + menu "Enable built-in fonts" + config LV_FONT_MONTSERRAT_8 + bool "Enable Montserrat 8" + config LV_FONT_MONTSERRAT_10 + bool "Enable Montserrat 10" + config LV_FONT_MONTSERRAT_12 + bool "Enable Montserrat 12" + config LV_FONT_MONTSERRAT_14 + bool "Enable Montserrat 14" + default y if !LV_CONF_MINIMAL + config LV_FONT_MONTSERRAT_16 + bool "Enable Montserrat 16" + config LV_FONT_MONTSERRAT_18 + bool "Enable Montserrat 18" + config LV_FONT_MONTSERRAT_20 + bool "Enable Montserrat 20" + config LV_FONT_MONTSERRAT_22 + bool "Enable Montserrat 22" + config LV_FONT_MONTSERRAT_24 + bool "Enable Montserrat 24" + config LV_FONT_MONTSERRAT_26 + bool "Enable Montserrat 26" + config LV_FONT_MONTSERRAT_28 + bool "Enable Montserrat 28" + config LV_FONT_MONTSERRAT_30 + bool "Enable Montserrat 30" + config LV_FONT_MONTSERRAT_32 + bool "Enable Montserrat 32" + config LV_FONT_MONTSERRAT_34 + bool "Enable Montserrat 34" + config LV_FONT_MONTSERRAT_36 + bool "Enable Montserrat 36" + config LV_FONT_MONTSERRAT_38 + bool "Enable Montserrat 38" + config LV_FONT_MONTSERRAT_40 + bool "Enable Montserrat 40" + config LV_FONT_MONTSERRAT_42 + bool "Enable Montserrat 42" + config LV_FONT_MONTSERRAT_44 + bool "Enable Montserrat 44" + config LV_FONT_MONTSERRAT_46 + bool "Enable Montserrat 46" + config LV_FONT_MONTSERRAT_48 + bool "Enable Montserrat 48" + + config LV_FONT_MONTSERRAT_28_COMPRESSED + bool "Enable Montserrat 28 compressed" + config LV_FONT_DEJAVU_16_PERSIAN_HEBREW + bool "Enable Dejavu 16 Persian, Hebrew, Arabic letters" + config LV_FONT_SIMSUN_16_CJK + bool "Enable Simsun 16 CJK" + + config LV_FONT_UNSCII_8 + bool "Enable UNSCII 8 (Perfect monospace font)" + default y if LV_CONF_MINIMAL + config LV_FONT_UNSCII_16 + bool "Enable UNSCII 16 (Perfect monospace font)" + endmenu + + choice LV_FONT_DEFAULT + prompt "Select theme default title font" + default LV_FONT_DEFAULT_MONTSERRAT_14 if !LV_CONF_MINIMAL + default LV_FONT_DEFAULT_UNSCII_8 if LV_CONF_MINIMAL + help + Select theme default title font + + config LV_FONT_DEFAULT_MONTSERRAT_8 + bool "Montserrat 8" + select LV_FONT_MONTSERRAT_8 + config LV_FONT_DEFAULT_MONTSERRAT_12 + bool "Montserrat 12" + select LV_FONT_MONTSERRAT_12 + config LV_FONT_DEFAULT_MONTSERRAT_14 + bool "Montserrat 14" + select LV_FONT_MONTSERRAT_14 + config LV_FONT_DEFAULT_MONTSERRAT_16 + bool "Montserrat 16" + select LV_FONT_MONTSERRAT_16 + config LV_FONT_DEFAULT_MONTSERRAT_18 + bool "Montserrat 18" + select LV_FONT_MONTSERRAT_18 + config LV_FONT_DEFAULT_MONTSERRAT_20 + bool "Montserrat 20" + select LV_FONT_MONTSERRAT_20 + config LV_FONT_DEFAULT_MONTSERRAT_22 + bool "Montserrat 22" + select LV_FONT_MONTSERRAT_22 + config LV_FONT_DEFAULT_MONTSERRAT_24 + bool "Montserrat 24" + select LV_FONT_MONTSERRAT_24 + config LV_FONT_DEFAULT_MONTSERRAT_26 + bool "Montserrat 26" + select LV_FONT_MONTSERRAT_26 + config LV_FONT_DEFAULT_MONTSERRAT_28 + bool "Montserrat 28" + select LV_FONT_MONTSERRAT_28 + config LV_FONT_DEFAULT_MONTSERRAT_30 + bool "Montserrat 30" + select LV_FONT_MONTSERRAT_30 + config LV_FONT_DEFAULT_MONTSERRAT_32 + bool "Montserrat 32" + select LV_FONT_MONTSERRAT_32 + config LV_FONT_DEFAULT_MONTSERRAT_34 + bool "Montserrat 34" + select LV_FONT_MONTSERRAT_34 + config LV_FONT_DEFAULT_MONTSERRAT_36 + bool "Montserrat 36" + select LV_FONT_MONTSERRAT_36 + config LV_FONT_DEFAULT_MONTSERRAT_38 + bool "Montserrat 38" + select LV_FONT_MONTSERRAT_38 + config LV_FONT_DEFAULT_MONTSERRAT_40 + bool "Montserrat 40" + select LV_FONT_MONTSERRAT_40 + config LV_FONT_DEFAULT_MONTSERRAT_42 + bool "Montserrat 42" + select LV_FONT_MONTSERRAT_42 + config LV_FONT_DEFAULT_MONTSERRAT_44 + bool "Montserrat 44" + select LV_FONT_MONTSERRAT_44 + config LV_FONT_DEFAULT_MONTSERRAT_46 + bool "Montserrat 46" + select LV_FONT_MONTSERRAT_46 + config LV_FONT_DEFAULT_MONTSERRAT_48 + bool "Montserrat 48" + select LV_FONT_MONTSERRAT_48 + config LV_FONT_DEFAULT_MONTSERRAT_28_COMPRESSED + bool "Montserrat 28 compressed" + select LV_FONT_MONTSERRAT_28_COMPRESSED + config LV_FONT_DEFAULT_DEJAVU_16_PERSIAN_HEBREW + bool "Dejavu 16 Persian, Hebrew, Arabic letters" + select LV_FONT_DEJAVU_16_PERSIAN_HEBREW + config LV_FONT_DEFAULT_SIMSUN_16_CJK + bool "Simsun 16 CJK" + select LV_FONT_SIMSUN_16_CJK + config LV_FONT_DEFAULT_UNSCII_8 + bool "UNSCII 8 (Perfect monospace font)" + select LV_FONT_UNSCII_8 + config LV_FONT_DEFAULT_UNSCII_16 + bool "UNSCII 16 (Perfect monospace font)" + select LV_FONT_UNSCII_16 + endchoice + + config LV_FONT_FMT_TXT_LARGE + bool "Enable it if you have fonts with a lot of characters" + help + The limit depends on the font size, font face and format + but with > 10,000 characters if you see issues probably you + need to enable it. + + config LV_USE_FONT_COMPRESSED + bool "Sets support for compressed fonts" + + config LV_USE_FONT_PLACEHOLDER + bool "Enable drawing placeholders when glyph dsc is not found" + default y + endmenu + + menu "Text Settings" + choice LV_TXT_ENC + prompt "Select a character encoding for strings" + help + Select a character encoding for strings. Your IDE or editor should have the same character encoding. + default LV_TXT_ENC_UTF8 if !LV_CONF_MINIMAL + default LV_TXT_ENC_ASCII if LV_CONF_MINIMAL + + config LV_TXT_ENC_UTF8 + bool "UTF8" + config LV_TXT_ENC_ASCII + bool "ASCII" + endchoice + + config LV_TXT_BREAK_CHARS + string "Can break (wrap) texts on these chars" + default " ,.;:-_)]}" + + config LV_TXT_LINE_BREAK_LONG_LEN + int "Line break long length" + default 0 + help + If a word is at least this long, will break wherever 'prettiest'. + To disable, set to a value <= 0. + + config LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN + int "Min num chars before break" + default 3 + depends on LV_TXT_LINE_BREAK_LONG_LEN > 0 + help + Minimum number of characters in a long word to put on a line before a break. + + config LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN + int "Min num chars after break" + default 3 + depends on LV_TXT_LINE_BREAK_LONG_LEN > 0 + help + Minimum number of characters in a long word to put on a line after a break + + config LV_USE_BIDI + bool "Support bidirectional texts" + help + Allows mixing Left-to-Right and Right-to-Left texts. + The direction will be processed according to the Unicode Bidirectional Algorithm: + https://www.w3.org/International/articles/inline-bidi-markup/uba-basics + + choice + prompt "Set the default BIDI direction" + default LV_BIDI_DIR_AUTO + depends on LV_USE_BIDI + + config LV_BIDI_DIR_LTR + bool "Left-to-Right" + config LV_BIDI_DIR_RTL + bool "Right-to-Left" + config LV_BIDI_DIR_AUTO + bool "Detect texts base direction" + endchoice + + config LV_USE_ARABIC_PERSIAN_CHARS + bool "Enable Arabic/Persian processing" + help + In these languages characters should be replaced with + an other form based on their position in the text. + endmenu + + menu "Widget Usage" + config LV_WIDGETS_HAS_DEFAULT_VALUE + bool "Widgets has default value" + default y if !LV_CONF_MINIMAL + config LV_USE_ANIMIMG + bool "Anim image" + default y if !LV_CONF_MINIMAL + config LV_USE_ARC + bool "Arc" + default y if !LV_CONF_MINIMAL + config LV_USE_BAR + bool "Bar" + default y if !LV_CONF_MINIMAL + config LV_USE_BUTTON + bool "Button" + default y if !LV_CONF_MINIMAL + config LV_USE_BUTTONMATRIX + bool "Button matrix" + default y if !LV_CONF_MINIMAL + config LV_USE_CALENDAR + bool "Calendar" + default y if !LV_CONF_MINIMAL + config LV_CALENDAR_WEEK_STARTS_MONDAY + bool "Calendar week starts monday" + depends on LV_USE_CALENDAR + config LV_USE_CALENDAR_HEADER_ARROW + bool "Use calendar header arrow" + depends on LV_USE_CALENDAR + default y + config LV_USE_CALENDAR_HEADER_DROPDOWN + bool "Use calendar header dropdown" + depends on LV_USE_CALENDAR + default y + config LV_USE_CANVAS + bool "Canvas. Requires: lv_image" + imply LV_USE_IMAGE + default y if !LV_CONF_MINIMAL + config LV_USE_CHART + bool "Chart" + default y if !LV_CONF_MINIMAL + config LV_USE_CHECKBOX + bool "Check Box" + default y if !LV_CONF_MINIMAL + config LV_USE_DROPDOWN + bool "Drop down list. Requires: lv_label" + imply LV_USE_LABEL + default y if !LV_CONF_MINIMAL + config LV_USE_IMAGE + bool "Image. Requires: lv_label" + imply LV_USE_LABEL + default y if !LV_CONF_MINIMAL + config LV_USE_IMAGEBUTTON + bool "ImageButton" + default y if !LV_CONF_MINIMAL + config LV_USE_KEYBOARD + bool "Keyboard" + default y if !LV_CONF_MINIMAL + config LV_USE_LABEL + bool "Label" + default y if !LV_CONF_MINIMAL + config LV_LABEL_TEXT_SELECTION + bool "Enable selecting text of the label" + depends on LV_USE_LABEL + default y + config LV_LABEL_LONG_TXT_HINT + bool "Store extra some info in labels (12 bytes) to speed up drawing of very long texts" + depends on LV_USE_LABEL + default y + config LV_LABEL_WAIT_CHAR_COUNT + int "The count of wait chart" + depends on LV_USE_LABEL + default 3 + config LV_USE_LED + bool "LED" + default y if !LV_CONF_MINIMAL + config LV_USE_LINE + bool "Line" + default y if !LV_CONF_MINIMAL + config LV_USE_LIST + bool "List" + default y if !LV_CONF_MINIMAL + config LV_USE_MENU + bool "Menu" + default y if !LV_CONF_MINIMAL + config LV_USE_MSGBOX + bool "Msgbox" + default y if !LV_CONF_MINIMAL + config LV_USE_OBSERVER + bool "Observer" + default n + config LV_USE_ROLLER + bool "Roller. Requires: lv_label" + imply LV_USE_LABEL + default y if !LV_CONF_MINIMAL + config LV_USE_SCALE + bool "Scale" + default y if !LV_CONF_MINIMAL + config LV_USE_SLIDER + bool "Slider. Requires: lv_bar" + imply LV_USE_BAR + default y if !LV_CONF_MINIMAL + config LV_USE_SPAN + bool "Span" + default y if !LV_CONF_MINIMAL + config LV_SPAN_SNIPPET_STACK_SIZE + int "Maximum number of span descriptor" + default 64 + depends on LV_USE_SPAN + config LV_USE_SPINBOX + bool "Spinbox" + default y if !LV_CONF_MINIMAL + config LV_USE_SPINNER + bool "Spinner" + default y if !LV_CONF_MINIMAL + config LV_USE_SWITCH + bool "Switch" + default y if !LV_CONF_MINIMAL + config LV_USE_TEXTAREA + bool "Text area. Requires: lv_label" + select LV_USE_LABEL + default y if !LV_CONF_MINIMAL + config LV_TEXTAREA_DEF_PWD_SHOW_TIME + int "Text area def. pwd show time [ms]" + default 1500 + depends on LV_USE_TEXTAREA + config LV_USE_TABLE + bool "Table" + default y if !LV_CONF_MINIMAL + config LV_USE_TABVIEW + bool "Tabview" + default y if !LV_CONF_MINIMAL + config LV_USE_TILEVIEW + bool "Tileview" + default y if !LV_CONF_MINIMAL + config LV_USE_WIN + bool "Win" + default y if !LV_CONF_MINIMAL + endmenu + + menu "Themes" + config LV_USE_THEME_DEFAULT + bool "A simple, impressive and very complete theme" + default y if !LV_COLOR_DEPTH_1 && !LV_CONF_MINIMAL + config LV_THEME_DEFAULT_DARK + bool "Yes to set dark mode, No to set light mode" + depends on LV_USE_THEME_DEFAULT + config LV_THEME_DEFAULT_GROW + bool "Enable grow on press" + default y + depends on LV_USE_THEME_DEFAULT + config LV_THEME_DEFAULT_TRANSITION_TIME + int "Default transition time in [ms]" + default 80 + depends on LV_USE_THEME_DEFAULT + config LV_USE_THEME_SIMPLE + bool "A very simple theme that is a good starting point for a custom theme" + default y if !LV_COLOR_DEPTH_1 && !LV_CONF_MINIMAL + config LV_USE_THEME_MONO + bool "Monochrome theme, suitable for some E-paper & dot matrix displays" + default y if LV_COLOR_DEPTH_1 && !LV_CONF_MINIMAL + endmenu + + menu "Layouts" + config LV_USE_FLEX + bool "A layout similar to Flexbox in CSS" + default y if !LV_CONF_MINIMAL + config LV_USE_GRID + bool "A layout similar to Grid in CSS" + default y if !LV_CONF_MINIMAL + endmenu + + menu "3rd Party Libraries" + config LV_USE_FS_STDIO + bool "File system on top of stdio API" + config LV_FS_STDIO_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65 )" + default 0 + depends on LV_USE_FS_STDIO + config LV_FS_STDIO_PATH + string "Set the working directory" + depends on LV_USE_FS_STDIO + config LV_FS_STDIO_CACHE_SIZE + int ">0 to cache this number of bytes in lv_fs_read()" + default 0 + depends on LV_USE_FS_STDIO + + config LV_USE_FS_POSIX + bool "File system on top of posix API" + config LV_FS_POSIX_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65)" + default 0 + depends on LV_USE_FS_POSIX + config LV_FS_POSIX_PATH + string "Set the working directory" + depends on LV_USE_FS_POSIX + config LV_FS_POSIX_CACHE_SIZE + int ">0 to cache this number of bytes in lv_fs_read()" + default 0 + depends on LV_USE_FS_POSIX + + config LV_USE_FS_WIN32 + bool "File system on top of Win32 API" + config LV_FS_WIN32_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65)" + default 0 + depends on LV_USE_FS_WIN32 + config LV_FS_WIN32_PATH + string "Set the working directory" + depends on LV_USE_FS_WIN32 + config LV_FS_WIN32_CACHE_SIZE + int ">0 to cache this number of bytes in lv_fs_read()" + default 0 + depends on LV_USE_FS_WIN32 + + config LV_USE_FS_FATFS + bool "File system on top of FatFS" + config LV_FS_FATFS_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65)" + default 0 + depends on LV_USE_FS_FATFS + config LV_FS_FATFS_CACHE_SIZE + int ">0 to cache this number of bytes in lv_fs_read()" + default 0 + depends on LV_USE_FS_FATFS + + config LV_USE_FS_MEMFS + bool "File system on top of memory-mapped API" + config LV_FS_MEMFS_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65)" + default 0 + depends on LV_USE_FS_MEMFS + + config LV_USE_FS_LITTLEFS + bool "File system on top of littlefs API" + config LV_FS_LITTLEFS_LETTER + int "Set an upper cased letter on which the drive will accessible (e.g. 'A' i.e. 65)" + default 0 + depends on LV_USE_FS_LITTLEFS + + config LV_USE_LODEPNG + bool "PNG decoder library" + + config LV_USE_LIBPNG + bool "PNG decoder(libpng) library" + + config LV_USE_BMP + bool "BMP decoder library" + + config LV_USE_TJPGD + bool "TJPGD decoder library" + + config LV_USE_LIBJPEG_TURBO + bool "libjpeg-turbo decoder library" + + config LV_USE_GIF + bool "GIF decoder library" + + config LV_GIF_CACHE_DECODE_DATA + bool "Use extra 16KB RAM to cache decoded data to accerlate" + depends on LV_USE_GIF + + config LV_BIN_DECODER_RAM_LOAD + bool "Decode whole image to RAM for bin decoder" + default n + + config LV_USE_RLE + bool "LVGL's version of RLE compression method" + + config LV_USE_QRCODE + bool "QR code library" + + config LV_USE_BARCODE + bool "Barcode library" + + config LV_USE_FREETYPE + bool "FreeType library" + config LV_FREETYPE_USE_LVGL_PORT + bool "Let FreeType to use LVGL memory and file porting" + default n + depends on LV_USE_FREETYPE + config LV_FREETYPE_CACHE_FT_GLYPH_CNT + int "The maximum number of Glyph in count" + default 256 + depends on LV_USE_FREETYPE + + config LV_USE_TINY_TTF + bool "Enable Tiny TTF decoder" + default n + config LV_TINY_TTF_FILE_SUPPORT + bool "Enable loading Tiny TTF data from files" + default n + depends on LV_USE_TINY_TTF + + config LV_USE_RLOTTIE + bool "Lottie library" + config LV_USE_THORVG + bool "ThorVG library" + choice + prompt "Use ThorVG config" + depends on LV_USE_THORVG + default LV_USE_THORVG_INTERNAL + config LV_USE_THORVG_INTERNAL + bool "Use ThorVG internal" + config LV_USE_THORVG_EXTERNAL + bool "Use ThorVG external" + endchoice + + config LV_USE_LZ4 + bool "Enable LZ4 compress/decompress lib" + choice + prompt "Choose lvgl built-in LZ4 lib or external lib" + depends on LV_USE_LZ4 + default LV_USE_LZ4_INTERNAL + config LV_USE_LZ4_INTERNAL + bool "Use lvgl built-in LZ4 lib" + config LV_USE_LZ4_EXTERNAL + bool "Use external LZ4 library" + endchoice + + config LV_USE_FFMPEG + bool "FFmpeg library" + config LV_FFMPEG_DUMP_FORMAT + bool "Dump format" + depends on LV_USE_FFMPEG + default n + endmenu + + menu "Others" + config LV_USE_SNAPSHOT + bool "Enable API to take snapshot" + default n if !LV_CONF_MINIMAL + + config LV_USE_SYSMON + bool "Enable system monitor component" + default n + + config LV_USE_PERF_MONITOR + bool "Show CPU usage and FPS count" + depends on LV_USE_SYSMON + + choice + prompt "Performance monitor position" + depends on LV_USE_PERF_MONITOR + default LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT + + config LV_PERF_MONITOR_ALIGN_TOP_LEFT + bool "Top left" + config LV_PERF_MONITOR_ALIGN_TOP_MID + bool "Top middle" + config LV_PERF_MONITOR_ALIGN_TOP_RIGHT + bool "Top right" + config LV_PERF_MONITOR_ALIGN_BOTTOM_LEFT + bool "Bottom left" + config LV_PERF_MONITOR_ALIGN_BOTTOM_MID + bool "Bottom middle" + config LV_PERF_MONITOR_ALIGN_BOTTOM_RIGHT + bool "Bottom right" + config LV_PERF_MONITOR_ALIGN_LEFT_MID + bool "Left middle" + config LV_PERF_MONITOR_ALIGN_RIGHT_MID + bool "Right middle" + config LV_PERF_MONITOR_ALIGN_CENTER + bool "Center" + endchoice + + config LV_USE_PERF_MONITOR_LOG_MODE + bool "Prints performance data using log" + depends on LV_USE_PERF_MONITOR + default n + + config LV_USE_MEM_MONITOR + bool "Show the used memory and the memory fragmentation" + default n + depends on LV_STDLIB_BUILTIN && LV_USE_SYSMON + + choice + prompt "Memory monitor position" + depends on LV_USE_MEM_MONITOR + default LV_MEM_MONITOR_ALIGN_BOTTOM_LEFT + + config LV_MEM_MONITOR_ALIGN_TOP_LEFT + bool "Top left" + config LV_MEM_MONITOR_ALIGN_TOP_MID + bool "Top middle" + config LV_MEM_MONITOR_ALIGN_TOP_RIGHT + bool "Top right" + config LV_MEM_MONITOR_ALIGN_BOTTOM_LEFT + bool "Bottom left" + config LV_MEM_MONITOR_ALIGN_BOTTOM_MID + bool "Bottom middle" + config LV_MEM_MONITOR_ALIGN_BOTTOM_RIGHT + bool "Bottom right" + config LV_MEM_MONITOR_ALIGN_LEFT_MID + bool "Left middle" + config LV_MEM_MONITOR_ALIGN_RIGHT_MID + bool "Right middle" + config LV_MEM_MONITOR_ALIGN_CENTER + bool "Center" + endchoice + + config LV_USE_MONKEY + bool "Enable Monkey test" + default n + + config LV_USE_PROFILER + bool "Runtime performance profiler" + config LV_USE_PROFILER_BUILTIN + bool "Enable the built-in profiler" + depends on LV_USE_PROFILER + default y + config LV_PROFILER_BUILTIN_BUF_SIZE + int "Default profiler trace buffer size in bytes" + depends on LV_USE_PROFILER_BUILTIN + default 16384 + config LV_PROFILER_INCLUDE + string "Header to include for the profiler" + depends on LV_USE_PROFILER + default "lvgl/src/misc/lv_profiler_builtin.h" + + config LV_USE_GRIDNAV + bool "Enable grid navigation" + default n + + config LV_USE_FRAGMENT + bool "Enable lv_obj fragment" + default n + + config LV_USE_IMGFONT + bool "draw image in label or span obj" + default n + + config LV_USE_IME_PINYIN + bool "Enable Pinyin input method" + default n + config LV_IME_PINYIN_USE_K9_MODE + bool "Enable Pinyin input method 9 key input mode" + depends on LV_USE_IME_PINYIN + default n + config LV_IME_PINYIN_K9_CAND_TEXT_NUM + int "Maximum number of candidate panels for 9-key input mode" + depends on LV_IME_PINYIN_USE_K9_MODE + default 3 + config LV_IME_PINYIN_USE_DEFAULT_DICT + bool "Use built-in Thesaurus" + depends on LV_USE_IME_PINYIN + default y + help + If you do not use the default thesaurus, be sure to use lv_ime_pinyin after setting the thesauruss + config LV_IME_PINYIN_CAND_TEXT_NUM + int "Maximum number of candidate panels" + depends on LV_USE_IME_PINYIN + default 6 + help + Set the maximum number of candidate panels that can be displayed. + This needs to be adjusted according to the size of the screen. + + config LV_USE_FILE_EXPLORER + bool "Enable file explorer" + default n + config LV_FILE_EXPLORER_PATH_MAX_LEN + int "Maximum length of path" + depends on LV_USE_FILE_EXPLORER + default 128 + config LV_FILE_EXPLORER_QUICK_ACCESS + bool "Enable quick access bar" + depends on LV_USE_FILE_EXPLORER + default y + help + This can save some memory, but not much. After the quick access bar is created, it can be hidden by clicking the button at the top left corner of the browsing area, which is very useful for small screen devices. + endmenu + + menu "Devices" + config LV_USE_SDL + bool "Use SDL to open window on PC and handle mouse and keyboard" + default n + config LV_SDL_INCLUDE_PATH + string "SDL include path" + depends on LV_USE_SDL + default "SDL2/SDL.h" + + choice + prompt "SDL rendering mode" + depends on LV_USE_SDL + default LV_SDL_RENDER_MODE_DIRECT + help + LV_DISPLAY_RENDER_MODE_DIRECT is recommended for best performance + + config LV_SDL_RENDER_MODE_PARTIAL + bool "Use the buffer(s) to render the screen is smaller parts" + + config LV_SDL_RENDER_MODE_DIRECT + bool "Only the changed areas will be updated with 2 screen sized buffers" + + config LV_SDL_RENDER_MODE_FULL + bool "Always redraw the whole screen even if only one pixel has been changed with 2 screen sized buffers" + endchoice + + choice + prompt "SDL buffer size" + depends on LV_USE_SDL + default LV_SDL_SINGLE_BUFFER + + config LV_SDL_SINGLE_BUFFER + bool "One screen-sized buffer" + + config LV_SDL_DOUBLE_BUFFER + bool "Two screen-sized buffer" + depends on !LV_SDL_RENDER_MODE_PARTIAL + + config LV_SDL_CUSTOM_BUFFER + bool "Custom-sized buffer" + depends on LV_SDL_RENDER_MODE_PARTIAL + endchoice + + config LV_SDL_BUFFER_COUNT + int + depends on LV_USE_SDL + default 0 if LV_SDL_CUSTOM_BUFFER + default 1 if LV_SDL_SINGLE_BUFFER + default 2 if LV_SDL_DOUBLE_BUFFER + + config LV_SDL_FULLSCREEN + bool "SDL fullscreen" + depends on LV_USE_SDL + default n + config LV_SDL_DIRECT_EXIT + bool "Exit the application when all SDL windows are closed" + depends on LV_USE_SDL + default y + + config LV_USE_X11 + bool "Use X11 window manager to open window on Linux PC and handle mouse and keyboard" + default n + config LV_X11_DOUBLE_BUFFER + bool "Use double buffers for lvgl rendering" + depends on LV_USE_X11 + default y + config LV_X11_DIRECT_EXIT + bool "Exit the application when all X11 windows have been closed" + depends on LV_USE_X11 + default y + choice + prompt "X11 device render mode" + depends on LV_USE_X11 + default LV_X11_RENDER_MODE_PARTIAL + + config LV_X11_RENDER_MODE_PARTIAL + bool "Partial render mode (preferred)" + help + Use the buffer(s) to render the screen is smaller parts. This way the buffers can be smaller then the display to save RAM. + Appr. 1/10 screen size buffer(s) are used. + config LV_X11_RENDER_MODE_DIRECT + bool "Direct render mode" + help + The buffer(s) has to be screen sized and LVGL will render into the correct location of the buffer. This way the buffer always contain the whole image. Only the changed ares will be updated. + With 2 buffers the buffers' content are kept in sync automatically and in flush_cb only address change is required. + config LV_X11_RENDER_MODE_FULL + bool "Full render mode" + help + Always redraw the whole screen even if only one pixel has been changed. + With 2 buffers in flush_cb only and address change is required. + endchoice + + config LV_USE_LINUX_FBDEV + bool "Use Linux framebuffer device" + default n + config LV_LINUX_FBDEV_BSD + bool "Use BSD flavored framebuffer device" + depends on LV_USE_LINUX_FBDEV + default n + + choice + prompt "Framebuffer device render mode" + depends on LV_USE_LINUX_FBDEV + default LV_LINUX_FBDEV_RENDER_MODE_PARTIAL + + config LV_LINUX_FBDEV_RENDER_MODE_PARTIAL + bool "Partial mode" + help + Use the buffer(s) to render the screen is smaller parts. This way the buffers can be smaller then the display to save RAM. At least 1/10 screen size buffer(s) are recommended. + + config LV_LINUX_FBDEV_RENDER_MODE_DIRECT + bool "Direct mode" + help + The buffer(s) has to be screen sized and LVGL will render into the correct location of the buffer. This way the buffer always contain the whole image. Only the changed ares will be updated. With 2 buffers the buffers' content are kept in sync automatically and in flush_cb only address change is required. + + config LV_LINUX_FBDEV_RENDER_MODE_FULL + bool "Full mode" + help + Always redraw the whole screen even if only one pixel has been changed. With 2 buffers in flush_cb only and address change is required. + + endchoice + + choice + prompt "Framebuffer size" + depends on LV_USE_LINUX_FBDEV + default LV_LINUX_FBDEV_SINGLE_BUFFER + + config LV_LINUX_FBDEV_SINGLE_BUFFER + bool "One screen-sized buffer" + + config LV_LINUX_FBDEV_DOUBLE_BUFFER + bool "Two screen-sized buffer" + depends on !LV_LINUX_FBDEV_RENDER_MODE_PARTIAL + + config LV_LINUX_FBDEV_CUSTOM_BUFFER + bool "Custom-sized buffer" + depends on LV_LINUX_FBDEV_RENDER_MODE_PARTIAL + + endchoice + + config LV_LINUX_FBDEV_BUFFER_COUNT + int + depends on LV_USE_LINUX_FBDEV + default 0 if LV_LINUX_FBDEV_CUSTOM_BUFFER + default 1 if LV_LINUX_FBDEV_SINGLE_BUFFER + default 2 if LV_LINUX_FBDEV_DOUBLE_BUFFER + + config LV_LINUX_FBDEV_BUFFER_SIZE + int "Custom partial buffer size (in number of rows)" + depends on LV_USE_LINUX_FBDEV && LV_LINUX_FBDEV_CUSTOM_BUFFER + default 60 + + config LV_USE_NUTTX + bool "Use Nuttx to open window and handle touchscreen" + default n + + config LV_USE_NUTTX_LIBUV + bool "Use uv loop to replace default timer loop and other fb/indev timers" + depends on LV_USE_NUTTX + default n + + config LV_USE_NUTTX_CUSTOM_INIT + bool "Use Custom Nuttx init API to open window and handle touchscreen" + depends on LV_USE_NUTTX + default n + + config LV_USE_NUTTX_LCD + bool "Use NuttX LCD device" + depends on LV_USE_NUTTX + default n + + choice + prompt "NuttX LCD buffer size" + depends on LV_USE_NUTTX_LCD + default LV_NUTTX_LCD_SINGLE_BUFFER + + config LV_NUTTX_LCD_SINGLE_BUFFER + bool "One screen-sized buffer" + + config LV_NUTTX_LCD_DOUBLE_BUFFER + bool "Two screen-sized buffer" + + config LV_NUTTX_LCD_CUSTOM_BUFFER + bool "Custom-sized buffer" + + endchoice + + config LV_NUTTX_LCD_BUFFER_COUNT + int + depends on LV_USE_NUTTX_LCD + default 0 if LV_NUTTX_LCD_CUSTOM_BUFFER + default 1 if LV_NUTTX_LCD_SINGLE_BUFFER + default 2 if LV_NUTTX_LCD_DOUBLE_BUFFER + + config LV_NUTTX_LCD_BUFFER_SIZE + int "Custom partial buffer size (in number of rows)" + depends on LV_USE_NUTTX_LCD && LV_NUTTX_LCD_CUSTOM_BUFFER + default 60 + + config LV_USE_NUTTX_TOUCHSCREEN + bool "Use NuttX touchscreen driver" + depends on LV_USE_NUTTX + default n + + config LV_USE_LINUX_DRM + bool "Use Linux DRM device" + default n + + config LV_USE_TFT_ESPI + bool "Use TFT_eSPI driver" + default n + + config LV_USE_EVDEV + bool "Use evdev input driver" + default n + + config LV_USE_LIBINPUT + bool "Use libinput input driver" + default n + + config LV_LIBINPUT_BSD + bool "Use the BSD variant of the libinput input driver" + depends on LV_USE_LIBINPUT + default n + + config LV_LIBINPUT_XKB + bool "Enable full keyboard support via XKB" + depends on LV_USE_LIBINPUT + default n + + config LV_USE_ST7735 + bool "Use ST7735 LCD driver" + default n + + config LV_USE_ST7789 + bool "Use ST7789 LCD driver" + default n + + config LV_USE_ST7796 + bool "Use ST7796 LCD driver" + default n + + config LV_USE_ILI9341 + bool "Use ILI9341 LCD driver" + default n + + config LV_USE_GENERIC_MIPI + bool "Generic MIPI driver" + default y if LV_USE_ST7735 || LV_USE_ST7789 || LV_USE_ST7796 || LV_USE_ILI9341 + + config LV_USE_WINDOWS + bool "Use LVGL Windows backend" + default n + endmenu + + menu "Examples" + config LV_BUILD_EXAMPLES + bool "Enable the examples to be built" + default y if !LV_CONF_MINIMAL + endmenu + + menu "Demos" + config LV_USE_DEMO_WIDGETS + bool "Show some widget" + default n + + config LV_USE_DEMO_KEYPAD_AND_ENCODER + bool "Demonstrate the usage of encoder and keyboard" + default n + + config LV_USE_DEMO_BENCHMARK + bool "Benchmark your system" + default n + depends on LV_FONT_MONTSERRAT_14 && LV_FONT_MONTSERRAT_24 && LV_USE_DEMO_WIDGETS + config LV_USE_DEMO_RENDER + bool "Render test for each primitives. Requires at least 480x272 display" + default n + + config LV_USE_DEMO_SCROLL + bool "Scroll settings test for LVGL" + default n + + config LV_USE_DEMO_STRESS + bool "Stress test for LVGL" + default n + + config LV_USE_DEMO_TRANSFORM + bool "Transform test for LVGL" + default n + depends on LV_FONT_MONTSERRAT_18 + + config LV_USE_DEMO_MUSIC + bool "Music player demo" + default n + config LV_DEMO_MUSIC_SQUARE + bool "Enable Square" + depends on LV_USE_DEMO_MUSIC + default n + config LV_DEMO_MUSIC_LANDSCAPE + bool "Enable Landscape" + depends on LV_USE_DEMO_MUSIC + default n + config LV_DEMO_MUSIC_ROUND + bool "Enable Round" + depends on LV_USE_DEMO_MUSIC + default n + config LV_DEMO_MUSIC_LARGE + bool "Enable Large" + depends on LV_USE_DEMO_MUSIC + default n + config LV_DEMO_MUSIC_AUTO_PLAY + bool "Enable Auto play" + depends on LV_USE_DEMO_MUSIC + default n + + config LV_USE_DEMO_FLEX_LAYOUT + bool "Flex layout previewer" + default n + config LV_USE_DEMO_MULTILANG + bool "multi-language demo" + default n + config LV_USE_DEMO_VECTOR_GRAPHIC + bool "vector graphic demo" + default n + depends on LV_USE_VECTOR_GRAPHIC + endmenu + +endmenu endif # GRAPHICS_LVGL diff --git a/graphics/lvgl/Make.defs b/graphics/lvgl/Make.defs index 453933cbf..0caf681f3 100644 --- a/graphics/lvgl/Make.defs +++ b/graphics/lvgl/Make.defs @@ -21,21 +21,9 @@ ifneq ($(CONFIG_GRAPHICS_LVGL),) CONFIGURED_APPS += $(APPDIR)/graphics/lvgl -# Use LVGL v9 dev version, removed after Release - -CFLAGS += -DLV_USE_DEV_VERSION=1 -CXXFLAGS += -DLV_USE_DEV_VERSION=1 - # It allows `` import. CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/graphics/lvgl CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/graphics/lvgl -# It allows `` import. - -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/graphics/lvgl/lvgl -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/graphics/lvgl/lvgl - --include $(APPDIR)/graphics/lvgl/ext/Make.defs - endif diff --git a/graphics/lvgl/Makefile b/graphics/lvgl/Makefile index 4c0c901c3..6f3eddc2b 100644 --- a/graphics/lvgl/Makefile +++ b/graphics/lvgl/Makefile @@ -25,65 +25,51 @@ include $(APPDIR)/Make.defs LVGL_DIR = . LVGL_DIR_NAME = lvgl -SUFFIX := lvgl - -# Relax format check for LVGL to avoid errors on prinf() use - -include ./lvgl/lvgl.mk --include ./ext/Makefile - -ifneq ($(CONFIG_LV_USE_LIBPNG),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/libpng -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/libpng/libpng -endif - -ifneq ($(CONFIG_LV_USE_LIBWEBP),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/libwebp/libwebp/src/ -endif - -ifneq ($(CONFIG_LV_USE_LIBJPEG_TURBO),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/libjpeg-turbo/libjpeg-turbo -endif - -ifneq ($(CONFIG_LV_USE_FFMPEG),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/ffmpeg/ffmpeg -endif - -ifneq ($(CONFIG_LV_USE_RLOTTIE),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/rlottie/rlottie/inc -endif - -ifneq ($(CONFIG_LVX_USE_QRSCAN),) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/external/quirc/quirc/lib -endif - ifneq ($(CONFIG_LV_ASSERT_HANDLER_INCLUDE), "") CFLAGS += "-DLV_ASSERT_HANDLER=ASSERT(0);" endif -ifeq ($(and $(CONFIG_LV_USE_PERF_MONITOR),$(CONFIG_SCHED_CPULOAD)),y) -CFLAGS += "-DLV_SYSMON_GET_IDLE=lv_nuttx_get_idle" -endif +# Set up build configuration and environment -ifeq ($(and $(CONFIG_SCHED_INSTRUMENTATION),$(CONFIG_LV_USE_PROFILER)),y) -CFLAGS += "-DLV_PROFILER_BEGIN=sched_note_beginex(NOTE_TAG_GRAPHICS, __func__)" -CFLAGS += "-DLV_PROFILER_END=sched_note_endex(NOTE_TAG_GRAPHICS, __func__)" +WD := ${shell echo $(CURDIR) | sed -e 's/ /\\ /g'} -CFLAGS += "-DLV_PROFILER_BEGIN_TAG(str)=sched_note_beginex(NOTE_TAG_GRAPHICS, str)" -CFLAGS += "-DLV_PROFILER_END_TAG(str)=sched_note_endex(NOTE_TAG_GRAPHICS, str)" -endif +CONFIG_GRAPH_LVGL_URL ?= "https://github.com/lvgl/lvgl/archive/refs/tags" -ifneq ($(CONFIG_LV_GPU_G2D_INCLUDE_PATH),) -CFLAGS += "-I$(addprefix $(strip $(INCDIR_PREFIX))$(APPDIR)/../,$(CONFIG_LV_GPU_G2D_INCLUDE_PATH))" -endif +LVGL_PATCHS ?= $(sort $(wildcard 000*.patch)) -ifeq ($(CONFIG_LV_USE_DRAW_VG_LITE),y) -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/../$(CONFIG_LV_DRAW_VG_LITE_INCLUDE) +LVGL_VERSION = 9.1.0 +LVGL_TARBALL = v$(LVGL_VERSION).zip -# Disable optimization for vg_lite_path.c to avoid a compiler bug. -# See: https://bugs.launchpad.net/gcc-arm-embedded/+bug/1982289 -$(CURDIR)/lvgl/src/draw/vg_lite/lv_vg_lite_path.c_CFLAGS += -O0 +LVGL_UNPACKNAME = lvgl +UNPACK ?= unzip -o $(if $(V),,-q) +CURL ?= curl -L -O $(if $(V),,-Ss) + +LVGL_UNPACKDIR = $(WD)/$(LVGL_UNPACKNAME) + +$(LVGL_TARBALL): + $(ECHO_BEGIN)"Downloading: $(LVGL_TARBALL)" + $(Q) $(CURL) $(CONFIG_GRAPH_LVGL_URL)/$(LVGL_TARBALL) + $(ECHO_END) + +$(LVGL_UNPACKNAME): $(LVGL_TARBALL) + $(ECHO_BEGIN)"Unpacking: $(LVGL_TARBALL) -> $(LVGL_UNPACKNAME)" + $(Q) $(UNPACK) $(LVGL_TARBALL) + $(Q) mv lvgl-$(LVGL_VERSION) $(LVGL_UNPACKNAME) + $(Q) cat $(LVGL_PATCHS) | patch -s -N -d $(LVGL_UNPACKNAME) -p1 + $(Q) touch $(LVGL_UNPACKNAME) + $(ECHO_END) + +# Download and unpack tarball if no git repo found +ifeq ($(wildcard $(LVGL_UNPACKNAME)/.git),) +context:: $(LVGL_UNPACKNAME) endif include $(APPDIR)/Application.mk + +ifeq ($(wildcard $(LVGL_UNPACKNAME)/.git),) +distclean:: + $(call DELDIR, $(LVGL_UNPACKNAME)) + $(call DELFILE, $(LVGL_TARBALL)) +endif diff --git a/graphics/lvgl/README.md b/graphics/lvgl/README.md deleted file mode 100644 index a3c846a8d..000000000 --- a/graphics/lvgl/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Graphics / `lvgl` LVGL - -## Usage - -Import with `#include ` or `#include `. - -Upstream example ported to NuttX is present at `examples/lvgldemo`. - -LVGL can be used with framebuffer device. To find example boards with this -preconfigured, search for `CONFIG_GRAPHICS_LVGL=y` in `defconfig` files. All of -them have also `CONFIG_VIDEO_FB=y` present. - -As a second option, LVGL can talk to a display driver and explicitly draw line -by line. For this case, there is no preconfigured board present. Go to _Porting_ -section of upstream documentation for more hints. - -## Resources - -- [API documentation with examples](https://docs.lvgl.io/latest/en/html/index.html) -- [GitHub / LVGL / LVGL library](https://github.com/lvgl/lvgl) -- [GitHub / LVGL / Examples, tutorials, applications](https://github.com/lvgl/lv_examples) -- [GitHub / LVGL / Desktop simulator](https://github.com/lvgl/lv_sim_eclipse_sdl) -- [GitHub / LVGL / Web simulator](https://github.com/lvgl/lv_sim_emscripten) diff --git a/graphics/lvgl/tools/config_checker.py b/graphics/lvgl/tools/config_checker.py deleted file mode 100644 index 95a034d58..000000000 --- a/graphics/lvgl/tools/config_checker.py +++ /dev/null @@ -1,151 +0,0 @@ -# -# Copyright (C) 2022 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# - -import sys -import yaml -import argparse -from tabulate import tabulate -import re - -def parse_config_h(file_path): - configs = {} - try: - with open(file_path, 'r') as file: - for line in file: - line = line.strip() - if line.startswith('#define'): - parts = line.split(maxsplit=2) - if len(parts) >= 3: - key = parts[1].replace('CONFIG_', '') - value = parts[2] - # Check if the value is a number - if re.match(r'^-?\d+$', value): - configs[key] = int(value) - else: - # Check if the value is surrounded by quotes - if not (value.startswith('"') and value.endswith('"')): - value = f'"{value}"' - configs[key] = value.strip('"') - except FileNotFoundError: - print("\033[91mFailed to open config.h file. Please compile to generate config.h.\033[0m") - exit(-1) - - return configs - -def parse_yaml(file_path): - configs = {} - try: - with open(file_path, 'r') as file: - configs = yaml.safe_load(file) - except FileNotFoundError: - print("\033[91mFailed to open Reference file. Please provide a valid Reference file.\033[0m") - exit(-1) - return configs - -def filter_yml_configs(yml_configs, groups): - group_configs = {} - for group in groups: - if group in yml_configs: - group_configs[group] = yml_configs[group] - return group_configs - -def compare_configs(config_h_configs, group_configs): - differences = {} - # Check for configurations present in YAML but missing in config.h - for group, configs in group_configs.items(): - for key, value in configs.items(): - if value == 0 and key not in config_h_configs: - continue # Ignore configurations with value 0 that are missing in config.h - elif key not in config_h_configs: - differences[key] = {'config_h_value': 'N/A', 'yml_value': value, 'group': group, 'status': 'Missing in config.h'} - - # Check for configurations with different values between config.h and YAML - for group, configs in group_configs.items(): - for key, value in configs.items(): - if key in config_h_configs and str(config_h_configs[key]) != str(value): - differences[key] = {'config_h_value': config_h_configs[key], 'yml_value': value, 'group': group, 'status': 'Mismatch'} - return differences - -def compare_and_print_differences(config_h_configs, group_configs): - differences = compare_configs(config_h_configs, group_configs) - print("\n\033[93mDifferences between config.h and Reference:") - if differences: - print_differences(differences) - else: - print("No differences found.") - -def print_differences(differences): - headers = ["Group", "Config", "config.h", "Reference", "Status"] - rows = [] - for key, values in differences.items(): - row = [values['group'], key, values['config_h_value'], values['yml_value'], values['status']] - rows.append(row) - print(tabulate(rows, headers=headers)) - -def print_grouped_configs(group_configs): - print("\n\033[92mConfigs from Reference file grouped by selected groups:") - headers = ["Group", "Config", "Value"] - rows = [] - for group, configs in group_configs.items(): - for key, value in configs.items(): - rows.append([group, key, value]) - print(tabulate(rows, headers=headers)) - -def print_help(): - print("Usage: python config_checker.py") - print("Options:") - print_args() - -def main(): - parser = argparse.ArgumentParser(description='Check differences between config.h and Reference config files.') - parser.add_argument('-c', '--config', help='Path to the config.h file', required=True) - parser.add_argument('-g', '--groups', help='Groups to include, separated by comma', required=True) - parser.add_argument('-r', '--refs', help='Path to the Reference reference file', required=True) - parser.add_argument('-d', '--debug', action='store_true', help='Enable debug mode') - args = parser.parse_args() - - file_path = args.config - groups = args.groups.split(',') - refs_path = args.refs - - print("User provided arguments:") - print(f"Config.h file path: {file_path}") - print(f"Groups to include: {', '.join(groups)}") - print(f"Refs file path: {refs_path}") - - config_h_configs = parse_config_h(file_path) - yml_configs = parse_yaml(refs_path) - selected_group_configs = filter_yml_configs(yml_configs, groups) - - if args.debug: - print("config_h_configs:") - for key, value in config_h_configs.items(): - print(f"{key}: {value}") - print() - - print("yml_configs:") - for key, value in yml_configs.items(): - print(f"{key}:") - for k, v in value.items(): - print(f" {k}: {v}") - print() - - print_grouped_configs(selected_group_configs) - - compare_and_print_differences(config_h_configs, selected_group_configs) - -if __name__ == "__main__": - main() diff --git a/graphics/lvgl/tools/config_refs.yml b/graphics/lvgl/tools/config_refs.yml deleted file mode 100644 index f9b8e529a..000000000 --- a/graphics/lvgl/tools/config_refs.yml +++ /dev/null @@ -1,69 +0,0 @@ -base: - GRAPHICS_LVGL: 1 - LV_CONF_SKIP: 1 - LV_USE_CLIB_MALLOC: 1 - LV_USE_CLIB_STRING: 1 - LV_USE_CLIB_SPRINTF: 1 - LV_DEF_REFR_PERIOD: 16 - LV_USE_LOG: 1 - LV_LOG_LEVEL_WARN: 1 - LV_LOG_LEVEL: 2 - LV_LOG_PRINTF: 0 - LV_LOG_USE_TIMESTAMP: 0 - LV_USE_FS_POSIX: 1 - LV_FS_POSIX_LETTER: 47 - LV_FS_POSIX_PATH: "/" - LIB_FREETYPE: 1 - LV_USE_FREETYPE: 1 - LV_USE_NUTTX: 1 - LV_USE_NUTTX_LIBUV: 1 - LV_USE_NUTTX_TOUCHSCREEN: 1 - -png: - LIB_PNG: 1 - LV_USE_LIBPNG: 1 - -jpeg: - LIB_JPEG_TURBO: 1 - LV_USE_LIBJPEG_TURBO: 1 - -cache: - LV_CACHE_DEF_SIZE: 8388608 - LV_IMAGE_HEADER_CACHE_DEF_CNT: 128 - LV_FREETYPE_CACHE_SIZE: 1024 - LV_FREETYPE_CACHE_FT_FACES: 8 - LV_FREETYPE_CACHE_FT_SIZES: 16 - LV_FREETYPE_CACHE_FT_GLYPH_CNT: 256 - LV_BIN_DECODER_RAM_LOAD: 1 - -32bit: - LV_COLOR_DEPTH_32: 1 - LV_COLOR_DEPTH: 32 - -16bit: - LV_COLOR_DEPTH_16: 1 - LV_COLOR_DEPTH: 16 - -perf: - DEBUG_CUSTOMOPT: 1 - DEBUG_OPTLEVEL: "-O3" - SCHED_INSTRUMENTATION: 0 - SCHED_IRQMONITOR: 0 - SCHED_CRITMONITOR: 0 - STACK_CANARIES: 0 - MM_KASAN: 0 - MM_BACKTRACE: -1 - LV_OBJ_STYLE_CACHE: 1 - LV_USE_ASSERT_NULL: 0 - LV_USE_ASSERT_MALLOC: 0 - LV_USE_ASSERT_STYLE: 0 - LV_USE_ASSERT_MEM_INTEGRITY: 0 - LV_USE_ASSERT_OBJ: 0 - -vg_lite: - LV_USE_DRAW_VG_LITE: 1 - LV_VG_LITE_USE_GPU_INIT: 1 - LV_DRAW_BUF_ALIGN: 64 - LV_ATTRIBUTE_MEM_ALIGN_SIZE: 64 - LV_USE_VECTOR_GRAPHIC: 1 - LV_USE_FLOAT: 1 diff --git a/graphics/nxwidgets/Doxygen/README.md b/graphics/nxwidgets/Doxygen/README.md deleted file mode 100644 index dc38ed5da..000000000 --- a/graphics/nxwidgets/Doxygen/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Graphics / `nxwidgets` NXWidgets / Doxygen - -This directory contains the documentation automatically generated by Doxygen. - -## Contents - -- Installing the necessary packages in Ubuntu -- Generating documentation -- References - -## Installing the Necessary Packages in Ubuntu - -1. Install the following packages. - - ```bash - $ sudo aptitude install doxygen doxygen-doc doxygen-gui dot2tex graphviz - ``` - -2. (Optional) Install Doxygen from the latest sourcode. - - The Ubuntu package is outdated. The newer the version of Doxygen, the better - the documentation looks. - - Place yourself in some temporary folder where you can download the source, - and run [1]: - - ```bash - $ svn co https://doxygen.svn.sourceforge.net/svnroot/doxygen/trunk doxygen-svn - $ cd doxygen-svn - $ ./configure - $ make - $ make install - ``` - -## Generating Documentation - -Two ways described here: - -1. Use the provided `gendoc.sh` script. - - ```bash - trunk/NXWidgets/Doxygen/gendoc.sh - ``` - - The script only needs the argument to the absolute path where to place the - generated documentation. I.e.: - - ```bash - $ cd /path/to/nuttx/trunk/NXWidgets/Doxygen/ - $ mkdir doc - $ ./gendoc.sh $PWD/doc - ``` - -2. Using the `Doxyfile` directly: - - The file `Doxyfile` contains the configuration of the Doxygen settings for - the run, edit only if necessary. - - To generate the documentation type: - - ```bash - $ cd /path/to/nuttx/trunk/NXWidgets/Doxygen/ - $ doxygen Doxyfile - ``` - -## References - -[1] http://www.stack.nl/~dimitri/doxygen/download.html diff --git a/graphics/nxwidgets/Makefile b/graphics/nxwidgets/Makefile index 809096cac..1b9a1112d 100644 --- a/graphics/nxwidgets/Makefile +++ b/graphics/nxwidgets/Makefile @@ -1,5 +1,5 @@ ################################################################################# -# appx/graphics/nxwidgets/Makefile +# apps/graphics/nxwidgets/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/graphics/nxwidgets/README.md b/graphics/nxwidgets/README.md deleted file mode 100644 index 5fc93f371..000000000 --- a/graphics/nxwidgets/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Graphics / `nxwidgets` NXWidgets - -In order to better support NuttX based platforms, a special graphical user -interface has been created called NXWidgets. NXWidgets is written in C++ and -integrates seamlessly with the NuttX NX graphics subsystem in order to provide -graphic objects, or _widgets_, in the NX Graphics Subsystem - -Some of the features of NXWidgets include: - -- Conservative C++ - - NXWidgets is written entirely in C++ but using only selected _embedded - friendly_ C++ constructs that are fully supported under NuttX. No additional - C++ support libraries are required. - -- NX Integration - - NXWidgets integrate seamlessly with the NX graphics system. Think of the X - server under Linux – the NX graphics system is like a tiny X server that - provides windowing under NuttX. By adding NXWidgets, you can support graphics - objects like buttons and text boxes in the NX windows and toolbars. - -- Small Footprint - - NXWidgets is tailored for use MCUs in embedded applications. It is ideally - suited for mid- and upper-range of most MCU families. A complete NXWidgets is - possible in as little as 40Kb of FLASH and maybe 4Kb of SRAM. - -- Output Devices - - NXWidgets will work on the high-end frame buffer devices as well as on LCDs - connected via serial or parallel ports to a small MCU. - -- Input Devices - - NXWidgets will accept position and selection inputs from a mouse or a - touchscreen. It will also support character input from a keyboard such as a - USB keyboard. NXWidgets supports on very special widget called `CKeypad` that - will provide keyboard input via an on-screen keypad that can be operated via - mouse or touchscreen inputs. - -- Many Graphic Objects - - Some of the graphic objects supported by NXWidgets include labels, buttons, - text boxes, button arrays, check boxes, cycle buttons, images, sliders, - scrollable list boxes, progress bars, and more. - -**Note**: Many of the fundamental classed in NxWidgets derive from the Antony -Dzeryn's _Woopsi_ project: http://woopsi.org/ which also has a BSD style -license. See the `COPYING` file for details. - -## Directory Structure - -- `Kconfig` - - This is a `Kconfig` file that should be provided at `apps/NxWidgets/Kconfig`. - When copied to that location, it will be used by the NuttX configuration - systems to configure settings for NxWidgets and NxWM - -- `nxwidgets` - - The source code, header files, and build environment for NxWidgets is provided - in this directory. - -- `UnitTests` - - Provides a collection of unit-level tests for many of the individual widgets - provided by `nxwidgets`. diff --git a/graphics/nxwidgets/UnitTests/CButton/Makefile b/graphics/nxwidgets/UnitTests/CButton/Makefile index cfefa0906..54695133e 100644 --- a/graphics/nxwidgets/UnitTests/CButton/Makefile +++ b/graphics/nxwidgets/UnitTests/CButton/Makefile @@ -1,5 +1,5 @@ ################################################################################# -# apps/graphics/nxwidgets/Unitests/CButton/Makefile +# apps/graphics/nxwidgets/UnitTests/CButton/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/graphics/nxwidgets/UnitTests/CKeypad/Makefile b/graphics/nxwidgets/UnitTests/CKeypad/Makefile index 4dab8d6f5..df283728f 100644 --- a/graphics/nxwidgets/UnitTests/CKeypad/Makefile +++ b/graphics/nxwidgets/UnitTests/CKeypad/Makefile @@ -1,5 +1,5 @@ ################################################################################# -# apps/graphics/nxwidgets/UnitTests/CKeyPad/Makefile +# apps/graphics/nxwidgets/UnitTests/CKeypad/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/graphics/nxwidgets/UnitTests/README.md b/graphics/nxwidgets/UnitTests/README.md deleted file mode 100644 index b96875485..000000000 --- a/graphics/nxwidgets/UnitTests/README.md +++ /dev/null @@ -1,259 +0,0 @@ -# Graphics / NXWidgets / Unit Tests - -This directory contains a collection of Unit Tests that can be used to verify -NXWidgets.: - -## Contents - -**Installing and Building the Unit Tests** - -1. Setup NuttX - 1. Configure NuttX - 2. Enable C++ Support - 3. Enable Debug Options - 4. Special configuration requirements for the nxwm unit test - 5. Other `.config` file changes – NSH configurations only - 6. Other `.config` file changes – NON-NSH configurations only -2. Adjust the Stack Size -3. Build NuttX including the unit test and the NXWidgets library - -**Work-Arounds** - -1. Build Issues - -**Unit Test Directories** - -## Installing and Building the Unit Tests - -1. Setup NuttX - - 1. Configure NuttX - - Configure NuttX to run one of the target configurations. For example, - let's assume that you are using the `sim/nsh2` configuration. The - `sim/nsh2` configuration was specially created for use NXWidgets on the - simulation platform. A similar, special configuration `stm3210e-eval/nsh2` - is also for the `STM3210E-EVAL` available. However, the unit test can be - run on other configurations (see steps d and e below). - - **Note**: There are some other special configurationsrecommended for - unit-leveling testing of NxWM because the configuration is more complex in - that case. These are: - - 1) `sim/nxwmm`, or the simulated platform (no touchscreen), and - 2) `stm3240g-evel`, for the `STM3240G-EVAL` board (with the STMPE11 - touchscreen) - - We will assume the `sim/nsh2` configuration in this discussion. The - `sim/nsh2` configuration is installed as follows: - - ```bash - cd - make distclean - tools/configure.sh sim:nsh2 - ``` - - Where: - - `` is the full, absolute path to the NuttX build - directory - - If you are using the `sim/nsh2` or `stm3210e-eval` configurations, then - skip to step 2 (Hmmm.. better check 1d) too). - - There may be certain requirements for the configuration that you select... - for example, certain widget tests may require touchscreen support or - special font selections. These test-specific requirements are addressed - below under _Unit Test Directories_ - - 2. Enable C++ Support - - If you are not using the `sim/nsh2` or `stm3210e-eval`, you will need to - add the following definitions to the NuttX configuration at - `nuttx/.config` to enable C++ support: - - ```conf - CONFIG_HAVE_CXX=y - ``` - - Check first, some configurations already have C++ support enabled (As of - this writing **ONLY** the `sim/nsh2` and `stm321-e-eval` configurations - have C++ support pre-enabled). - - 3. Enable Debug Options - - If you are running on a simulated target, then you might also want to - enable debug symbols: - - ```conf - CONFIG_DEBUG_SYMBOLS=y - ``` - - Then you can run the simulation using GDB or DDD which is a very powerful - debugging environment! - - 4. Special configuration requirements for the nxwm unit test. - - ```conf - CONFIG_NXTERM=y - ``` - - 5. Other `.config` file changes – NSH configurations only. - - If the configuration that you are using supports NSH and NSH built-in - tasks then all is well. If it is an NSH configuration, then you will have - to define the following in your `nuttx/.config` file as well (if it is not - already defined): - - ```conf - CONFIG_NSH_BUILTIN_APPS=y - ``` - - `sim/nsh2` and `stm3210e-eval/nsh2` already has this setting. You do not - need to change anything further in the `nuttx/.config` file if you are - using either of these configurations. - - 6. Other `.config` file changes – NON-NSH configurations only. - - Entry Point. You will need to set the entry point in the .config file. For - NSH configurations, the entry point will always be `nsh_main` and you will - see that setting like: - - ```conf - CONFIG_INIT_ENTRYPOINT="nsh_main" - ``` - - If you are not using in NSH, then each unit test has a unique entry point. - That entry point is the name of the unit test directory in all lower case - plus the suffix `_main`. So, for example, the correct entry for the - `UnitTests/CButton` would be: - - ```conf - CONFIG_INIT_ENTRYPOINT="cbutton_main" - ``` - - And the correct entry point for `UnitTests/nxwm` would be: - - ```conf - CONFIG_INIT_ENTRYPOINT="nxwm_main" - ``` - - etc. - - For non-NSH configurations (such as the `sim/touchscreen`) you will have - to remove the configuration setting that provided the `main` function so - that you use the `main` in the unit test code instead. So, for example, - with the `sim/touchscreen` configuration you need to remove the following - from the NuttX configuration file (`.config`): - - ```conf - CONFIG_EXAMPLES_TOUSCHCREEN=y ## REMOVE (provided "tc_main") - ``` - -2. Adjust the Stack Size - - If using an simulation configuration (like `sim/nsh2`) and your unit test - uses X11 as its display device, then you would have to increase the size of - unit test stack as described below under _Stack Size Issues with the X11 - Simulation_. - -3. Build NuttX including the unit test and the NXWidgets library - - ```bash - cd - . ./setenv.sh - make - ``` - -## Work-Arounds - -### Build Issues - -1. I have seen this error on Cygwin building C++ code: - - ``` - LD: nuttx.rel - ld: skipping incompatible /home/patacongo/projects/nuttx/nuttx/trunk/nuttx/libxx//liblibxx.a when searching for -llibxx - ld: cannot find -llibxx - ``` - - The problem seems to be caused because `gcc` build code for 32-bit mode and - `g++` builds code for 64-bit mode. Add the `-m32` option to the `g++` command - line seems to fix the problem. In `Make.defs`: - - ```makefile - CXXFLAGS = -m32 $(ARCHWARNINGSXX) $(ARCHOPTIMIZATION) \ - $(ARCHCXXFLAGS) $(ARCHINCLUDESXX) $(ARCHDEFINES) $(EXTRADEFINES) -pipe - ``` - -2. Stack Size Issues with the X11 Simulation - - When you run the NuttX simulation, it uses stacks allocated by NuttX from the - NuttX heap. The memory management model is exactly the same in the simulation - as it is real, target system. This is good because this produces a higher - fidelity simulation. - - However, when the simulation calls into Linux/Cygwin libraries, it will still - use these small simulation stacks. This happens, for example, when you call - into the system to get and put characters to the console window or when you - make x11 calls into the system. The programming model within those libraries - will assume a Linux/Cygwin environment where the stack size grows dynamically - - As a consequence, those system libraries may allocate large data structures - on the stack and overflow the small NuttX stacks. X11, in particular, - requires large stacks. If you are using X11 in the simulation, make sure that - you set aside a "lot" of stack for the X11 system calls (maybe 8 or 16Kb). - The stack size for the thread that begins with user start is controlled by - the configuration setting `CONFIG_INIT_STACKSIZE`; you may need to - increase this value to larger number to survive the X11 system calls. - - If you are running X11 applications as NSH add-on programs, then the stack - size of the add-on program is controlled in another way. Here are the steps - for increasing the stack size in that case: - - ```bash - cd ../apps/namedapps # Go to the namedapps directory - vi namedapps_list.h # Edit this file and increase the stack size of the add-on - rm .built *.o # This will force the namedapps logic to rebuild - ``` - -## Unit Tests - -The following provide simple unit tests for each of the NXWidgets. In addition, -these unit tests provide examples for the use of each widget type. - -- `CButton` - - Exercises the `CButton` widget. - - Depends on `CLabel`. -- `CButtonArray` - - Exercises the `CButtonArray` widget. -- `CCheckBox` - - Exercises the `CCheckBox` widget. - - Depends on `CLabel` and `CButton`. -- `CGlyphButton` - - Exercises the `CGlyphButton` widget. - - Depends on `CLabel` and `CButton`. -- `CImage` - - Exercises the `CImage` widget. -- `CLabel` - - Exercises the `CLabel` widget. -- `CProgressBar` - - Exercises the `CProgressBar` widget. -- `CRadioButton` - - Exercises the `CRadioButton` and `CRadioButtonGroup` widgets. - - Depends on `CLabel` and `CButton`. -- `CScrollBarHorizontal` - - Exercises the `ScrollbarHorizontal`. - - Depends on `CSliderHorizontal` and `CGlyphButton`. -- `CScrollBarVertical` - - Exercises the `ScrollbarHorizontal`. - - Depends on `CSliderVertical` and `CGlyphButton`. -- `CSliderHorizontal` - - Exercises the `CSliderHorizontal`. - - Depends on `CSliderHorizontalGrip`. -- `CSliderVertical` - - Exercises the `CSliderVertical`. - - Depends on `CSliderVerticalGrip`. -- `CTextBox` - - Exercises the `CTextBox` widget. - - Depends on `CLabel`. diff --git a/graphics/nxwm/Doxygen/README.md b/graphics/nxwm/Doxygen/README.md deleted file mode 100644 index cf4436347..000000000 --- a/graphics/nxwm/Doxygen/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Graphics / `nxwm` NxWM / Doxygen - -This directory contains the documentation automatically generated by Doxygen. - -## Contents - -- Installing the necessary packages in Ubuntu -- Generating documentation -- References - -## Installing the necessary packages in Ubuntu - -1. Install the following packages. - - ```bash - $ sudo aptitude install doxygen doxygen-doc doxygen-gui dot2tex graphviz - ``` - -2. (Optional) Install Doxygen from the latest sourcode. - - The Ubuntu package is outdated. The newer the version of Doxygen, the better - the documentation looks. - - Place yourself in some temporary folder where you can download the source, - and run [1]: - - ```bash - $ svn co https://doxygen.svn.sourceforge.net/svnroot/doxygen/trunk doxygen-svn - $ cd doxygen-svn - $ ./configure - $ make - $ make install - ``` - -## Generating documentation - -Two ways described here: - -1. Use the provided `gendoc.sh` script. - - ```bash - trunk/NXWidgets/Doxygen/gendoc.sh - ``` - - The script only needs the argument to the absolute path where to place the - generated documentation. I.e.: - - ```bash - $ cd /path/to/nuttx/trunk/NXWidgets/Doxygen/ - $ mkdir doc - $ ./gendoc.sh $PWD/doc - ``` - -2. Using the `Doxyfile` directly: - - The file `Doxyfile` contains the configuration of the Doxygen settings for - the run, edit only if necessary. - - To generate the documentation type: - - ```bash - $ cd /path/to/nuttx/trunk/NXWidgets/Doxygen/ - $ doxygen Doxyfile - ``` - -## References - -[1] http://www.stack.nl/~dimitri/doxygen/download.html diff --git a/graphics/nxwm/README.md b/graphics/nxwm/README.md deleted file mode 100644 index 2578a46f2..000000000 --- a/graphics/nxwm/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Graphics / `nxwm` NxWM - -This directory holds a tiny desktop for small embedded devices with a -touchscreen,. NxWM. NxWM is true multiple window manager but only one window is -displayed at a time. This simplification helps performance on LCD based products -(in the same way that a tiled window manager helps) and also makes the best use -of small displays. It is awkward from a human factors point-of-view trying to -manage multiple windows on a small display. - -The window manager consists of a task bar with icons representing the running -tasks. If you touch the task's icon, it comes to the top. Each window has a -toolbar with (1) a title, (2) a minimize button, and (3) a stop application -button using the standard icons for these things. - -There is always a start window that is available in the task bar. When you touch -the start window icon, it brings up the start window containing icons -representing all of the available applications. If you touch an icon in the -start window, it will be started and added to the task bar. - -There is a base class that defines an add-on application and an interface that -supports incorporation of new application. The only application that is provided -is NxTerm. This is an NSH session running in a window. You should be able to -select the NX icon in the start menu and create as many NSH sessions in windows -as you want. (keybard input still comes through serial). - -Note 1: NwWM requires `NuttX-7.19` or above to work with the current -`NxWidgets-1.18` release. diff --git a/graphics/pdcurs34/pdcurses/Make.defs b/graphics/pdcurs34/pdcurses/Make.defs index d8ebe865b..5d6a8ccf5 100644 --- a/graphics/pdcurs34/pdcurses/Make.defs +++ b/graphics/pdcurs34/pdcurses/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/graphics/pdcurs34/Make.defs +# apps/graphics/pdcurs34/pdcurses/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/graphics/screenshot/Makefile b/graphics/screenshot/Makefile index 5e8cfae58..9847dd22f 100644 --- a/graphics/screenshot/Makefile +++ b/graphics/screenshot/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/screenshot/Makefile +# apps/graphics/screenshot/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/graphics/tiff/README.md b/graphics/tiff/README.md deleted file mode 100644 index dd4620715..000000000 --- a/graphics/tiff/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Graphics / `tiff` TIFF Creation Library - -This directory contains a library that can be used to create TIFF image files. -This file was created for the purpose of supporting screen dumps from an LCD. -Howeve, the logic is general and could be used for most any purpose. - -The only usage documentation is in the (rather extensive) comments in the file -`apps/include/tiff.h`. - -## Unit Test - -See `apps/examples/tiff`. diff --git a/graphics/twm4nx/README.md b/graphics/twm4nx/README.md deleted file mode 100644 index 5c594b94d..000000000 --- a/graphics/twm4nx/README.md +++ /dev/null @@ -1,386 +0,0 @@ -# Graphics / `twm4nx` Tab Window Manager (TWM) - -Twm4Nx is a port of twm, Tab Window Manager (or Tom's Window Manager) version -`1.0.10` to NuttX NX windows server. No, a port is not the right word. It is a -re-design of TWM from the inside out to work with the NuttX NX server. The name -Twm4Nx reflects this legacy. But Twm4Nx is more a homage to TWM than a port of -TWM. - -The original TWM was based on X11 which provides a rich set of features. TWM -provided titlebars, shaped windows, several forms of icon management, -user-defined macro functions, click-to-type and pointer-driven keyboard focus, -graphic contexts, and user-specified key and pointer button bindings, etc. - -Twm4Nx, on the other hand is based on the NuttX NX server which provides -comparatively minimal support. Additional drawing support comes from the NuttX -NxWidgets library (which necessitated the change to C++). - -Twm4Nx is greatly stripped down and targeted on small embedded systems with -minimal resources. For example, no assumption is made about the availability of -a file system; no `.twmrc` file is used. Bitmaps are not used (other than for -fonts). - -The TWM license is, I believe compatible with the BSD license used by NuttX. The -origin TWM license required notice of copyrights within each file and a full -copy of the original license which you can find in the `COPYING` file. within -this directory. - -## Status - -### Progress - -- `2019-04-28` This port was brutal. Much TWM logic was removed because it - depended on X11 features (or just because I could not understand how to use - it). The replacement logic is only mostly in place but more needs to be done - to have a complete system (hence, it is marked `EXPERIMENTAL`). The kinds of - things that need to done are: - - 1. Right click should bring up a window list (like the icon manager???) - 2. For TWM-like behavior, a window frame and toolbar should be highlighted - when the window has focus. - 3. A right click on the toolbar should bring up a window-specific menu. - -- `2019-05-02` Some testing progress. The system comes up, connects to and - initializes the VNC window. For some reason, the VNC client breaks the - connection. The server is no longer connected so Twm4Nx constipates and and - eventually hangs. - -- `2019-05-08` I abandoned the VNC interface and found that things are much - better using a direct, hardware framebuffer. The background comes up properly - and the Icon Manager appears properly in the upper right hand corner. The Icon - Manager Window can be iconified or de-iconified. The Icon Manager window can - be grabbed by the toolbar title and moved about on the window (the movement is - not very smooth on the particular hardware that I am working with). - -- `2019-05-10` A left click on the background brings up the main menu. At - present there are only two options: _Desktop_ which will iconify all windows - and _Twm4Nx Icon Manager_ which will de-iconify and/or raise the Icon Manager - window to the top of the hierarchy. That latter option is only meaningful when - the desktop is very crowded. - -- `2019-05-13` Added the NxTerm application. If enabled via - `CONFIG_TWM4XN_NXTERM`, there will now be a _NuttShell_ entry in the Main - Menu. When pressed, this will bring up an NSH session in a Twm4Nx window. - -- `2019-05-14` We can now move an icon on the desktop. Includes logic to avoid - collisions with other icons and with the background image. That later is an - issue. The background image image widget needs to be removed; it can occlude a - desktop icon. We need to paint the image directly on the background without - the use of a widget. - -- `2019-05-15` Resizing now seems to work correctly in Twm4Nx. - -- `2019-05-20` Calibration screen is now in place. - -- `2019-05-21` A `CONTEMPORARY` theme was added. Still has a few glitches. - -- `2019-06-01` A retro, emulated segment LCD clock is now in place. - -## How To - -### Icon Manager - -- At start up, only the Icon Manager window is shown. The Icon Manager is a TWM - alternative to more common desktop icons. Currently Twm4Nx supports both - desktop icons and the Icon Manager. - - Whenever a new application is started from the Main Menu, its name shows up in - the Icon Manager. Selecting the name will either de-iconify the window, or - just raise it to the top of the display. - -### Main Menu: - -- A touch/click at any open location on the background (except the image at the - center or on another icon) will bring up the Main Menu. Options: - - Desktop. Iconify all windows and show the desktop - - Twm4Nx Icom Manager. De-iconify and/or raise the Icon Manager to the top of - the display. - - Calibration. Perform touchscreen re-calibration. - - Clock. Start and instance of clock in the window. The uses the the retro, - LCD emulation of `apps/graphics/slcd`. - - NuttShell. Start and instance of NSH running in an NxTerm. -- All windows close after the terminal menu option is selected. - -### Window Toolbar - -- Most windows have a toolbar at the top. It is optional but used in most - windows. -- The toolbar contains window title and from zero to 4 buttons: - - Right side: A menu button may be presented. The menu button is not used by - anything in the current implementation and is always suppressed - - Left side: The far left is (1) the terminate button (if present). If - present, it will close window when selected. Not all windows can be closed. - You can't close the Icon Manager or menu windows, for example. Then (2) a - resize button. If presented and is selected, then the resize sequence - described below it started. This may the be preceded by a minimize button - that iconifies the window. - -### Moving a Window: - -- Grab the title in the toolbar and move the window to the desired position. - -### Resizing a Window: - -- A window must have the green resize button with the square or it cannot be - resized. -- Press resize button. A small window should pop-up in the upper left hand - corner showing the current window size. -- Touch anywhere in window (not the toolbar) and slide your finger. The resize - window will show the new size but there will be no other update to the - display. It is thought that continuous size updates would overwhelm lower end - MCUs. Movements support include: - - Move toward the right increases the width of the window - - Move toward the left decreases the width of the window - - Move toward the bottom increases the height of the window - - Move toward the top decreases the height of the Window - - Other moves will affect both the height and width of the window. -- **Note**: While resizing, non-critical events from all other windows are - ignored. - -### Themes - -- There are two themes support by the configuration system: - - `CONFIG_TWM4NX_CLASSIC` – Strong bordered windows with dark primary colors. - Reminiscent of Windows 98. - - `CONFIG_TWM4NX_CONTEMPORARY` – Border-less windows in pastel shades for a - more contemporary look. - -## Issues: - -`2019-05-16` Twm4Nx is in a very complete state but only at perhaps _alpha_ in -its maturity. You should expect to see some undocumented problems. If you see -such problems and can describe a sequence to actions to reproduce the problem, -let me know and I will try to resolve the problems. - -Here are all known issues and features that are missing: - -TWM Compatibilities Issues: -1. Resizing works a little differently in Twm4Nx. -2. Right click should bring up a window list -3. For TWM-like behavior, a window frame and toolbar should be highlighted when - the window has focus. -4. A right click on the toolbar should bring up a window-specific menu. - -There are no near-term plans to address these compatibility issues. - -Other issues/bugs. All-in-all, I would say that Twm4Nx is maturing well and is -attaining stability. That being said, there are some issues and untested -functionality that should be addressed: - -1. Icon drag movement includes logic to avoid collisions with other icons and - with the background image. That later is an issue. We need to paint the image - directly on the background without the use of a widget. -2. There are a few color artifacts in the toolbar of the `CONTEMPORARY` theme. - These look like borders are being drawn around the toolbar widgets (even - though the are configured to be borderless). -3. Most Twm4Nx configuration settings are hard-coded in `*_config.hxx` header - files. These all need to be brought out and made accessible via Kconfig files -4. I have seen some odd behavior when many NxTerm windows have been opened - (around 15). Specifically, I see failures to start NSH in the windows so they - come up blank. All other behaviors seem normal. Most likely, some NxTerm - resource allocation is failing silently and leaving things in an unusable - state. The board I am using has 128Mb of SDRAM so I can't believe that memory - is the limiting factor. These are, however, RAM-backed windows and will use - significant amounts of memory. The primary issue is that the number of - windows should probably be managed in some way to assure that the end-user - does not experience odd behaviors when resource usage is high. -5. Menus with sub-menus have not been verified. There is no use of sub- menus in - the current code base so I expect that there are issues when, for example, - and item from a sub-menu item: That menu and all of its antecedent menus - should be closed. -6. There is an optional MENU button that may appear at the far left on the - toolbar. It is not used by any window in the current code base and, hence, is - unverified. I would expect some issues with generating and routing the MENU - button events to applications. There are likely other unverified features. -7. X/Y input may be either via a touchscreen or a mouse. Only touchscreen input - has been verified. There is, however, very little difference. The primary - issue is in cursor support: Cursors are needed with a mouse. Cursor images - also change depending on the state (like grabbing and dragging or resizing). - There is also a possibility of using auto-raise with a mouse as well. All of - this logic is in place, but none has been verified. -8. NxTerm windows really need to be scrollable. They are difficult to use with - only a few lines on a small display. A related usability issue is the font - height: The fonts report a maximum font height that results in a large line - spacing on the display and, hence, fewer lines visible in the small window. - This is latter issues is a problem with the fonts not Twm4Nx, however. -9. There is a trivial rounding error in the calculation of the LCD width in - `SLcd::CSLcd::getWidth()`. It currently truncates down. It needs to round up. - This sometimes leaves a small, one-pixel- wide sliver on the clock display. - This display always recovers and this only cosmetic. - -## Adding Twm4Nx Applications - -### Application Factories and the Main Menu - -The original TWM supported a .twmrc in which you could describe application -programs supported on the desktop. Currently no such start-up file is available -for Twm4Nx. Rather, all applications must be added via run-time interfaces. And -overview of these interfaces is provided in this paragraph. - -Currently, there are only two applications developed for Twm4Nx: (1) An NxTerm -hosting NSH that is analogous to an XTerm hosting the Bash shell in a Unix -environment, and (2) a touchscreen calibration application. Let's focus instead -on the NxTerm application as an example because the touchscreen calibration is a -rather unusual beast. - -These example applications can be found at: `apps/graphics/twm4nx/apps` and -`apps/include/graphics/twm4nx/apps` - -In short, adding an application involves a _Factory Object_ that is hooked into -the Main Menu. A Factory Object is an object that is used to create other object -instances. The way in which the Factory Object is represented is purely a -decision of the application developer. One option, however, is to use the pure -virtual base class `IApplicationFactory` as defined in -`apps/include/graphics/twm4nx/iapplication.hxx`. This base class provides only a -single method: - -```cpp -bool initialize(FAR CTwm4Nx *twm4nx); -``` - -where CTwm4Nx is the Twm4NX session instance that allows the class -implementation to interact with session specific resources. Multiple sessions -would be required, for example, if the platform supported multiple displays. - -In practice, the application factory implementation class inherits from the -following base classes: - -1. `IApplicationFactory`. Provides the common `initialize()` method. -2. `IApplication`. Provides the information for the application's entry in the - Main Menu -3. `CTwm4NxEvent`. Hooks the application factory into the Twm4Nx event - notification system. - -Initialization consists of instantiating the application factory instance and -calling its `IApplicationFactory::initialize()` method. The application factory -instance is a singleton that must persist for the life of the session. For the -NxTerm application factory, this is done in -`apps/graphics/twm4nx/src/twm4nx_main.c` like: - -```cpp -CNxTermFactory nxtermFactory; -success = nxtermFactory.initialize(twm4nx); -``` - -In addition to general initialization, the `IApplicationFactory::initialize()` -method must register a new entry with the main menu. You can see an example of -this in `apps/graphics/twm4nx/apps/cnxterm.c`: - -```cpp -FAR CMainMenu *cmain = twm4nx->getMainMenu(); -return cmain->addApplication(this); -``` - -The argument to the `CMainMenu::addApplication()` method is of type -`IApplication *`. Remember, however, that our application implementation `class` -inherited from `IApplication`. - -The IApplication pure virtual base class is also defined in -`apps/include/graphics/twm4nx/iapplication.hxx`. It essentially describes what -the Main Menu logic should do when the menu item is selected. It includes these -methods: - -1. `getName()`. Provides the name string that will be shown in the Main Menu for - this selection. -2. `getSubMenu()`. One possibility is that selecting the Main Menu item is that - it may bring up yet another sub-menu of options. -3. `getEventHandler()`. Returns an instance of `CTwm4NxEvent` that is used to - route menu selection events. Remember that our application factory inherits - from `CTwm4NxEvent` so this function only needs to return the 'this' - pointer. -4. `getEvent()`. Provides the event ID that will be used in the event - notification. The returned value must conform to the description in - `apps/include/graphics/twm4nx/twm4nx_events.hxx`. In particular, the - recipient of the event must be `EVENT_RECIPIENT_APP`. - -The Twm4Nx application is then started when the application factory's -`CTwm4NxEvent::event()` method is called with the specified event. - -### Application Windows - -How the application factory starts an application instance is purely up to the -application designer. Typically this would include starting a new application -task. General characteristics of an application include: - -1. It probably should inherit from `CTwm4NxEvent` so that it can receive events - from the system. -2. To create the window, it must instantiate and initialize an instance of - `CWindow`. -3. It must configure application events to receive notifications from Twm4Nx. - -To create an application window, the application must call the -`CWindowFactory::createWindow()` method. For the NxTerm example, this looks -like: - -```cpp -NXWidgets::CNxString name("NuttShell"); - -uint8_t wflags = (WFLAGS_NO_MENU_BUTTON | WFLAGS_HIDDEN); - -FAR CWindowFactory *factory = m_twm4nx->getWindowFactory(); -m_nxtermWindow = factory->createWindow(name, &CONFIG_TWM4NX_NXTERM_ICON, - (FAR CIconMgr *)0, wflags); -``` - -The window factory is another factory that creates and manages window instance. -The `createWindow()` method requires four parameters: - -1. The name of the window. This is the name that is show in the window toolbar - and may be the same name as was used in the Main Menu entry. -2. A reference to the the Icon image associated with the window. This is the - image that is show on the desktop when the window is iconified. It is of - type `NXWidgets::SRlePaletteBitmap`. -3. A pointer to the Icon Manager instance that this window belongs with. This - can be NULL to use the default Twm4Nx Icon Manager. -4. A set of flags that describe properties of the windows. - - The flag values are defined byte `WFLAGS_*` definitions provided in - `apps/include/graphics/twm4nx/cwindow.hxx`: - - - `WFLAGS_NO_MENU_BUTTON` – Omit the menu button from the toolbar. - - `WFLAGS_NO_DELETE_BUTTON` – Omit the delete button from the toolbar. - - `WFLAGS_NO_RESIZE_BUTTON` – Omit the resize button from the toolbar. - - `WFLAGS_NO_MINIMIZE_BUTTON` – Omit the minimize button from the toolbar. - - `WFLAGS_NO_TOOLBAR` – Omit the toolbar altogether. - - `WFLAGS_ICONMGR` – This window is an icon manager. - - `WFLAGS_MENU` – This window is a menu window. - - `WFLAGS_HIDDEN` – Start with the window hidden. - -Once the `CWindow` is instantiated, events needed by the application can be -configured as is done in the NxTerm application: - -```cpp -struct SAppEvents events; -events.eventObj = (FAR void *)this; -events.redrawEvent = EVENT_NXTERM_REDRAW; -events.resizeEvent = EVENT_NXTERM_RESIZE; -events.mouseEvent = EVENT_NXTERM_XYINPUT; -events.kbdEvent = EVENT_NXTERM_KBDINPUT; -events.closeEvent = EVENT_NXTERM_CLOSE; -events.deleteEvent = EVENT_NXTERM_DELETE; - -bool success = m_nxtermWindow->configureEvents(events); -``` - -Again, recall that the application inherits from `CTwm4NxEvent`. So passing -`this` as the event object above assures that the specific events are routed to -the application instance. - -Drawing in the application window can be performed using that facilities of -NXWidgets using the `NXWidgets::CGraphicsPort` associated with the window. The -NxTerm application does not perform any drawing, however; that drawing is -performed by the NxTerm driver. - -The `NXWidgets::CGraphicsPort` can be obtained from a `CWindow` instance, say -`m_window`, like: - -```cpp -FAR NXWidgets::CWidgetControl *control = m_window->getWidgetControl(); -NXWidgets::CGraphicsPort *port = control->getGraphicsPort(); -``` - -That `CGraphicsPort` is then passed to the widget constructor, binding the -widget to that window and forcing all widget drawing to occur within the window. - -Obviously, a lot more could be written about drawing, much more than can be -addressed in this README file. diff --git a/import/Make.defs b/import/Make.defs index ac3e999e2..050a5d3e1 100644 --- a/import/Make.defs +++ b/import/Make.defs @@ -95,5 +95,5 @@ endif ifeq ($(CONFIG_BINFMT_ELF_RELOCATABLE),y) LDELFFLAGS += -r endif -LDELFFLAGS += -e _start -Bstatic +LDELFFLAGS += -e __start -Bstatic LDELFFLAGS += $(addprefix -T,$(call CONVERT_PATH,$(TOPDIR)/scripts/gnu-elf.ld)) diff --git a/include/audioutils/nxaudio.h b/include/audioutils/nxaudio.h index 0d0acb133..519fb2cf4 100644 --- a/include/audioutils/nxaudio.h +++ b/include/audioutils/nxaudio.h @@ -63,6 +63,9 @@ extern "C" int init_nxaudio(FAR struct nxaudio_s *nxaudio, int fs, int bps, int chnum); +int init_nxaudio_devname(FAR struct nxaudio_s *nxaudio, + int fs, int bps, int chnum, + const char *devname, const char *mqname); void fin_nxaudio(FAR struct nxaudio_s *nxaudio); int nxaudio_enqbuffer(FAR struct nxaudio_s *nxaudio, FAR struct ap_buffer_s *apb); diff --git a/include/crypto/controlse/ccertificate.hxx b/include/crypto/controlse/ccertificate.hxx new file mode 100644 index 000000000..72bc45ac7 --- /dev/null +++ b/include/crypto/controlse/ccertificate.hxx @@ -0,0 +1,122 @@ +//*************************************************************************** +// apps/include/crypto/controlse/ccertificate.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//*************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element_object.hxx" +#include + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +namespace Controlse +{ +class ISecureElement; +class CPublicKey; +class CSerialNumber; + +class CCertificate : public ISecureElementObject +{ +public: + CCertificate(const ISecureElement &se, uint32_t keystore_id); + CCertificate(const uint8_t *crt_der_or_pem, size_t crt_size); + CCertificate(const ISecureElement &se, const uint8_t *csr_der_or_pem, + size_t csr_size, uint32_t keystore_id); + + // from_datetime and to_datetime need to have format: YYYYMMDDHHMMSSZ + CCertificate(const ISecureElement &se, const uint8_t *csr_der_or_pem, + size_t csr_size, uint32_t keystore_id, + const char *from_datetime, const char *to_datetime); + CCertificate(const CCertificate &) = delete; + CCertificate(CCertificate &&) = default; + ~CCertificate(); + + CCertificate &operator=(const CCertificate &other) = delete; + + bool IsLoaded() const; + bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const; + bool LoadFromSecureElement(const ISecureElement &se, uint32_t keystore_id); + bool LoadFromDerOrPem(const uint8_t *crt_der_or_pem, size_t crt_size); + bool LoadFromCsrDerOrPem(const ISecureElement &se, + const uint8_t *csr_der_or_pem, size_t csr_size, + uint32_t keystore_id, const char *from_datetime, + const char *to_datetime); + + bool VerifyAgainst(const ISecureElement &se, + uint32_t verify_against_id) const; + + // Test time range is valid + // returns 0 if valid + // -1 when expired + // 1 when not yet valid + int TestValidTimerange(time_t now) const; + + // Get public key from certificate + // returns pointer to public key when successful otherwise NULL + // note: must be deleted by caller when not NULL + CPublicKey *GetPublicKey() const; + + // Get oid from certificate if available + // oid must be one of MBEDTLS_OID_AT* from mbedtls/oid.h + // + // returns zero terminated text string when successful otherwise NULL + // note: must be deleted by caller when not NULL + char *GetOid(const char *oid) const; + + // Get serial number from from certificate + // returns pointer to CSerialNumber when successful otherwise NULL + // note: must be deleted by caller when not NULL + CSerialNumber *GetSerialNumber() const; + + size_t GetNumberOfSubjectAlternativeNames() const; + + // Get SAN from from certificate + // returns pointer to array when successful otherwise NULL + // note: must be deleted by caller when not NULL + char *GetSubjectAlternativeName(int item) const; + + // Get certificate in DER format + // returns size of the der array otherwise 0 + // note: der must be deleted by caller when not NULL + size_t GetDer(uint8_t **der) const; + + // Get certificate in PEM format + // returns pointer to pem string when successful otherwise NULL + // note: must be deleted by caller when not NULL + char *GetPem() const; + + bool ContainsSan(const char *name, size_t size) const; + + static constexpr char TAG_ID_SIZE = 18; + +private: + bool is_loaded = false; + + mbedtls_x509_crt crt; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/ccsr.hxx b/include/crypto/controlse/ccsr.hxx new file mode 100644 index 000000000..672866050 --- /dev/null +++ b/include/crypto/controlse/ccsr.hxx @@ -0,0 +1,92 @@ +//*************************************************************************** +// apps/include/crypto/controlse/ccsr.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element_object.hxx" +#include "mbedtls/x509_csr.h" + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CCsr : public ISecureElementObject +{ +public: + class CsrBuilder; + class CsrBuilder + { + public: + CsrBuilder(ISecureElement &se, const char *subject, uint32_t key_slot_id); + CsrBuilder(const CsrBuilder &) = delete; + CsrBuilder(CsrBuilder &&) = default; + + CsrBuilder &operator=(const CsrBuilder &other) = delete; + + CsrBuilder *AddExtension(const char *oid, size_t oid_size, + const uint8_t *value, size_t value_size); + + // result: pointer to dynamically allocated Csr (to be deleted) or nullptr + // if error + CCsr *Build(); + + private: + mbedtls_x509write_csr csr_w; + mbedtls_pk_context key; + bool ready; + }; + + CCsr(const ISecureElement &se, uint32_t keystore_id); + CCsr(const uint8_t *der_or_pem, size_t size); + CCsr(const CCsr &) = delete; + CCsr(CCsr &&) = default; + ~CCsr(); + + CCsr &operator=(const CCsr &other) = delete; + + bool IsLoaded() const; + bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const; + bool LoadFromSecureElement(const ISecureElement &se, uint32_t keystore_id); + + // Get CSR in DER format + // returns size of the der array otherwise 0 + // note: der must be deleted by caller when not NULL + size_t GetDer(uint8_t **der) const; + + // Get certificate in PEM format + // returns pointer to pem string when successful otherwise NULL + // note: must be deleted by caller when not NULL + char *GetPem() const; + +private: + mbedtls_x509_csr csr; + bool is_loaded = false; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/chex_util.hxx b/include/crypto/controlse/chex_util.hxx new file mode 100644 index 000000000..446518148 --- /dev/null +++ b/include/crypto/controlse/chex_util.hxx @@ -0,0 +1,62 @@ +//*************************************************************************** +// apps/include/crypto/controlse/chex_util.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CHexUtil +{ +public: + static size_t GetByteArraySizeFromHexString(const char *hex_buffer); + static size_t GetByteArraySizeFromHexStringSize(size_t hex_buffer_size); + static size_t GetHexStringSizeFromByteArraySize(size_t byte_array_size); + + // result contains allocated pointer to byte array (delete[] afterwards) if + // successfull otherwise nullptr + static uint8_t *ConvertHexStringToByteArray(const char *hex_buffer); + + // result contains allocated pointer to byte array (delete[] afterwards) if + // successfull otherwise nullptr + static uint8_t *ConvertHexStringToByteArray(const char *hex_buffer, + size_t hex_buffer_size); + + // result contains allocated pointer to hex string (delete[] afterwards) if + // successfull otherwise nullptr + static char *ByteArrayToHexString(const uint8_t bytearray[], size_t size); + +private: + static constexpr size_t AMOUNT_OF_HEXDIGITS_PER_BYTE = 2; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/cpublic_key.hxx b/include/crypto/controlse/cpublic_key.hxx new file mode 100644 index 000000000..eed61ca15 --- /dev/null +++ b/include/crypto/controlse/cpublic_key.hxx @@ -0,0 +1,82 @@ +//*************************************************************************** +// apps/include/crypto/controlse/cpublic_key.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element_object.hxx" +#include + +struct mbedtls_x509_crt; + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class ISecureElement; + +class CPublicKey : public ISecureElementObject +{ +public: + CPublicKey(const ISecureElement &se, uint32_t keystore_id); + CPublicKey(const uint8_t *buffer, size_t buffer_size); + CPublicKey(const char *pem); + CPublicKey(const CPublicKey &p1); + ~CPublicKey(); + + CPublicKey &operator=(const CPublicKey &other); + + bool IsLoaded() const; + bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const; + bool LoadFromSecureElement(const ISecureElement &se, uint32_t keystore_id); + bool operator==(const CPublicKey &a) const; + bool operator!=(const CPublicKey &a) const; + + size_t GetRawSize() const; + void GetRaw(uint8_t *raw_buffer) const; + + // Get public key in PEM format + // returns pointer to pem string when successful otherwise NULL + // note: must be deleted by caller when not NULL + char *GetPem() const; + +private: + void Unload(); + static int convert_public_key_raw_to_pem(char *pem_buf, size_t pem_buf_size, + const uint8_t *key_buf, + size_t key_buf_size); + static int convert_public_key_pem_to_raw(uint8_t *key_buf, + size_t key_buf_size, + size_t *key_size, + const char *pem_buf); + + uint8_t *m_key = nullptr; + size_t m_size = 0; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/csan_builder.hxx b/include/crypto/controlse/csan_builder.hxx new file mode 100644 index 000000000..c992e94c0 --- /dev/null +++ b/include/crypto/controlse/csan_builder.hxx @@ -0,0 +1,69 @@ +//*************************************************************************** +// apps/include/crypto/controlse/csan_builder.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CSanBuilder; +class CSanBuilder +{ +public: + CSanBuilder() = default; + CSanBuilder(const CSanBuilder &) = delete; + CSanBuilder(CSanBuilder &&) = default; + ~CSanBuilder(); + + CSanBuilder &operator=(const CSanBuilder &other) = delete; + + CSanBuilder *AddSan(uint8_t type, const char *value, size_t value_size); + + // result: pointer to dynamically allocated san (to be deleted with delete[]) + // or error when size == 0 + size_t Build(uint8_t **san); + + uint32_t GetNumberOfSan(); + +private: + struct List + { + char *p; + size_t size; + uint8_t type; + List *next; + }; + size_t total_size = 0; + List *entry = nullptr; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/csecure_element.hxx b/include/crypto/controlse/csecure_element.hxx new file mode 100644 index 000000000..ac79bad10 --- /dev/null +++ b/include/crypto/controlse/csecure_element.hxx @@ -0,0 +1,73 @@ +//*************************************************************************** +// apps/include/crypto/controlse/csecure_element.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element.hxx" + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CCertificate; +class CertificateCatalog; +class CPublicKey; + +class CSecureElement : public ISecureElement +{ +public: + explicit CSecureElement(const char *se05x_device); + explicit CSecureElement(int fd); + CSecureElement(const CSecureElement &) = delete; + CSecureElement(CSecureElement &&) = default; + ~CSecureElement(); + + CSecureElement &operator=(const CSecureElement &other) = delete; + + bool IsReady() const; + bool GenerateKey(struct se05x_generate_keypair_s &args) const; + bool SetKey(struct se05x_key_transmission_s &args) const; + bool GetKey(struct se05x_key_transmission_s &args) const; + bool DeleteKey(uint32_t id) const; + bool SetData(struct se05x_key_transmission_s &args) const; + bool GetData(struct se05x_key_transmission_s &args) const; + bool CreateSignature(struct se05x_signature_s &args) const; + bool Verify(struct se05x_signature_s &args) const; + bool DeriveSymmetricalKey(struct se05x_derive_key_s &args) const; + bool GetUid(struct se05x_uid_s &args) const; + bool GetInfo(struct se05x_info_s &args) const; + + CCertificate *GetCertificate(uint32_t keystore_id); + CPublicKey *GetPublicKey(uint32_t keystore_id); + +private: + const int se05x_fd; + const bool close_device_at_destructor; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/cserial_number.hxx b/include/crypto/controlse/cserial_number.hxx new file mode 100644 index 000000000..d8dde8df8 --- /dev/null +++ b/include/crypto/controlse/cserial_number.hxx @@ -0,0 +1,62 @@ +//*************************************************************************** +// apps/include/crypto/controlse/cserial_number.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element_object.hxx" +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CSerialNumber : ISecureElementObject +{ +public: + static constexpr size_t SERIAL_NUMBER_SIZE = 20; + CSerialNumber(const ISecureElement &se, uint32_t keystore_id); + CSerialNumber(uint8_t const *serial_number_byte_array); + + bool operator==(CSerialNumber &a) const; + bool operator!=(CSerialNumber &a) const; + bool operator<(const CSerialNumber &a) const; + + bool IsLoaded() const; + bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const; + bool LoadFromSecureElement(const ISecureElement &se, uint32_t keystore_id); + + bool + GetSerialNumber(uint8_t serial_number_destination[SERIAL_NUMBER_SIZE]) const; + +private: + bool is_loaded = false; + uint8_t serial_number[SERIAL_NUMBER_SIZE]; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/cstring.hxx b/include/crypto/controlse/cstring.hxx new file mode 100644 index 000000000..4e744f9d4 --- /dev/null +++ b/include/crypto/controlse/cstring.hxx @@ -0,0 +1,64 @@ +//*************************************************************************** +// apps/include/crypto/controlse/cstring.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include "crypto/controlse/isecure_element_object.hxx" +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class CString : public ISecureElementObject +{ +public: + CString(const ISecureElement &se, uint32_t keystore_id); + CString(char *string, size_t size); + CString(const CString &p1); + ~CString(); + + CString &operator=(const CString &other); + bool operator==(CString &a) const; + bool operator!=(CString &a) const; + + // return value is string otherwise nullptr + // NOTE: need to delete[] return value + char *c_str(void) const; + + bool IsLoaded() const; + bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const; + bool LoadFromSecureElement(const ISecureElement &se, uint32_t keystore_id); + +private: + size_t m_size = 0; + char *m_string = nullptr; +}; +} // namespace Controlse diff --git a/include/crypto/controlse/isecure_element.hxx b/include/crypto/controlse/isecure_element.hxx new file mode 100644 index 000000000..ad559f96e --- /dev/null +++ b/include/crypto/controlse/isecure_element.hxx @@ -0,0 +1,71 @@ +//*************************************************************************** +// apps/include/crypto/controlse/isecure_element.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#pragma once + +#include "crypto/controlse/isecure_element_object.hxx" +#include +#include + +struct se05x_key_transmission_s; +struct se05x_signature_s; +struct se05x_uid_s; +struct se05x_info_s; +struct se05x_generate_keypair_s; +struct se05x_derive_key_s; + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class ISecureElement +{ +public: + virtual ~ISecureElement() = default; + + virtual bool IsReady() const = 0; + virtual bool GenerateKey(struct se05x_generate_keypair_s &args) const = 0; + virtual bool SetKey(struct se05x_key_transmission_s &args) const = 0; + virtual bool GetKey(struct se05x_key_transmission_s &args) const = 0; + virtual bool DeleteKey(uint32_t id) const = 0; + virtual bool SetData(struct se05x_key_transmission_s &args) const = 0; + virtual bool GetData(struct se05x_key_transmission_s &args) const = 0; + virtual bool CreateSignature(struct se05x_signature_s &args) const = 0; + virtual bool Verify(struct se05x_signature_s &args) const = 0; + virtual bool DeriveSymmetricalKey(struct se05x_derive_key_s &args) const = 0; + virtual bool GetUid(struct se05x_uid_s &args) const = 0; + virtual bool GetInfo(struct se05x_info_s &args) const = 0; + + virtual bool Set(uint32_t keystore_id, + const ISecureElementObject &object) const + { + return object.StoreOnSecureElement(*this, keystore_id); + } +}; +} // namespace Controlse diff --git a/include/crypto/controlse/isecure_element_object.hxx b/include/crypto/controlse/isecure_element_object.hxx new file mode 100644 index 000000000..ecff59015 --- /dev/null +++ b/include/crypto/controlse/isecure_element_object.hxx @@ -0,0 +1,51 @@ +//*************************************************************************** +// apps/include/crypto/controlse/isecure_element_object.hxx +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. The +// ASF licenses this file to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance with the +// License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations +// under the License. +// +//************************************************************************** + +// Copyright 2024 NXP + +#pragma once + +//*************************************************************************** +// Included Files +//*************************************************************************** + +#include + +namespace Controlse +{ + +//*************************************************************************** +// Class definitions +//*************************************************************************** + +class ISecureElement; + +class ISecureElementObject +{ +public: + virtual ~ISecureElementObject() = default; + virtual bool IsLoaded() const = 0; + virtual bool StoreOnSecureElement(const ISecureElement &se, + uint32_t keystore_id) const = 0; + virtual bool LoadFromSecureElement(const ISecureElement &se, + uint32_t keystore_id) + = 0; +}; +} // namespace Controlse diff --git a/include/fsutils/passwd.h b/include/fsutils/passwd.h index b8eac9fb4..2b8234301 100644 --- a/include/fsutils/passwd.h +++ b/include/fsutils/passwd.h @@ -59,7 +59,7 @@ * ****************************************************************************/ -#if defined(CONFIG_FSUTILS_PASSWD_READONLY) +#if !defined(CONFIG_FSUTILS_PASSWD_READONLY) int passwd_adduser(FAR const char *username, FAR const char *password); /**************************************************************************** diff --git a/system/uorb/sensor/gas.c b/include/industry/foc/fixed16/foc_feedforward.h similarity index 74% rename from system/uorb/sensor/gas.c rename to include/industry/foc/fixed16/foc_feedforward.h index 72fd0e51c..742537a18 100644 --- a/system/uorb/sensor/gas.c +++ b/include/industry/foc/fixed16/foc_feedforward.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/system/uorb/sensor/gas.c + * apps/include/industry/foc/fixed16/foc_feedforward.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -18,23 +18,28 @@ * ****************************************************************************/ +#ifndef __INDUSTRY_FOC_FIXED16_FOC_FEEDFORWARD_H +#define __INDUSTRY_FOC_FIXED16_FOC_FEEDFORWARD_H + /**************************************************************************** * Included Files ****************************************************************************/ -#include +#include + +#include /**************************************************************************** - * Private Functions + * Public Type Definition ****************************************************************************/ -#ifdef CONFIG_DEBUG_UORB -static const char sensor_gas_format[] = - "timestamp:%" PRIu64 ",gas_resistance:%hf"; -#endif - /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_gas, struct sensor_gas, sensor_gas_format); +int foc_feedforward_pmsm_b16(FAR struct motor_phy_params_b16_s *phy, + FAR dq_frame_b16_t *idq, + b16_t vel_now, + FAR dq_frame_b16_t *vdq_comp); + +#endif /* __INDUSTRY_FOC_FIXED16_FOC_FEEDFORWARD_H */ diff --git a/include/industry/foc/fixed16/foc_handler.h b/include/industry/foc/fixed16/foc_handler.h index 793aeafa8..8e1601f41 100644 --- a/include/industry/foc/fixed16/foc_handler.h +++ b/include/industry/foc/fixed16/foc_handler.h @@ -104,6 +104,11 @@ struct foc_modulation_ops_b16_s CODE void (*run)(FAR foc_handler_b16_t *h, FAR ab_frame_b16_t *v_ab_mod, FAR b16_t *duty); + + /* Get modulation state */ + + CODE void (*state_get)(FAR foc_handler_b16_t *h, + FAR void *state); }; /* Current/voltage controller operations */ @@ -235,7 +240,8 @@ void foc_handler_cfg_b16(FAR foc_handler_b16_t *h, ****************************************************************************/ void foc_handler_state_b16(FAR foc_handler_b16_t *h, - FAR struct foc_state_b16_s *state); + FAR struct foc_state_b16_s *state, + FAR void *mod_state); #ifdef CONFIG_INDUSTRY_FOC_HANDLER_PRINT /**************************************************************************** diff --git a/examples/sotest/modprint/modprint.c b/include/industry/foc/float/foc_feedforward.h similarity index 75% rename from examples/sotest/modprint/modprint.c rename to include/industry/foc/float/foc_feedforward.h index 3bcfbae22..6be81336c 100644 --- a/examples/sotest/modprint/modprint.c +++ b/include/industry/foc/float/foc_feedforward.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/examples/sotest/modprint/modprint.c + * apps/include/industry/foc/float/foc_feedforward.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -18,35 +18,28 @@ * ****************************************************************************/ +#ifndef __INDUSTRY_FOC_FLOAT_FOC_FEEDFORWARD_H +#define __INDUSTRY_FOC_FLOAT_FOC_FEEDFORWARD_H + /**************************************************************************** * Included Files ****************************************************************************/ #include -#include -#include -#include -#include - -#include -#include +#include /**************************************************************************** - * Private Functions + * Public Type Definition ****************************************************************************/ /**************************************************************************** - * Name: modprint + * Public Data ****************************************************************************/ -__attribute__((visibility("default"))) -void modprint(FAR const char *fmt, ...) -{ - va_list ap; - - va_start(ap, fmt); - vsyslog(LOG_INFO, fmt, ap); - va_end(ap); -} +int foc_feedforward_pmsm_f32(FAR struct motor_phy_params_f32_s *phy, + FAR dq_frame_f32_t *idq, + float vel_now, + FAR dq_frame_f32_t *vdq_comp); +#endif /* __INDUSTRY_FOC_FLOAT_FOC_FEEDFORWARD_H */ diff --git a/include/industry/foc/float/foc_handler.h b/include/industry/foc/float/foc_handler.h index ada230692..662491be0 100644 --- a/include/industry/foc/float/foc_handler.h +++ b/include/industry/foc/float/foc_handler.h @@ -104,6 +104,11 @@ struct foc_modulation_ops_f32_s CODE void (*run)(FAR foc_handler_f32_t *h, FAR ab_frame_f32_t *v_ab_mod, FAR float *duty); + + /* Get modulation state */ + + CODE void (*state_get)(FAR foc_handler_f32_t *h, + FAR void *state); }; /* Current/voltage controller operations */ @@ -236,7 +241,8 @@ void foc_handler_cfg_f32(FAR foc_handler_f32_t *h, ****************************************************************************/ void foc_handler_state_f32(FAR foc_handler_f32_t *h, - FAR struct foc_state_f32_s *state); + FAR struct foc_state_f32_s *state, + FAR void *mod_state); #ifdef CONFIG_INDUSTRY_FOC_HANDLER_PRINT /**************************************************************************** diff --git a/include/industry/foc/foc_common.h b/include/industry/foc/foc_common.h index fa50f5dab..4530647ca 100644 --- a/include/industry/foc/foc_common.h +++ b/include/industry/foc/foc_common.h @@ -80,6 +80,15 @@ enum foc_angle_type_e FOC_ANGLE_TYPE_MECH = 2, /* Mechanical angle */ }; +/* Open-loop stage */ + +enum foc_openloop_stage_e +{ + FOC_OPENLOOP_ENABLED = 1, /* Open-loop enabled */ + FOC_OPENLOOP_TRANSITION = 2, /* Open-loop to closed-loop transition */ + FOC_OPENLOOP_DISABLED = 3, /* Open-loop disabled */ +}; + /**************************************************************************** * Public Function Prototypes ****************************************************************************/ diff --git a/include/industry/foc/foc_log.h b/include/industry/foc/foc_log.h index 0634d4924..bc8b1c43f 100644 --- a/include/industry/foc/foc_log.h +++ b/include/industry/foc/foc_log.h @@ -35,8 +35,22 @@ * Pre-processor Definitions ****************************************************************************/ -#define FOCLIBLOG(format, ...) printf(format, ##__VA_ARGS__) -#define FOCLIBERR(format, ...) printf(format, ##__VA_ARGS__) -#define FOCLIBWARN(format, ...) printf(format, ##__VA_ARGS__) +#ifdef CONFIG_INDUSTRY_FOC_DEBUG +# define FOCLIBLOG(format, ...) printf(format, ##__VA_ARGS__) +#else +# define FOCLIBLOG(format, ...) +#endif + +#ifdef CONFIG_INDUSTRY_FOC_ERROR +# define FOCLIBERR(format, ...) printf(format, ##__VA_ARGS__) +#else +# define FOCLIBERR(format, ...) +#endif + +#ifdef CONFIG_INDUSTRY_FOC_WARN +# define FOCLIBWARN(format, ...) printf(format, ##__VA_ARGS__) +#else +# define FOCLIBWARN(format, ...) +#endif #endif /* __APPS_INCLUDE_INDUSTRY_FOC_FOC_LOG_H */ diff --git a/include/interpreters/minibasic.h b/include/interpreters/minibasic.h index 083911c14..1520f30d6 100644 --- a/include/interpreters/minibasic.h +++ b/include/interpreters/minibasic.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/interpreters/minibasic/basic.c + * apps/include/interpreters/minibasic.h * * Copyright (C) 2016 Gregory Nutt. All rights reserved. * diff --git a/include/logging/nxscope/nxscope_intf.h b/include/logging/nxscope/nxscope_intf.h index 0a4aa412a..61f7e7099 100644 --- a/include/logging/nxscope/nxscope_intf.h +++ b/include/logging/nxscope/nxscope_intf.h @@ -85,7 +85,7 @@ struct nxscope_ser_cfg_s { FAR char *path; /* Device path */ bool nonblock; /* Nonblocking operation */ - speed_t baud; /* Baud rate */ + speed_t baud; /* Baud rate. Ignored if set to 0 */ }; #endif diff --git a/include/lte/lte_lwm2m.h b/include/lte/lte_lwm2m.h index 4bbc793a5..c9fc564a1 100644 --- a/include/lte/lte_lwm2m.h +++ b/include/lte/lte_lwm2m.h @@ -250,7 +250,8 @@ typedef CODE void (*lwm2mstub_ovstart_cb_t)(int seq_no, int srv_id, typedef CODE void (*lwm2mstub_ovstop_cb_t)(int seq_no, int srv_id, FAR struct lwm2mstub_instance_s *inst, FAR char *token); -typedef CODE void (*lwm2mstub_operation_cb_t)(int event); +typedef CODE void (*lwm2mstub_operation_cb_t)(int event, int srv_id, + FAR struct lwm2mstub_instance_s *inst); typedef CODE void (*lwm2mstub_fwupstate_cb_t)(int event); diff --git a/include/modbus/mbport.h b/include/modbus/mbport.h index ab4a374f9..eabf23072 100644 --- a/include/modbus/mbport.h +++ b/include/modbus/mbport.h @@ -126,7 +126,7 @@ bool xMBPortEventGet(eMBEventType *eEvent); bool xMBMasterPortEventInit(void); bool xMBMasterPortEventPost(eMBMasterEventType eEvent); -bool xMBMasterPortEventGet(eMBMasterEventType * eEvent); +bool xMBMasterPortEventGet(eMBMasterEventType *eEvent); void vMBMasterOsResInit(void); bool xMBMasterRunResTake(int32_t time); void vMBMasterRunResRelease(void); @@ -138,7 +138,7 @@ bool xMBPortSerialInit(uint8_t ucPort, speed_t ulBaudRate, void vMBPortClose(void); void xMBPortSerialClose(void); void vMBPortSerialEnable(bool xRxEnable, bool xTxEnable); -bool xMBPortSerialGetByte(int8_t * pucByte); +bool xMBPortSerialGetByte(int8_t *pucByte); bool xMBPortSerialPutByte(int8_t ucByte); bool xMBMasterPortSerialInit(uint8_t ucPort, speed_t ulBaudRate, @@ -146,7 +146,7 @@ bool xMBMasterPortSerialInit(uint8_t ucPort, speed_t ulBaudRate, void vMBMasterPortClose(void); void xMBMasterPortSerialClose(void); void vMBMasterPortSerialEnable(bool xRxEnable, bool xTxEnable); -bool xMBMasterPortSerialGetByte(int8_t * pucByte); +bool xMBMasterPortSerialGetByte(int8_t *pucByte); bool xMBMasterPortSerialPutByte(int8_t ucByte); /* Timers functions */ diff --git a/include/nshlib/nshlib.h b/include/nshlib/nshlib.h index 8b642a90e..68ab44810 100644 --- a/include/nshlib/nshlib.h +++ b/include/nshlib/nshlib.h @@ -26,8 +26,8 @@ ****************************************************************************/ #include + #include -#include /**************************************************************************** * Pre-processor Definitions @@ -301,28 +301,6 @@ int nsh_system(int argc, FAR char *argv[]); int nsh_system_ctty(int argc, FAR char *argv[]); -/**************************************************************************** - * Name: nsh_spawn - * - * Description: - * Attempt to execute the application task foreground or background - * - * Returned Value: - * 0 (OK) if the application task corresponding to 'appname' was - * and successfully started. - * If wait enabled, indicates that the - * application returned successful status (EXIT_SUCCESS) - * If wait not enabled, should not be here. - * >0 If wait enabled, PID of the exec'ed module. - * If wait not enabled, indicates the application - * returned status. - * - ****************************************************************************/ - -int nsh_spawn(FAR const char *appname, FAR main_t main, - FAR char * const *argv, int priority, size_t stacksize, - FAR const char *redirfile, int oflags, bool wait); - #undef EXTERN #ifdef __cplusplus } diff --git a/include/system/settings.h b/include/system/settings.h new file mode 100644 index 000000000..e4f7eddb6 --- /dev/null +++ b/include/system/settings.h @@ -0,0 +1,306 @@ +/**************************************************************************** + * apps/include/system/settings.h + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +#ifndef UTILS_SETTINGS_H_ +#define UTILS_SETTINGS_H_ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define VALID 0x600d /* "Magic" number to confirm storage is OK */ + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +enum settings_type_e +{ + SETTING_EMPTY = 0, + SETTING_INT, /* INT32 */ + SETTING_BOOL, + SETTING_FLOAT, + SETTING_STRING, + SETTING_IP_ADDR, +}; + +typedef struct +{ + char key[CONFIG_SYSTEM_SETTINGS_KEY_SIZE]; + enum settings_type_e type; + union + { + int i; + double f; + char s[CONFIG_SYSTEM_SETTINGS_VALUE_SIZE]; + struct in_addr ip; + } val; +} setting_t; + +typedef struct +{ + char file[CONFIG_SYSTEM_SETTINGS_MAX_FILENAME]; + + int (*load_fn)(FAR char *file); + int (*save_fn)(FAR char *file); +} storage_t; + +struct notify_s +{ + pid_t pid; + uint8_t signo; +}; + +enum storage_type_e +{ + STORAGE_BINARY = 0, + STORAGE_TEXT, +}; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Name: settings_init + * + * Description: + * Initializes the settings storage. + * + * Input Parameters: none + * + * Returned Value: none + * + ****************************************************************************/ + +void settings_init(void); + +/**************************************************************************** + * Name: settings_setstorage + * + * Description: + * Sets a file to be used as a settings storage. + * Except from the first file, if loading the file causes any changes + * to the settings, then the new map will be dumped to all files + * (effectively it syncs all storages). + * + * Input Parameters: + * file - the filename of the storage to use + * type - the type of the storage (BINARY or TEXT) + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_setstorage(FAR char *file, enum storage_type_e type); + +/**************************************************************************** + * Name: settings_sync + * + * Description: + * Synchronizes the storage. + * + * wait_dump - if cached saves are enabled, this determines whether + * the function will wait until the save is actually + * completed or just schedule a new save + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_sync(bool wait_dump); + +/**************************************************************************** + * Name: settings_notify + * + * Description: + * Registers a task to be notified on any change of the settings. + * Whenever any value is changed, a signal will be sent to all + * registered threads. Signals are NOT sent when new settings are + * created or when the whole storage is cleared. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_notify(void); + +/**************************************************************************** + * Name: settings_hash + * + * Description: + * Gets the hash of the settings storage. + * + * This hash represents the internal state of the settings map. A + * unique number is calculated based on the contents of the whole map. + * + * This hash can be used to check the settings for any alterations, i.e. + * any setting that may had its value changed since last check. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_hash(FAR uint32_t *h); + +/**************************************************************************** + * Name: settings_clear + * + * Description: + * Clears all settings. + * Data in all storages are purged. + * + * Note that if the settings are cleared during the application run-time + * (i.e. not during initialization), every access to the settings storage + * will fail. + * + * All settings must be created again. This can be done either by calling + * Settings_create() again, or by restarting the application. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_clear(void); + +/**************************************************************************** + * Name: settings_create + * + * Description: + * Creates a new setting. + * + * If the setting is found to exist in any of the storages, it will + * be loaded. Else, it will be created and the default value will be + * assigned. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting. + * ... - the default value of the setting. + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_create(FAR char *key, enum settings_type_e type, ...); + +/**************************************************************************** + * Name: settings_type + * + * Description: + * Gets the type of a setting. + * + * Input Parameters: + * key - the key of the setting. + * type = pointer to int for the returned setting type + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_type(FAR char *key, FAR enum settings_type_e *stype); + +/**************************************************************************** + * Name: settings_get + * + * Description: + * Gets the value of a setting. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting + * ... - pointer to store the setting value. + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_get(FAR char *key, FAR enum settings_type_e type, ...); + +/**************************************************************************** + * Name: settings_set + * + * Description: + * Sets the value of a setting. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting + * ... - the new value of the setting. + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_set(FAR char *key, FAR enum settings_type_e type, ...); + +/**************************************************************************** + * Name: settings_iterate + * + * Description: + * Gets a copy of a setting at the specified position. It can be used to + * iterate over the settings map, by using successive values of idx. + * + * Input Parameters: + * idx - the iteration index for the setting. + * setting - pointer to return the setting value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_iterate(int idx, FAR setting_t *setting); + +#endif /* UTILS_SETTINGS_H_ */ + diff --git a/include/wasm/.gitignore b/include/wasm/.gitignore new file mode 100644 index 000000000..e27b5465e --- /dev/null +++ b/include/wasm/.gitignore @@ -0,0 +1 @@ +math.h \ No newline at end of file diff --git a/include/wasm/math.h b/include/wasm/math.h deleted file mode 100644 index b7918c3bd..000000000 --- a/include/wasm/math.h +++ /dev/null @@ -1,32 +0,0 @@ -/**************************************************************************** - * apps/include/wasm/math.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __INCLUDE_WASM_MATH_H -#define __INCLUDE_WASM_MATH_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -/* Forwards math.h to nuttx/include/nuttx/lib/math.h */ - -#include - -#endif /* __INCLUDE_WASM_MATH_H */ diff --git a/include/wireless/wapi.h b/include/wireless/wapi.h index 084dbac62..d4cf69036 100644 --- a/include/wireless/wapi.h +++ b/include/wireless/wapi.h @@ -53,7 +53,6 @@ * Included Files ****************************************************************************/ -#include #include #include #include @@ -964,59 +963,6 @@ int wapi_set_pta_prio(int sock, FAR const char *ifname, int wapi_get_pta_prio(int sock, FAR const char *ifname, enum wapi_pta_prio_e *pta_prio); -/**************************************************************************** - * Name: wapi_set_pmksa - * - * Description: - * Set the wlan pmksa. - * - ****************************************************************************/ - -int wapi_set_pmksa(int sock, FAR const char *ifname, - FAR const uint8_t *pmk, int len); - -/**************************************************************************** - * Name: wapi_get_pmksa - * - * Description: - * Get the wlan pmksa. - * - ****************************************************************************/ - -int wapi_get_pmksa(int sock, FAR const char *ifname, - FAR uint8_t *pmk, int len); - -/**************************************************************************** - * Name: wapi_extend_params - * - * Description: - * wapi extension interface for privatization method. - * cmd should be definded in wireless_priv.h before use. - * - ****************************************************************************/ - -int wapi_extend_params(int sock, int cmd, FAR struct iwreq *wrq); - -/**************************************************************************** - * Name: wapi_set_power_save - * - * Description: - * Set power save status of wifi. - * - ****************************************************************************/ - -int wapi_set_power_save(int sock, FAR const char *ifname, bool on); - -/**************************************************************************** - * Name: wapi_get_power_save - * - * Description: - * Get power save status of wifi. - * - ****************************************************************************/ - -int wapi_get_power_save(int sock, FAR const char *ifname, bool *on); - #undef EXTERN #ifdef __cplusplus } diff --git a/industry/abnt_codi/README.md b/industry/abnt_codi/README.md deleted file mode 100644 index 849e2dc96..000000000 --- a/industry/abnt_codi/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Industry / `abnt_codi` ABNT CODI - -The ABNT CODI is an old energy meter standard used in Brazil. - -This code interprets the end user serial output existent in the energy meter. -That output externalizes its data blinking an LED as a serial protocol at the -baudrate of `110 BPS` and uses `8` octects: - -| Octet | Bits | Description -|:-----:|------:|------------- -| `001` | `0-7` | Number of seconds to the end of current active demand (`LSB`) -| `002` | `0-3` | Number of seconds to the end of current active demand (`MSB`) -| | `4` | Bill indicator. It is inverted at each demand replenishment -| | `5` | Reactive Interval Indicator. Inverted at end react interval -| | `6` | If `1` means the reactive-capacitive is used to calculate `UFER` -| | `7` | If `1` means the reactive-inductive is used to calculate `UFER` -| `003` | `0-3` | Current seasonal segment:
`0001` – tip
`0010` – out of tip
`1000` – reserved -| | `4-5` | Type of charging indicator (flag):
`00` – Blue
`01` – Green
`10` – Irrigators
`11` – Other -| | `6` | Not used -| | `7` | If equal `1` means reactive rate is enabled -| `004` | `0-7` | Number of pulses for active energy of cur dem interv (`LSB`) -| `005` | `0-6` | Number of pulses for active energy of cur dem interv (`MSB`) -| | `7` | Not used -| `006` | `0-7` | Number of pulses for reactive energy of cur dem interv (`LSB`) -| `007` | `0-6` | Number of pulses for reactive energy of cur dem interv (`MSB`) -| | `7` | Not used -| `008` | `0-7` | Inverted bits of _xor_ from previous octects diff --git a/industry/foc/CMakeLists.txt b/industry/foc/CMakeLists.txt index 3d5402dca..e0f1d2592 100644 --- a/industry/foc/CMakeLists.txt +++ b/industry/foc/CMakeLists.txt @@ -23,7 +23,9 @@ if(CONFIG_INDUSTRY_FOC) set(CSRCS foc_utils.c) if(CONFIG_INDUSTRY_FOC_FLOAT) - list(APPEND CSRCS + list( + APPEND + CSRCS float/foc_ramp.c float/foc_handler.c float/foc_angle.c @@ -85,10 +87,16 @@ if(CONFIG_INDUSTRY_FOC) if(CONFIG_INDUSTRY_FOC_VELOCITY_OPLL) list(APPEND CSRCS float/foc_vel_opll.c) endif() + + if(CONFIG_INDUSTRY_FOC_FEEDFORWARD) + list(APPEND CSRCS float/foc_feedforward.c) + endif() endif() if(CONFIG_INDUSTRY_FOC_FIXED16) - list(APPEND CSRCS + list( + APPEND + CSRCS fixed16/foc_ramp.c fixed16/foc_handler.c fixed16/foc_angle.c @@ -150,6 +158,10 @@ if(CONFIG_INDUSTRY_FOC) if(CONFIG_INDUSTRY_FOC_VELOCITY_OPLL) list(APPEND CSRCS fixed16/foc_vel_opll.c) endif() + + if(CONFIG_INDUSTRY_FOC_FEEDFORWARD) + list(APPEND CSRCS fixed16/foc_feedforward.c) + endif() endif() target_sources(apps PRIVATE ${CSRCS}) diff --git a/industry/foc/Kconfig b/industry/foc/Kconfig index 15719f6c9..1bbe71ad0 100644 --- a/industry/foc/Kconfig +++ b/industry/foc/Kconfig @@ -7,14 +7,28 @@ config INDUSTRY_FOC bool "FOC Library" default n select LIBDSP + depends on MOTOR_FOC ---help--- Enable or disable the FOC Library if INDUSTRY_FOC +config INDUSTRY_FOC_DEBUG + bool "Enable FOCLIB debug log" + default n + +config INDUSTRY_FOC_ERROR + bool "Enable FOCLIB error log" + default n + +config INDUSTRY_FOC_WARN + bool "Enable FOCLIB warn log" + default n + config INDUSTRY_FOC_CORDIC bool "Enable CORDIC support" default n + depends on MATH_CORDIC ---help--- Enable support for CORDIC hardware acceleration @@ -116,6 +130,12 @@ config INDUSTRY_FOC_MODULATION_SVM3 ---help--- Enable support for FOC 3-phase space vector modulation +config INDUSTRY_FOC_FEEDFORWARD + bool "FOC current controller feedforward compensation" + default n + ---help--- + Enable support for current controller feed forward compensation + config INDUSTRY_FOC_MODEL_PMSM bool "FOC PMSM model support" select INDUSTRY_FOC_HAVE_MODEL @@ -135,6 +155,12 @@ config INDUSTRY_FOC_ALIGN if INDUSTRY_FOC_ALIGN +config INDUSTRY_FOC_ALIGN_DIR + bool "FOC alignment direction support" + default n + ---help--- + Enable support for sensor direction alignment + config INDUSTRY_FOC_ALIGN_INDEX bool "FOC alignment index search support" default n diff --git a/industry/foc/Makefile b/industry/foc/Makefile index 4923de19c..bdc0efaf8 100644 --- a/industry/foc/Makefile +++ b/industry/foc/Makefile @@ -75,6 +75,9 @@ endif ifeq ($(CONFIG_INDUSTRY_FOC_VELOCITY_OPLL),y) CSRCS += float/foc_vel_opll.c endif +ifeq ($(CONFIG_INDUSTRY_FOC_FEEDFORWARD),y) +CSRCS += float/foc_feedforward.c +endif endif @@ -129,6 +132,9 @@ endif ifeq ($(CONFIG_INDUSTRY_FOC_VELOCITY_OPLL),y) CSRCS += fixed16/foc_vel_opll.c endif +ifeq ($(CONFIG_INDUSTRY_FOC_FEEDFORWARD),y) +CSRCS += fixed16/foc_feedforward.c +endif endif diff --git a/industry/foc/fixed16/foc_align.c b/industry/foc/fixed16/foc_align.c index 0f0ecbee5..ab8d9b74e 100644 --- a/industry/foc/fixed16/foc_align.c +++ b/industry/foc/fixed16/foc_align.c @@ -75,7 +75,9 @@ enum foc_align_run_stage_e FOC_ALIGN_RUN_INDEX, #endif FOC_ALIGN_RUN_OFFSET, +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR FOC_ALIGN_RUN_DIR, +#endif FOC_ALIGN_RUN_IDLE, FOC_ALIGN_RUN_DONE }; @@ -347,6 +349,7 @@ errout: return ret; } +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR /**************************************************************************** * Name: foc_align_dir_move_b16 ****************************************************************************/ @@ -399,6 +402,8 @@ static void foc_align_dir_move_b16(FAR struct foc_align_b16_s *align, static void foc_align_dir_hold_b16(FAR struct foc_align_b16_s *align, b16_t dir, bool last, bool diff) { + b16_t tmp = 0; + DEBUGASSERT(align); /* Lock angle */ @@ -419,13 +424,16 @@ static void foc_align_dir_hold_b16(FAR struct foc_align_b16_s *align, if (diff == true) { + tmp = align->angle_now - align->angle_last; + angle_norm_2pi_b16(&tmp, -b16PI, b16PI); + if (dir == DIR_CW_B16) { - align->diff_cw += (align->angle_now - align->angle_last); + align->diff_cw += tmp; } else if (dir == DIR_CCW_B16) { - align->diff_ccw += (align->angle_now - align->angle_last); + align->diff_ccw += tmp; } else { @@ -663,6 +671,7 @@ errout: return ret; } +#endif /**************************************************************************** * Name: foc_align_idle_run_b16 @@ -910,6 +919,7 @@ int foc_routine_align_run_b16(FAR foc_routine_b16_t *r, break; } +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR case FOC_ALIGN_RUN_DIR: { /* Align direction procedure */ @@ -930,6 +940,7 @@ int foc_routine_align_run_b16(FAR foc_routine_b16_t *r, break; } +#endif case FOC_ALIGN_RUN_IDLE: { @@ -999,5 +1010,12 @@ int foc_routine_align_final_b16(FAR foc_routine_b16_t *r, FAR void *data) memcpy(data, &a->final, sizeof(struct foc_routine_aling_final_b16_s)); + /* Reset data but leave configuration */ + + memset(&a->final, + 0, + (sizeof(struct foc_align_b16_s) - + sizeof(struct foc_routine_align_cfg_b16_s))); + return OK; } diff --git a/industry/foc/fixed16/foc_ang_onfo.c b/industry/foc/fixed16/foc_ang_onfo.c index 76b54a6a3..af1d7565f 100644 --- a/industry/foc/fixed16/foc_ang_onfo.c +++ b/industry/foc/fixed16/foc_ang_onfo.c @@ -35,16 +35,10 @@ * Pre-processor Definitions ****************************************************************************/ -#define SIGN(x) ((x > 0) ? b16ONE : -b16ONE) - #define LINEAR_MAP(x, in_min, in_max, out_min, out_max) \ (b16divb16(b16mulb16((x - in_min), (out_max - out_min)), \ (in_max - in_min)) + out_min) -#ifndef ABS -# define ABS(a) (a < 0 ? -a : a) -#endif - /**************************************************************************** * Private Data Types ****************************************************************************/ @@ -285,6 +279,15 @@ static int foc_angle_onfo_run_b16(FAR foc_angle_b16_t *h, DEBUGASSERT(h->data); ob = h->data; + if (in->vel == 0) + { + /* Do nothing if motor stopped */ + + out->type = FOC_ANGLE_TYPE_ELE; + out->angle = 0; + return OK; + } + /* Normalize the d-q voltage to get the d-q modulation * voltage */ @@ -294,12 +297,12 @@ static int foc_angle_onfo_run_b16(FAR foc_angle_b16_t *h, /* Update duty cycle now */ - duty_now = b16mulb16(SIGN(in->state->vdq.q), + duty_now = b16mulb16(b16sign(in->state->vdq.q), vector2d_mag_b16(v_dq_mod.d, v_dq_mod.q)); /* Update and the observer gain. */ - dyn_gain = b16mulb16(LINEAR_MAP(ABS(duty_now), + dyn_gain = b16mulb16(LINEAR_MAP(b16abs(duty_now), 0, b16ONE, b16mulb16(ob->cfg.gain, ob->cfg.gain_slow), diff --git a/industry/foc/fixed16/foc_ang_openloop.c b/industry/foc/fixed16/foc_ang_openloop.c index 64f8194b8..8744f2da5 100644 --- a/industry/foc/fixed16/foc_ang_openloop.c +++ b/industry/foc/fixed16/foc_ang_openloop.c @@ -258,9 +258,11 @@ static int foc_angle_ol_run_b16(FAR foc_angle_b16_t *h, DEBUGASSERT(h->data); ol = h->data; - /* Update open-loop */ + /* Update open-loop. + * NOTE: we don't use dir argument here, instead we use signed velocity. + */ - motor_openloop_b16(&ol->data, in->vel, in->dir); + motor_openloop_b16(&ol->data, in->vel, 1); tmp = motor_openloop_angle_get_b16(&ol->data); diff --git a/industry/foc/fixed16/foc_ang_osmo.c b/industry/foc/fixed16/foc_ang_osmo.c index 90acd2a86..d4c6d3152 100644 --- a/industry/foc/fixed16/foc_ang_osmo.c +++ b/industry/foc/fixed16/foc_ang_osmo.c @@ -268,6 +268,15 @@ static int foc_angle_osmo_run_b16(FAR foc_angle_b16_t *h, DEBUGASSERT(h->data); ob = h->data; + if (in->vel == 0) + { + /* Do nothing if motor stopped */ + + out->type = FOC_ANGLE_TYPE_ELE; + out->angle = 0; + return OK; + } + /* Update observer */ motor_aobserver_smo_b16(&ob->o, &in->state->iab, &in->state->vab, diff --git a/industry/foc/fixed16/foc_feedforward.c b/industry/foc/fixed16/foc_feedforward.c new file mode 100644 index 000000000..e45511e52 --- /dev/null +++ b/industry/foc/fixed16/foc_feedforward.c @@ -0,0 +1,68 @@ +/**************************************************************************** + * apps/industry/foc/fixed16/foc_feedforward.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include + +#include "industry/foc/fixed16/foc_feedforward.h" + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: foc_feedforward_pmsm_b16 + * + * Description: + * Feed forward compensation for PMSM (fixed16) + * + * Input Parameter: + * phy - motor physical parameters + * idq - iqd frame + * vel_now - electrical velocity + * vdq_comp - compensation vdq frame + * + ****************************************************************************/ + +int foc_feedforward_pmsm_b16(FAR struct motor_phy_params_b16_s *phy, + FAR dq_frame_b16_t *idq, + b16_t vel_now, + FAR dq_frame_b16_t *vdq_comp) +{ + DEBUGASSERT(phy); + DEBUGASSERT(idq); + DEBUGASSERT(vdq_comp); + + /* NOTE: vdq_comp is substracted from vdq_ref in foc_current_control() + * so vq compensation must be negative here. + */ + + vdq_comp->q = -b16mulb16(vel_now, + (phy->flux_link + b16mulb16(phy->ind, + idq->q))); + vdq_comp->d = b16mulb16(b16mulb16(vel_now, phy->ind), idq->q); + + return OK; +} diff --git a/industry/foc/fixed16/foc_handler.c b/industry/foc/fixed16/foc_handler.c index 976904846..bd338587d 100644 --- a/industry/foc/fixed16/foc_handler.c +++ b/industry/foc/fixed16/foc_handler.c @@ -310,18 +310,25 @@ errout: * Get FOC handler state (fixed16) * * Input Parameter: - * h - pointer to FOC handler - * state - pointer to FOC state data + * h - pointer to FOC handler + * state - pointer to FOC state data + * mod_state - pointer to modulation state data (optional) * ****************************************************************************/ void foc_handler_state_b16(FAR foc_handler_b16_t *h, - FAR struct foc_state_b16_s *state) + FAR struct foc_state_b16_s *state, + FAR void *mod_state) { DEBUGASSERT(h); DEBUGASSERT(state); h->ops.ctrl->state_get(h, state); + + if (mod_state) + { + h->ops.mod->state_get(h, mod_state); + } } #ifdef CONFIG_INDUSTRY_FOC_HANDLER_PRINT diff --git a/industry/foc/fixed16/foc_ramp.c b/industry/foc/fixed16/foc_ramp.c index 237ebd3b8..443f021fe 100644 --- a/industry/foc/fixed16/foc_ramp.c +++ b/industry/foc/fixed16/foc_ramp.c @@ -85,6 +85,8 @@ int foc_ramp_init_b16(FAR struct foc_ramp_b16_s *ramp, b16_t per, int foc_ramp_run_b16(FAR struct foc_ramp_b16_s *ramp, b16_t des, b16_t now, FAR b16_t *set) { + b16_t sign = b16ONE; + DEBUGASSERT(ramp); /* Check if we require soft start/stop operation. @@ -95,14 +97,42 @@ int foc_ramp_run_b16(FAR struct foc_ramp_b16_s *ramp, b16_t des, { ramp->diff = des - *set; - if (ramp->diff >= ramp->ramp_thr) + /* If we change direction then the first vel target is 0 */ + + if (des * (*set) < 0) { + ramp->diff = -now; + des = 0; + } + + if (now >= 0 && ramp->diff >= ramp->ramp_thr) + { + /* Soft start in CW direction */ + + sign = b16ONE; ramp->ramp_mode = RAMP_MODE_SOFTSTART; } - else if (ramp->diff <= -ramp->ramp_thr) + else if (now >= 0 && ramp->diff <= -ramp->ramp_thr) { + /* Soft stop in CW direction */ + + sign = -b16ONE; ramp->ramp_mode = RAMP_MODE_SOFTSTOP; } + else if (now < 0 && ramp->diff >= ramp->ramp_thr) + { + /* Soft stop in CCW direction */ + + sign = b16ONE; + ramp->ramp_mode = RAMP_MODE_SOFTSTOP; + } + else if (now < 0 && ramp->diff <= -ramp->ramp_thr) + { + /* Soft start in CCW direction */ + + sign = -b16ONE; + ramp->ramp_mode = RAMP_MODE_SOFTSTART; + } else { /* Just set new setpoint */ @@ -129,38 +159,18 @@ int foc_ramp_run_b16(FAR struct foc_ramp_b16_s *ramp, b16_t des, case RAMP_MODE_SOFTSTART: { - if (des - *set >= ramp->ramp_thr) - { - /* Increase setpoint with ramp */ + /* Increase setpoint with ramp */ - *set = now + ramp->ramp_acc_per; - } - else - { - /* Set final setpoint and exit soft start */ - - *set = des; - ramp->ramp_mode = RAMP_MODE_NORMAL; - } + *set = now + b16mulb16(sign, ramp->ramp_acc_per); break; } case RAMP_MODE_SOFTSTOP: { - if (des - *set <= -ramp->ramp_thr) - { - /* Stop motor with ramp */ + /* Stop motor with ramp */ - *set = now - ramp->ramp_dec_per; - } - else - { - /* Set final setpoint and exit soft stop */ - - *set = des; - ramp->ramp_mode = RAMP_MODE_NORMAL; - } + *set = now + b16mulb16(sign, ramp->ramp_dec_per); break; } diff --git a/industry/foc/fixed16/foc_svm3.c b/industry/foc/fixed16/foc_svm3.c index 63ec4f7b2..649ea2419 100644 --- a/industry/foc/fixed16/foc_svm3.c +++ b/industry/foc/fixed16/foc_svm3.c @@ -73,6 +73,8 @@ static void foc_modulation_vbase_get_b16(FAR foc_handler_b16_t *h, static void foc_modulation_run_b16(FAR foc_handler_b16_t *h, FAR ab_frame_b16_t *v_ab_mod, FAR b16_t *duty); +static void foc_modulation_state_b16(FAR foc_handler_b16_t *h, + FAR void *v_priv); /**************************************************************************** * Public Data @@ -88,6 +90,7 @@ struct foc_modulation_ops_b16_s g_foc_mod_svm3_b16 = .current = foc_modulation_current_b16, .vbase_get = foc_modulation_vbase_get_b16, .run = foc_modulation_run_b16, + .state_get = foc_modulation_state_b16, }; /**************************************************************************** @@ -243,7 +246,7 @@ static void foc_modulation_current_b16(FAR foc_handler_b16_t *h, } /**************************************************************************** - * Name: foc_modulation_b16 + * Name: foc_modulation_run_b16 * * Description: * Handle the SVM3 modulation (fixed16) @@ -286,3 +289,33 @@ static void foc_modulation_run_b16(FAR foc_handler_b16_t *h, f_saturate_b16(&duty[1], 0, svm->cfg.pwm_duty_max); f_saturate_b16(&duty[2], 0, svm->cfg.pwm_duty_max); } + +/**************************************************************************** + * Name: foc_modulation_state_b16 + * + * Description: + * Get the SVM3 modulation state (fixed16) + * + * Input Parameter: + * h - pointer to FOC handler + * state - pointer to modulation specific data + * + ****************************************************************************/ + +static void foc_modulation_state_b16(FAR foc_handler_b16_t *h, + FAR void *state) +{ + FAR struct foc_svm3mod_b16_s *svm = NULL; + + DEBUGASSERT(h); + DEBUGASSERT(state); + + /* Get modulation data */ + + DEBUGASSERT(h->modulation); + svm = h->modulation; + + /* Copy data */ + + memcpy(state, &svm->state, sizeof(struct svm3_state_b16_s)); +} diff --git a/industry/foc/fixed16/foc_vel_odiv.c b/industry/foc/fixed16/foc_vel_odiv.c index 5df851893..a5460fa1d 100644 --- a/industry/foc/fixed16/foc_vel_odiv.c +++ b/industry/foc/fixed16/foc_vel_odiv.c @@ -214,6 +214,8 @@ static int foc_velocity_div_zero_b16(FAR foc_velocity_b16_t *h) div->cfg.filter, div->cfg.per); + div->o.speed = 0; + return ret; } diff --git a/industry/foc/fixed16/foc_vel_opll.c b/industry/foc/fixed16/foc_vel_opll.c index b16cbee1d..36abdd56a 100644 --- a/industry/foc/fixed16/foc_vel_opll.c +++ b/industry/foc/fixed16/foc_vel_opll.c @@ -212,6 +212,8 @@ static int foc_velocity_pll_zero_b16(FAR foc_velocity_b16_t *h) pll->cfg.kp, pll->cfg.ki); + pll->o.speed = 0; + return ret; } diff --git a/industry/foc/float/foc_align.c b/industry/foc/float/foc_align.c index a7ff85aec..ffd6a7bb5 100644 --- a/industry/foc/float/foc_align.c +++ b/industry/foc/float/foc_align.c @@ -75,8 +75,10 @@ enum foc_align_run_stage_e FOC_ALIGN_RUN_INDEX, #endif FOC_ALIGN_RUN_OFFSET, +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR FOC_ALIGN_RUN_DIR, FOC_ALIGN_RUN_IDLE, +#endif FOC_ALIGN_RUN_DONE }; @@ -347,6 +349,7 @@ errout: return ret; } +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR /**************************************************************************** * Name: foc_align_dir_move_f32 ****************************************************************************/ @@ -399,6 +402,8 @@ static void foc_align_dir_move_f32(FAR struct foc_align_f32_s *align, static void foc_align_dir_hold_f32(FAR struct foc_align_f32_s *align, float dir, bool last, bool diff) { + float tmp = 0.0f; + DEBUGASSERT(align); /* Lock angle */ @@ -419,13 +424,16 @@ static void foc_align_dir_hold_f32(FAR struct foc_align_f32_s *align, if (diff == true) { + tmp = align->angle_now - align->angle_last; + angle_norm_2pi(&tmp, -M_PI_F, M_PI_F); + if (dir == DIR_CW) { - align->diff_cw += (align->angle_now - align->angle_last); + align->diff_cw += tmp; } else if (dir == DIR_CCW) { - align->diff_ccw += (align->angle_now - align->angle_last); + align->diff_ccw += tmp; } else { @@ -709,6 +717,7 @@ static int foc_align_idle_run_f32(FAR struct foc_align_f32_s *align, return ret; } +#endif /**************************************************************************** * Name: foc_routine_align_init_f32 @@ -910,6 +919,7 @@ int foc_routine_align_run_f32(FAR foc_routine_f32_t *r, break; } +#ifdef CONFIG_INDUSTRY_FOC_ALIGN_DIR case FOC_ALIGN_RUN_DIR: { /* Align direction procedure */ @@ -951,6 +961,7 @@ int foc_routine_align_run_f32(FAR foc_routine_f32_t *r, break; } +#endif case FOC_ALIGN_RUN_DONE: { @@ -999,5 +1010,12 @@ int foc_routine_align_final_f32(FAR foc_routine_f32_t *r, FAR void *data) memcpy(data, &a->final, sizeof(struct foc_routine_aling_final_f32_s)); + /* Reset data but leave configuration */ + + memset(&a->final, + 0, + (sizeof(struct foc_align_f32_s) - + sizeof(struct foc_routine_align_cfg_f32_s))); + return OK; } diff --git a/industry/foc/float/foc_ang_onfo.c b/industry/foc/float/foc_ang_onfo.c index 14149de31..665eba832 100644 --- a/industry/foc/float/foc_ang_onfo.c +++ b/industry/foc/float/foc_ang_onfo.c @@ -280,6 +280,15 @@ static int foc_angle_onfo_run_f32(FAR foc_angle_f32_t *h, DEBUGASSERT(h->data); ob = h->data; + if (in->vel == 0.0f) + { + /* Do nothing if motor stopped */ + + out->type = FOC_ANGLE_TYPE_ELE; + out->angle = 0.0f; + return OK; + } + /* Normalize the d-q voltage to get the d-q modulation voltage */ v_dq_mod.d = in->state->vdq.d * in->state->mod_scale; @@ -291,8 +300,8 @@ static int foc_angle_onfo_run_f32(FAR foc_angle_f32_t *h, /* Update and the observer gain. */ - dyn_gain = LINEAR_MAP(fabsf(duty_now), 0.0, 1.0, - ob->cfg.gain * ob->cfg.gain_slow, ob->cfg.gain) * 0.5; + dyn_gain = LINEAR_MAP(fabsf(duty_now), 0.0f, 1.0f, + ob->cfg.gain * ob->cfg.gain_slow, ob->cfg.gain) * 0.5f; /* Update observer */ diff --git a/industry/foc/float/foc_ang_openloop.c b/industry/foc/float/foc_ang_openloop.c index 44122025a..d33f30169 100644 --- a/industry/foc/float/foc_ang_openloop.c +++ b/industry/foc/float/foc_ang_openloop.c @@ -259,9 +259,11 @@ static int foc_angle_ol_run_f32(FAR foc_angle_f32_t *h, DEBUGASSERT(h->data); ol = h->data; - /* Update open-loop */ + /* Update open-loop. + * NOTE: we don't use dir argument here, instead we use signed velocity. + */ - motor_openloop(&ol->data, in->vel, in->dir); + motor_openloop(&ol->data, in->vel, 1.0f); /* Get open-loop angle */ diff --git a/industry/foc/float/foc_ang_osmo.c b/industry/foc/float/foc_ang_osmo.c index ce693f3b7..4d31a399c 100644 --- a/industry/foc/float/foc_ang_osmo.c +++ b/industry/foc/float/foc_ang_osmo.c @@ -268,6 +268,15 @@ static int foc_angle_osmo_run_f32(FAR foc_angle_f32_t *h, DEBUGASSERT(h->data); ob = h->data; + if (in->vel == 0.0f) + { + /* Do nothing if motor stopped */ + + out->type = FOC_ANGLE_TYPE_ELE; + out->angle = 0.0f; + return OK; + } + /* Update observer */ motor_aobserver_smo(&ob->o, &in->state->iab, &in->state->vab, diff --git a/industry/foc/float/foc_feedforward.c b/industry/foc/float/foc_feedforward.c new file mode 100644 index 000000000..d6da4c53b --- /dev/null +++ b/industry/foc/float/foc_feedforward.c @@ -0,0 +1,66 @@ +/**************************************************************************** + * apps/industry/foc/float/foc_feedforward.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include + +#include "industry/foc/float/foc_feedforward.h" + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: foc_feedforward_pmsm_f32 + * + * Description: + * Feed forward compensation for PMSM (float32) + * + * Input Parameter: + * phy - motor physical parameters + * idq - iqd frame + * vel_now - electrical velocity + * vdq_comp - compensation vdq frame + * + ****************************************************************************/ + +int foc_feedforward_pmsm_f32(FAR struct motor_phy_params_f32_s *phy, + FAR dq_frame_f32_t *idq, + float vel_now, + FAR dq_frame_f32_t *vdq_comp) +{ + DEBUGASSERT(phy); + DEBUGASSERT(idq); + DEBUGASSERT(vdq_comp); + + /* NOTE: vdq_comp is substracted from vdq_ref in foc_current_control() + * so vq compensation must be negative here. + */ + + vdq_comp->q = -vel_now * (phy->flux_link + phy->ind * idq->q); + vdq_comp->d = vel_now * phy->ind * idq->q; + + return OK; +} diff --git a/industry/foc/float/foc_handler.c b/industry/foc/float/foc_handler.c index 8d8703ef2..6c3da8330 100644 --- a/industry/foc/float/foc_handler.c +++ b/industry/foc/float/foc_handler.c @@ -310,18 +310,25 @@ errout: * Get FOC handler state (float32) * * Input Parameter: - * h - pointer to FOC handler - * state - pointer to FOC state data + * h - pointer to FOC handler + * state - pointer to FOC state data + * mod_state - pointer to modulation state data (optional) * ****************************************************************************/ void foc_handler_state_f32(FAR foc_handler_f32_t *h, - FAR struct foc_state_f32_s *state) + FAR struct foc_state_f32_s *state, + FAR void *mod_state) { DEBUGASSERT(h); DEBUGASSERT(state); h->ops.ctrl->state_get(h, state); + + if (mod_state) + { + h->ops.mod->state_get(h, mod_state); + } } #ifdef CONFIG_INDUSTRY_FOC_HANDLER_PRINT diff --git a/industry/foc/float/foc_ramp.c b/industry/foc/float/foc_ramp.c index 566ee1144..ead702752 100644 --- a/industry/foc/float/foc_ramp.c +++ b/industry/foc/float/foc_ramp.c @@ -85,6 +85,8 @@ int foc_ramp_init_f32(FAR struct foc_ramp_f32_s *ramp, float per, int foc_ramp_run_f32(FAR struct foc_ramp_f32_s *ramp, float des, float now, FAR float *set) { + float sign = 1.0f; + DEBUGASSERT(ramp); /* Check if we require soft start/stop operation. @@ -95,14 +97,42 @@ int foc_ramp_run_f32(FAR struct foc_ramp_f32_s *ramp, float des, { ramp->diff = des - *set; - if (ramp->diff >= ramp->ramp_thr) + /* If we change direction then the first vel target is 0 */ + + if (des * (*set) < 0.0f) { + ramp->diff = -now; + des = 0.0f; + } + + if (now >= 0.0f && ramp->diff >= ramp->ramp_thr) + { + /* Soft start in CW direction */ + + sign = 1.0f; ramp->ramp_mode = RAMP_MODE_SOFTSTART; } - else if (ramp->diff <= -ramp->ramp_thr) + else if (now >= 0.0f && ramp->diff <= -ramp->ramp_thr) { + /* Soft stop in CW direction */ + + sign = -1.0f; ramp->ramp_mode = RAMP_MODE_SOFTSTOP; } + else if (now < 0.0f && ramp->diff >= ramp->ramp_thr) + { + /* Soft stop in CCW direction */ + + sign = 1.0f; + ramp->ramp_mode = RAMP_MODE_SOFTSTOP; + } + else if (now < 0.0f && ramp->diff <= -ramp->ramp_thr) + { + /* Soft start in CCW direction */ + + sign = -1.0f; + ramp->ramp_mode = RAMP_MODE_SOFTSTART; + } else { /* Just set new setpoint */ @@ -129,38 +159,18 @@ int foc_ramp_run_f32(FAR struct foc_ramp_f32_s *ramp, float des, case RAMP_MODE_SOFTSTART: { - if (des - *set >= ramp->ramp_thr) - { - /* Increase setpoin with ramp */ + /* Increase setpoin with ramp */ - *set = now + ramp->ramp_acc_per; - } - else - { - /* Set final setpoint and exit soft start */ - - *set = des; - ramp->ramp_mode = RAMP_MODE_NORMAL; - } + *set = now + sign * ramp->ramp_acc_per; break; } case RAMP_MODE_SOFTSTOP: { - if (des - *set <= -ramp->ramp_thr) - { - /* Stop motor with ramp */ + /* Stop motor with ramp */ - *set = now - ramp->ramp_dec_per; - } - else - { - /* Set final setpint and exit soft stop */ - - *set = des; - ramp->ramp_mode = RAMP_MODE_NORMAL; - } + *set = now + sign * ramp->ramp_dec_per; break; } diff --git a/industry/foc/float/foc_svm3.c b/industry/foc/float/foc_svm3.c index 36babe7f0..9c812e734 100644 --- a/industry/foc/float/foc_svm3.c +++ b/industry/foc/float/foc_svm3.c @@ -73,6 +73,8 @@ static void foc_modulation_vbase_get_f32(FAR foc_handler_f32_t *h, static void foc_modulation_run_f32(FAR foc_handler_f32_t *h, FAR ab_frame_f32_t *v_ab_mod, FAR float *duty); +static void foc_modulation_state_f32(FAR foc_handler_f32_t *h, + FAR void *v_priv); /**************************************************************************** * Public Data @@ -88,6 +90,7 @@ struct foc_modulation_ops_f32_s g_foc_mod_svm3_f32 = .current = foc_modulation_current_f32, .vbase_get = foc_modulation_vbase_get_f32, .run = foc_modulation_run_f32, + .state_get = foc_modulation_state_f32, }; /**************************************************************************** @@ -243,7 +246,7 @@ static void foc_modulation_current_f32(FAR foc_handler_f32_t *h, } /**************************************************************************** - * Name: foc_modulation_f32 + * Name: foc_modulation_run_f32 * * Description: * Handle the SVM3 modulation (float32) @@ -286,3 +289,33 @@ static void foc_modulation_run_f32(FAR foc_handler_f32_t *h, f_saturate(&duty[1], 0.0f, svm->cfg.pwm_duty_max); f_saturate(&duty[2], 0.0f, svm->cfg.pwm_duty_max); } + +/**************************************************************************** + * Name: foc_modulation_state_f32 + * + * Description: + * Get the SVM3 modulation state (float32) + * + * Input Parameter: + * h - pointer to FOC handler + * state - pointer to modulation specific data + * + ****************************************************************************/ + +static void foc_modulation_state_f32(FAR foc_handler_f32_t *h, + FAR void *state) +{ + FAR struct foc_svm3mod_f32_s *svm = NULL; + + DEBUGASSERT(h); + DEBUGASSERT(state); + + /* Get modulation data */ + + DEBUGASSERT(h->modulation); + svm = h->modulation; + + /* Copy data */ + + memcpy(state, &svm->state, sizeof(struct svm3_state_f32_s)); +} diff --git a/industry/foc/float/foc_vel_odiv.c b/industry/foc/float/foc_vel_odiv.c index 43491b5a5..dfb8d820f 100644 --- a/industry/foc/float/foc_vel_odiv.c +++ b/industry/foc/float/foc_vel_odiv.c @@ -214,6 +214,8 @@ static int foc_velocity_div_zero_f32(FAR foc_velocity_f32_t *h) div->cfg.filter, div->cfg.per); + div->o.speed = 0.0f; + return ret; } diff --git a/industry/foc/float/foc_vel_opll.c b/industry/foc/float/foc_vel_opll.c index 0e554848a..a18b6675c 100644 --- a/industry/foc/float/foc_vel_opll.c +++ b/industry/foc/float/foc_vel_opll.c @@ -212,6 +212,8 @@ static int foc_velocity_pll_zero_f32(FAR foc_velocity_f32_t *h) pll->cfg.kp, pll->cfg.ki); + pll->o.speed = 0.0f; + return ret; } diff --git a/examples/sotest/.gitignore b/inertial/.gitignore similarity index 100% rename from examples/sotest/.gitignore rename to inertial/.gitignore diff --git a/examples/canard/CMakeLists.txt b/inertial/CMakeLists.txt similarity index 89% rename from examples/canard/CMakeLists.txt rename to inertial/CMakeLists.txt index 390b8d8a0..fb213b9ee 100644 --- a/examples/canard/CMakeLists.txt +++ b/inertial/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/examples/canard/CMakeLists.txt +# apps/inertial/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,6 +18,4 @@ # # ############################################################################## -if(CONFIG_EXAMPLES_LIBCANARD) - nuttx_add_application(NAME canard) -endif() +nuttx_generate_kconfig(MENUDESC "Inertial Libraries Support") diff --git a/math/ruy/Make.defs b/inertial/Make.defs similarity index 90% rename from math/ruy/Make.defs rename to inertial/Make.defs index bdba60a48..03113ac85 100644 --- a/math/ruy/Make.defs +++ b/inertial/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/ruy/Make.defs +# apps/inertial/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,4 @@ # ############################################################################ -ifneq ($(CONFIG_MATH_RUY),) -CONFIGURED_APPS += $(APPDIR)/math/ruy -endif +include $(wildcard $(APPDIR)/inertial/*/Make.defs) diff --git a/games/shift/Make.defs b/inertial/Makefile similarity index 89% rename from games/shift/Make.defs rename to inertial/Makefile index 65e059924..e05b10cd2 100644 --- a/games/shift/Make.defs +++ b/inertial/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/games/shift/Make.defs +# apps/inertial/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,6 @@ # ############################################################################ -ifneq ($(CONFIG_GAMES_SHIFT),) -CONFIGURED_APPS += $(APPDIR)/games/shift -endif +MENUDESC = "Inertial Libraries Support" + +include $(APPDIR)/Directory.mk diff --git a/inertial/madgwick/Kconfig b/inertial/madgwick/Kconfig new file mode 100644 index 000000000..98d0e1db0 --- /dev/null +++ b/inertial/madgwick/Kconfig @@ -0,0 +1,21 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config LIB_MADGWICK + bool "Madgwick Fusion Algorithm" + default n + depends on ALLOW_MIT_COMPONENTS + ---help--- + Enable madgwick fusion algorithm. + Madgwick is a quick fusion algorithm use integrate + accelerometer, gyroscope and magnotomer (compass). + +if LIB_MADGWICK + +config LIB_MADGWICK_VER + string "Lib Madgwick version" + default "1.2.1" + +endif # LIB_MADGWICK diff --git a/inertial/madgwick/Make.defs b/inertial/madgwick/Make.defs new file mode 100644 index 000000000..814fb83af --- /dev/null +++ b/inertial/madgwick/Make.defs @@ -0,0 +1,26 @@ +############################################################################ +# apps/inertial/madgwick/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_LIB_MADGWICK),) +CONFIGURED_APPS += $(APPDIR)/inertial/madgwick + +CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/inertial/madgwick/fusion +CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/inertial/madgwick/fusion +endif diff --git a/math/kissfft/Makefile b/inertial/madgwick/Makefile similarity index 64% rename from math/kissfft/Makefile rename to inertial/madgwick/Makefile index 3a3b2e824..936d28219 100644 --- a/math/kissfft/Makefile +++ b/inertial/madgwick/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/kissfft/Makefile +# apps/inertial/madgwick/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,26 +20,28 @@ include $(APPDIR)/Make.defs -CSRCS += kissfft/tools/kiss_fftr.c -CSRCS += kissfft/kiss_fft.c +SRC = fusion/Fusion -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/kissfft/kissfft +CSRCS += $(SRC)/FusionAhrs.c +CSRCS += $(SRC)/FusionCompass.c +CSRCS += $(SRC)/FusionOffset.c -KISSFFT_VER = 130 -KISSFFT_UNPACK = kissfft +CFLAGS += -Wno-shadow -Wno-strict-prototypes -Wno-unknown-pragmas -kissfft.zip: - $(Q) curl -L https://github.com/mborgerding/kissfft/archive/refs/tags/v$(KISSFFT_VER).zip -o kissfft.zip - $(Q) unzip -o kissfft.zip - $(Q) mv kissfft-$(KISSFFT_VER) kissfft - $(Q) patch -d $(KISSFFT_UNPACK) -p1 < kissfft.patch +MODULE = $(CONFIG_LIB_MADGWICK) + +libmadgwick.tar.gz: + $(Q) curl -L https://github.com/xioTechnologies/Fusion/archive/refs/tags/v$(CONFIG_LIB_MADGWICK_VER).tar.gz -o libmadgwick.tar.gz + $(Q) tar xf libmadgwick.tar.gz + $(Q) mv Fusion-$(CONFIG_LIB_MADGWICK_VER) fusion # Download and unpack tarball if no git repo found -ifeq ($(wildcard kissfft/.git),) -context:: kissfft.zip +ifeq ($(wildcard madgwick/fusion),) +context:: libmadgwick.tar.gz + distclean:: - $(call DELDIR, kissfft) - $(call DELFILE, kissfft.zip) + $(call DELDIR, fusion) + $(call DELFILE, libmadgwick.tar.gz) endif include $(APPDIR)/Application.mk diff --git a/interpreters/CMakeLists.txt b/interpreters/CMakeLists.txt index ab62fe9d9..f48cce189 100644 --- a/interpreters/CMakeLists.txt +++ b/interpreters/CMakeLists.txt @@ -19,4 +19,3 @@ # ############################################################################## nuttx_generate_kconfig(MENUDESC "Interpreters") -add_subdirectory(quickjs) diff --git a/interpreters/README.md b/interpreters/README.md deleted file mode 100644 index 0a1d1c66f..000000000 --- a/interpreters/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# Interpreters - -This `apps/` directory is set aside to hold interpreters that may be -incorporated into NuttX. - -## Ficl - -This is DIY port of Ficl (the _Forth Inspired Command Language_). See -http://ficl.sourceforge.net/. It is a _DIY_ port because the Ficl source is not -in that directory, only an environment and instructions that will let you build -Ficl under NuttX. The rest is up to you. - -## Lua - -Fetch and build a Lua interpreter. Versions 5.2 through 5.4 are supported. The -`lua` command will be added to NSH. Lua can run a script for a given path, -execute a string of code, or open a readline compatible REPL on the NSH console. -The `` and `` headers are available to start a new embedded -interpreter or extend Lua with C modules. See the `luamod_hello` example for how -to include a built-in module. - -A math library is required to build. Enable the `LIBM` config or use a -toolchain provided math library. - -The following configs are recommended for a full featured Lua interpreter: -- `LIBC_FLOATINGPOINT` -- `SYSTEM_READLINE` - -## Mini Basic - -The Mini Basic implementation at `apps/interpreters` derives from version `1.0` -by Malcolm McLean, Leeds University, and was released under the Creative Commons -Attibution license. I am not legal expert, but this license appears to be -compatible with the NuttX BSD license see: -https://creativecommons.org/licenses/. I, however, cannot take responsibility -for any actions that you might take based on my understanding. Please use your -own legal judgement. diff --git a/interpreters/bas/Kconfig b/interpreters/bas/Kconfig index 074fa477b..db84d3d07 100644 --- a/interpreters/bas/Kconfig +++ b/interpreters/bas/Kconfig @@ -72,7 +72,7 @@ config INTERPRETER_BAS_HAVE_FTRUNCATE config EXAMPLES_BAS_SHELL bool "Shell support" default n - depends on ARCH_HAVE_VFORK && EXPERIMENTAL + depends on ARCH_HAVE_FORK && EXPERIMENTAL select LIBC_EXECFUNCS select SCHED_WAITPID ---help--- diff --git a/interpreters/bas/README.md b/interpreters/bas/README.md deleted file mode 100644 index be3f431eb..000000000 --- a/interpreters/bas/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# Interpreters / `bas` Bas BASIC - -## Introduction - -Bas is an interpreter for the classic dialect of the programming language BASIC. -It is pretty compatible to typical BASIC interpreters of the 1980s, unlike some -other UNIX BASIC interpreters, that implement a different syntax, breaking -compatibility to existing programs. Bas offers many ANSI BASIC statements for -structured programming, such as procedures, local variables and various loop -types. Further there are matrix operations, automatic LIST indentation and many -statements and functions found in specific classic dialects. Line numbers are -not required. - -The interpreter tokenises the source and resolves references to variables and -jump targets before running the program. This compilation pass increases -efficiency and catches syntax errors, type errors and references to variables -that are never initialised. Bas is written in ANSI C for UNIX systems. - -## License - -BAS 2.4 is released as part of NuttX under the standard 3-clause BSD license use -by all components of NuttX. This is not incompatible with the original BAS 2.4 -licensing - -Copyright (c) 1999-2014 Michael Haardt - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -## Bas 2.4 Release Notes - -Changes compared to version `2.3` - -- Matrix inversion on integer arrays with option base 1 fixed. -- `PRINT USING` behaviour for `!` fixed. -- `PRINT`, separator should advance to the next zone, even if the current - position is at the start of a zone. -- Added `ip()`, `frac()`, `fp()`, `log10()`, `log2()`, `min()` and `max()`. -- Fixed `NEXT` checking the variable case sensitive. -- Use `terminfo` capability cr to make use of its padding. -- `LET` segmentation fault fixed. -- `PRINT` now uses print items. -- `-r` for restricted operation. -- `MAT INPUT` does not drop excess arguments, but uses them for the next row. -- License changed to MIT. diff --git a/interpreters/bas/bas_statement.c b/interpreters/bas/bas_statement.c index 482f94f62..5172bdfb3 100644 --- a/interpreters/bas/bas_statement.c +++ b/interpreters/bas/bas_statement.c @@ -1051,7 +1051,7 @@ struct Value *stmt_DOcondition(struct Value *value) struct Value *stmt_EDIT(struct Value *value) { -#if defined(CONFIG_EXAMPLES_BAS_EDITOR) && defined(CONFIG_EXAMPLES_BAS_SHELL) && defined(CONFIG_ARCH_HAVE_VFORK) +#if defined(CONFIG_EXAMPLES_BAS_EDITOR) && defined(CONFIG_EXAMPLES_BAS_SHELL) && defined(CONFIG_ARCH_HAVE_FORK) long int line; struct Pc statementpc = g_pc; int status; @@ -5674,7 +5674,7 @@ struct Value *stmt_SELECTCASE(struct Value *value) struct Value *stmt_SHELL(struct Value *value) { -#if defined(CONFIG_EXAMPLES_BAS_SHELL) && defined(CONFIG_ARCH_HAVE_VFORK) +#if defined(CONFIG_EXAMPLES_BAS_SHELL) && defined(CONFIG_ARCH_HAVE_FORK) pid_t pid; int status; diff --git a/interpreters/ficl/README.md b/interpreters/ficl/README.md deleted file mode 100644 index 743a1ee63..000000000 --- a/interpreters/ficl/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# Interpreters / `ficl` Ficl - -Ficl is a programming language interpreter designed to be embedded into other -systems as a command, macro, and development prototyping language. Ficl is an -acronym for _Forth Inspired Command Language_. See http://ficl.sourceforge.net/ - -## Build Instructions - -Disclaimer: This installation steps have only been exercised using Ficl 4.1.0. -With new versions you will likely have to make some adjustments to this -instructtions or to the files within this directory. Think of this information -as _recommendations_ - not necessarily proven instructions. - -1. `cd` to `interpreters/ficl` - -2. Download Ficl: http://sourceforge.net/projects/ficl/files/ - -3. Uznip the Ficl compressed file. - - For example, `unzip ficl-4.1.0.zip` will leave the file - `interpreters/ficl/ficl-4.1.0`. - -4. Configure to build Ficl in the `interpreters/ficl` directory using the - `configure.sh` script. - - For example, `./configure.sh ficl-4.1.0` will leave the Makefile fragment - `Make.srcs` in the ficl build directory. - -5. Create your NuttX configuration. Using the `make menuconfig`, you should - select: - - ```conf - CONFIG_INTERPRETERS_FICL=y - ``` - -6. Configure and build NuttX. On successful completion, the Ficl objects will be - available in `apps/libapps.a` and that NuttX binary will be linked against - that file. Of course, Ficl will do nothing unless you have written some - application code that uses it! diff --git a/interpreters/luamodules/luv/README.md b/interpreters/luamodules/luv/README.md deleted file mode 100644 index 6e615925c..000000000 --- a/interpreters/luamodules/luv/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# lua_luv_nuttx -Lua Luv C module for NuttX - -[Luv](https://github.com/luvit/luv) provides bare libuv bindings for Lua. - -This NuttX app builds Luv and registers it as a C module for the [NuttX Lua interpreter](https://github.com/apache/incubator-nuttx-apps/tree/master/interpreters#lua). diff --git a/interpreters/minibasic/script.c b/interpreters/minibasic/script.c index 8d87ad0b8..1710433b6 100644 --- a/interpreters/minibasic/script.c +++ b/interpreters/minibasic/script.c @@ -1,6 +1,5 @@ - /**************************************************************************** - * apps/interpreters/minibasic/sript.c + * apps/interpreters/minibasic/script.c * Driver file for MiniBasic. * * Copyright (C) 2016 Gregory Nutt. All rights reserved. diff --git a/interpreters/quickjs/CMakeLists.txt b/interpreters/quickjs/CMakeLists.txt deleted file mode 100644 index 9d0c9a82e..000000000 --- a/interpreters/quickjs/CMakeLists.txt +++ /dev/null @@ -1,160 +0,0 @@ -if(CONFIG_INTERPRETERS_QUICKJS) - set(CMAKE_C_STANDARD 11) - set(CMAKE_CXX_STANDARD 17) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - include(ExternalProject) - - # add quickjs to global INCLUDE DIR - list(APPEND CFLAGS ${INCDIR_PREFIX}$(APPDIR)/interpreters/quickjs) - list(APPEND CXXFLAGS ${INCDIR_PREFIX}$(APPDIR)/interpreters/quickjs) - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${NUTTX_APPS_DIR}/interpreters/quickjs) - set(QUICKJS_DIR ${CMAKE_CURRENT_LIST_DIR}/quickjs) - set(QUICKJS_VERSION "\"2020-11-08\"") - set(QUICKJS_FLAGS) - set(QUICKJS_INCDIR) - set(QUICKJS_CSRCS) - set(QUICKJS_SRCS) - set(QUICKAPP_DIR ${NUTTX_APPS_DIR}/frameworks/quickapp) - - if(CONFIG_INTERPRETERS_QUICKJS_MINI) - list(APPEND QUICKJS_SRCS qjsmini.c) - endif() - - list( - APPEND - QUICKJS_FLAGS - -Wno-shadow - -Wno-array-bounds - -Wno-incompatible-pointer-types - -Wno-implicit-function-declaration - -Wno-unused-function - -Wno-format - -D__linux__ - -DCONFIG_VERSION=${QUICKJS_VERSION} - -include - alloca.h) - - list(APPEND QUICKJS_INCDIR ${QUICKJS_DIR}) - - list( - APPEND - QUICKJS_CSRCS - ${QUICKJS_DIR}/quickjs.c - ${QUICKJS_DIR}/libregexp.c - ${QUICKJS_DIR}/libbf.c - ${QUICKJS_DIR}/libunicode.c - ${QUICKJS_DIR}/cutils.c) - - if(CONFIG_ARCH_ARM) - list(APPEND QUICKJS_FLAGS -DFE_TONEAREST=0x00000000) - list(APPEND QUICKJS_FLAGS -DFE_UPWARD=0x00400000) - list(APPEND QUICKJS_FLAGS -DFE_DOWNWARD=0x00800000) - list(APPEND QUICKJS_FLAGS -DFE_TOWARDZERO=0x00c00000) - endif() - - if(CONFIG_INTERPRETERS_QUICKJS_BIGNUM) - list(APPEND QUICKJS_FLAGS -DCONFIG_BIGNUM) - list(APPEND QUICKJS_CSRCS ${CMAKE_CURRENT_BINARY_DIR}/qjscalc.c) - endif() - - if(CONFIG_INTERPRETERS_QUICKJS_DEBUG) - list(APPEND QUICKJS_CSRCS ${QUICKJS_DIR}/quickjs-debugger.c - ${QUICKJS_DIR}/quickjs-memorydump.c) - endif() - - if(CONFIG_INTERPRETERS_QUICKJS_CONFIG_TOOL) - list(APPEND QUICKJS_FLAGS -DQUICKJS_CONFIG_TOOL) - endif() - - if(CONFIG_INTERPRETERS_QUICKJS_EXPORT_API) - list(APPEND QUICKJS_FLAGS -DDISABLE_EXPORT_API) - endif() - - if(CONFIG_INTERPRETERS_QUICKJS_FULL) - add_custom_command( - PRE_BUILD - COMMAND ${CMAKE_CURRENT_BINARY_DIR}/qjsc -c -o - ${CMAKE_CURRENT_BINARY_DIR}/repl.c -m ${QUICKJS_DIR}/repl.js - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/repl.c - DEPENDS qjsc) - add_custom_command( - PRE_BUILD - COMMAND ${CMAKE_CURRENT_BINARY_DIR}/qjsc -fbignum -c -o - ${CMAKE_CURRENT_BINARY_DIR}/qjscalc.c ${QUICKJS_DIR}/qjscalc.js - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/qjscalc.c - DEPENDS qjsc) - list(APPEND QUICKJS_SRCS ${QUICKJS_DIR}/qjs.c - ${CMAKE_CURRENT_BINARY_DIR}/repl.c) - list(APPEND QUICKJS_CSRCS ${QUICKJS_DIR}/quickjs-libc.c) - endif() - - nuttx_add_library(libqjs) - target_sources(libqjs PRIVATE ${QUICKJS_CSRCS}) - target_include_directories(libqjs PRIVATE ${QUICKJS_INCDIR}) - target_compile_options(libqjs PRIVATE ${QUICKJS_FLAGS}) - nuttx_export_header(TARGET libqjs INCLUDE_DIRECTORIES ${QUICKJS_DIR}) - - if(NOT CONFIG_INTERPRETERS_QUICKJS_NONE) - set(QJS_PRIORITY ${CONFIG_INTERPRETERS_QUICKJS_PRIORITY}) - set(QJS_STACKSIZE ${CONFIG_INTERPRETERS_QUICKJS_STACKSIZE}) - nuttx_add_application( - NAME - qjs - PRIORITY - ${QJS_PRIORITY} - STACKSIZE - ${QJS_STACKSIZE} - SRCS - ${QUICKJS_SRCS} - INCLUDE_DIRECTORIES - ${QUICKJS_INCDIR} - COMPILE_FLAGS - ${QUICKJS_FLAGS} - DEPENDS - libqjs) - endif() - - if(CONFIG_QUICKAPP_AIOTJSC) - message("build aiotjsc compiler....") - nuttx_add_application( - NAME - aiotjsc - INCLUDE_DIRECTORIES - ${QUICKAPP_COMMON_INCLUDES} - ${QUICKAPP_DIR}/src/jse/quickjs - ${QUICKAPP_DIR}/src/jse - ${QUICKAPP_DIR}/src - SRCS - ${QUICKAPP_DIR}/src/ajs_compile.cpp - ${QUICKAPP_DIR}/src/ajs_log.cpp - ${QUICKAPP_DIR}/src/jse/quickjs/jse_quickjs.cpp - DEFINITIONS - -DDEBUG - -DCONFIG_VERSION=${QUICKJS_VERSION} - -DAIOTJS_USE_QUICKJS - -DCONFIG_BIGNUM=${CONFIG_INTERPRETERS_QUICKJS_BIGNUM} - STACKSIZE - ${CONFIG_QUICKAPP_STACKSIZE} - PRIORITY - ${CONFIG_QUICKAPP_PRIORITY} - DEPENDS - libqjs) - endif(CONFIG_QUICKAPP_AIOTJSC) - - set(AIOTJSC_PATH - ${CMAKE_CURRENT_BINARY_DIR} - CACHE INTERNAL "") - - ExternalProject_Add( - qjsc - SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/quickjs - BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/ - CMAKE_ARGS -DCONFIG_BIGNUM=${CONFIG_INTERPRETERS_QUICKJS_BIGNUM} - -DQUICKJS_VERSION=${QUICKJS_VERSION} -DAPPDIR=${NUTTX_APPS_DIR} - TEST_COMMAND "" - INSTALL_COMMAND "") - -endif() diff --git a/interpreters/quickjs/Kconfig b/interpreters/quickjs/Kconfig index 79749a156..cc10f7799 100644 --- a/interpreters/quickjs/Kconfig +++ b/interpreters/quickjs/Kconfig @@ -47,33 +47,4 @@ config INTERPRETERS_QUICKJS_EXT_HOOK Since minimal interpreter only support 'console.log', you can export custom module by implement init/destory hook. -config INTERPRETERS_QUICKJS_DEBUG - bool "QuickJS interpreter debug support" - default n - ---help--- - Enable this if you want js debugger support. -config MEMORY_LEAK_TRACK - bool "QuickJS interpreter memory leak track support" - default n - ---help--- - Enable this if you want js debugger support. - -config INTERPRETERS_QUICKJS_CONFIG_TOOL - bool "QuickJS interpreter config tool support" - default n - ---help--- - Enable this if you want js config tool support. - -config INTERPRETERS_QUICKJS_EXPORT_API - bool "Export API to WAMR" - default n - -config INTERPRETERS_QUICKJS_HEAPDUMP - bool "Enable QUICKJS_HEAPDUMP" - default n - -config INTERPRETERS_QUICKJS_CPUPROFILING - bool "Enable QUICKJS_CPUPROFILING" - default n - endif # INTERPRETERS_QUICKJS diff --git a/interpreters/quickjs/Makefile b/interpreters/quickjs/Makefile index 6faacfe66..7fc846621 100644 --- a/interpreters/quickjs/Makefile +++ b/interpreters/quickjs/Makefile @@ -50,31 +50,7 @@ CFLAGS += -DCONFIG_BIGNUM CSRCS += qjscalc.c endif -ifeq ($(CONFIG_INTERPRETERS_QUICKJS_CPUPROFILING),y) -CFLAGS += -DCONFIG_QUICKJS_CPUPROFILING -CSRCS += profile_utils.c -endif - -ifeq ($(CONFIG_INTERPRETERS_QUICKJS_HEAPDUMP),y) -CFLAGS += -DCONFIG_QUICKJS_HEAPDUMP -CSRCS += profile_utils.c -endif - -ifeq ($(CONFIG_INTERPRETERS_QUICKJS_DEBUG),y) -CSRCS += quickjs-debugger.c -CSRCS += quickjs-memorydump.c -endif - -ifeq ($(CONFIG_INTERPRETERS_QUICKJS_CONFIG_TOOL),y) -CFLAGS += -DQUICKJS_CONFIG_TOOL -endif - -ifneq ($(CONFIG_INTERPRETERS_QUICKJS_EXPORT_API),y) -CFLAGS += -DDISABLE_EXPORT_API -endif - VPATH += $(QUICKJS_UNPACK) -DEPPATH += --dep-path $(QUICKJS_UNPACK) ifneq ($(CONFIG_INTERPRETERS_QUICKJS_NONE),y) PROGNAME = qjs diff --git a/interpreters/toywasm/Makefile b/interpreters/toywasm/Makefile index 603f2e351..f70b5239d 100644 --- a/interpreters/toywasm/Makefile +++ b/interpreters/toywasm/Makefile @@ -31,11 +31,14 @@ CSRCS += repl.c # lib CSRCS += bitmap.c +CSRCS += cconv.c CSRCS += cell.c CSRCS += context.c CSRCS += decode.c CSRCS += endian.c CSRCS += exec.c +CSRCS += exec_debug.c +CSRCS += exec_insn_subr.c CSRCS += expr.c CSRCS += fileio.c CSRCS += host_instance.c @@ -48,9 +51,11 @@ CSRCS += list.c CSRCS += load_context.c CSRCS += module.c CSRCS += module_writer.c +CSRCS += name.c CSRCS += nbio.c CSRCS += options.c CSRCS += report.c +CSRCS += restart.c CSRCS += shared_memory.c CSRCS += timeutil.c CSRCS += toywasm_config.c @@ -69,11 +74,48 @@ CSRCS += waitlist.c # libwasi CSRCS += wasi.c +CSRCS += wasi_abi_clock.c +CSRCS += wasi_abi_environ.c +CSRCS += wasi_abi_fd.c +CSRCS += wasi_abi_path.c +CSRCS += wasi_abi_poll.c +CSRCS += wasi_abi_prestat.c +CSRCS += wasi_abi_proc.c +CSRCS += wasi_abi_random.c +CSRCS += wasi_abi_sched.c +CSRCS += wasi_abi_sock.c +CSRCS += wasi_fdinfo.c CSRCS += wasi_fdtable.c +CSRCS += wasi_host_dirent.c +CSRCS += wasi_host_fdop.c +CSRCS += wasi_host_pathop.c +CSRCS += wasi_host_subr.c +CSRCS += wasi_path_subr.c +CSRCS += wasi_poll_subr.c +CSRCS += wasi_subr.c +CSRCS += wasi_table.c +CSRCS += wasi_uio.c +CSRCS += wasi_vfs.c +CSRCS += wasi_vfs_impl_host.c # TOYWASM_ENABLE_WASI_THREADS CSRCS += wasi_threads.c +# libwasi_littlefs TOYWASM_ENABLE_WASI_LITTLEFS +#CSRCS += wasi_littlefs.c +#CSRCS += wasi_littlefs_impl.c +#CSRCS += wasi_littlefs_mount.c +#CSRCS += wasi_littlefs_ops.c +#CSRCS += wasi_vfs_impl_littlefs.c +#CSRCS += lfs.c +#CSRCS += lfs_util.c +#toywasm/libwasi_littlefs/littlefs/lfs.c_CFLAGS += -Wno-shadow +#CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/toywasm/libwasi_littlefs +#CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/toywasm/libwasi_littlefs/littlefs +#CFLAGS += -DLFS_THREADSAFE +#VPATH += $(TOYWASM_UNPACK)/libwasi_littlefs +#VPATH += $(TOYWASM_UNPACK)/libwasi_littlefs/littlefs + # TOYWASM_ENABLE_DYLD CSRCS += dyld.c CSRCS += dyld_plt.c @@ -81,12 +123,20 @@ CSRCS += dyld_plt.c # TOYWASM_ENABLE_DYLD_DLFCN CSRCS += dyld_dlfcn.c +ifeq ($(shell $(CC) --version | grep -i clang),) +CFLAGS += -Wno-maybe-uninitialized +endif CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/include CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/toywasm/lib CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/toywasm/libwasi CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/interpreters/toywasm/toywasm/libdyld -TOYWASM_VERSION = e03d1f61d3f3163da76b33c4c770dbf0d2024324 +# Keep the compilation parameters consistent with toywasm mainline +# https://github.com/yamt/toywasm/blob/master/cmake/ToywasmConfig.cmake#L298-L302 + +CFLAGS += -Wno-unknown-warning-option -Wno-unused-but-set-variable -Wno-unused-variable -Wno-return-type + +TOYWASM_VERSION = 9f77f3519f84e9bb0074d855a04d731a5f56ce84 TOYWASM_UNPACK = toywasm TOYWASM_TARBALL = $(TOYWASM_VERSION).zip TOYWASM_URL_BASE = https://github.com/yamt/toywasm/archive/ diff --git a/interpreters/toywasm/include/toywasm_config.h b/interpreters/toywasm/include/toywasm_config.h index 7b46d9496..7aef2a18f 100644 --- a/interpreters/toywasm/include/toywasm_config.h +++ b/interpreters/toywasm/include/toywasm_config.h @@ -34,10 +34,14 @@ #define TOYWASM_USE_LOCALTYPE_CELLIDX #define TOYWASM_ENABLE_WRITER #define TOYWASM_ENABLE_WASM_SIMD +#define TOYWASM_ENABLE_WASM_EXCEPTION_HANDLING +#define TOYWASM_EXCEPTION_MAX_CELLS 4 #define TOYWASM_ENABLE_WASM_EXTENDED_CONST #define TOYWASM_ENABLE_WASM_MULTI_MEMORY #define TOYWASM_ENABLE_WASM_TAILCALL #define TOYWASM_ENABLE_WASM_THREADS +#define TOYWASM_ENABLE_WASM_CUSTOM_PAGE_SIZES +#define TOYWASM_ENABLE_WASM_NAME_SECTION #define TOYWASM_ENABLE_WASI #define TOYWASM_ENABLE_WASI_THREADS #define TOYWASM_ENABLE_DYLD diff --git a/interpreters/toywasm/include/toywasm_version.h b/interpreters/toywasm/include/toywasm_version.h index d6b949b38..43e5002f7 100644 --- a/interpreters/toywasm/include/toywasm_version.h +++ b/interpreters/toywasm/include/toywasm_version.h @@ -21,6 +21,6 @@ #if !defined(_TOYWASM_VERSION_H) #define _TOYWASM_VERSION_H -#define TOYWASM_VERSION "v33.0.0-4-ge03d1f6" +#define TOYWASM_VERSION "v45.0.0" #endif /* !defined(_TOYWASM_VERSION_H) */ diff --git a/interpreters/toywasm/regen.sh b/interpreters/toywasm/regen.sh index 2f0e02f42..091484cd0 100755 --- a/interpreters/toywasm/regen.sh +++ b/interpreters/toywasm/regen.sh @@ -20,9 +20,11 @@ git -C ${DIR} checkout FETCH_HEAD cmake -B ${BUILDDIR} \ -DTOYWASM_USE_SHORT_ENUMS=OFF \ +-DTOYWASM_ENABLE_WASM_EXCEPTION_HANDLING=ON \ -DTOYWASM_ENABLE_WASM_EXTENDED_CONST=ON \ -DTOYWASM_ENABLE_WASM_MULTI_MEMORY=ON \ -DTOYWASM_ENABLE_WASM_TAILCALL=ON \ +-DTOYWASM_ENABLE_WASM_CUSTOM_PAGE_SIZES=ON \ -DTOYWASM_ENABLE_WASM_THREADS=ON \ -DTOYWASM_ENABLE_WASI_THREADS=ON \ -DTOYWASM_ENABLE_DYLD=ON \ diff --git a/interpreters/toywasm/src/toywasm_config.c b/interpreters/toywasm/src/toywasm_config.c index 2e7893ecf..76e01372b 100644 --- a/interpreters/toywasm/src/toywasm_config.c +++ b/interpreters/toywasm/src/toywasm_config.c @@ -28,6 +28,7 @@ const char *const toywasm_config_string = "\tTOYWASM_USE_SEPARATE_EXECUTE = ON\n" +"\tTOYWASM_USE_SEPARATE_VALIDATE = OFF\n" "\tTOYWASM_USE_TAILCALL = ON\n" "\tTOYWASM_FORCE_USE_TAILCALL = OFF\n" "\tTOYWASM_USE_SIMD = OFF\n" @@ -47,12 +48,18 @@ const char *const toywasm_config_string = "\tTOYWASM_USE_LOCALTYPE_CELLIDX = ON\n" "\tTOYWASM_PREALLOC_SHARED_MEMORY = OFF\n" "\tTOYWASM_ENABLE_WRITER = ON\n" +"\tTOYWASM_ENABLE_WASM_EXCEPTION_HANDLING = ON\n" +"\tTOYWASM_EXCEPTION_MAX_CELLS = 4\n" "\tTOYWASM_ENABLE_WASM_SIMD = ON\n" "\tTOYWASM_ENABLE_WASM_EXTENDED_CONST = ON\n" "\tTOYWASM_ENABLE_WASM_MULTI_MEMORY = ON\n" "\tTOYWASM_ENABLE_WASM_TAILCALL = ON\n" "\tTOYWASM_ENABLE_WASM_THREADS = ON\n" +"\tTOYWASM_ENABLE_WASM_CUSTOM_PAGE_SIZES = ON\n" +"\tTOYWASM_ENABLE_WASM_NAME_SECTION = ON\n" "\tTOYWASM_ENABLE_WASI = ON\n" "\tTOYWASM_ENABLE_WASI_THREADS = ON\n" +"\tTOYWASM_ENABLE_WASI_LITTLEFS = OFF\n" +"\tTOYWASM_ENABLE_LITTLEFS_STATS = OFF\n" "\tTOYWASM_ENABLE_DYLD = ON\n" "\tTOYWASM_ENABLE_DYLD_DLFCN = ON\n"; diff --git a/interpreters/wamr/CMakeLists.txt b/interpreters/wamr/CMakeLists.txt new file mode 100644 index 000000000..ce3be5f35 --- /dev/null +++ b/interpreters/wamr/CMakeLists.txt @@ -0,0 +1,74 @@ +# ############################################################################## +# apps/interpreters/wamr/CMakeLists.txt +# +# Licensed to the Apache Software Foundation (ASF) under one or more contributor +# license agreements. See the NOTICE file distributed with this work for +# additional information regarding copyright ownership. The ASF licenses this +# file to you under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. +# +# ############################################################################## + +if(CONFIG_INTERPRETERS_WAMR) + + # ############################################################################ + # Config and Fetch lib + # ############################################################################ + + set(WAMR_DIR ${CMAKE_CURRENT_LIST_DIR}/wamr) + + if(NOT EXISTS ${WAMR_DIR}) + set(WAMR_URL_BASE + https://github.com/bytecodealliance/wasm-micro-runtime/archive/) + + FetchContent_Declare( + wamr_fetch + URL ${WAMR_URL_BASE}/${CONFIG_INTERPRETERS_WAMR_VERSION}.zip SOURCE_DIR + ${CMAKE_CURRENT_LIST_DIR}/wamr BINARY_DIR + ${CMAKE_BINARY_DIR}/apps/interpreters/wamr/wamr + DOWNLOAD_NO_PROGRESS true + TIMEOUT 30) + + FetchContent_GetProperties(wamr_fetch) + + if(NOT wamr_fetch_POPULATED) + FetchContent_Populate(wamr_fetch) + endif() + endif() + + nuttx_add_library(wamr STATIC) + + include(${WAMR_DIR}/product-mini/platforms/nuttx/CMakeLists.txt) + target_sources(wamr PRIVATE ${WAMR_SOURCES}) + target_compile_options(wamr PRIVATE ${WAMR_CFLAGS}) + # the WAMR_INCDIRS and WAMR_DEFINITIONS already exist in the directory domain + nuttx_add_application( + MODULE + ${CONFIG_INTERPRETERS_WAMR} + NAME + iwasm + STACKSIZE + ${CONFIG_INTERPRETERS_WAMR_STACKSIZE} + PRIORITY + ${CONFIG_INTERPRETERS_WAMR_PRIORITY} + SRCS + ${WAMR_DIR}/product-mini/platforms/nuttx/main.c + COMPILE_FLAGS + ${WAMR_CFLAGS} + DEFINITIONS + ${WAMR_DEFINITIONS} + INCLUDE_DIRECTORIES + ${WAMR_INCDIRS} + DEPENDS + wamr) + +endif() diff --git a/interpreters/wamr/Kconfig b/interpreters/wamr/Kconfig index 6c4b692db..6f3dba779 100644 --- a/interpreters/wamr/Kconfig +++ b/interpreters/wamr/Kconfig @@ -31,10 +31,6 @@ config INTERPRETERS_WAMR_STACKSIZE endif # INTERPRETERS_IWASM_TASK -config INTERPRETERS_WAMR_USE_SIMPLE_LIBDYNTYPE - bool "Enable Simple Dyntype" - default n - config INTERPRETERS_WAMR_AOT bool "Enable AOT" select ARCH_USE_TEXT_HEAP if ARCH_HAVE_TEXT_HEAP @@ -51,6 +47,16 @@ config INTERPRETERS_WAMR_AOT_QUICK_ENTRY signature. Enable this option will increase the size of runtime, ~8KB. +config INTERPRETERS_WAMR_AOT_WORD_ALIGN_READ + bool "Make WAMR AOT loader use word-aligned read" + default y if ARCH_HAVE_TEXT_HEAP_WORD_ALIGNED_READ + default n + +config INTERPRETERS_WAMR_MEM_DUAL_BUS_MIRROR + bool "Make WAMR AOT loader aware of separate instruction/data memory mapping" + default y if ARCH_HAVE_TEXT_HEAP_SEPARATE_DATA_ADDRESS + default n + choice prompt "Enable interpreter" default INTERPRETERS_NONE @@ -66,11 +72,10 @@ config INTERPRETERS_NONE endchoice # Enable interpreter -config INTERPRETERS_WAMR_GC - bool "Enable GC support" +config INTERPRETERS_WAMR_DEBUG_AOT + bool "Enable debugger support for AOT modules" default n - ---help--- - Note: Only WAMR 2.0 support this option + depends on INTERPRETERS_WAMR_AOT config INTERPRETERS_WAMR_DEBUG_INTERP bool "Enable debugger support in the interpreter" @@ -87,15 +92,6 @@ config INTERPRETERS_WAMR_LOG bool "Enable log" default n -config INTERPRETERS_WAMR_LIBC_NUTTX - bool "Bypass to NuttX libc" - default n - -config INTERPRETERS_WAMR_LIBC_NUTTX_POSIXMEMALIGN_MAP_SIZE - int "Map size for posix_memalign" - default 64 - depends on INTERPRETERS_WAMR_LIBC_NUTTX - config INTERPRETERS_WAMR_LIBC_BUILTIN bool "Enable built-in libc" default n @@ -144,10 +140,18 @@ config INTERPRETERS_WAMR_TAIL_CALL config INTERPRETERS_WAMR_STACK_GUARD_SIZE int "Custom stack guard size" - default 0 + default 1024 ---help--- - Reserve some space in stack as guard to detect stack overflow, - use stack base by default but may not safe enough. + Reserve some space in stack as guard to detect stack overflow. + + Please consider this extra stack consumption when deciding the stack + size of your NuttX task on which you run WAMR. + + The default value here (1024) was chosen to match the default value on + the majority of other platforms, including Linux. It also matches + the expections in the WAMR AoT compiler. + On the other hand, it might be a bit larger than what's strictly + necessary, especially for typical NuttX targets. config INTERPRETERS_WAMR_THREAD_MGR bool "Enable thread manager" @@ -196,7 +200,12 @@ config INTERPRETERS_WAMR_DUMP_CALL_STACK config INTERPRETERS_WAMR_DISABLE_HW_BOUND_CHECK bool "Disable hardware bound check" - default n + default y + ---help--- + This option is currently a no-op because + NuttX doesn't have necessary functionalities. + That is, regardless of this setting, WAMR's HW bounds + check is not available for NuttX. config INTERPRETERS_WAMR_LOAD_CUSTOM_SECTIONS bool "Enable load custom section support" diff --git a/interpreters/wamr/Makefile b/interpreters/wamr/Makefile index acbf3d290..45d368282 100644 --- a/interpreters/wamr/Makefile +++ b/interpreters/wamr/Makefile @@ -30,7 +30,6 @@ WAMR_URL = $(WAMR_URL_BASE)/$(WAMR_TARBALL) -include $(WAMR_UNPACK)/product-mini/platforms/nuttx/wamr.mk VPATH += $(WAMR_UNPACK)/product-mini/platforms/nuttx -DEPPATH += --dep-path $(WAMR_UNPACK)/product-mini/platforms/nuttx ifeq ($(CONFIG_INTERPRETERS_IWASM_TASK),y) MAINSRC = main.c @@ -39,26 +38,6 @@ PROGNAME = iwasm PRIORITY = $(CONFIG_INTERPRETERS_WAMR_PRIORITY) STACKSIZE = $(CONFIG_INTERPRETERS_WAMR_STACKSIZE) MODULE = $(CONFIG_INTERPRETERS_WAMR) - -endif - -ifeq ($(CONFIG_INTERPRETERS_WAMR_LIBC_NUTTX),y) - -$(WAMR_UNPACK)/product-mini/platforms/nuttx/main.c_CFLAGS = -Dwasm_runtime_full_init=wamr_custom_init - -CSRCS += wamr_custom_init.c libc_nuttx.c - -GLUECSRCS = syscall_glue.c libc_glue.c libm_glue.c -CSVSRCS = $(TOPDIR)/syscall/syscall.csv $(TOPDIR)/libs/libc/libc.csv $(TOPDIR)/libs/libm/libm.csv - -$(GLUECSRCS): $(CSVSRCS) $(APPDIR)/tools/mkwamrglue.py - $(Q) $(APPDIR)/tools/mkwamrglue.py -i $(TOPDIR)/syscall/syscall.csv -o syscall_glue.c - $(Q) $(APPDIR)/tools/mkwamrglue.py -i $(TOPDIR)/libs/libc/libc.csv -o libc_glue.c - $(Q) $(APPDIR)/tools/mkwamrglue.py -i $(TOPDIR)/libs/libm/libm.csv -o libm_glue.c - - -depend:: $(GLUECSRCS) - endif $(WAMR_TARBALL): diff --git a/interpreters/wamr/libc_nuttx.c b/interpreters/wamr/libc_nuttx.c deleted file mode 100644 index f2b6f7bbb..000000000 --- a/interpreters/wamr/libc_nuttx.c +++ /dev/null @@ -1,673 +0,0 @@ -/**************************************************************************** - * apps/interpreters/wamr/libc_nuttx.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "wasm_export.h" -#include "wasm_native.h" - -#include "wamr_custom_init.h" - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static sem_t g_aligned_memory_map_sem = SEM_INITIALIZER(1); -static uintptr_t g_aligned_memory_map - [CONFIG_INTERPRETERS_WAMR_LIBC_NUTTX_POSIXMEMALIGN_MAP_SIZE][2] = -{ - 0 -}; - -static bool -add_to_aligned_map(uintptr_t mapped, uintptr_t raw) -{ - int i; - bool ret = false; - - sem_wait(&g_aligned_memory_map_sem); - - for (i = 0; i < CONFIG_INTERPRETERS_WAMR_LIBC_NUTTX_POSIXMEMALIGN_MAP_SIZE; - i++) - { - DEBUGASSERT(g_aligned_memory_map[i][0] != mapped); - - if (g_aligned_memory_map[i][0] == 0 && g_aligned_memory_map[i][1] == 0) - { - g_aligned_memory_map[i][0] = mapped; - g_aligned_memory_map[i][1] = raw; - ret = true; - break; - } - } - - sem_post(&g_aligned_memory_map_sem); - return ret; -} - -static uintptr_t -remove_from_aligned_map(uintptr_t mapped) -{ - int i; - uintptr_t ret = 0; - - if (mapped == 0) - { - return ret; - } - - sem_wait(&g_aligned_memory_map_sem); - - for (i = 0; i < CONFIG_INTERPRETERS_WAMR_LIBC_NUTTX_POSIXMEMALIGN_MAP_SIZE; - i++) - { - if (g_aligned_memory_map[i][0] == mapped) - { - g_aligned_memory_map[i][0] = 0; - ret = g_aligned_memory_map[i][1]; - g_aligned_memory_map[i][1] = 0; - break; - } - } - - sem_post(&g_aligned_memory_map_sem); - return ret; -} - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void -va_list_string2conv(wasm_exec_env_t exec_env, const char *format, - va_list ap, bool to_native) -{ - wasm_module_inst_t module_inst = get_module_inst(exec_env); - char *pos = *((char **)&ap); - - if (pos == NULL) - { - return; - } - - int long_ctr = 0; - int might = 0; - - while (*format) - { - if (!might) - { - if (*format == '%') - { - might = 1; - long_ctr = 0; - } - } - else - { - switch (*format) - { - case '.': - case '+': - case '-': - case ' ': - case '#': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - goto still_might; - - case 't': - case 'z': - long_ctr = 1; - goto still_might; - - case 'j': - long_ctr = 2; - goto still_might; - - case 'l': - long_ctr++; - case 'h': - goto still_might; - - case 'o': - case 'd': - case 'i': - case 'u': - case 'p': - case 'x': - case 'X': - case 'c': - { - if (long_ctr < 2) - { - pos += sizeof(int32_t); - } - else - { - pos += sizeof(int64_t); - } - break; - } - - case 'e': - case 'E': - case 'g': - case 'G': - case 'f': - case 'F': - { - pos += sizeof(double); - break; - } - - case 's': - { - if (to_native) - { - *(uintptr_t *)pos = - (uintptr_t)addr_app_to_native(*(uintptr_t *)pos); - } - else - { - *(uintptr_t *)pos = - (uintptr_t)addr_native_to_app(*(uintptr_t *)pos); - } - - pos += sizeof(uintptr_t); - break; - } - - default: - break; - } - - might = 0; - } - - still_might: - ++format; - } -} - -#define va_list_string2native(exec_env, format, ap) \ - va_list_string2conv(exec_env, format, ap, true) - -#define va_list_string2app(exec_env, format, ap) \ - va_list_string2conv(exec_env, format, ap, false) - -static void -scanf_begin(wasm_module_inst_t module_inst, va_list ap) -{ - uintptr_t *apv = *(uintptr_t **)≈ - if (apv == NULL) - { - return; - } - while (*apv != 0) - { - *apv = (uintptr_t)addr_app_to_native(*apv); - apv++; - } -} - -static void -scanf_end(wasm_module_inst_t module_inst, va_list ap) -{ - uintptr_t *apv = *(uintptr_t **)≈ - if (apv == NULL) - { - return; - } - while (*apv != 0) - { - *apv = (uintptr_t)addr_native_to_app((void *)*apv); - apv++; - } -} - -static pthread_mutex_t g_compare_mutex = PTHREAD_MUTEX_INITIALIZER; -static wasm_exec_env_t g_compare_env; -static void *g_compare_func; - -static int -compare_proxy(const void *a, const void *b) -{ - wasm_module_inst_t module_inst = get_module_inst(g_compare_env); - uint32_t argv[2]; - - argv[0] = addr_native_to_app((void *)a); - argv[1] = addr_native_to_app((void *)b); - - return wasm_runtime_call_indirect(g_compare_env, - (uint32_t)addr_native_to_app(g_compare_func), 2, argv) ? - argv[0] : 0; -} - -#ifndef GLUE_FUNCTION_qsort -#define GLUE_FUNCTION_qsort -void glue_qsort(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3, uintptr_t parm4) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - pthread_mutex_lock(&g_compare_mutex); - g_compare_env = env; - g_compare_func = parm4; - qsort((FAR void *)parm1, (size_t)parm2, - (size_t)parm3, compare_proxy); - pthread_mutex_unlock(&g_compare_mutex); -} - -#endif /* GLUE_FUNCTION_qsort */ - -#ifndef GLUE_FUNCTION_bsearch -#define GLUE_FUNCTION_bsearch -uintptr_t glue_bsearch(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3, uintptr_t parm4, uintptr_t parm5) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - - pthread_mutex_lock(&g_compare_mutex); - g_compare_env = env; - g_compare_func = parm5; - ret = bsearch((FAR const void *)parm1, - (FAR const void *)parm2, - (size_t)parm3, (size_t)parm4, compare_proxy); - pthread_mutex_unlock(&g_compare_mutex); - ret = addr_native_to_app((void *)ret); - return ret; -} - -#endif /* GLUE_FUNCTION_bsearch */ - -static void glue_msghdr_begin(wasm_module_inst_t module_inst, - FAR struct msghdr *hdr) -{ - int i; - - hdr->msg_iov = addr_app_to_native((uintptr_t)hdr->msg_iov); - - for (i = 0; i < hdr->msg_iovlen; i++) - { - hdr->msg_iov[i].iov_base = - addr_app_to_native((uintptr_t)hdr->msg_iov[i].iov_base); - } - - if (hdr->msg_name != NULL && hdr->msg_namelen > 0) - { - hdr->msg_name = addr_app_to_native(hdr->msg_name); - } - - if (hdr->msg_control != NULL && hdr->msg_controllen > 0) - { - hdr->msg_control = addr_app_to_native((uintptr_t)hdr->msg_control); - } -} - -static void glue_msghdr_end(wasm_module_inst_t module_inst, - FAR struct msghdr *hdr) -{ - int i; - - for (i = 0; i < hdr->msg_iovlen; i++) - { - hdr->msg_iov[i].iov_base = - addr_native_to_app((uintptr_t)hdr->msg_iov[i].iov_base); - } - - hdr->msg_iov = addr_native_to_app((uintptr_t)hdr->msg_iov); - - if (hdr->msg_name != NULL && hdr->msg_namelen > 0) - { - hdr->msg_name = addr_native_to_app(hdr->msg_name); - } - - if (hdr->msg_control != NULL && hdr->msg_controllen > 0) - { - hdr->msg_control = addr_native_to_app((uintptr_t)hdr->msg_control); - } -} - -#ifndef GLUE_FUNCTION_sendmsg -#define GLUE_FUNCTION_sendmsg -uintptr_t glue_sendmsg(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2, uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - FAR struct msghdr *hdr = - (FAR struct msghdr *)(uintptr_t)parm2; - - glue_msghdr_begin(module_inst, hdr); - uintptr_t ret = sendmsg((int)parm1, - (FAR struct msghdr *)(parm2), - (int)parm3); - glue_msghdr_end(module_inst, hdr); - - return ret; -} - -#endif /* GLUE_FUNCTION_sendmsg */ - -#ifndef GLUE_FUNCTION_recvmsg -#define GLUE_FUNCTION_recvmsg -uintptr_t glue_recvmsg(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2, uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - FAR struct msghdr *hdr = - (FAR struct msghdr *)((uintptr_t)parm2); - - glue_msghdr_begin(module_inst, hdr); - uintptr_t ret = recvmsg((int)parm1, - (FAR struct msghdr *)(parm2), - (int)parm3); - glue_msghdr_end(module_inst, hdr); - - return ret; -} - -#endif /* GLUE_FUNCTION_recvmsg */ - -#ifndef GLUE_FUNCTION_strsep -#define GLUE_FUNCTION_strsep -uintptr_t glue_strsep(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - FAR char **stringp = parm1; - - if (*stringp != NULL) - { - *stringp = addr_app_to_native(*stringp); - } - - return addr_native_to_app((uintptr_t)strsep( - (FAR char **)addr_app_to_native(parm1), - (FAR const char *)addr_app_to_native(parm2))); -} - -#endif /* GLUE_FUNCTION_strsep */ - -#ifndef GLUE_FUNCTION_scandir -#define GLUE_FUNCTION_scandir -uintptr_t glue_scandir(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3, uintptr_t parm4) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - int ret = 0; - int i = 0; - - ret = scandir((FAR const char *)parm1, - (FAR struct dirent ** *)parm2, - (FAR void *)parm3, alphasort); - - for (i = 0; i < ret; i++) - { - (*(uintptr_t **)parm2)[i] = - addr_native_to_app((*(uintptr_t **)parm2)[i]); - } - - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - - return ret; -} - -#endif /* GLUE_FUNCTION_scandir */ - -#ifndef GLUE_FUNCTION_daemon -#define GLUE_FUNCTION_daemon -uintptr_t glue_daemon(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2) -{ - return 0; -} - -#endif /* GLUE_FUNCTION_daemon */ - -#ifndef GLUE_FUNCTION_posix_memalign -#define GLUE_FUNCTION_posix_memalign -uintptr_t glue_posix_memalign(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2, uintptr_t parm3) -{ - uintptr_t rawptr; - wasm_module_inst_t module_inst = get_module_inst(env); - - /* Extra size for align */ - - parm3 += parm2; - int ret = posix_memalign((FAR void **)parm1, (size_t)parm2, (size_t)parm3); - - /* If the memory allocation is failed, return NULL */ - - if (ret != OK) - { - return NULL; - } - - /* Add the original pointer to the map */ - - rawptr = *(uintptr_t *)parm1; - *(void **)parm1 = addr_native_to_app((uintptr_t)*(void **)parm1); - *(uintptr_t *)parm1 = (*(uintptr_t *)parm1 + parm2 - 1) & ~(parm2 - 1); - - if (add_to_aligned_map(*(uintptr_t *)parm1, rawptr)) - { - return ret; - } - else - { - free(rawptr); - return NULL; - } -} -#endif /* GLUE_FUNCTION_posix_memalign */ - -#ifndef GLUE_FUNCTION_free -#define GLUE_FUNCTION_free -void glue_free(wasm_exec_env_t env, uintptr_t parm1) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret = NULL; - uintptr_t app_addr = NULL; - - /* Try to pop the original pointer from the map */ - - if (parm1 != (uintptr_t)NULL) - { - app_addr = addr_native_to_app(parm1); - ret = remove_from_aligned_map(app_addr); - } - - if (ret) - { - parm1 = ret; - } - - free((FAR void *)parm1); -} - -#endif /* GLUE_FUNCTION_free */ - -#ifndef GLUE_FUNCTION_vasprintf -#define GLUE_FUNCTION_vasprintf -uintptr_t glue_vasprintf(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t format, va_list ap) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - va_list_string2native(env, format, ap); - ret = vasprintf((FAR char **)parm1, (FAR const IPTR char *)format, ap); - *(uintptr_t *)parm1 = addr_native_to_app(*(uintptr_t *)parm1); - return ret; -} -#endif /* GLUE_FUNCTION_vasprintf */ - -#ifndef GLUE_FUNCTION_strtol -#define GLUE_FUNCTION_strtol -uintptr_t glue_strtol(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - ret = strtol((FAR const char *)parm1, (FAR char **)parm2, (int)parm3); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - return ret; -} - -#endif /* GLUE_FUNCTION_strtol */ - -#if defined(CONFIG_HAVE_LONG_LONG) -#ifndef GLUE_FUNCTION_strtoll -#define GLUE_FUNCTION_strtoll -uintptr_t glue_strtoll(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - ret = strtoll((FAR const char *)parm1, (FAR char **)parm2, (int)parm3); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - return ret; -} -#endif /* GLUE_FUNCTION_strtoll */ -#endif - -#ifndef GLUE_FUNCTION_strtoul -#define GLUE_FUNCTION_strtoul -uintptr_t glue_strtoul(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2, uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - ret = strtoul((FAR const char *)parm1, (FAR char **)parm2, (int)parm3); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - return ret; -} - -#endif /* GLUE_FUNCTION_strtoul */ - -#ifndef GLUE_FUNCTION_strtoull -#define GLUE_FUNCTION_strtoull -uintptr_t glue_strtoull(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2, uintptr_t parm3) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - ret = strtoull((FAR const char *)parm1, (FAR char **)parm2, (int)parm3); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - return ret; -} - -#endif /* GLUE_FUNCTION_strtoull */ - -#if defined(CONFIG_LIBC_LOCALE) - -#ifndef GLUE_FUNCTION_iconv -#define GLUE_FUNCTION_iconv -uintptr_t glue_iconv(wasm_exec_env_t env, uintptr_t parm1, uintptr_t parm2, - uintptr_t parm3, uintptr_t parm4, uintptr_t parm5) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - *(uintptr_t *)parm4 = addr_app_to_native(*(uintptr_t *)parm4); - ret = iconv((iconv_t)parm1, (FAR char **)parm2, (FAR size_t *)parm3, - (FAR char **)parm4, (FAR size_t *)parm5); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - *(uintptr_t *)parm4 = addr_native_to_app(*(uintptr_t *)parm4); - return ret; -} - -#endif /* GLUE_FUNCTION_iconv */ -#endif /* defined(CONFIG_LIBC_LOCALE) */ - -#ifndef GLUE_FUNCTION_versionsort -#define GLUE_FUNCTION_versionsort -uintptr_t glue_versionsort(wasm_exec_env_t env, uintptr_t parm1, - uintptr_t parm2) -{ - wasm_module_inst_t module_inst = get_module_inst(env); - uintptr_t ret; - *(uintptr_t *)parm1 = addr_app_to_native(*(uintptr_t *)parm1); - *(uintptr_t *)parm2 = addr_app_to_native(*(uintptr_t *)parm2); - ret = versionsort((FAR const struct dirent **)parm1, - (FAR const struct dirent **)parm2); - *(uintptr_t *)parm1 = addr_native_to_app(*(uintptr_t *)parm1); - *(uintptr_t *)parm2 = addr_native_to_app(*(uintptr_t *)parm2); - return ret; -} - -#endif /* GLUE_FUNCTION_versionsort */ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "libc_glue.c" -#include "libm_glue.c" -#include "syscall_glue.c" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -bool -wamr_libc_nuttx_register(void) -{ - bool ret; - - /* Add extra init hook here */ - - ret = wasm_native_register_natives("env", g_syscall_native_symbols, - nitems(g_syscall_native_symbols)); - if (ret == true) - { - ret = wasm_native_register_natives("env", g_libc_native_symbols, - nitems(g_libc_native_symbols)); - if (ret == true) - { - ret = wasm_native_register_natives("env", g_libm_native_symbols, - nitems(g_libm_native_symbols)); - } - } - - return ret; -} diff --git a/interpreters/wamr/wamr_custom_init.h b/interpreters/wamr/wamr_custom_init.h deleted file mode 100644 index 0e1ab755f..000000000 --- a/interpreters/wamr/wamr_custom_init.h +++ /dev/null @@ -1,36 +0,0 @@ -/**************************************************************************** - * apps/interpreters/wamr/wamr_custom_init.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __WAMR_CUSTOM_INIT_H -#define __WAMR_CUSTOM_INIT_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Functions Prototypes - ****************************************************************************/ - -bool wamr_libc_nuttx_register(void); - -#endif /* __WAMR_CUSTOM_INIT_H */ diff --git a/logging/embedlog/Makefile b/logging/embedlog/Makefile index 0401f34d4..747b7ec5c 100644 --- a/logging/embedlog/Makefile +++ b/logging/embedlog/Makefile @@ -26,8 +26,8 @@ PACKEXT = .tar.gz NXTOOLSDIR = $(APPDIR)/tools EMBEDLOG_URL = https://distfiles.bofc.pl/embedlog -EMBEDLOG_VERSION = 0.6.0 -EMBEDLOG_SRC_SHA256 = f5f15dd124d113c7c8cc286f17fc633e1ade90acb6633dc98277968ab2a149d5 +EMBEDLOG_VERSION = 0.7.0 +EMBEDLOG_SRC_SHA256 = 154cbcb9a14809f14c5c4a5e11a3b6da23be2858a1d7a2b4054bb05f062f41c5 EMBEDLOG_EXT = tar.gz EMBEDLOG_SOURCES = embedlog-$(EMBEDLOG_VERSION) EMBEDLOG_TARBALL = $(EMBEDLOG_SOURCES).$(EMBEDLOG_EXT) diff --git a/logging/nxscope/README.md b/logging/nxscope/README.md deleted file mode 100644 index 87e0674b9..000000000 --- a/logging/nxscope/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# `NxScope Library` - -This library provides real-time data logging functionality for NuttX. - -The principle of action is to accumulate data gathered in virtual channels -and periodically send buffered data through a dedicated interface packed -with a custom protocol. - -Supported features: - - up to 255 channels possible - - support for standard data types and user-specific data (`enum nxscope_sample_dtype_e`) - - support for vector data or point data - - support for character-based channels (text messages) - - support for channel metadata - can be used to enumerate samples or timestamp - - stream buffer overflow detection (`NXSCOPE_STREAM_FLAGS_OVERFLOW`) - - remote control with commands (`enum nxscope_hdr_id_e`) - - protocol and interface implementation can be different for control commands and stream data - - (optional) support for user-specific commands (`NXSCOPE_HDRID_USER` and `struct nxscope_callbacks_s`) - - (optional) support for samples divider (`CONFIG_LOGGING_NXSCOPE_DIVIDER`) - - (optional) support for ACK frames (`CONFIG_LOGGING_NXSCOPE_ACKFRAMES`) - - (optional) support for user-defined types (`CONFIG_LOGGING_NXSCOPE_USERTYPES`) - - (optional) support for non-buffered critical channels (`CONFIG_LOGGING_NXSCOPE_CRICHANNELS`) - -A custom interface and a custom protocol can be implemented with -`struct nxscope_intf_s` and `struct nxscope_proto_s` structures. - -Supported interfaces: - 1. a serial port: `logging/nxscope/nxscope_iser.c` - 2. a dummy interface for debug purposes: `logging/nxscope/nxscope_idummy.c` - -A default serial protocol is implemented in `apps/logging/nxscope/nxscope_pser.c` -It just packs NxScope data into simple frames with a CRC-16 checksum. - -## External tools - -- [Nxslib](https://github.com/railab/nxslib) - a Python (3.10+) client library for NxScope devices, -- [Nxscli](https://github.com/railab/nxscli) - a Python (3.10+) command-line interface for NxScope, -supporting data capture and visualization diff --git a/logging/nxscope/nxscope.c b/logging/nxscope/nxscope.c index 5be4e601e..011aa93c2 100644 --- a/logging/nxscope/nxscope.c +++ b/logging/nxscope/nxscope.c @@ -353,7 +353,7 @@ static int nxscope_div_req(FAR struct nxscope_s *s, { _err("ERROR: invalid div bulk dlen = %d\n", dlen); ret = -EINVAL; - goto errout; + goto errout; } /* Write configuration */ diff --git a/logging/nxscope/nxscope_iser.c b/logging/nxscope/nxscope_iser.c index 816c096a6..d91cf61d5 100644 --- a/logging/nxscope/nxscope_iser.c +++ b/logging/nxscope/nxscope_iser.c @@ -207,15 +207,16 @@ int nxscope_ser_init(FAR struct nxscope_intf_s *intf, tcgetattr(priv->fd, &tio); #ifdef CONFIG_SERIAL_TERMIOS - /* Configure a baud rate */ - - DEBUGASSERT(priv->cfg->baud > 0); - - ret = cfsetspeed(&tio, priv->cfg->baud); - if (ret < 0) + if (priv->cfg->baud > 0) { - _err("ERROR: failed to set baud rate %d\n", errno); - goto errout; + /* Configure a baud rate */ + + ret = cfsetspeed(&tio, priv->cfg->baud); + if (ret < 0) + { + _err("ERROR: failed to set baud rate %d\n", errno); + goto errout; + } } #endif diff --git a/lte/alt1250/alt1250_atcmd.c b/lte/alt1250/alt1250_atcmd.c index 33b280dba..bdd7e2853 100644 --- a/lte/alt1250/alt1250_atcmd.c +++ b/lte/alt1250/alt1250_atcmd.c @@ -245,7 +245,7 @@ static int send_internal_at_command(FAR struct alt1250_s *dev, err_alt1250("Internal ATCMD : %s\n", dev->tx_buff); - ret = altdevice_send_command(dev->altfd, container, usock_result); + ret = altdevice_send_command(dev, dev->altfd, container, usock_result); if (ret == REP_NO_ACK) { /* In case of no error */ @@ -431,6 +431,33 @@ int ltenwop_send_setnwoptp(FAR struct alt1250_s *dev, return send_internal_at_command(dev, container, -1, NULL, 0, &dummy); } +/**************************************************************************** + * name: ltesp_send_getscanplan + ****************************************************************************/ + +int ltesp_send_getscanplan(FAR struct alt1250_s *dev, + FAR struct alt_container_s *container) +{ + int32_t dummy; + snprintf((FAR char *)dev->tx_buff, _TX_BUFF_SIZE, + "AT%%GETCFG=\"SCAN_PLAN_EN\"\r"); + return send_internal_at_command(dev, container, -1, NULL, 0, &dummy); +} + +/**************************************************************************** + * name: ltesp_send_setscanplan + ****************************************************************************/ + +int ltesp_send_setscanplan(FAR struct alt1250_s *dev, + FAR struct alt_container_s *container, + bool enable) +{ + int32_t dummy; + snprintf((FAR char *)dev->tx_buff, _TX_BUFF_SIZE, + "AT%%SETCFG=\"SCAN_PLAN_EN\",\"%s\"\r", (enable ? "1" : "0")); + return send_internal_at_command(dev, container, -1, NULL, 0, &dummy); +} + /**************************************************************************** * name: lwm2mstub_send_getqueuemode ****************************************************************************/ diff --git a/lte/alt1250/alt1250_atcmd.h b/lte/alt1250/alt1250_atcmd.h index 62cc56d1e..d732a3313 100644 --- a/lte/alt1250/alt1250_atcmd.h +++ b/lte/alt1250/alt1250_atcmd.h @@ -109,6 +109,13 @@ int ltenwop_send_getnwop(FAR struct alt1250_s *dev, int ltenwop_send_setnwoptp(FAR struct alt1250_s *dev, FAR struct alt_container_s *container); +int ltesp_send_getscanplan(FAR struct alt1250_s *dev, + FAR struct alt_container_s *container); + +int ltesp_send_setscanplan(FAR struct alt1250_s *dev, + FAR struct alt_container_s *container, + bool enable); + int lwm2mstub_send_getqueuemode(FAR struct alt1250_s *dev, FAR struct alt_container_s *container, int16_t usockid, FAR int32_t *ures); diff --git a/lte/alt1250/alt1250_devevent.c b/lte/alt1250/alt1250_devevent.c index 7d16f53ae..118f31254 100644 --- a/lte/alt1250/alt1250_devevent.c +++ b/lte/alt1250/alt1250_devevent.c @@ -298,6 +298,19 @@ exit: altdevice_powerresponse(dev->altfd, LTE_CMDID_STOPAPI, ret); } +/**************************************************************************** + * Name: perform_alt1250_restartevt + ****************************************************************************/ + +static void perform_alt1250_restartevt(FAR struct alt1250_s *dev) +{ + /* All LTE API/Socket requests must be available. */ + + alt1250_set_api_enable(dev, true); + + altdevice_powerresponse(dev->altfd, LTE_CMDID_RESTARTAPI, OK); +} + /**************************************************************************** * Name: perform_alt1250_suspendevt ****************************************************************************/ @@ -398,6 +411,12 @@ int perform_alt1250events(FAR struct alt1250_s *dev) perform_alt1250_apistopevt(dev); } + else if (bitmap & ALT1250_EVTBIT_RESTARTAPI) + { + /* Handling API restart request */ + + perform_alt1250_restartevt(dev); + } else if (bitmap & ALT1250_EVTBIT_SUSPEND) { /* Handling Suspend request */ diff --git a/lte/alt1250/alt1250_devif.c b/lte/alt1250/alt1250_devif.c index 374af6214..d58f3c75f 100644 --- a/lte/alt1250/alt1250_devif.c +++ b/lte/alt1250/alt1250_devif.c @@ -92,10 +92,20 @@ FAR struct alt_container_s *altdevice_exchange_selcontainer(int fd, * name: altdevice_send_command ****************************************************************************/ -int altdevice_send_command(int fd, FAR struct alt_container_s *container, +int altdevice_send_command(FAR struct alt1250_s *dev, int fd, + FAR struct alt_container_s *container, FAR int32_t *usock_res) { int ret; + +#ifdef CONFIG_LTE_ALT1250_ENABLE_HIBERNATION_MODE + if (dev->is_resuming) + { + *usock_res = -EOPNOTSUPP; + return REP_SEND_ACK; + } +#endif + ret = ioctl_wrapper(fd, ALT1250_IOC_SEND, (unsigned long)container); if (ret < 0) { diff --git a/lte/alt1250/alt1250_devif.h b/lte/alt1250/alt1250_devif.h index a1a3bb19a..5a01b647d 100644 --- a/lte/alt1250/alt1250_devif.h +++ b/lte/alt1250/alt1250_devif.h @@ -28,6 +28,7 @@ #include #include +#include "alt1250_daemon.h" #define DEV_ALT1250 "/dev/alt1250" @@ -39,7 +40,8 @@ int init_alt1250_device(void); void finalize_alt1250_device(int fd); FAR struct alt_container_s *altdevice_exchange_selcontainer(int fd, FAR struct alt_container_s *container); -int altdevice_send_command(int fd, FAR struct alt_container_s *container, +int altdevice_send_command(FAR struct alt1250_s *dev, int fd, + FAR struct alt_container_s *container, FAR int32_t *usock_res); int altdevice_powercontrol(int fd, uint32_t cmd); int altdevice_seteventbuff(int fd, FAR struct alt_evtbuffer_s *buffers); diff --git a/lte/alt1250/alt1250_netdev.c b/lte/alt1250/alt1250_netdev.c index ee9e9602a..1f8fff8f2 100644 --- a/lte/alt1250/alt1250_netdev.c +++ b/lte/alt1250/alt1250_netdev.c @@ -30,6 +30,8 @@ #include "alt1250_netdev.h" +#define ALT1250_SUBNET_MASK 0xFFFFFF00 /* 255.255.255.0 this is dummy */ + /**************************************************************************** * Public Functions ****************************************************************************/ @@ -61,6 +63,8 @@ void alt1250_netdev_ifdown(FAR struct alt1250_s *dev) dev->net_dev.d_flags = IFF_DOWN; #ifdef CONFIG_NET_IPv4 memset(&dev->net_dev.d_ipaddr, 0, sizeof(dev->net_dev.d_ipaddr)); + memset(&dev->net_dev.d_draddr, 0, sizeof(dev->net_dev.d_draddr)); + memset(&dev->net_dev.d_netmask, 0, sizeof(dev->net_dev.d_netmask)); #endif #ifdef CONFIG_NET_IPv6 memset(&dev->net_dev.d_ipv6addr, 0, sizeof(dev->net_dev.d_ipv6addr)); @@ -85,6 +89,17 @@ void alt1250_netdev_ifup(FAR struct alt1250_s *dev, FAR lte_pdn_t *pdn) inet_pton(AF_INET, (FAR const char *)pdn->address[i].address, (FAR void *)&dev->net_dev.d_ipaddr); + inet_pton(AF_INET, + (FAR const char *)pdn->address[i].address, + (FAR void *)&dev->net_dev.d_draddr); + + /* The following parameters are dummy values because + * they cannot be obtained from alt1250. + */ + + dev->net_dev.d_draddr = htonl((ntohl(dev->net_dev.d_draddr) & + ALT1250_SUBNET_MASK) | 1); + dev->net_dev.d_netmask = htonl(ALT1250_SUBNET_MASK); } #endif diff --git a/lte/alt1250/alt1250_reset_seq.c b/lte/alt1250/alt1250_reset_seq.c index e7eba13da..3dc836803 100644 --- a/lte/alt1250/alt1250_reset_seq.c +++ b/lte/alt1250/alt1250_reset_seq.c @@ -116,7 +116,7 @@ static int send_getversion_onreset(FAR struct alt1250_s *dev, set_container_postproc(container, postproc_ponresetseq, (unsigned long)&reset_arg); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -192,6 +192,37 @@ static int recv_atreply_onreset(atreply_parser_t parse, return ret; } +/**************************************************************************** + * name: alt1250_disable_scanplan + ****************************************************************************/ + +static int alt1250_disable_scanplan(FAR struct alt1250_s *dev, + FAR struct alt_container_s *container) +{ + int recv_ret; + struct atreply_truefalse_s t_or_f; + + t_or_f.target_str = "0"; + ltesp_send_getscanplan(dev, container); + recv_ret = recv_atreply_onreset(check_atreply_truefalse, dev, &t_or_f); + if (recv_ret == REP_MODEM_RESET) + { + return recv_ret; + } + + if (!t_or_f.result) + { + ltesp_send_setscanplan(dev, container, false); + recv_ret = recv_atreply_onreset(check_atreply_ok, dev, NULL); + if (recv_ret == REP_MODEM_RESET) + { + return recv_ret; + } + } + + return recv_ret; +} + /**************************************************************************** * name: alt1250_lwm2m_ponreset ****************************************************************************/ @@ -319,6 +350,14 @@ static int alt1250_lwm2m_ponreset(FAR struct alt1250_s *dev, ret = REP_SEND_ACK; } + /* Make sure SCAN_PALAN_EN is 0 */ + + recv_ret = alt1250_disable_scanplan(dev, container); + if (recv_ret == REP_MODEM_RESET) + { + return recv_ret; + } + if (ret == REP_SEND_ACK) { /* Force Reset is needed. */ diff --git a/lte/alt1250/alt1250_select.c b/lte/alt1250/alt1250_select.c index ecac3771a..e608e3532 100644 --- a/lte/alt1250/alt1250_select.c +++ b/lte/alt1250/alt1250_select.c @@ -119,7 +119,7 @@ static int send_select_command(FAR struct alt1250_s *dev, set_container_ids(&container, 0, LTE_CMDID_SELECT); set_container_argument(&container, in, nitems(in)); - return altdevice_send_command(dev->altfd, &container, &usock_result); + return altdevice_send_command(dev, dev->altfd, &container, &usock_result); } /**************************************************************************** diff --git a/lte/alt1250/alt1250_usockif.c b/lte/alt1250/alt1250_usockif.c index f421361e5..f85d05a61 100644 --- a/lte/alt1250/alt1250_usockif.c +++ b/lte/alt1250/alt1250_usockif.c @@ -281,7 +281,7 @@ int usockif_readreqioctl(int fd, FAR struct usrsock_request_buff_s *buf) break; default: dbg_alt1250("Unsupported command:0x%08lx\n", req->cmd); - return -EINVAL; + return -ENOTTY; break; } diff --git a/lte/alt1250/callback_handlers/alt1250_evt.c b/lte/alt1250/callback_handlers/alt1250_evt.c index a2ab7782a..73bf1a840 100644 --- a/lte/alt1250/callback_handlers/alt1250_evt.c +++ b/lte/alt1250/callback_handlers/alt1250_evt.c @@ -638,9 +638,10 @@ static FAR void *g_lwm2movstopargs[] = /* event argument for LTE_CMDID_LWM2M_SERVEROP_EVT */ +static struct lwm2mstub_instance_s g_lwm2msrvop_inst; static FAR void *g_lwm2moperationargs[] = { - NULL + NULL, NULL, &g_lwm2msrvop_inst }; /* event argument for LTE_CMDID_LWM2M_FWUP_EVT */ @@ -1445,7 +1446,8 @@ static uint64_t lwm2m_operation_evt_cb(FAR void *cb, FAR void **cbarg, if (callback) { - callback((int)cbarg[0]); + callback((int)cbarg[0], (int)cbarg[1], + (FAR struct lwm2mstub_instance_s *)cbarg[2]); } return 0ULL; diff --git a/lte/alt1250/usock_handlers/alt1250_accepthdlr.c b/lte/alt1250/usock_handlers/alt1250_accepthdlr.c index f9565be0b..9b2bf1d52 100644 --- a/lte/alt1250/usock_handlers/alt1250_accepthdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_accepthdlr.c @@ -90,7 +90,7 @@ static int send_close_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_accepterr, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -188,7 +188,7 @@ static int send_accept_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_accept, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_bindhdlr.c b/lte/alt1250/usock_handlers/alt1250_bindhdlr.c index 527cf9361..b79ea10cb 100644 --- a/lte/alt1250/usock_handlers/alt1250_bindhdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_bindhdlr.c @@ -65,7 +65,7 @@ static int send_bind_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_closehdlr.c b/lte/alt1250/usock_handlers/alt1250_closehdlr.c index 0b61c2b15..c2c25dd1a 100644 --- a/lte/alt1250/usock_handlers/alt1250_closehdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_closehdlr.c @@ -63,7 +63,7 @@ static int send_close_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_connecthdlr.c b/lte/alt1250/usock_handlers/alt1250_connecthdlr.c index 4e70d316c..7df629b84 100644 --- a/lte/alt1250/usock_handlers/alt1250_connecthdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_connecthdlr.c @@ -175,7 +175,7 @@ static int send_connect_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_connect, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_getsocknamehdlr.c b/lte/alt1250/usock_handlers/alt1250_getsocknamehdlr.c index b7539847d..b6df94887 100644 --- a/lte/alt1250/usock_handlers/alt1250_getsocknamehdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_getsocknamehdlr.c @@ -114,7 +114,7 @@ static int send_getsockname_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_getsockname, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_getsockopthdlr.c b/lte/alt1250/usock_handlers/alt1250_getsockopthdlr.c index 673d54d17..28174fce8 100644 --- a/lte/alt1250/usock_handlers/alt1250_getsockopthdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_getsockopthdlr.c @@ -146,7 +146,7 @@ int send_getsockopt_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, func, priv); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_ioctl_event.c b/lte/alt1250/usock_handlers/alt1250_ioctl_event.c index aeeb61903..913f456d4 100644 --- a/lte/alt1250/usock_handlers/alt1250_ioctl_event.c +++ b/lte/alt1250/usock_handlers/alt1250_ioctl_event.c @@ -53,7 +53,7 @@ static int send_eventnotice_command(FAR struct alt1250_s *dev, set_container_response(container, ltecmd->outparam, ltecmd->outparamlen); set_container_postproc(container, NULL, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_ioctl_fwupdate.c b/lte/alt1250/usock_handlers/alt1250_ioctl_fwupdate.c index 291c4ec6b..7fa67e298 100644 --- a/lte/alt1250/usock_handlers/alt1250_ioctl_fwupdate.c +++ b/lte/alt1250/usock_handlers/alt1250_ioctl_fwupdate.c @@ -445,7 +445,7 @@ int usockreq_ioctl_fwupdate(FAR struct alt1250_s *dev, ltecmd->outparamlen); set_container_postproc(container, postproc_hdlr, postproc_priv); - ret = altdevice_send_command(dev->altfd, container, usock_result); + ret = altdevice_send_command(dev, dev->altfd, container, usock_result); if (IS_NEED_CONTAINER_FREE(ret)) { diff --git a/lte/alt1250/usock_handlers/alt1250_ioctl_ifreq.c b/lte/alt1250/usock_handlers/alt1250_ioctl_ifreq.c index 1bae245f1..5e327043a 100644 --- a/lte/alt1250/usock_handlers/alt1250_ioctl_ifreq.c +++ b/lte/alt1250/usock_handlers/alt1250_ioctl_ifreq.c @@ -101,7 +101,7 @@ static int send_actpdn_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_actpdn, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -124,7 +124,7 @@ static int send_radio_command(FAR struct alt1250_s *dev, set_container_postproc(container, on ? postproc_radioon : postproc_radiooff, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -369,7 +369,7 @@ int send_reportnet_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, func, priv); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -391,7 +391,11 @@ int usockreq_ioctl_ifreq(FAR struct alt1250_s *dev, *usock_result = OK; *usock_xid = request->head.xid; - if (if_req->ifr_flags & IFF_UP) + if (!dev->usock_enable) + { + *usock_result = -ENOTTY; + } + else if (if_req->ifr_flags & IFF_UP) { ret = do_ifup(dev, req, usock_result, usock_xid, ackinfo); } diff --git a/lte/alt1250/usock_handlers/alt1250_ioctl_normal.c b/lte/alt1250/usock_handlers/alt1250_ioctl_normal.c index 7eaed8757..8c116833a 100644 --- a/lte/alt1250/usock_handlers/alt1250_ioctl_normal.c +++ b/lte/alt1250/usock_handlers/alt1250_ioctl_normal.c @@ -201,7 +201,7 @@ int send_lapi_command(FAR struct alt1250_s *dev, set_container_response(container, ltecmd->outparam, ltecmd->outparamlen); set_container_postproc(container, hdlr, priv); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } #ifdef CONFIG_LTE_ALT1250_ENABLE_HIBERNATION_MODE @@ -238,7 +238,7 @@ static int send_getversion_command(FAR struct alt1250_s *dev, set_container_response(container, alt1250_getevtarg(LTE_CMDID_GETVER), 2); set_container_postproc(container, postproc_fwgetversion, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -257,7 +257,7 @@ static int send_register_command(FAR struct alt1250_s *dev, set_container_response(container, ltecmd->outparam, ltecmd->outparamlen); set_container_postproc(container, postproc_setreport, index); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -355,6 +355,13 @@ static int lte_context_resume(FAR struct alt1250_s *dev, goto error; } + /* After the retry mode is disabled, the ALT1250 daemon can receive + * commands from the ALT1250 and the ALT1250 daemon is ready for normal + * operation, so the "is_resuming" flag is disabled. + */ + + dev->is_resuming = false; + /* If the ALT1250 is not powered on, return Resume as failure. */ power = altdevice_powercontrol(dev->altfd, LTE_CMDID_GET_POWER_STAT); @@ -376,10 +383,6 @@ static int lte_context_resume(FAR struct alt1250_s *dev, dbg_alt1250("Failed to send resume commands.\n"); } - /* Resume phase is over */ - - dev->is_resuming = false; - return ret; error: diff --git a/lte/alt1250/usock_handlers/alt1250_listenhdlr.c b/lte/alt1250/usock_handlers/alt1250_listenhdlr.c index 1475008d5..a3c3bed26 100644 --- a/lte/alt1250/usock_handlers/alt1250_listenhdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_listenhdlr.c @@ -65,7 +65,7 @@ static int send_listen_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_recvfromhdlr.c b/lte/alt1250/usock_handlers/alt1250_recvfromhdlr.c index 460287ae8..906a0b9bb 100644 --- a/lte/alt1250/usock_handlers/alt1250_recvfromhdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_recvfromhdlr.c @@ -142,7 +142,7 @@ static int send_recvfrom_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx++); set_container_postproc(container, postproc_recvfrom, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_sendtohdlr.c b/lte/alt1250/usock_handlers/alt1250_sendtohdlr.c index 9bd43b8a2..e47b26d9f 100644 --- a/lte/alt1250/usock_handlers/alt1250_sendtohdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_sendtohdlr.c @@ -71,7 +71,7 @@ static int send_sendto_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_setsockopthdlr.c b/lte/alt1250/usock_handlers/alt1250_setsockopthdlr.c index 72d033708..f4c5106b1 100644 --- a/lte/alt1250/usock_handlers/alt1250_setsockopthdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_setsockopthdlr.c @@ -67,7 +67,7 @@ static int send_setsockopt_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_shutdownhdlr.c b/lte/alt1250/usock_handlers/alt1250_shutdownhdlr.c index 5a3058b95..0c8a9765b 100644 --- a/lte/alt1250/usock_handlers/alt1250_shutdownhdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_shutdownhdlr.c @@ -64,7 +64,7 @@ static int send_shutdown_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_sockcommon, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** diff --git a/lte/alt1250/usock_handlers/alt1250_sms.c b/lte/alt1250/usock_handlers/alt1250_sms.c index 0a2dea196..610669cfc 100644 --- a/lte/alt1250/usock_handlers/alt1250_sms.c +++ b/lte/alt1250/usock_handlers/alt1250_sms.c @@ -172,7 +172,7 @@ static int send_smsinit_command(FAR struct alt1250_s *dev, set_container_response(container, &dummy_output, 1); set_container_postproc(container, func, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -197,7 +197,7 @@ static int send_smsfin_command(FAR struct alt1250_s *dev, set_container_response(container, &dummy_output, 1); set_container_postproc(container, func, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -239,7 +239,7 @@ static int send_smssend_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_smssend, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -270,7 +270,7 @@ static int send_smsdelete_command(FAR struct alt1250_s *dev, set_container_response(container, &dummy_output, 1); set_container_postproc(container, postproc_smsdelete, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -286,7 +286,7 @@ static int send_smsreportrecv_command(FAR struct alt1250_s *dev, set_container_ids(&container, 0, LTE_CMDID_SMS_REPORT_RECV); - return altdevice_send_command(dev->altfd, &container, usock_result); + return altdevice_send_command(dev, dev->altfd, &container, usock_result); } /**************************************************************************** @@ -728,7 +728,7 @@ int alt1250_sms_init(FAR struct alt1250_s *dev, FAR struct usock_s *usock, if (IS_SMS_UNAVAIL_FWVERSION(dev)) { dbg_alt1250("This ALT1250 FW version does not support SMS.\n"); - *usock_result = -ENOTSUP; + *usock_result = -EAFNOSUPPORT; return REP_SEND_ACK_WOFREE; } diff --git a/lte/alt1250/usock_handlers/alt1250_sockethdlr.c b/lte/alt1250/usock_handlers/alt1250_sockethdlr.c index d43e044b9..8d6321879 100644 --- a/lte/alt1250/usock_handlers/alt1250_sockethdlr.c +++ b/lte/alt1250/usock_handlers/alt1250_sockethdlr.c @@ -94,7 +94,7 @@ static int send_fctl_command(FAR struct alt1250_s *dev, set_container_postproc(container, cmd == ALTCOM_SETFL ? postproc_setfl : cmd == ALTCOM_GETFL ? postproc_getfl : NULL, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -331,7 +331,7 @@ static int send_socket_command(FAR struct alt1250_s *dev, set_container_response(container, USOCKET_REP_RESPONSE(usock), idx); set_container_postproc(container, postproc_socket, 0); - return altdevice_send_command(dev->altfd, container, usock_result); + return altdevice_send_command(dev, dev->altfd, container, usock_result); } /**************************************************************************** @@ -393,11 +393,11 @@ int usockreq_socket(FAR struct alt1250_s *dev, request->type != SOCK_CTRL) { /* If domain is AF_INET while usock_enable is false, - * set usockid to -EPROTONOSUPPORT to fallback kernel + * set usockid to -ENOTSUP to fallback kernel * network stack. */ - *usock_result = -EPROTONOSUPPORT; + *usock_result = -ENOTSUP; return REP_SEND_ACK_WOFREE; } diff --git a/lte/lapi/Kconfig b/lte/lapi/Kconfig index 61af77282..76125b2b4 100644 --- a/lte/lapi/Kconfig +++ b/lte/lapi/Kconfig @@ -21,7 +21,7 @@ config LTE_LAPI_KEEP_COMPATIBILITY default n ---help--- lte_get_operator_sync, lte_get_imsi_sync, lte_get_imei_sync, lte_get_phoneno_sync, - these functions have changed their specifications to specify the length of the + these functions have changed their specifications to specify the length of the argument string. Functions in the old spec will be discarded, but enabling this option makes you be able to use them. Furthermore, this option will be removed in the near future, and functions in @@ -45,5 +45,4 @@ config LTE_LAPI_ENABLE_DEPRECATED_API Deprecated APIs will be removed in the future, please use the synchronous API instead. -endif - +endif # LTE_LAPI diff --git a/math/gemmlowp/.gitignore b/math/gemmlowp/.gitignore deleted file mode 100644 index 72be90b84..000000000 --- a/math/gemmlowp/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/gemmlowp diff --git a/math/gemmlowp/CMakeLists.txt b/math/gemmlowp/CMakeLists.txt deleted file mode 100644 index acff6f113..000000000 --- a/math/gemmlowp/CMakeLists.txt +++ /dev/null @@ -1,46 +0,0 @@ -# ############################################################################## -# apps/math/gemmlowp/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_MATH_GEMMLOWP) - - # ############################################################################ - # Config and Fetch gemmlowp lib - # ############################################################################ - - set(GEMMLOWP_DIR ${CMAKE_CURRENT_LIST_DIR}/gemmlowp) - - if(NOT EXISTS ${GEMMLOWP_DIR}) - set(GEMMLOWP_URL - https://github.com/google/gemmlowp/archive/719139ce755a0f31cbf1c37f7f98adcc7fc9f425.zip - ) - FetchContent_Declare( - gemmlowp_fetch - URL ${GEMMLOWP_URL} SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/gemmlowp - BINARY_DIR ${CMAKE_BINARY_DIR}/apps/math/gemmlowp/gemmlowp - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(gemmlowp_fetch) - - if(NOT gemmlowp_fetch_POPULATED) - FetchContent_Populate(gemmlowp_fetch) - endif() - endif() -endif() diff --git a/math/gemmlowp/Kconfig b/math/gemmlowp/Kconfig deleted file mode 100644 index b4b4a5a4a..000000000 --- a/math/gemmlowp/Kconfig +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/math/gemmlowp/Kconfig -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -config MATH_GEMMLOWP - bool "Gemmlowp" - default n - ---help--- - Enable gemmlowp. diff --git a/math/kissfft/.gitignore b/math/kissfft/.gitignore deleted file mode 100644 index 2f47d6a3a..000000000 --- a/math/kissfft/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/kissfft diff --git a/math/kissfft/CMakeLists.txt b/math/kissfft/CMakeLists.txt deleted file mode 100644 index 07c8e5f06..000000000 --- a/math/kissfft/CMakeLists.txt +++ /dev/null @@ -1,74 +0,0 @@ -# ############################################################################## -# apps/math/kissfft/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_MATH_KISSFFT) - - # ############################################################################ - # Config and Fetch kissfft lib - # ############################################################################ - - set(KISSFFT_DIR ${CMAKE_CURRENT_LIST_DIR}/kissfft) - - if(NOT EXISTS ${KISSFFT_DIR}) - set(KISSFFT_URL - https://github.com/mborgerding/kissfft/archive/refs/tags/v130.zip) - FetchContent_Declare( - kissfft_fetch - URL ${KISSFFT_URL} SOURCE_DIR ${KISSFFT_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/math/kissfft/kissfft - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(kissfft_fetch) - - if(NOT kissfft_fetch_POPULATED) - FetchContent_Populate(kissfft_fetch) - - # Apply the patch after fetching the content - execute_process( - COMMAND ${CMAKE_COMMAND} -E echo "Applying patch to kissfft" - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) - - execute_process(COMMAND patch -d ${KISSFFT_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/kissfft.patch) - endif() - endif() - - # ############################################################################ - # Sources - # ############################################################################ - - set(CSRCS ${KISSFFT_DIR}/kiss_fft.c ${KISSFFT_DIR}/tools/kiss_fftr.c) - - # ############################################################################ - # Include Directory - # ############################################################################ - - set(INCDIR ${CMAKE_CURRENT_LIST_DIR}/kissfft) - - # ############################################################################ - # Library Configuration - # ############################################################################ - - nuttx_add_library(kissfft STATIC) - target_sources(kissfft PRIVATE ${CSRCS}) - target_include_directories(kissfft PUBLIC ${INCDIR}) - -endif() diff --git a/math/kissfft/kissfft.patch b/math/kissfft/kissfft.patch deleted file mode 100644 index 404d91f9e..000000000 --- a/math/kissfft/kissfft.patch +++ /dev/null @@ -1,116 +0,0 @@ -diff --git a/_kiss_fft_guts.h b/_kiss_fft_guts.h -index ba66144..1a0f4c2 100644 ---- a/_kiss_fft_guts.h -+++ b/_kiss_fft_guts.h -@@ -1,3 +1,6 @@ -+#ifndef _KISS_FFT_GUTS_H -+#define _KISS_FFT_GUTS_H -+ - /* - Copyright (c) 2003-2010, Mark Borgerding - -@@ -135,7 +138,7 @@ struct kiss_fft_state{ - #else - # define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) - # define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) --# define HALF_OF(x) ((x)*.5) -+# define HALF_OF(x) ((x)*(kiss_fft_scalar).5) - #endif - - #define kf_cexp(x,phase) \ -@@ -162,3 +165,4 @@ struct kiss_fft_state{ - #define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) - #define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) - #endif -+#endif // _KISS_FFT_GUTS_H -diff --git a/kiss_fft.c b/kiss_fft.c -index 465d6c9..9133a01 100644 ---- a/kiss_fft.c -+++ b/kiss_fft.c -@@ -375,7 +375,7 @@ void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout, - //It just performs an out-of-place FFT into a temp buffer - kiss_fft_cpx * tmpbuf = (kiss_fft_cpx*)KISS_FFT_TMP_ALLOC( sizeof(kiss_fft_cpx)*st->nfft); - kf_work(tmpbuf,fin,1,in_stride, st->factors,st); -- memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); -+ /* memcpy(fout,tmpbuf,sizeof(kiss_fft_cpx)*st->nfft); */ - KISS_FFT_TMP_FREE(tmpbuf); - }else{ - kf_work( fout, fin, 1,in_stride, st->factors,st ); -diff --git a/kiss_fft.h b/kiss_fft.h -index 64c50f4..24e4d0c 100644 ---- a/kiss_fft.h -+++ b/kiss_fft.h -@@ -7,7 +7,7 @@ - #include - - #ifdef __cplusplus --extern "C" { -+extern "C++" { - #endif - - /* -@@ -29,13 +29,13 @@ extern "C" { - #define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) - #define KISS_FFT_FREE _mm_free - #else --#define KISS_FFT_MALLOC malloc --#define KISS_FFT_FREE free -+#define KISS_FFT_MALLOC(X) (void*)(0x0) /* Patched. */ -+#define KISS_FFT_FREE(X) /* Patched. */ - #endif - - - #ifdef FIXED_POINT --#include -+#include /* Patched. */ - # if (FIXED_POINT == 32) - # define kiss_fft_scalar int32_t - # else -diff --git a/tools/kiss_fftr.c b/tools/kiss_fftr.c -index b8e238b..0d22a04 100644 ---- a/tools/kiss_fftr.c -+++ b/tools/kiss_fftr.c -@@ -31,7 +31,7 @@ kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem,size_t * lenme - size_t subsize, memneeded; - - if (nfft & 1) { -- fprintf(stderr,"Real FFT optimization must be even.\n"); -+ /* fprintf(stderr,"Real FFT optimization must be even.\n"); */ - return NULL; - } - nfft >>= 1; -@@ -71,8 +71,8 @@ void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_cpx *fr - kiss_fft_cpx fpnk,fpk,f1k,f2k,tw,tdc; - - if ( st->substate->inverse) { -- fprintf(stderr,"kiss fft usage error: improper alloc\n"); -- exit(1); -+ /* fprintf(stderr,"kiss fft usage error: improper alloc\n"); */ -+ return; /* exit(1); */ - } - - ncfft = st->substate->nfft; -@@ -126,8 +126,8 @@ void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_cpx *freqdata,kiss_fft_scalar *t - int k, ncfft; - - if (st->substate->inverse == 0) { -- fprintf (stderr, "kiss fft usage error: improper alloc\n"); -- exit (1); -+ /* fprintf (stderr, "kiss fft usage error: improper alloc\n"); */ -+ return; /* exit (1); */ - } - - ncfft = st->substate->nfft; -diff --git a/tools/kiss_fftr.h b/tools/kiss_fftr.h -index 72e5a57..b888a28 100644 ---- a/tools/kiss_fftr.h -+++ b/tools/kiss_fftr.h -@@ -3,7 +3,7 @@ - - #include "kiss_fft.h" - #ifdef __cplusplus --extern "C" { -+extern "C++" { - #endif - - diff --git a/math/libtommath/Makefile b/math/libtommath/Makefile index 4c54d99ed..f729ba4ad 100644 --- a/math/libtommath/Makefile +++ b/math/libtommath/Makefile @@ -53,12 +53,10 @@ bn_s_mp_rand_jenkins.c bn_s_mp_rand_platform.c bn_s_mp_reverse.c bn_s_mp_sqr.c b bn_s_mp_sub.c bn_s_mp_toom_mul.c bn_s_mp_toom_sqr.c VPATH += $(LIBTOMMATH_UNPACKNAME) -DEPPATH += --dep-path $(LIBTOMMATH_UNPACKNAME) ifneq ($(CONFIG_LIBTOMMATH_DEMOS),) CSRCS += shared.c VPATH += $(LIBTOMMATH_UNPACKNAME)/demo -DEPPATH += --dep-path $(LIBTOMMATH_UNPACKNAME)/demo ifneq ($(CONFIG_LIBTOMMATH_TEST),) MAINSRC += test.c @@ -87,7 +85,6 @@ endif ifneq ($(CONFIG_LIBTOMMATH_MTEST),) MAINSRC += mtest.c VPATH += $(LIBTOMMATH_UNPACKNAME)/mtest -DEPPATH += --dep-path $(LIBTOMMATH_UNPACKNAME)/mtest PROGNAME += $(CONFIG_LIBTOMMATH_MTEST_PROGNAME) PRIORITY += $(CONFIG_LIBTOMMATH_MTEST_PRIORITY) diff --git a/math/ruy/.gitignore b/math/ruy/.gitignore deleted file mode 100644 index 8566c611d..000000000 --- a/math/ruy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/ruy diff --git a/mlearning/cmsis-nn/.gitignore b/mlearning/cmsis-nn/.gitignore deleted file mode 100644 index 3a811c638..000000000 --- a/mlearning/cmsis-nn/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/cmsis-nn diff --git a/mlearning/cmsis-nn/CMakeLists.txt b/mlearning/cmsis-nn/CMakeLists.txt deleted file mode 100644 index c5944620d..000000000 --- a/mlearning/cmsis-nn/CMakeLists.txt +++ /dev/null @@ -1,90 +0,0 @@ -# ############################################################################## -# apps/mlearning/cmsis-nn/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_MLEARNING_CMSIS_NN) - - # ############################################################################ - # Config and Fetch CMSIS-NN lib - # ############################################################################ - - set(CMSIS_NN_DIR ${CMAKE_CURRENT_LIST_DIR}/cmsis-nn) - - if(NOT EXISTS ${CMSIS_NN_DIR}) - set(CMSIS_NN_URL - https://github.com/ARM-software/CMSIS-NN/archive/72e1ebf623ab1660a3e14e4e36fdcddce46f1991.zip - ) - FetchContent_Declare( - cmsis_nn_fetch - URL ${CMSIS_NN_URL} SOURCE_DIR ${CMSIS_NN_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/mlearning/cmsis-nn/cmsis-nn - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(cmsis_nn_fetch) - - if(NOT cmsis_nn_fetch_POPULATED) - FetchContent_Populate(cmsis_nn_fetch) - endif() - endif() - - # ############################################################################ - # Flags - # ############################################################################ - - set(CFLAGS -Wno-undef -O3) - - # ############################################################################ - # Sources - # ############################################################################ - - file( - GLOB - CMSIS_NN_SRCS - ${CMSIS_NN_DIR}/Source/ActivationFunctions/*.c - ${CMSIS_NN_DIR}/Source/BasicMathFunctions/*.c - ${CMSIS_NN_DIR}/Source/PoolingFunctions/*.c - ${CMSIS_NN_DIR}/Source/ConvolutionFunctions/*.c - ${CMSIS_NN_DIR}/Source/SVDFunctions/*.c - ${CMSIS_NN_DIR}/Source/FullyConnectedFunctions/*.c - ${CMSIS_NN_DIR}/Source/NNSupportFunctions/*.c - ${CMSIS_NN_DIR}/Source/ConcatenationFunctions/*.c - ${CMSIS_NN_DIR}/Source/SoftmaxFunctions/*.c - ${CMSIS_NN_DIR}/Source/LSTMFunctions/*.c - ${CMSIS_NN_DIR}/Source/ReshapeFunctions/*.c) - - if(CONFIG_ARM_NEON) - list( - REMOVE_ITEM - CMSIS_NN_SRCS - ${CMSIS_NN_DIR}/Source/BasicMathFunctions/arm_elementwise_add_s8.c - ${CMSIS_NN_DIR}/Source/ConvolutionFunctions/arm_convolve_s8.c - ${CMSIS_NN_DIR}/Source/NNSupportFunctions/arm_nn_mat_mult_kernel_s8_s16.c - ${CMSIS_NN_DIR}/Source/NNSupportFunctions/arm_q7_to_q15_with_offset.c) - endif() - - # ############################################################################ - # Library Configuration - # ############################################################################ - - nuttx_add_library(cmsis_nn STATIC) - target_compile_options(cmsis_nn PRIVATE ${CFLAGS}) - target_sources(cmsis_nn PRIVATE ${CMSIS_NN_SRCS}) - -endif() diff --git a/mlearning/cmsis-nn/Kconfig b/mlearning/cmsis-nn/Kconfig deleted file mode 100644 index 1500f7d07..000000000 --- a/mlearning/cmsis-nn/Kconfig +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/mlearning/cmsis-nn/Kconfig -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -config MLEARNING_CMSIS_NN - bool "CMSIS_NN Library" - default n - ---help--- - Enable CMSIS_NN. diff --git a/mlearning/cmsis-nn/Make.defs b/mlearning/cmsis-nn/Make.defs deleted file mode 100644 index 669ca73a2..000000000 --- a/mlearning/cmsis-nn/Make.defs +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/mlearning/cmsis/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_MLEARNING_CMSIS_NN),) -CONFIGURED_APPS += $(APPDIR)/mlearning/cmsis-nn -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/mlearning/cmsis-nn/cmsis-nn/Include -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/mlearning/cmsis-nn/cmsis-nn/Include -endif diff --git a/mlearning/cmsis-nn/Makefile b/mlearning/cmsis-nn/Makefile deleted file mode 100644 index f45d1b1e0..000000000 --- a/mlearning/cmsis-nn/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -############################################################################ -# apps/mlearning/cmsis-nn/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -CMSIS_NN = cmsis-nn/Source - -CMSIS_NN_VER = 72e1ebf623ab1660a3e14e4e36fdcddce46f1991 - -cmsis-nn.zip: - $(Q) curl -L https://github.com/ARM-software/CMSIS-NN/archive/$(CMSIS_NN_VER).zip -o cmsis-nn.zip - $(Q) unzip -o cmsis-nn.zip - $(Q) mv CMSIS-NN-$(CMSIS_NN_VER) cmsis-nn - -ifeq ($(wildcard cmsis-nn/.git),) -context:: cmsis-nn.zip -distclean:: - $(call DELDIR, cmsis-nn) - $(call DELFILE, cmsis-nn.zip) -endif - -CFLAGS += -Wno-undef -CFLAGS += -O3 - -CSRCS += $(wildcard $(CMSIS_NN)/ActivationFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/BasicMathFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/PoolingFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/ConvolutionFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/SVDFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/FullyConnectedFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/NNSupportFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/ConcatenationFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/SoftmaxFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/LSTMFunctions/*.c) -CSRCS += $(wildcard $(CMSIS_NN)/ReshapeFunctions/*.c) - -ifeq ($(CONFIG_ARM_NEON),y) -EXCLUDED_FILES := arm_elementwise_add_s8.c arm_convolve_s8.c arm_nn_mat_mult_kernel_s8_s16.c arm_q7_to_q15_with_offset.c -CSRCS := $(filter-out $(addprefix $(CMSIS_NN)/BasicMathFunctions/, $(EXCLUDED_FILES)), $(CSRCS)) -CSRCS := $(filter-out $(addprefix $(CMSIS_NN)/NNSupportFunctions/, $(EXCLUDED_FILES)), $(CSRCS)) -CSRCS := $(filter-out $(addprefix $(CMSIS_NN)/ConvolutionFunctions/, $(EXCLUDED_FILES)), $(CSRCS)) -endif - -include $(APPDIR)/Application.mk \ No newline at end of file diff --git a/mlearning/tflite-micro/.gitignore b/mlearning/tflite-micro/.gitignore deleted file mode 100644 index 60853abb5..000000000 --- a/mlearning/tflite-micro/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/tflite-micro \ No newline at end of file diff --git a/mlearning/tflite-micro/0001-dequantize-int8.patch b/mlearning/tflite-micro/0001-dequantize-int8.patch deleted file mode 100644 index 92babecac..000000000 --- a/mlearning/tflite-micro/0001-dequantize-int8.patch +++ /dev/null @@ -1,101 +0,0 @@ -From 0cd2a39a346d84da3002fa7ba4085cfc3c61c8ee Mon Sep 17 00:00:00 2001 -From: jihandong -Date: Mon, 22 Apr 2024 18:14:44 +0800 -Subject: [PATCH 2/2] dequantize int8 - -VELAPLATFO-30990 - -Change-Id: I0e741a72464c7e497425175d2fcd63f14ed6897b -Signed-off-by: jihandong ---- - tensorflow/lite/micro/kernels/dequantize.cc | 21 +++++++++++++++++++ - tensorflow/lite/micro/kernels/dequantize.h | 5 ++++- - .../lite/micro/micro_mutable_op_resolver.h | 6 ++++-- - 3 files changed, 29 insertions(+), 3 deletions(-) - -diff --git a/tensorflow/lite/micro/kernels/dequantize.cc b/tensorflow/lite/micro/kernels/dequantize.cc -index 428c866a..48f50de4 100644 ---- a/tensorflow/lite/micro/kernels/dequantize.cc -+++ b/tensorflow/lite/micro/kernels/dequantize.cc -@@ -76,9 +76,30 @@ TfLiteStatus DequantizeEval(TfLiteContext* context, TfLiteNode* node) { - return kTfLiteOk; - } - -+TfLiteStatus DequantizeEvalInt8(TfLiteContext* context, TfLiteNode* node) { -+ TFLITE_DCHECK(node->user_data != nullptr); -+ DequantizeOpData* data = static_cast(node->user_data); -+ -+ const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0); -+ TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, 0); -+ -+ TFLITE_DCHECK(input->type == kTfLiteInt8 && output->type == kTfLiteFloat32); -+ reference_ops::Dequantize(data->quantization_params, -+ tflite::micro::GetTensorShape(input), -+ tflite::micro::GetTensorData(input), -+ tflite::micro::GetTensorShape(output), -+ tflite::micro::GetTensorData(output)); -+ return kTfLiteOk; -+} -+ - TFLMRegistration Register_DEQUANTIZE() { - return tflite::micro::RegisterOp(DequantizeInit, DequantizePrepare, - DequantizeEval); - } - -+TFLMRegistration Register_DEQUANTIZE_INT8() { -+ return tflite::micro::RegisterOp(DequantizeInit, DequantizePrepare, -+ DequantizeEvalInt8); -+} -+ - } // namespace tflite -diff --git a/tensorflow/lite/micro/kernels/dequantize.h b/tensorflow/lite/micro/kernels/dequantize.h -index fe6ec169..3dede725 100644 ---- a/tensorflow/lite/micro/kernels/dequantize.h -+++ b/tensorflow/lite/micro/kernels/dequantize.h -@@ -17,8 +17,8 @@ limitations under the License. - #define TENSORFLOW_LITE_MICRO_KERNELS_DEQUANTIZE_H_ - - #include "tensorflow/lite/c/builtin_op_data.h" --#include "tensorflow/lite/c/common.h" - #include "tensorflow/lite/kernels/internal/types.h" -+#include "tensorflow/lite/micro/micro_common.h" - - namespace tflite { - -@@ -33,6 +33,9 @@ struct DequantizeOpData { - - TfLiteStatus DequantizePrepare(TfLiteContext* context, TfLiteNode* node); - -+TFLMRegistration Register_DEQUANTIZE(); -+TFLMRegistration Register_DEQUANTIZE_INT8(); -+ - } // namespace tflite - - #endif // TENSORFLOW_LITE_MICRO_KERNELS_DEQUANTIZE_H_ -diff --git a/tensorflow/lite/micro/micro_mutable_op_resolver.h b/tensorflow/lite/micro/micro_mutable_op_resolver.h -index f5f6e38e..b3e3cbcf 100644 ---- a/tensorflow/lite/micro/micro_mutable_op_resolver.h -+++ b/tensorflow/lite/micro/micro_mutable_op_resolver.h -@@ -26,6 +26,7 @@ limitations under the License. - #include "tensorflow/lite/micro/kernels/add.h" - #include "tensorflow/lite/micro/kernels/conv.h" - #include "tensorflow/lite/micro/kernels/depthwise_conv.h" -+#include "tensorflow/lite/micro/kernels/dequantize.h" - #include "tensorflow/lite/micro/kernels/ethosu.h" - #include "tensorflow/lite/micro/kernels/fully_connected.h" - #include "tensorflow/lite/micro/kernels/micro_ops.h" -@@ -217,8 +218,9 @@ class MicroMutableOpResolver : public MicroOpResolver { - ParseDepthwiseConv2D); - } - -- TfLiteStatus AddDequantize() { -- return AddBuiltin(BuiltinOperator_DEQUANTIZE, tflite::Register_DEQUANTIZE(), -+ TfLiteStatus AddDequantize( -+ const TFLMRegistration& registration = Register_DEQUANTIZE()) { -+ return AddBuiltin(BuiltinOperator_DEQUANTIZE, registration, - ParseDequantize); - } - --- -2.25.1 - diff --git a/mlearning/tflite-micro/0002-quantize-int8.patch b/mlearning/tflite-micro/0002-quantize-int8.patch deleted file mode 100644 index 138eea987..000000000 --- a/mlearning/tflite-micro/0002-quantize-int8.patch +++ /dev/null @@ -1,108 +0,0 @@ -From b7c954c7594b9a39df5604dbadf6e59b6f98b1e9 Mon Sep 17 00:00:00 2001 -From: xinhaiteng -Date: Wed, 24 Apr 2024 09:18:52 +0800 -Subject: [PATCH] tflite: add quantize float32 to int8 operator - -VELAPLATFO-30990 - -Separate the 'Float32 to Int8' implementation of the 'quantize' operator to reduce the code size. - -Change-Id: I83dc809d36587741f3087b25e83e454b30f9626b -Signed-off-by: xinhaiteng ---- - tensorflow/lite/micro/kernels/quantize.cc | 5 +++++ - tensorflow/lite/micro/kernels/quantize.h | 4 ++++ - tensorflow/lite/micro/kernels/quantize_common.cc | 16 ++++++++++++++++ - .../lite/micro/micro_mutable_op_resolver.h | 7 ++++--- - 4 files changed, 29 insertions(+), 3 deletions(-) - -diff --git a/tensorflow/lite/micro/kernels/quantize.cc b/tensorflow/lite/micro/kernels/quantize.cc -index ba11f19b6..a6ff4f055 100644 ---- a/tensorflow/lite/micro/kernels/quantize.cc -+++ b/tensorflow/lite/micro/kernels/quantize.cc -@@ -39,4 +39,9 @@ TFLMRegistration Register_QUANTIZE() { - InitQuantizeReference, PrepareQuantizeReference, EvalQuantizeReference); - } - -+TFLMRegistration Register_QUANTIZE_FLOAT32_INT8() { -+ return tflite::micro::RegisterOp( -+ InitQuantizeReference, PrepareQuantizeReference, EvalQuantizeReferenceFloat32ToInt8); -+} -+ - } // namespace tflite -diff --git a/tensorflow/lite/micro/kernels/quantize.h b/tensorflow/lite/micro/kernels/quantize.h -index ba93809a2..b97e4a2ab 100644 ---- a/tensorflow/lite/micro/kernels/quantize.h -+++ b/tensorflow/lite/micro/kernels/quantize.h -@@ -17,6 +17,7 @@ limitations under the License. - - #include "tensorflow/lite/c/common.h" - #include "tensorflow/lite/kernels/internal/types.h" -+#include "tensorflow/lite/micro/micro_common.h" - - namespace tflite { - -@@ -31,7 +32,10 @@ struct OpDataQuantizeReference { - }; - - TfLiteStatus EvalQuantizeReference(TfLiteContext* context, TfLiteNode* node); -+TfLiteStatus EvalQuantizeReferenceFloat32ToInt8(TfLiteContext* context, TfLiteNode* node); - TfLiteStatus PrepareQuantizeReference(TfLiteContext* context, TfLiteNode* node); -+ -+TFLMRegistration Register_QUANTIZE_FLOAT32_INT8(); - } // namespace tflite - - #endif // TENSORFLOW_LITE_MICRO_KERNELS_QUANTIZE_H_ -diff --git a/tensorflow/lite/micro/kernels/quantize_common.cc b/tensorflow/lite/micro/kernels/quantize_common.cc -index cb04eafce..6bdd0df39 100644 ---- a/tensorflow/lite/micro/kernels/quantize_common.cc -+++ b/tensorflow/lite/micro/kernels/quantize_common.cc -@@ -236,4 +236,20 @@ TfLiteStatus EvalQuantizeReference(TfLiteContext* context, TfLiteNode* node) { - return kTfLiteOk; - } - -+TfLiteStatus EvalQuantizeReferenceFloat32ToInt8(TfLiteContext* context, TfLiteNode* node) { -+ TFLITE_DCHECK(node->user_data != nullptr); -+ auto* data = static_cast(node->user_data); -+ -+ const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0); -+ TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, 0); -+ -+ TFLITE_DCHECK(input->type == kTfLiteFloat32 && output->type == kTfLiteInt8); -+ reference_ops::AffineQuantize( -+ data->quantization_params, tflite::micro::GetTensorShape(input), -+ tflite::micro::GetTensorData(input), -+ tflite::micro::GetTensorShape(output), -+ tflite::micro::GetTensorData(output)); -+ return kTfLiteOk; -+} -+ - } // namespace tflite -diff --git a/tensorflow/lite/micro/micro_mutable_op_resolver.h b/tensorflow/lite/micro/micro_mutable_op_resolver.h -index b3e3cbcf8..ec8979c4e 100644 ---- a/tensorflow/lite/micro/micro_mutable_op_resolver.h -+++ b/tensorflow/lite/micro/micro_mutable_op_resolver.h -@@ -32,6 +32,7 @@ limitations under the License. - #include "tensorflow/lite/micro/kernels/micro_ops.h" - #include "tensorflow/lite/micro/kernels/mul.h" - #include "tensorflow/lite/micro/kernels/pooling.h" -+#include "tensorflow/lite/micro/kernels/quantize.h" - #include "tensorflow/lite/micro/kernels/reduce.h" - #include "tensorflow/lite/micro/kernels/softmax.h" - #include "tensorflow/lite/micro/kernels/transpose_conv.h" -@@ -481,9 +482,9 @@ class MicroMutableOpResolver : public MicroOpResolver { - ParsePrelu); - } - -- TfLiteStatus AddQuantize() { -- return AddBuiltin(BuiltinOperator_QUANTIZE, Register_QUANTIZE(), -- ParseQuantize); -+ TfLiteStatus AddQuantize( -+ const TFLMRegistration& registration = Register_QUANTIZE()) { -+ return AddBuiltin(BuiltinOperator_QUANTIZE, registration, ParseQuantize); - } - - TfLiteStatus AddReadVariable() { --- -2.25.1 - diff --git a/mlearning/tflite-micro/0003-mean-int8.patch b/mlearning/tflite-micro/0003-mean-int8.patch deleted file mode 100644 index de45afe8b..000000000 --- a/mlearning/tflite-micro/0003-mean-int8.patch +++ /dev/null @@ -1,112 +0,0 @@ -From 9507345939722d4bc2f2791394217680fc5c987b Mon Sep 17 00:00:00 2001 -From: xinhaiteng -Date: Wed, 24 Apr 2024 09:26:54 +0800 -Subject: [PATCH] tflite: add mean-int8 operator - -VELAPLATFO-30990 - -Separate the Int8 implementation of the 'mean' operator to reduce the code size. - -Change-Id: I5eb9e3cc939668b6531ef9e56f7c32090f1de141 -Signed-off-by: xinhaiteng ---- - tensorflow/lite/micro/kernels/reduce.cc | 9 +++++++++ - tensorflow/lite/micro/kernels/reduce.h | 3 +++ - tensorflow/lite/micro/kernels/reduce_common.cc | 16 ++++++++++++++++ - .../lite/micro/micro_mutable_op_resolver.h | 5 +++-- - 4 files changed, 31 insertions(+), 2 deletions(-) - -diff --git a/tensorflow/lite/micro/kernels/reduce.cc b/tensorflow/lite/micro/kernels/reduce.cc -index a689d3b93..090bafc3c 100644 ---- a/tensorflow/lite/micro/kernels/reduce.cc -+++ b/tensorflow/lite/micro/kernels/reduce.cc -@@ -49,6 +49,11 @@ TfLiteStatus EvalMean(TfLiteContext* context, TfLiteNode* node) { - static_cast(node->user_data)); - } - -+TfLiteStatus EvalMeanInt8(TfLiteContext* context, TfLiteNode* node) { -+ return EvalMeanHelperInt8(context, node, -+ static_cast(node->user_data)); -+} -+ - TfLiteStatus EvalMax(TfLiteContext* context, TfLiteNode* node) { - OpDataReduce* op_data = static_cast(node->user_data); - return EvalMaxHelper(context, node, op_data); -@@ -63,6 +68,10 @@ TFLMRegistration Register_MEAN() { - return tflite::micro::RegisterOp(InitReduce, PrepareMeanOrSum, EvalMean); - } - -+TFLMRegistration Register_MEAN_INT8() { -+ return tflite::micro::RegisterOp(InitReduce, PrepareMeanOrSum, EvalMeanInt8); -+} -+ - TFLMRegistration Register_REDUCE_MAX() { - return tflite::micro::RegisterOp(InitReduce, PrepareMax, EvalMax); - } -diff --git a/tensorflow/lite/micro/kernels/reduce.h b/tensorflow/lite/micro/kernels/reduce.h -index 2daeef5fe..0e29b3af8 100644 ---- a/tensorflow/lite/micro/kernels/reduce.h -+++ b/tensorflow/lite/micro/kernels/reduce.h -@@ -50,6 +50,8 @@ TfLiteStatus EvalMaxHelper(TfLiteContext* context, TfLiteNode* node, - OpDataReduce* op_data); - TfLiteStatus EvalMeanHelper(TfLiteContext* context, TfLiteNode* node, - OpDataReduce* op_data); -+TfLiteStatus EvalMeanHelperInt8(TfLiteContext* context, TfLiteNode* node, -+ OpDataReduce* op_data); - TfLiteStatus EvalSumHelper(TfLiteContext* context, TfLiteNode* node, - OpDataReduce* op_data); - -@@ -57,6 +59,7 @@ void ReduceResolveAxis(const int* axis_data, int axis_count, - MeanParams* op_params); - - TFLMRegistration Register_MEAN(); -+TFLMRegistration Register_MEAN_INT8(); - TFLMRegistration Register_REDUCE_MAX(); - TFLMRegistration Register_SUM(); - -diff --git a/tensorflow/lite/micro/kernels/reduce_common.cc b/tensorflow/lite/micro/kernels/reduce_common.cc -index 2c1a92a50..6e4ab1cc9 100644 ---- a/tensorflow/lite/micro/kernels/reduce_common.cc -+++ b/tensorflow/lite/micro/kernels/reduce_common.cc -@@ -236,6 +236,22 @@ TfLiteStatus EvalMeanHelper(TfLiteContext* context, TfLiteNode* node, - return kTfLiteOk; - } - -+TfLiteStatus EvalMeanHelperInt8(TfLiteContext* context, TfLiteNode* node, -+ OpDataReduce* op_data) { -+ const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0); -+ const TfLiteEvalTensor* axis = tflite::micro::GetEvalInput(context, node, 1); -+ -+ int num_axis = static_cast(ElementCount(*axis->dims)); -+ int temp_index[kMaxNumberOfAxis]; -+ int resolved_axis[kMaxNumberOfReducedAxis]; -+ -+ TFLITE_DCHECK(input->type == kTfLiteInt8); -+ TF_LITE_ENSURE_OK( -+ context, EvalIntegerMean(context, node, num_axis, op_data, -+ temp_index, resolved_axis)); -+ return kTfLiteOk; -+} -+ - TfLiteStatus EvalMaxHelper(TfLiteContext* context, TfLiteNode* node, - OpDataReduce* op_data) { - const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, 0); -diff --git a/tensorflow/lite/micro/micro_mutable_op_resolver.h b/tensorflow/lite/micro/micro_mutable_op_resolver.h -index ec8979c4e..253f83de1 100644 ---- a/tensorflow/lite/micro/micro_mutable_op_resolver.h -+++ b/tensorflow/lite/micro/micro_mutable_op_resolver.h -@@ -432,8 +432,9 @@ class MicroMutableOpResolver : public MicroOpResolver { - ParseMirrorPad); - } - -- TfLiteStatus AddMean() { -- return AddBuiltin(BuiltinOperator_MEAN, Register_MEAN(), ParseReducer); -+ TfLiteStatus AddMean( -+ const TFLMRegistration& registration = Register_MEAN()) { -+ return AddBuiltin(BuiltinOperator_MEAN, registration, ParseReducer); - } - - TfLiteStatus AddMinimum() { --- -2.25.1 - diff --git a/mlearning/tflite-micro/CMakeLists.txt b/mlearning/tflite-micro/CMakeLists.txt deleted file mode 100644 index c52d492d0..000000000 --- a/mlearning/tflite-micro/CMakeLists.txt +++ /dev/null @@ -1,164 +0,0 @@ -# ############################################################################## -# apps/mlearning/tflite-micro/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_TFLITEMICRO) - - # ############################################################################ - # Config and Fetch TFLITE-MICRO - # ############################################################################ - - set(TFLITE_MICRO_DIR ${CMAKE_CURRENT_LIST_DIR}/tflite-micro) - - if(NOT EXISTS ${TFLITE_MICRO_DIR}) - set(TFLITE_MICRO_URL - https://github.com/tensorflow/tflite-micro/archive/cfa4c91d1b36c37c7c104b9c664615e59f1abfe3.zip - ) - FetchContent_Declare( - tflite_micro_fetch - URL ${TFLITE_MICRO_URL} SOURCE_DIR ${TFLITE_MICRO_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/mlearning/tflite-micro/tflite-micro - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(tflite_micro_fetch) - - if(NOT tflite_micro_fetch_POPULATED) - FetchContent_Populate(tflite_micro_fetch) - - # Apply the patch after fetching the content - execute_process( - COMMAND ${CMAKE_COMMAND} -E echo "Applying patch to tflite-micro" - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) - execute_process(COMMAND patch -d ${TFLITE_MICRO_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/tflite-micro.patch) - execute_process( - COMMAND patch -d ${TFLITE_MICRO_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/0001-dequantize-int8.patch) - execute_process( - COMMAND patch -d ${TFLITE_MICRO_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/0002-quantize-int8.patch) - execute_process(COMMAND patch -d ${TFLITE_MICRO_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/0003-mean-int8.patch) - endif() - endif() - - # ############################################################################ - # Flags - # ############################################################################ - - set(COMMON_FLAGS - -DTF_LITE_STATIC_MEMORY - -DTF_LITE_DISABLE_X86_NEON - -DTF_LITE_STRIP_ERROR_STRINGS - -Wno-sign-compare - -Wno-unused-variable - -Wno-undef - -Wno-shadow - -O3) - - if(CONFIG_MLEARNING_CMSIS_NN) - list(APPEND COMMON_FLAGS -DCMSIS_NN) - endif() - - # ############################################################################ - # Sources - # ############################################################################ - - file( - GLOB - TFLITE_MICRO_SRCS - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/kernels/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/c/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/schema/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/core/c/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/kernels/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/kernels/internal/optimized/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/kernels/internal/reference/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/kernels/internal/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/core/api/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/arena_allocator/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/memory_planner/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/*.cc - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/tflite_bridge/*.cc) - - # Remove test file - list(FILTER TFLITE_MICRO_SRCS EXCLUDE REGEX ".*test.cc") - - if(CONFIG_MLEARNING_CMSIS_NN) - list(APPEND COMMON_FLAGS -DCMSIS_NN) - - file(GLOB CMSIS_NN_SRCS - ${TFLITE_MICRO_DIR}/tensorflow/lite/micro/kernels/cmsis_nn/*.cc) - - # Remove the directory and get only filename - set(CMSIS_NN_FILENAMES) - foreach(file ${CMSIS_NN_SRCS}) - get_filename_component(filename ${file} NAME) - list(APPEND CMSIS_NN_FILENAMES ${filename}) - endforeach() - - # Remove files with the same filename without the directory - set(NEW_TFLITE_MICRO_SRCS) - foreach(file ${TFLITE_MICRO_SRCS}) - get_filename_component(filename ${file} NAME) - if(NOT filename IN_LIST CMSIS_NN_FILENAMES) - list(APPEND NEW_TFLITE_MICRO_SRCS ${file}) - endif() - endforeach() - - # 添加CMSIS_NN文件 - list(APPEND NEW_TFLITE_MICRO_SRCS ${CMSIS_NN_SRCS}) - set(TFLITE_MICRO_SRCS ${NEW_TFLITE_MICRO_SRCS}) - - if(CONFIG_ARM_NEON) - list( - APPEND - TFLITE_MICRO_SRCS - ${TFLITE_MICRO_DIR}/operators/neon/arm_convolve_s8.c - ${TFLITE_MICRO_DIR}/operators/neon/arm_nn_mat_mult_kernel_s8_s16.c - ${TFLITE_MICRO_DIR}/operators/neon/arm_q7_to_q15_with_offset.c - ${TFLITE_MICRO_DIR}/operators/neon/arm_elementwise_add_s8.c) - endif() - endif() - - # ############################################################################ - # Include Directory - # ############################################################################ - - set(INCDIR - ${CMAKE_BINARY_DIR}/apps/math/gemmlowp/gemmlowp - ${CMAKE_BINARY_DIR}/apps/math/ruy/ruy - ${CMAKE_BINARY_DIR}/apps/math/kissfft/kissfft - ${CMAKE_BINARY_DIR}/apps/math/tflite-micro/tflite-micro) - - if(CONFIG_MLEARNING_CMSIS_NN) - list(APPEND INCDIR ${CMAKE_BINARY_DIR}/apps/mlearning/cmsis-nn/cmsis-nn) - endif() - - # ############################################################################ - # Library Configuration - # ############################################################################ - - nuttx_add_library(tflite_micro STATIC) - target_compile_options(tflite_micro PRIVATE ${COMMON_FLAGS}) - target_sources(tflite_micro PRIVATE ${TFLITE_MICRO_SRCS}) - target_include_directories(tflite_micro PUBLIC ${INCDIR}) - -endif() diff --git a/mlearning/tflite-micro/Kconfig b/mlearning/tflite-micro/Kconfig deleted file mode 100644 index 15b841ef6..000000000 --- a/mlearning/tflite-micro/Kconfig +++ /dev/null @@ -1,24 +0,0 @@ -############################################################################ -# apps/mlearning/tflite-micro/Kconfig -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -config TFLITEMICRO - bool "TFLiteMicro" - default n - depends on SYSTEM_FLATBUFFERS && MATH_GEMMLOWP && MATH_KISSFFT && MATH_RUY diff --git a/mlearning/tflite-micro/Make.defs b/mlearning/tflite-micro/Make.defs deleted file mode 100644 index bd3752539..000000000 --- a/mlearning/tflite-micro/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/mlearning/tflite-micro/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_TFLITEMICRO),) -CONFIGURED_APPS += $(APPDIR)/mlearning/tflite-micro -endif diff --git a/mlearning/tflite-micro/Makefile b/mlearning/tflite-micro/Makefile deleted file mode 100644 index c016ed8c8..000000000 --- a/mlearning/tflite-micro/Makefile +++ /dev/null @@ -1,98 +0,0 @@ -############################################################################ -# apps/mlearning/tflite-micro/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -TFLITE_MICRO_VER = cfa4c91d1b36c37c7c104b9c664615e59f1abfe3 -TFLITE_MICRO_UNPACK = tflite-micro - -tflite-micro.zip: - $(Q) curl -L https://github.com/tensorflow/tflite-micro/archive/$(TFLITE_MICRO_VER).zip -o tflite-micro.zip - $(Q) unzip -o tflite-micro.zip - $(Q) mv tflite-micro-$(TFLITE_MICRO_VER) tflite-micro - $(Q) patch -d $(TFLITE_MICRO_UNPACK) -p1 < tflite-micro.patch - $(Q) patch -d $(TFLITE_MICRO_UNPACK) -p1 < 0001-dequantize-int8.patch - $(Q) patch -d $(TFLITE_MICRO_UNPACK) -p1 < 0002-quantize-int8.patch - $(Q) patch -d $(TFLITE_MICRO_UNPACK) -p1 < 0003-mean-int8.patch - -# Download and unpack tarball if no git repo found -ifeq ($(wildcard tflite-micro/.git),) -context:: tflite-micro.zip -distclean:: - $(call DELDIR, tflite-micro) - $(call DELFILE, tflite-micro.zip) -endif - -CXXEXT := .cc - -COMMON_FLAGS += -DTF_LITE_STATIC_MEMORY -COMMON_FLAGS += -DTF_LITE_DISABLE_X86_NEON -COMMON_FLAGS += -DTF_LITE_STRIP_ERROR_STRINGS -COMMON_FLAGS += -Wno-sign-compare -COMMON_FLAGS += -Wno-unused-variable -COMMON_FLAGS += -Wno-undef -COMMON_FLAGS += -Wno-shadow -COMMON_FLAGS += -O3 - -SRC_FILES := $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/kernels/*.cc) - -ifeq ($(CONFIG_MLEARNING_CMSIS_NN),y) -COMMON_FLAGS += -DCMSIS_NN -COMMON_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/mlearning/cmsis-nn/cmsis-nn -NEW_SRC_FILES := $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/kernels/cmsis_nn/*.cc) -SRC_FILES := $(filter-out $(notdir $(NEW_SRC_FILES)), $(notdir $(SRC_FILES))) -SRC_FILES := $(addprefix $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/kernels/, $(SRC_FILES)) -SRC_FILES += $(NEW_SRC_FILES) - -ifeq ($(CONFIG_ARM_NEON),y) -CSRCS += operators/neon/arm_convolve_s8.c -CSRCS += operators/neon/arm_nn_mat_mult_kernel_s8_s16.c -CSRCS += operators/neon/arm_q7_to_q15_with_offset.c -CSRCS += operators/neon/arm_elementwise_add_s8.c -endif - -endif - -COMMON_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/gemmlowp/gemmlowp -COMMON_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/ruy/ruy -COMMON_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/math/kissfft/kissfft -COMMON_FLAGS += ${INCDIR_PREFIX}$(APPDIR)/mlearning/tflite-micro/tflite-micro - -CFLAGS += ${COMMON_FLAGS} -CXXFLAGS += ${COMMON_FLAGS} - -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/c/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/schema/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/core/c/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/kernels/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/kernels/internal/optimized/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/kernels/internal/reference/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/kernels/internal/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/core/api/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/arena_allocator/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/memory_planner/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/*.cc) -SRC_FILES += $(wildcard $(APPDIR)/mlearning/tflite-micro/tflite-micro/tensorflow/lite/micro/tflite_bridge/*.cc) - -SRC_FILES := $(filter-out %test.cc, $(SRC_FILES)) - -CXXSRCS += $(SRC_FILES) - -include $(APPDIR)/Application.mk \ No newline at end of file diff --git a/mlearning/tflite-micro/operators/neon/arm_convolve_s8.c b/mlearning/tflite-micro/operators/neon/arm_convolve_s8.c deleted file mode 100644 index 454c467a1..000000000 --- a/mlearning/tflite-micro/operators/neon/arm_convolve_s8.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - * SPDX-FileCopyrightText: Copyright 2010-2023 Arm Limited and/or its affiliates - * - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "arm_nnfunctions.h" -#include "arm_nnsupportfunctions.h" - -/** - * @ingroup Public - */ - -/** - * @addtogroup NNConv - * @{ - */ - -/* - * Basic s8 convolution function. - * - * Refer header file for details. Optimal use case for the DSP/MVE implementation is when input and output channels - * are multiples of 4 or atleast greater than 4. - * - */ -arm_cmsis_nn_status arm_convolve_s8(const cmsis_nn_context *ctx, - const cmsis_nn_conv_params *conv_params, - const cmsis_nn_per_channel_quant_params *quant_params, - const cmsis_nn_dims *input_dims, - const int8_t *input_data, - const cmsis_nn_dims *filter_dims, - const int8_t *filter_data, - const cmsis_nn_dims *bias_dims, - const int32_t *bias_data, - const cmsis_nn_dims *output_dims, - int8_t *output_data) -{ - (void)bias_dims; - - if (ctx->buf == NULL) - { - return ARM_CMSIS_NN_ARG_ERROR; - } - int16_t *buffer_a = (int16_t *)ctx->buf; - - const int32_t input_batches = input_dims->n; - const uint16_t input_x = input_dims->w; - const uint16_t input_y = input_dims->h; - const uint16_t input_ch = input_dims->c; - const uint16_t kernel_x = filter_dims->w; - const uint16_t kernel_y = filter_dims->h; - const uint16_t output_x = output_dims->w; - const uint16_t output_y = output_dims->h; - const uint16_t output_ch = output_dims->c; - - const uint16_t pad_x = conv_params->padding.w; - const uint16_t pad_y = conv_params->padding.h; - const uint16_t stride_x = conv_params->stride.w; - const uint16_t stride_y = conv_params->stride.h; - const int32_t dilation_x = conv_params->dilation.w; - const int32_t dilation_y = conv_params->dilation.h; - const int32_t out_offset = conv_params->output_offset; - const int32_t out_activation_min = conv_params->activation.min; - const int32_t out_activation_max = conv_params->activation.max; - const int32_t rhs_cols = kernel_x * kernel_y * input_ch; - const int32_t input_offset = conv_params->input_offset; - - int32_t *output_mult = quant_params->multiplier; - int32_t *output_shift = quant_params->shift; - - int i_batch; - for (i_batch = 0; i_batch < input_batches; i_batch++) - { - const int32_t remainder = rhs_cols % 4; - const int32_t aligned_rhs_cols = remainder != 0 ? rhs_cols + 4 - remainder : rhs_cols; - /** - * Use Im2col to speed up conv2d calculations. - * Use as a ping-pong buffer for unordered elements. - */ - int8_t *im2col_buf = (int8_t *)buffer_a + aligned_rhs_cols * 2; - int16_t *im2col_buf_start_s16 = buffer_a; - int8_t *out = output_data; - int32_t lhs_rows = 0; - /* This part implements the im2col function */ - for (int i_out_x = 0; i_out_x < output_x; i_out_x++) - { - const int32_t base_idx_x = stride_x * i_out_x - pad_x; - for (int i_out_y = 0; i_out_y < output_y; i_out_y++) - { - const int32_t base_idx_y = stride_y * i_out_y - pad_y; - for (int32_t i_ker_x = 0; i_ker_x < kernel_x; i_ker_x++) - { - int32_t k_x = base_idx_x + dilation_x * i_ker_x; - int32_t k_y = base_idx_y - dilation_y; - for (int32_t i_ker_y = 0; i_ker_y < kernel_y; i_ker_y++) - { - k_y += dilation_y; - arm_memcpy_s8(im2col_buf, - input_data + (k_y * input_x + k_x) * input_ch, - input_ch); - im2col_buf += input_ch; - } - } - lhs_rows++; - /* Extend the input data from int8 to int16, and add offset. */ - arm_q7_to_q15_with_offset(im2col_buf - rhs_cols, - im2col_buf_start_s16, - rhs_cols, - (int16_t)input_offset); - im2col_buf_start_s16 += aligned_rhs_cols; - if (lhs_rows & 2) - { - out = arm_nn_mat_mult_kernel_s8_s16(filter_data, - buffer_a, - output_ch, - output_shift, - output_mult, - out_offset, - out_activation_min, - out_activation_max, - rhs_cols, - aligned_rhs_cols, - bias_data, - out); - /* counter reset */ - im2col_buf_start_s16 = buffer_a; - im2col_buf = (int8_t *)buffer_a + (aligned_rhs_cols << 1); - lhs_rows = 0; - } - } - } - if (lhs_rows != 0) - { - const int8_t *ker_a = filter_data; - int i; - for (i = 0; i < output_ch; i++) - { - /* Load the accumulator with bias first */ - uint16_t col_count = rhs_cols / 8; - int32_t sum = 0; - const int16_t *ip_as_col = buffer_a; - int32x4_t res_s32 = vdupq_n_s32(0); - if (bias_data) - { - sum = bias_data[i]; - } - while (col_count) - { - int8x8_t filter_s8 = vld1_s8(ker_a); - int16x8_t input_s16 = vld1q_s16(ip_as_col); - int16x8_t filter_s16 = vmovl_s8(filter_s8); - ker_a += 8; - ip_as_col += 8; - res_s32 = vmlal_s16(res_s32, - vget_low_s16(input_s16), - vget_low_s16(filter_s16)); - res_s32 = vmlal_s16(res_s32, - vget_high_s16(input_s16), - vget_high_s16(filter_s16)); - col_count --; - } - sum += vgetq_lane_s32(res_s32, 0); - sum += vgetq_lane_s32(res_s32, 1); - sum += vgetq_lane_s32(res_s32, 2); - sum += vgetq_lane_s32(res_s32, 3); - col_count = rhs_cols % 8; - while (col_count) - { - int8_t ker_a1 = *ker_a++; - int16_t ip_b1 = *ip_as_col++; - sum += ker_a1 * ip_b1; - col_count--; - } - sum = arm_nn_requantize(sum, output_mult[i], output_shift[i]); - sum += out_offset; - sum = MAX(sum, out_activation_min); - sum = MIN(sum, out_activation_max); - *out++ = (int8_t)sum; - } - } - /* Advance to the next batch */ - input_data += (input_x * input_y * input_ch); - output_data += (output_x * output_y * output_ch); - } - /* Return to application */ - return ARM_CMSIS_NN_SUCCESS; -} - -/** - * @} end of NNConv group - */ \ No newline at end of file diff --git a/mlearning/tflite-micro/operators/neon/arm_elementwise_add_s8.c b/mlearning/tflite-micro/operators/neon/arm_elementwise_add_s8.c deleted file mode 100644 index 678ae69fd..000000000 --- a/mlearning/tflite-micro/operators/neon/arm_elementwise_add_s8.c +++ /dev/null @@ -1,149 +0,0 @@ -/* - * SPDX-FileCopyrightText: Copyright 2010-2023 Arm Limited and/or its affiliates - * - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "arm_nnfunctions.h" -#include "arm_nnsupportfunctions.h" - -/* Note: __SHIFT is expected to be <=0 */ -__STATIC_FORCEINLINE int32x4_t arm_requantize_neon(const int32x4_t val, const int32_t multiplier, const int32_t shift) -{ - int32x4_t dividend = vqrdmulhq_n_s32(vshlq_s32(val, vdupq_n_s32(LEFT_SHIFT(shift))), multiplier); - int32_t exponent = RIGHT_SHIFT(shift); - int32x4_t shift__ = vdupq_n_s32(-exponent); - int32x4_t fixup__ = vshrq_n_s32(vandq_s32(dividend, shift__), 31); - int32x4_t fixed_up_dividend = vqaddq_s32(dividend, fixup__); - return vrshlq_s32(fixed_up_dividend, shift__); -} - -/** - * @ingroup Public - */ - -/** - * @addtogroup groupElementwise - * @{ - */ - -/* - * s8 elementwise add - * - * Refer header file for details. - * - */ - -arm_cmsis_nn_status arm_elementwise_add_s8(const int8_t *input_1_vect, - const int8_t *input_2_vect, - const int32_t input_1_offset, - const int32_t input_1_mult, - const int32_t input_1_shift, - const int32_t input_2_offset, - const int32_t input_2_mult, - const int32_t input_2_shift, - const int32_t left_shift, - int8_t *output, - const int32_t out_offset, - const int32_t out_mult, - const int32_t out_shift, - const int32_t out_activation_min, - const int32_t out_activation_max, - const int32_t block_size) -{ - int32_t loop_count = block_size / 8; - const int8_t *input_1 = input_1_vect; - const int8_t *input_2 = input_2_vect; - int8_t *output_ = output; - - while (loop_count) - { - int8x8_t res; - int8x8_t input_1_s8; - int8x8_t input_2_s8; - int16x8_t i1_val_16; - int16x8_t input_1_s16; - int16x8_t input_2_s16; - int32x4_t input_1_s16_low; - int32x4_t input_1_s16_high; - int32x4_t input_2_s16_low; - int32x4_t input_2_s16_high; - - input_1_s8 = vld1_s8(input_1); - input_2_s8 = vld1_s8(input_2); - input_1_s16 = vmovl_s8(input_1_s8); - input_2_s16 = vmovl_s8(input_2_s8); - input_1 += 8; - input_2 += 8; - - input_1_s16_low = vaddw_s16(vdupq_n_s32(input_1_offset), vget_low_s16(input_1_s16)); - input_1_s16_high = vaddw_s16(vdupq_n_s32(input_1_offset), vget_high_s16(input_1_s16)); - input_2_s16_low = vaddw_s16(vdupq_n_s32(input_2_offset), vget_low_s16(input_2_s16)); - input_2_s16_high = vaddw_s16(vdupq_n_s32(input_2_offset), vget_high_s16(input_2_s16)); - - input_1_s16_low = vshlq_s32(input_1_s16_low, vdupq_n_s32(left_shift)); - input_2_s16_low = vshlq_s32(input_2_s16_low, vdupq_n_s32(left_shift)); - input_1_s16_high = vshlq_s32(input_1_s16_high, vdupq_n_s32(left_shift)); - input_2_s16_high = vshlq_s32(input_2_s16_high, vdupq_n_s32(left_shift)); - - input_1_s16_low = arm_requantize_neon(input_1_s16_low, input_1_mult, input_1_shift); - input_1_s16_high = arm_requantize_neon(input_1_s16_high, input_1_mult, input_1_shift); - input_2_s16_low = arm_requantize_neon(input_2_s16_low, input_2_mult, input_2_shift); - input_2_s16_high = arm_requantize_neon(input_2_s16_high, input_2_mult, input_2_shift); - - input_1_s16_low = vaddq_s32(input_1_s16_low, input_2_s16_low); - input_1_s16_high = vaddq_s32(input_1_s16_high, input_2_s16_high); - - input_1_s16_low = arm_requantize_neon(input_1_s16_low, out_mult, out_shift); - input_1_s16_high = arm_requantize_neon(input_1_s16_high, out_mult, out_shift); - - input_1_s16_low = vaddq_s32(input_1_s16_low, vdupq_n_s32(out_offset)); - input_1_s16_high = vaddq_s32(input_1_s16_high, vdupq_n_s32(out_offset)); - - input_1_s16_low = vmaxq_s32(input_1_s16_low, vdupq_n_s32(out_activation_min)); - input_1_s16_high = vmaxq_s32(input_1_s16_high, vdupq_n_s32(out_activation_min)); - input_1_s16_low = vminq_s32(input_1_s16_low, vdupq_n_s32(out_activation_max)); - input_1_s16_high = vminq_s32(input_1_s16_high, vdupq_n_s32(out_activation_max)); - - i1_val_16 = vcombine_s16(vmovn_s32(input_1_s16_low), vmovn_s32(input_1_s16_high)); - res = vmovn_s16(i1_val_16); - - vst1_s8(output_, res); - output_ += 8; - loop_count--; - } - - loop_count = block_size % 8; - while (loop_count) - { - int32_t a1 = (*input_1++ + input_1_offset) << left_shift; - int32_t a2 = (*input_2++ + input_2_offset) << left_shift; - a1 = arm_nn_requantize(a1, input_1_mult, input_1_shift); - a2 = arm_nn_requantize(a2, input_2_mult, input_2_shift); - - int32_t sum = a1 + a2; - sum = arm_nn_requantize(sum, out_mult, out_shift); - sum += out_offset; - - sum = MAX(sum, out_activation_min); - sum = MIN(sum, out_activation_max); - *output_ = (int8_t) sum; - loop_count--; - output_++; - } - - return (ARM_CMSIS_NN_SUCCESS); -} diff --git a/mlearning/tflite-micro/operators/neon/arm_nn_mat_mult_kernel_s8_s16.c b/mlearning/tflite-micro/operators/neon/arm_nn_mat_mult_kernel_s8_s16.c deleted file mode 100644 index 6cbea4de0..000000000 --- a/mlearning/tflite-micro/operators/neon/arm_nn_mat_mult_kernel_s8_s16.c +++ /dev/null @@ -1,363 +0,0 @@ -/* - * SPDX-FileCopyrightText: Copyright 2010-2023 Arm Limited and/or its affiliates - * - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* ---------------------------------------------------------------------- - * Project: CMSIS NN Library - * Title: arm_nn_mat_mult_kernel_s8_s16.c - * Description: Matrix-multiplication function for convolution - * - * $Date: 29 May 2023 - * $Revision: V.2.0.0 - * - * Target : Arm(R) M-Profile Architecture - * -------------------------------------------------------------------- */ - -#include -#include "arm_nnfunctions.h" -#include "arm_nnsupportfunctions.h" - -/* - * Matrix-multiplication function for convolution with per-channel requantization. - * - * Refer header file for details. - * - */ -int8_t *arm_nn_mat_mult_kernel_s8_s16(const int8_t *input_a, - const int16_t *input_b, - const uint16_t output_ch, - const int32_t *out_shift, - const int32_t *out_mult, - const int32_t out_offset, - const int16_t activation_min, - const int16_t activation_max, - const int32_t num_col_a, - const int32_t aligned_num_col_a, - const int32_t *const output_bias, - int8_t *out_0) -{ - int8_t *out_1 = out_0 + output_ch; - const int32_t *bias = output_bias; - - uint16_t row_count = output_ch / 4; - const int8_t *ip_a0 = input_a; - - /* this loop over rows in A */ - while (row_count) - { - int32_t col_count = num_col_a / 8; - const int16_t *ip_b0 = input_b; - const int16_t *ip_b1 = ip_b0 + aligned_num_col_a; - const int8_t *ip_a[4] = {ip_a0, - ip_a0 + num_col_a, - ip_a0 + 2 * num_col_a, - ip_a0 + 3 * num_col_a}; - int32_t ch_out[4][2] = {0}; - int32x4_t res[8]; - - for (int i = 0; i < 8; i++) - { - res[i] = vdupq_n_s32(0); - } - - /* Init accumulator with bias for channel N and N + 1 */ - if (bias) - { - for (int i = 0; i < 4; i++) - { - ch_out[i][0] = *bias; - ch_out[i][1] = *bias++; - } - } - - /** - * Each time eight int8 data of four filters and eight int16 data - * of two inputs are read.First, the filter data is expanded to - * int16, and then cross-multiplied to obtain eight calculation results. - */ - while (col_count) - { - int8x8_t filter_s8[4]; - int16x8_t input_s16[2]; - int16x8_t filter_s16[4]; - - input_s16[0] = vld1q_s16(ip_b0); - ip_b0 += 8; - input_s16[1] = vld1q_s16(ip_b1); - ip_b1 += 8; - - for (int i = 0; i < 4; i++) - { - filter_s8[i] = vld1_s8(ip_a[i]); - ip_a[i] += 8; - filter_s16[i] = vmovl_s8(filter_s8[i]); - res[i * 2] = vmlal_s16(res[i * 2], - vget_low_s16(filter_s16[i]), - vget_low_s16(input_s16[0])); - res[i * 2 + 1] = vmlal_s16(res[i * 2 + 1], - vget_low_s16(filter_s16[i]), - vget_low_s16(input_s16[1])); - res[i * 2] = vmlal_s16(res[i * 2], - vget_high_s16(filter_s16[i]), - vget_high_s16(input_s16[0])); - res[i * 2 + 1] = vmlal_s16(res[i * 2 + 1], - vget_high_s16(filter_s16[i]), - vget_high_s16(input_s16[1])); - } - - col_count --; - } - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < 2; j++) - { - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 0); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 1); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 2); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 3); - } - } - - col_count = num_col_a % 8; - while (col_count) - { - int16_t b0 = *ip_b0++; - int16_t b1 = *ip_b1++; - - for (int i = 0; i < 4; i++) - { - int8_t input_remaining = *(ip_a[i]++); - ch_out[i][0] += input_remaining * b0; - ch_out[i][1] += input_remaining * b1; - } - col_count--; - } /* while over col_count */ - - for (int i = 0; i < 4; i++) - { - ch_out[i][0] = arm_nn_requantize(ch_out[i][0], *out_mult, *out_shift); - ch_out[i][1] = arm_nn_requantize(ch_out[i][1], *out_mult, *out_shift); - ch_out[i][0] += out_offset; - ch_out[i][1] += out_offset; - ch_out[i][0] = MAX(ch_out[i][0], activation_min); - ch_out[i][1] = MAX(ch_out[i][1], activation_min); - ch_out[i][0] = MIN(ch_out[i][0], activation_max); - ch_out[i][1] = MIN(ch_out[i][1], activation_max); - *out_0++ = (int8_t)ch_out[i][0]; - *out_1++ = (int8_t)ch_out[i][1]; - out_mult++; - out_shift++; - } - - /* skip row */ - ip_a0 = ip_a[3]; - row_count--; - } - row_count = output_ch % 4; - if (row_count >= 2) - { - int32_t col_count = num_col_a / 8; - const int8_t *ip_a1 = ip_a0 + num_col_a; - const int16_t *ip_b0 = input_b; - const int16_t *ip_b1 = ip_b0 + aligned_num_col_a; - int32_t ch_out[2][2] = {0}; - int32x4_t res[4]; - - /* Init accumulator with bias for channel N and N + 1 */ - if (bias) - { - for (int i = 0; i < 2; i++) - { - ch_out[i][0] = *bias; - ch_out[i][1] = *bias++; - } - } - - for (int i = 0; i < 4; i++) - { - res[i] = vdupq_n_s32(0); - } - - /** - * Each time eight int8 data of four filters and eight int16 data - * of two inputs are read.First, the filter data is expanded to - * int16, and then cross-multiplied to obtain 8 calculation results. - */ - while (col_count) - { - int8x8_t filter_s8[2]; - int16x8_t input_s16[2]; - int16x8_t filter_s16[2]; - - filter_s8[0] = vld1_s8(ip_a0); - ip_a0 += 8; - filter_s8[1] = vld1_s8(ip_a1); - ip_a1 += 8; - - input_s16[0] = vld1q_s16(ip_b0); - ip_b0 += 8; - input_s16[1] = vld1q_s16(ip_b1); - ip_b1 += 8; - - for (int i = 0; i < 2; i++) - { - filter_s16[i] = vmovl_s8(filter_s8[i]); - res[i * 2] = vmlal_s16(res[i * 2], - vget_low_s16(filter_s16[i]), - vget_low_s16(input_s16[0])); - res[i * 2 + 1] = vmlal_s16(res[i * 2 + 1], - vget_low_s16(filter_s16[i]), - vget_low_s16(input_s16[1])); - res[i * 2] = vmlal_s16(res[i * 2], - vget_high_s16(filter_s16[i]), - vget_high_s16(input_s16[0])); - res[i * 2 + 1] = vmlal_s16(res[i * 2 + 1], - vget_high_s16(filter_s16[i]), - vget_high_s16(input_s16[1])); - } - - col_count --; - } - for (int i = 0; i < 2; i++) - { - for (int j = 0; j < 2; j++) - { - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 0); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 1); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 2); - ch_out[i][j] += vgetq_lane_s32(res[i * 2 + j], 3); - } - } - - col_count = num_col_a % 8; - while (col_count) - { - int8_t a0 = *ip_a0++; // filter - int8_t a1 = *ip_a1++; - int16_t b0 = *ip_b0++; // input - int16_t b1 = *ip_b1++; - - ch_out[0][0] += a0 * b0; - ch_out[1][1] += a1 * b1; - ch_out[1][0] += a1 * b0; - ch_out[0][1] += a0 * b1; - col_count--; - } /* while over col_count */ - - for (int i = 0; i < 2; i++) - { - ch_out[i][0] = arm_nn_requantize(ch_out[i][0], *out_mult, *out_shift); - ch_out[i][1] = arm_nn_requantize(ch_out[i][1], *out_mult, *out_shift); - ch_out[i][0] += out_offset; - ch_out[i][1] += out_offset; - ch_out[i][0] = MAX(ch_out[i][0], activation_min); - ch_out[i][1] = MAX(ch_out[i][1], activation_min); - ch_out[i][0] = MIN(ch_out[i][0], activation_max); - ch_out[i][1] = MIN(ch_out[i][1], activation_max); - *out_0++ = (int8_t)ch_out[i][0]; - *out_1++ = (int8_t)ch_out[i][1]; - out_mult++; - out_shift++; - } - - /* skip row */ - ip_a0 += num_col_a; - row_count -= 2; - } - - /* compute the last odd numbered row if any */ - if (output_ch & 0x1) - { - int32_t col_count = num_col_a / 8; - const int16_t *ip_b0 = input_b; - const int16_t *ip_b1 = ip_b0 + aligned_num_col_a; - int32_t ch_out[2] = {0}; - int32x4_t res[2]; - - /* load the bias */ - if (bias) - { - ch_out[0] = *bias; - ch_out[1] = *bias++; - } - - res[0] = vdupq_n_s32(0); - res[1] = vdupq_n_s32(0); - - while(col_count) - { - int8x8_t filter_s8 = vld1_s8(ip_a0); - int16x8_t filter_s16 = vmovl_s8(filter_s8); - int16x8_t input_0_s16 = vld1q_s16(ip_b0); - int16x8_t input_1_s16 = vld1q_s16(ip_b1); - ip_a0 += 8; - ip_b0 += 8; - ip_b1 += 8; - res[0] = vmlal_s16(res[0], - vget_low_s16(filter_s16), - vget_low_s16(input_0_s16)); - res[1] = vmlal_s16(res[1], - vget_low_s16(filter_s16), - vget_low_s16(input_1_s16)); - res[0] = vmlal_s16(res[0], - vget_high_s16(filter_s16), - vget_high_s16(input_0_s16)); - res[1] = vmlal_s16(res[1], - vget_high_s16(filter_s16), - vget_high_s16(input_1_s16)); - col_count --; - } - - for (int i = 0; i < 4; i++) - { - ch_out[0] += vgetq_lane_s32(res[0], i); - ch_out[1] += vgetq_lane_s32(res[1], 1); - } - - col_count = num_col_a % 8; - while (col_count) - { - int8_t a0 = *ip_a0++; - int16_t b0 = *ip_b0++; - int16_t b1 = *ip_b1++; - - ch_out[0] += a0 * b0; - ch_out[1] += a0 * b1; - col_count--; - } - - ch_out[0] = arm_nn_requantize(ch_out[0], *out_mult, *out_shift); - ch_out[0] += out_offset; - ch_out[0] = MAX(ch_out[0], activation_min); - ch_out[0] = MIN(ch_out[0], activation_max); - *out_0++ = (int8_t)ch_out[0]; - - ch_out[1] = arm_nn_requantize(ch_out[1], *out_mult, *out_shift); - ch_out[1] += out_offset; - ch_out[1] = MAX(ch_out[1], activation_min); - ch_out[1] = MIN(ch_out[1], activation_max); - *out_1++ = (int8_t)ch_out[1]; - - out_mult++; - out_shift++; - } - - out_0 += output_ch; - - /* return the new output pointer with offset */ - return out_0; -} diff --git a/mlearning/tflite-micro/operators/neon/arm_q7_to_q15_with_offset.c b/mlearning/tflite-micro/operators/neon/arm_q7_to_q15_with_offset.c deleted file mode 100644 index b7156e473..000000000 --- a/mlearning/tflite-micro/operators/neon/arm_q7_to_q15_with_offset.c +++ /dev/null @@ -1,60 +0,0 @@ -/* - * SPDX-FileCopyrightText: Copyright 2010-2023 Arm Limited and/or its affiliates - * - * SPDX-License-Identifier: Apache-2.0 - * - * Licensed under the Apache License, Version 2.0 (the License); you may - * not use this file except in_q7x4 compliance with the License. - * You may obtain a copy of the License at - * - * www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in_q7x4 writing, software - * distributed under the License is distributed on an AS IS BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "arm_nnsupportfunctions.h" - -/** - * @ingroup groupSupport - */ - -/** - * @addtogroup supportConversion - * @{ - */ - -void arm_q7_to_q15_with_offset(const int8_t *src, int16_t *dst, int32_t block_size, int16_t offset) -{ - int32_t block_cnt; - - block_cnt = block_size / 8; - int16x8_t offset_s16 = vdupq_n_s16(offset); - while (block_cnt) - { - int8x8_t src_s8 = vld1_s8(src); - int16x8_t src_s16 = vmovl_s8(src_s8); - src += 8; - src_s16 = vaddq_s16(offset_s16, src_s16); - block_cnt--; - vst1q_s16(dst, src_s16); - dst += 8; - } - - block_cnt = block_size % 8; - while (block_cnt > 0) - { - *dst++ = (int16_t)*src++ + offset; - - /* Decrement the loop counter */ - block_cnt--; - } -} - -/** - * @} end of Doxygen group - */ diff --git a/mlearning/tflite-micro/tflite-micro.patch b/mlearning/tflite-micro/tflite-micro.patch deleted file mode 100644 index 7c39ee527..000000000 --- a/mlearning/tflite-micro/tflite-micro.patch +++ /dev/null @@ -1,32 +0,0 @@ -From e6049c8ddd7e36db4993e3c6d8b4e5a7114db2c5 Mon Sep 17 00:00:00 2001 -From: renzhiyuan1 -Date: Mon, 4 Dec 2023 12:30:20 +0800 -Subject: [PATCH] Patch files in tflite-micro - -VELAPLATFO-20049 - -Patch files in tflite-micro - -Change-Id: Ic683fe4f12221d214ca77515c7b9487bb76a923f -Signed-off-by: renzhiyuan1 ---- - signal/src/circular_buffer.cc | 2 ++ - 1 file changed, 2 insertions(+) - -diff --git a/signal/src/circular_buffer.cc b/signal/src/circular_buffer.cc -index 7638d912e..3261be56c 100644 ---- a/signal/src/circular_buffer.cc -+++ b/signal/src/circular_buffer.cc -@@ -19,7 +19,9 @@ limitations under the License. - #include - #include - -+#ifndef ASSERT - #define ASSERT assert -+#endif - - namespace tflite { - namespace tflm_signal { --- -2.25.1 - diff --git a/modbus/README.md b/modbus/README.md deleted file mode 100644 index 07bdc45dc..000000000 --- a/modbus/README.md +++ /dev/null @@ -1,120 +0,0 @@ -# Modbus - -This directory contains a port of last open source version of FreeModBus (BSD -license). The code in this directory is a subset of FreeModBus version 1.5.0 -(June 6, 2010) that can be downloaded in its entirety from -http://developer.berlios.de/project/showfiles.php?group_id=6120. - -Includes extensions to support RTU master mode by Armink(383016632@qq.com): -https://github.com/armink/FreeModbus_Slave-Master-RTT-STM32. Ported to NuttX by -Darcy Gong. - -## Directory Structure / Relation to freemodbus-v1.5.0 - -The original FreeModBus download consists of several directories. This subset -takes only the contents of one directory, `modbus/`, that implements the core -modbus logic and integrates that directory into the NuttX build system. The -mapping between `freemodbus-v1.5.0` and the nuttx directories is shown below: - -``` ---------------------------- ---------------------------------------------- -freemodbus-v1.5.0 NuttX ---------------------------- ---------------------------------------------- -All top level .txt files Not included -demo/ Not included. This directory contains demo - and porting code for a variety of platforms. - The NuttX demo was ported from the LINUX - demo in this directory and can be found at - apps/examples/modbus. -doc/ Not included. This directory contains Doxygen - support files. -modbus/ Included in its entirety in various locations: - ascii apps/modbus/ascii - functions apps/modbus/functions - include apps/include/modbus - mb.c apps/modbus/mb.c - rtu apps/modbus/rtu - tcp apps/modbus/tcp -tools/ Not included. This directory contains Doxygen - tools. ---------------------------- ---------------------------------------------- -``` - -So this directory is equivalent to the `freemodbus-v1.5.0/modbus` directory -except that (1) it may include modifications for the integration with NuttX and -(2) the modbus/include directory was moved to `apps/modbus`. - -The original, unmodified `freemodbus-v1.5.0` was checked in as SVN revision -`4960`. - -The other directory here, `nuttx/`, implements the NuttX modbus interface. It -derives from the `freemodbus-v1.5.0/demo/LINUX/port` directory. - -## Configuration Options - -In the original `freemodbus-v1.5.0` release, the FreeModBus configuration was -controlled by the header file `mbconfig.h`. This header file was eliminated -(post revision `4960`) and the FreeModBus configuration was integrated into the -NuttX configuration system. - -The NuttX-named configuration options that are available include: - -- `CONFIG_MODBUS` – General ModBus support. -- `CONFIG_MB_ASCII_ENABLED` – Modbus ASCII support. -- `CONFIG_MB_ASCII_MASTER` – Modbus ASCII master support. -- `CONFIG_MB_RTU_ENABLED` – Modbus RTU support. -- `CONFIG_MB_RTU_MASTER` – Modbus RTU master support. -- `CONFIG_MB_TCP_ENABLED` – Modbus TCP support. -- `CONFIG_MB_ASCII_TIMEOUT_SEC` – Character timeout value for Modbus ASCII. The - character timeout value is not fixed for Modbus ASCII and is therefore a - configuration option. It should be set to the maximum expected delay time of - the network. Default: `1`. -- `CONFIG_MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS` – Timeout to wait in ASCII prior - to enabling transmitter. If defined the function calls `vMBPortSerialDelay` - with the argument `CONFIG_MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS` to allow for a - delay before the serial transmitter is enabled. This is required because some - targets are so fast that there is no time between receiving and transmitting - the frame. If the master is too slow with enabling its receiver then it will - not receive the response correctly. -- `CONFIG_MB_FUNC_HANDLERS_MAX` – Maximum number of Modbus functions codes the - protocol stack should support. The maximum number of supported Modbus - functions must be greater than the sum of all enabled functions in this file - and custom function handlers. If set too small, adding more functions will - fail. -- `CONFIG_MB_FUNC_OTHER_REP_SLAVEID_BUF` – Number of bytes which should be - allocated for the Report Slave ID command. This number limits the maximum size - of the additional segment in the report slave id function. See - `eMBSetSlaveID()` for more information on how to set this value. It is only - used if `CONFIG_MB_FUNC_OTHER_REP_SLAVEID_ENABLED` is set to `1`. -- `CONFIG_MB_FUNC_OTHER_REP_SLAVEID_ENABLED` – If the Report Slave ID function - should be enabled. -- `CONFIG_MB_FUNC_READ_INPUT_ENABLED` – If the Read Input Registers function - should be enabled. -- `CONFIG_MB_FUNC_READ_HOLDING_ENABLED` – If the Read Holding Registers function - should be enabled. -- `CONFIG_MB_FUNC_WRITE_HOLDING_ENABLED` – If the Write Single Register function - should be enabled. -- `CONFIG_MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED` – If the Write Multiple - registers function should be enabled. -- `CONFIG_MB_FUNC_READ_COILS_ENABLED` – If the Read Coils function should be - enabled. -- `CONFIG_MB_FUNC_WRITE_COIL_ENABLED` – If the Write Coils function should be - enabled. -- `CONFIG_MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED` – If the Write Multiple Coils - function should be enabled. -- `CONFIG_MB_FUNC_READ_DISCRETE_INPUTS_ENABLED` – If the Read Discrete Inputs - function should be enabled. -- `CONFIG_MB_FUNC_READWRITE_HOLDING_ENABLED` – If the Read/Write Multiple - Registers function should be enabled. - -See also other serial settings, in particular: - -- `CONFIG_SERIAL_TERMIOS` – Serial driver supports `termios.h` interfaces - If this is not defined, then the terminal settings (baud, parity, etc.) - are not configurable at runtime. - -## Note - -The developer of FreeModBus, Christian Walter, is still developing Modbus -libraries, although they are now commercial. See -http://www.embedded-solutions.at/ for further information. diff --git a/modbus/mb_m.c b/modbus/mb_m.c index 336181136..16323d770 100644 --- a/modbus/mb_m.c +++ b/modbus/mb_m.c @@ -429,6 +429,13 @@ eMBErrorCode eMBMasterPoll(void) vMBMasterRunResRelease(); break; + + case EV_MASTER_PROCESS_SUCCESS: + case EV_MASTER_ERROR_RESPOND_TIMEOUT: + case EV_MASTER_ERROR_RECEIVE_DATA: + case EV_MASTER_ERROR_EXECUTE_FUNCTION: + default: + break; } } diff --git a/modbus/nuttx/portevent_m.c b/modbus/nuttx/portevent_m.c index cc7dd824e..2f6143943 100644 --- a/modbus/nuttx/portevent_m.c +++ b/modbus/nuttx/portevent_m.c @@ -94,7 +94,7 @@ bool xMBMasterPortEventPost(eMBMasterEventType eEvent) return true; } -bool xMBMasterPortEventGet(eMBMasterEventType * eEvent) +bool xMBMasterPortEventGet(eMBMasterEventType *eEvent) { bool xEventHappened = false; @@ -102,7 +102,6 @@ bool xMBMasterPortEventGet(eMBMasterEventType * eEvent) if (eQueuedEvent & ~(WAITER_EVENTS)) { - /* Fetch events by priority */ if (eQueuedEvent & EV_MASTER_READY) @@ -136,9 +135,9 @@ bool xMBMasterPortEventGet(eMBMasterEventType * eEvent) else { /* Poll the serial device. The serial device timeouts if no characters - * have been received within for t3.5 during an active transmission or if - * nothing happens within a specified amount of time. Both timeouts are - * configured from the timer init functions. + * have been received within for t3.5 during an active transmission or + * if nothing happens within a specified amount of time. Both timeouts + * are configured from the timer init functions. */ xMBMasterPortSerialPoll(); @@ -188,6 +187,7 @@ bool xMBMasterRunResTake(int32_t lTimeOut) { return false; } + return true; } else @@ -198,6 +198,7 @@ bool xMBMasterRunResTake(int32_t lTimeOut) { return false; } + return true; } } @@ -227,7 +228,7 @@ void vMBMasterRunResRelease(void) */ void vMBMasterErrorCBRespondTimeout(uint8_t ucDestAddress, - const uint8_t * pucPDUData, + const uint8_t *pucPDUData, uint16_t usPDULength) { xMBMasterPortEventPost(EV_MASTER_ERROR_RESPOND_TIMEOUT); @@ -243,7 +244,7 @@ void vMBMasterErrorCBRespondTimeout(uint8_t ucDestAddress, */ void vMBMasterErrorCBReceiveData(uint8_t ucDestAddress, - const uint8_t * pudPDUData, + const uint8_t *pudPDUData, uint16_t usPDULength) { xMBMasterPortEventPost(EV_MASTER_ERROR_RECEIVE_DATA); @@ -259,7 +260,7 @@ void vMBMasterErrorCBReceiveData(uint8_t ucDestAddress, */ void vMBMasterErrorCBExecuteFunction(uint8_t ucDestAddress, - const uint8_t * pucPDUData, + const uint8_t *pucPDUData, uint16_t usPDULength) { xMBMasterPortEventPost(EV_MASTER_ERROR_EXECUTE_FUNCTION); @@ -274,7 +275,8 @@ void vMBMasterCBRequestSuccess(void) xMBMasterPortEventPost(EV_MASTER_PROCESS_SUCCESS); } -/* This function will wait for Modbus Master request finish and return result. +/* This function will wait for Modbus Master request finish + * and return result. */ eMBMasterReqErrCode eMBMasterWaitRequestFinish(void) @@ -303,6 +305,7 @@ eMBMasterReqErrCode eMBMasterWaitRequestFinish(void) { eErrStatus = MB_MRE_EXE_FUN; } + eQueuedEvent &= ~WAITER_EVENTS; } diff --git a/modbus/nuttx/portother.c b/modbus/nuttx/portother.c index a2e0070a0..7cb453819 100644 --- a/modbus/nuttx/portother.c +++ b/modbus/nuttx/portother.c @@ -74,17 +74,21 @@ void vMBPortLogFile(FILE * fNewLogFile) fLogFile = fNewLogFile; } -void vMBPortLog(eMBPortLogLevel eLevel, const char * szModule, const char * szFmt, ...) +void vMBPortLog(eMBPortLogLevel eLevel, const char * szModule, + const char * szFmt, ...) { char szBuf[512]; int i; va_list args; FILE *fOutput = fLogFile == NULL ? stderr : fLogFile; - static const char *arszLevel2Str[] = { "ERROR", "WARN", "INFO", "DEBUG" }; - - i = snprintf(szBuf, NELEMS(szBuf), "%s: %s: ", arszLevel2Str[eLevel], szModule); + static const char *arszLevel2Str[] = + { + "ERROR", "WARN", "INFO", "DEBUG" + }; + i = snprintf(szBuf, NELEMS(szBuf), "%s: %s: ", + arszLevel2Str[eLevel], szModule); if (i != 0) { va_start(args, szFmt); @@ -106,7 +110,8 @@ void vMBPortEnterCritical(void) int ret = pthread_mutex_lock(&xLock); if (ret != 0) { - vMBPortLog(MB_LOG_ERROR, "OTHER", "Locking primitive failed: %d\n", ret); + vMBPortLog(MB_LOG_ERROR, "OTHER", + "Locking primitive failed: %d\n", ret); } } @@ -115,6 +120,7 @@ void vMBPortExitCritical(void) int ret = pthread_mutex_unlock(&xLock); if (ret != 0) { - vMBPortLog(MB_LOG_ERROR, "OTHER", "Locking primitive failed: %d\n", ret); + vMBPortLog(MB_LOG_ERROR, + "OTHER", "Locking primitive failed: %d\n", ret); } } diff --git a/modbus/nuttx/portother_m.c b/modbus/nuttx/portother_m.c index befb28a89..799cef6c6 100644 --- a/modbus/nuttx/portother_m.c +++ b/modbus/nuttx/portother_m.c @@ -84,7 +84,10 @@ void vMBMasterPortLog(eMBPortLogLevel eLevel, const char * szModule, va_list args; FILE *fOutput = fLogFile == NULL ? stderr : fLogFile; - static const char *arszLevel2Str[] = { "ERROR", "WARN", "INFO", "DEBUG" }; + static const char *arszLevel2Str[] = + { + "ERROR", "WARN", "INFO", "DEBUG" + }; i = snprintf(szBuf, NELEMS(szBuf), "%s: %s: ", arszLevel2Str[eLevel], szModule); diff --git a/modbus/nuttx/porttimer_m.c b/modbus/nuttx/porttimer_m.c index af595f12a..96b355cc3 100644 --- a/modbus/nuttx/porttimer_m.c +++ b/modbus/nuttx/porttimer_m.c @@ -75,7 +75,7 @@ bool bTimeoutEnable; /* timeout is active */ * Private Functions ****************************************************************************/ -void vMBMasterPortTimersEnable( void ) +void vMBMasterPortTimersEnable(void) { int res = gettimeofday(&xTimeLast, NULL); @@ -114,33 +114,33 @@ bool xMBMasterPortTimersInit(uint16_t usTimeOut50us) return xMBMasterPortSerialSetTimeout(ulTimeOut); } -void xMBMasterPortTimersClose() +void xMBMasterPortTimersClose(void) { /* Does not use any hardware resources. */ } -INLINE void vMBMasterPortTimersT35Enable( void ) +INLINE void vMBMasterPortTimersT35Enable(void) { vMBMasterPortTimersEnable(); ulTimeOut = ulTimeoutT35; vMBMasterSetCurTimerMode(MB_TMODE_T35); } -INLINE void vMBMasterPortTimersConvertDelayEnable( void ) +INLINE void vMBMasterPortTimersConvertDelayEnable(void) { vMBMasterPortTimersEnable(); ulTimeOut = ulTimeoutConvertDelay; vMBMasterSetCurTimerMode(MB_TMODE_CONVERT_DELAY); } -INLINE void vMBMasterPortTimersRespondTimeoutEnable( void ) +INLINE void vMBMasterPortTimersRespondTimeoutEnable(void) { vMBMasterPortTimersEnable(); ulTimeOut = ulTimeoutResponse; - vMBMasterSetCurTimerMode( MB_TMODE_RESPOND_TIMEOUT ); + vMBMasterSetCurTimerMode(MB_TMODE_RESPOND_TIMEOUT); } -void vMBMasterPortTimerPoll( void ) +void vMBMasterPortTimerPoll(void) { uint32_t ulDeltaMS; struct timeval xTimeCur; @@ -168,7 +168,7 @@ void vMBMasterPortTimerPoll( void ) } } -void vMBMasterPortTimersDisable() +void vMBMasterPortTimersDisable(void) { bTimeoutEnable = false; } diff --git a/modbus/rtu/mbrtu_m.c b/modbus/rtu/mbrtu_m.c index d835b5a7f..3fde50670 100644 --- a/modbus/rtu/mbrtu_m.c +++ b/modbus/rtu/mbrtu_m.c @@ -278,7 +278,7 @@ bool xMBMasterRTUReceiveFSM(void) /* Always read the character. */ - xMBMasterPortSerialGetByte((uint8_t *) & ucByte); + xMBMasterPortSerialGetByte((int8_t *) & ucByte); switch (eRcvState) { @@ -397,6 +397,10 @@ bool xMBMasterRTUTransmitFSM(void) } } break; + + case STATE_M_TX_XFWR: + default: + break; } return xNeedPoll; diff --git a/netutils/README.md b/netutils/README.md deleted file mode 100644 index 3ddf9a93f..000000000 --- a/netutils/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Network Utilities - -## Contents - -- uIP Applications -- Other Network Applications -- Tips for Using Telnetd -- Tips for Using DHCPC - -## uIP Applications - -This directory contains most of the network applications contained under the -`uIP-1.0` apps directory. As the uIP `apps/README.md` says, these applications -_are not all heavily tested_. These uIP-based apps include: - -- `dhcpc` – Dynamic Host Configuration Protocol (DHCP) client. See - `apps/include/netutils/dhcpc.h` for interface information. - -- `smtp` – Simple Mail Transfer Protocol (SMTP) client. See - `apps/include/netutils/smtp.h` for interface information. - -- `webclient` – HTTP web client. See `apps/include/netutils/webclient.h` for - interface information. - -- `webserver` – HTTP web server. See `apps/include/netutils/httpd.h` for - interface information. - -You may find additional information on these apps in the uIP forum accessible -through: http://www.sics.se/~adam/uip/index.php/Main_Page. Some of these (such -as the uIP web server) have grown some additional functionality due primarily to -NuttX user contributions. - -## Other Network Applications - -Additional applications that were not part of uIP (but which are highly -influenced by uIP) include: - -- `dhcpd` – Dynamic Host Configuration Protocol (DHCP) server. See - `apps/include/netutils/dhcpd.h` for interface information. - -- `discover` – This daemon is useful for discovering devices in local networks, - especially with DHCP configured devices. It listens for UDP broadcasts which - also can include a device class so that groups of devices can be discovered. - It is also possible to address all classes with a kind of broadcast discover. - (Contributed by Max Holtzberg). - -- `esp8266` – An ESP8266 networking layer contributed by Pierre-Noel Bouteville. - -- `json` – cJSON is an ultra-lightweight, portable, single-file, - simple-as-can-be ANSI-C compliant JSON parser, under MIT license. Embeddable - Lightweight XML-RPC Server discussed at - http://www.drdobbs.com/web-development/an-embeddable-lightweight-xml-rpc-server/184405364. - - This code was taken from http://sourceforge.net/projects/cjson/ and adapted - for NuttX by Darcy Gong. - -- `tftpc` – TFTP client. See `apps/include/netutils/tftp.h` for interface - information. - -- `telnetc` – This is a port of libtelnet to NuttX. This is a public domain - Telnet client library available from - https://github.com/seanmiddleditch/libtelnet modified for use with NuttX. - Original Authors: Sean Middleditch , Jack Kelly - and Katherine Flavel - -- `telnetd` – TELNET server. This is the Telnet logic adapted from uIP and - generalized for use as the front end to any shell. The telnet daemon creates - sessions that are _wrapped_ as character devices and mapped to `stdin`, - `stdout` and `stderr`. Now the telnet session can be inherited by spawned - tasks. - -- `ftpc` – FTP client. See `apps/include/netutils/ftpc.h` for interface - information. - -- `ftpd` – FTP server. See `apps/include/netutils/ftpd.h` for interface - information. - -- `ntpclient` – This is a fragmentary NTP client. It neither well-tested nor - mature nor complete at this point in time. - -- `thttpd` – This is a port of Jef Poskanzer's THTTPD HTPPD server. See - http://acme.com/software/thttpd/ for general THTTPD information. See - `apps/include/netutils/thttpd.h` for interface information. Applications using - this `thttpd` will need to provide the following definitions in the - `defconfig` file to select the appropriate `netutils` libraries: - - ```conf - CONFIG_NETUTILS_NETLIB=y - CONFIG_NETUTILS_THTTPD=y - ``` - -- `xmlrpc` – The Embeddable Lightweight XML-RPC Server discussed at - http://www.drdobbs.com/web-development/an-embeddable-lightweight-xml-rpc-server/184405364 - -- `ping` – This is an unfinished implementation of ping and ping6 using raw - sockets. It is not yet hooked into the configuration or build systems. - - Current `ping`/`ping6` logic in NSH makes illegal calls into the OS in order - to implement `ping`/`ping6`. One correct implementation would be to use raw - sockets to implement `ping`/`ping6` as a user application. This is a first cut - at such an implementation. - -## Tips for Using Telnetd - -Telnetd is set up to be the front end for a shell. The primary use of Telnetd in -NuttX is to support the NuttShell (NSH) Telnet front end. See -`apps/include/netutils/telnetd.h` for information about how to incorporate -Telnetd into your custom applications. - -To enable and link the Telnetd daemon, you need to include the following in in -your defconfig file: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_TELNETD=y -``` - -Also if the Telnet console is enabled, make sure that you have the following set -in the NuttX configuration file or else the performance will be very bad -(because there will be only one character per TCP transfer): - -- `CONFIG_STDIO_BUFFER_SIZE` – Some value `>= 64`. -- `CONFIG_STDIO_LINEBUFFER=y` – Since Telnetd is line oriented, line buffering - is optimal. - -## Tips for Using DHCPC - -If you use DHCPC/D, then some special configuration network options are -required. These include: - -- `CONFIG_NET=y` -- `CONFIG_NET_UDP=y` – UDP support is required for DHCP (as well as various - other UDP-related configuration settings). -- `CONFIG_NET_BROADCAST=y` – UDP broadcast support is needed. -- `CONFIG_NET_ETH_PKTSIZE=650` or larger. The client must be prepared to receive - DHCP messages of up to `576` bytes (excluding Ethernet, IP or UDP headers and - FCS). **Note**: Note that the actual MTU setting will depend upon the specific - link protocol. Here Ethernet is indicated. diff --git a/netutils/connectedhomeip/CMakeLists.txt b/netutils/connectedhomeip/CMakeLists.txt index 4f5988994..3db205e46 100644 --- a/netutils/connectedhomeip/CMakeLists.txt +++ b/netutils/connectedhomeip/CMakeLists.txt @@ -65,8 +65,11 @@ if(CONFIG_MATTER) endfunction() get_filename_component( - CHIP_ROOT ${NUTTX_APPS_DIR}/netutils/connectedhomeip/connectedhomeip + LOCAL_CHIP_ROOT ${NUTTX_APPS_DIR}/netutils/connectedhomeip/connectedhomeip REALPATH) + if(NOT CHIP_ROOT) + set(CHIP_ROOT ${LOCAL_CHIP_ROOT}) + endif() chip_download_and_patch( NAME @@ -74,7 +77,7 @@ if(CONFIG_MATTER) URL https://github.com/project-chip/connectedhomeip/archive/refs/tags/v1.2.0.1.zip SOURCE_DIR - ${CMAKE_CURRENT_LIST_DIR}/connectedhomeip + ${CHIP_ROOT} BINARY_DIR ${CMAKE_BINARY_DIR}/apps/netutils/connectedhomeip TIMEOUT @@ -162,32 +165,20 @@ if(CONFIG_MATTER) set(MATTER_INCDIR ${nuttx_include_dirs} ${CMAKE_BINARY_DIR}/apps/netutils/connectedhomeip/gen/include - ${NUTTX_APPS_DIR}/include ${NUTTX_APPS_DIR}/netutils/jsoncpp/jsoncpp/include inipp nlio/include nlassert/include - connectedhomeip/src - connectedhomeip/src/include - connectedhomeip/src/lib/dnssd - connectedhomeip/src/app/util/mock/include - connectedhomeip/zzz_generated - connectedhomeip/zzz_generated/lighting-app - connectedhomeip/zzz_generated/app-common - connectedhomeip/src/platform/Linux - connectedhomeip/examples/platform/linux - connectedhomeip/examples/lighting-app/lighting-common/include - connectedhomeip/examples/all-clusters-app/all-clusters-common/include) - - set(gn_depens mbedtls) - - if(CONFIG_BT) - set(MATTER_INCDIR - ${MATTER_INCDIR} ${NUTTX_APPS_DIR}/external/zblue/zblue/port/include - ${NUTTX_APPS_DIR}/external/zblue/zblue/include - ${NUTTX_APPS_DIR}/external/zblue/zblue/subsys/testsuite/ztest/include) - list(APPEND gn_depens zblue) - endif() + ${CHIP_ROOT}/src + ${CHIP_ROOT}/src/include + ${CHIP_ROOT}/src/lib/dnssd + ${CHIP_ROOT}/src/app/util/mock/include + ${CHIP_ROOT}/zzz_generated + ${CHIP_ROOT}/zzz_generated/lighting-app + ${CHIP_ROOT}/zzz_generated/app-common + ${CHIP_ROOT}/src/platform/Linux + ${CHIP_ROOT}/examples/platform/linux + ${CHIP_ROOT}/examples/lighting-app/lighting-common/include) set(MATTER_FLAGS -DCHIP_HAVE_CONFIG_H @@ -249,22 +240,10 @@ if(CONFIG_MATTER) endif() endif() - matter_add_gn_arg_bool("enable_eventlist_attribute" true) - matter_add_gn_arg_bool("chip_use_external_jsoncpp" true) matter_add_gn_arg_bool("chip_inet_config_enable_ipv4" CONFIG_NET_IPv4) - matter_add_gn_arg_bool("chip_config_network_layer_ble" CONFIG_BT) - matter_add_gn_arg_bool("chip_enable_wifi" CONFIG_WIRELESS) - matter_add_gn_arg_bool("chip_example_all_clusters_app" - CONFIG_MATTER_EXAMPLE_ALL_CLUSTERS_APP) - matter_add_gn_arg_bool("chip_example_lighting" CONFIG_MATTER_EXAMPLE_LIGHTING) - if(NOT CONFIG_MATTER_LOG) - matter_add_gn_arg_bool("chip_error_logging") - matter_add_gn_arg_bool("chip_progress_logging") - matter_add_gn_arg_bool("chip_detail_logging") - matter_add_gn_arg_bool("chip_automation_logging") - matter_add_gn_arg_bool("chip_pw_tokenizer_logging") - matter_add_gn_arg_bool("chip_use_pw_logging") - endif() + matter_add_gn_arg_bool("chip_enable_ble") + matter_add_gn_arg_bool("chip_example_lighting" true) + matter_add_gn_arg_bool("chip_config_network_layer_ble") matter_get_compiler_flags_from_targets(nuttx) matter_common_gn_args(PROJECT_CONFIG_INC_DIR ${EXTERNAL_MATTER_INCDIR}) @@ -281,75 +260,74 @@ if(CONFIG_MATTER) ${CONFIG_CHIP_BUILD_TESTS} LIB_MBEDTLS GN_DEPENDENCIES - ${gn_depens}) + mbedtls) - add_custom_command( - OUTPUT connectedhomeip/third_party/pigweed/repo - COMMAND rm ${CHIP_ROOT}/third_party/pigweed/repo -rf - COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/pigweed - ${CHIP_ROOT}/third_party/pigweed/repo) + if(${CHIP_ROOT} STREQUAL ${LOCAL_CHIP_ROOT}) + add_custom_command( + OUTPUT connectedhomeip/third_party/pigweed/repo + COMMAND rm ${CHIP_ROOT}/third_party/pigweed/repo -rf + COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/pigweed + ${CHIP_ROOT}/third_party/pigweed/repo) - add_custom_target(chippigweed ALL - DEPENDS connectedhomeip/third_party/pigweed/repo) - ExternalProject_Add_StepDependencies(chip-gn configure chippigweed) + add_custom_target(chippigweed ALL + DEPENDS connectedhomeip/third_party/pigweed/repo) + ExternalProject_Add_StepDependencies(chip-gn configure chippigweed) - add_custom_command( - OUTPUT ${CHIP_ROOT}/build_overrides/pigweed_environment.gni - COMMAND touch ${CHIP_ROOT}/build_overrides/pigweed_environment.gni) + add_custom_command( + OUTPUT ${CHIP_ROOT}/build_overrides/pigweed_environment.gni + COMMAND touch ${CHIP_ROOT}/build_overrides/pigweed_environment.gni) - add_custom_target( - chipnpigweedenv ALL - DEPENDS ${CHIP_ROOT}/build_overrides/pigweed_environment.gni) - ExternalProject_Add_StepDependencies(chip-gn configure chipnpigweedenv) - add_dependencies(chippigweed chipnpigweedenv) + add_custom_target( + chipnpigweedenv ALL + DEPENDS ${CHIP_ROOT}/build_overrides/pigweed_environment.gni) + ExternalProject_Add_StepDependencies(chip-gn configure chipnpigweedenv) + add_dependencies(chippigweed chipnpigweedenv) - add_custom_command( - OUTPUT connectedhomeip/third_party/nlassert/repo - COMMAND rm ${CHIP_ROOT}/third_party/nlassert/repo -rf - COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlassert - ${CHIP_ROOT}/third_party/nlassert/repo) + add_custom_command( + OUTPUT connectedhomeip/third_party/nlassert/repo + COMMAND rm ${CHIP_ROOT}/third_party/nlassert/repo -rf + COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlassert + ${CHIP_ROOT}/third_party/nlassert/repo) - add_custom_target(chipnlassert ALL - DEPENDS connectedhomeip/third_party/nlassert/repo) - ExternalProject_Add_StepDependencies(chip-gn configure chipnlassert) + add_custom_target(chipnlassert ALL + DEPENDS connectedhomeip/third_party/nlassert/repo) + ExternalProject_Add_StepDependencies(chip-gn configure chipnlassert) - add_custom_command( - OUTPUT connectedhomeip/third_party/nlio/repo - COMMAND rm ${CHIP_ROOT}/third_party/nlio/repo -rf - COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlio - ${CHIP_ROOT}/third_party/nlio/repo) + add_custom_command( + OUTPUT connectedhomeip/third_party/nlio/repo + COMMAND rm ${CHIP_ROOT}/third_party/nlio/repo -rf + COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlio + ${CHIP_ROOT}/third_party/nlio/repo) - add_custom_target(chipnlio ALL DEPENDS connectedhomeip/third_party/nlio/repo) - ExternalProject_Add_StepDependencies(chip-gn configure chipnlio) + add_custom_target(chipnlio ALL + DEPENDS connectedhomeip/third_party/nlio/repo) + ExternalProject_Add_StepDependencies(chip-gn configure chipnlio) - add_custom_command( - OUTPUT connectedhomeip/third_party/nlunit-test/repo - COMMAND rm ${CHIP_ROOT}/third_party/nlunit-test/repo -rf - COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlunit-test - ${CHIP_ROOT}/third_party/nlunit-test/repo) + add_custom_command( + OUTPUT connectedhomeip/third_party/nlunit-test/repo + COMMAND rm ${CHIP_ROOT}/third_party/nlunit-test/repo -rf + COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/connectedhomeip/nlunit-test + ${CHIP_ROOT}/third_party/nlunit-test/repo) - add_custom_target(chipnlunit-test ALL - DEPENDS connectedhomeip/third_party/nlunit-test/repo) - ExternalProject_Add_StepDependencies(chip-gn configure chipnlunit-test) + add_custom_target(chipnlunit-test ALL + DEPENDS connectedhomeip/third_party/nlunit-test/repo) + ExternalProject_Add_StepDependencies(chip-gn configure chipnlunit-test) - add_custom_command( - OUTPUT connectedhomeip/third_party/jsoncpp/repo - COMMAND rm -rf ${CHIP_ROOT}/third_party/jsoncpp/repo - COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/jsoncpp/jsoncpp - ${CHIP_ROOT}/third_party/jsoncpp/repo) + add_custom_command( + OUTPUT connectedhomeip/third_party/jsoncpp/repo + COMMAND rm -rf ${CHIP_ROOT}/third_party/jsoncpp/repo + COMMAND ln -s ${NUTTX_APPS_DIR}/netutils/jsoncpp/jsoncpp + ${CHIP_ROOT}/third_party/jsoncpp/repo) - add_custom_target(chipjsoncpp ALL - DEPENDS connectedhomeip/third_party/jsoncpp/repo) - ExternalProject_Add_StepDependencies(chip-gn configure chipjsoncpp) - - if(CONFIG_MATTER_EXAMPLE_LIGHTING) - set(DEMOSRC - ${CHIP_ROOT}/examples/lighting-app/linux/main.cpp - ${CHIP_ROOT}/examples/lighting-app/linux/LightingAppCommandDelegate.cpp) - elseif(CONFIG_MATTER_EXAMPLE_ALL_CLUSTERS_APP) - set(DEMOSRC ${CHIP_ROOT}/examples/all-clusters-app/linux/main.cpp) + add_custom_target(chipjsoncpp ALL + DEPENDS connectedhomeip/third_party/jsoncpp/repo) + ExternalProject_Add_StepDependencies(chip-gn configure chipjsoncpp) endif() + set(DEMOSRC + ${CHIP_ROOT}/examples/lighting-app/linux/main.cpp + ${CHIP_ROOT}/examples/lighting-app/linux/LightingAppCommandDelegate.cpp) + nuttx_add_application( NAME matter diff --git a/netutils/connectedhomeip/Kconfig b/netutils/connectedhomeip/Kconfig index d02c9d5a8..83a93d2bd 100644 --- a/netutils/connectedhomeip/Kconfig +++ b/netutils/connectedhomeip/Kconfig @@ -8,24 +8,3 @@ config MATTER default n ---help--- Enable the Connected Home over IP (CHIP) - -if MATTER - -config MATTER_LOG - bool "Build matter with logs" - default n - ---help--- - To reduce flash size, logs are not opened by default - -choice - prompt "Matter Example Configuration" - default MATTER_EXAMPLE_LIGHTING - -config MATTER_EXAMPLE_LIGHTING - bool "Enable Lighting Example" - -config MATTER_EXAMPLE_ALL_CLUSTERS_APP - bool "Enable All Clusters App Example" -endchoice - -endif diff --git a/netutils/dhcp6c/dhcp6c.c b/netutils/dhcp6c/dhcp6c.c index ae0fa931f..a26472131 100644 --- a/netutils/dhcp6c/dhcp6c.c +++ b/netutils/dhcp6c/dhcp6c.c @@ -49,6 +49,7 @@ #include #include #include +#include #include "netutils/netlib.h" #include "netutils/dhcp6c.h" @@ -432,8 +433,8 @@ static void dhcp6c_get_result(FAR void *handle, presult->t1 = pdhcp6c->t1; presult->t2 = pdhcp6c->t2; - ninfo("T1:%" PRIu32 " T2:%" PRIu32 " for iface %i\n", - presult->t1, presult->t2, pdhcp6c->ifindex); + ninfo("T1:%"PRIu32" T2:%"PRIu32" for iface %i\n", presult->t1, presult->t2, + pdhcp6c->ifindex); } static void dhcp6c_switch_process(FAR void *handle, FAR const char *name) @@ -793,7 +794,7 @@ static int dhcp6c_command(FAR void *handle, enum dhcpv6_msg_e type) goto end; } - ninfo("Sending %s (timeout %" PRIu32 " s)\n", retx->name, timeout); + ninfo("Sending %s (timeout %"PRIu32" s)\n", retx->name, timeout); start = dhcp6c_get_milli_time(); round_start = start; diff --git a/netutils/dhcpc/dhcpc.c b/netutils/dhcpc/dhcpc.c index 88ccbdacc..4027b14ce 100644 --- a/netutils/dhcpc/dhcpc.c +++ b/netutils/dhcpc/dhcpc.c @@ -544,6 +544,7 @@ FAR void *dhcpc_open(FAR const char *interface, FAR const void *macaddr, * used by another client. */ +#if defined(CONFIG_DEV_URANDOM) || defined(CONFIG_DEV_RANDOM) ret = getrandom(pdhcpc->xid, 4, 0); if (ret != 4) { @@ -553,6 +554,9 @@ FAR void *dhcpc_open(FAR const char *interface, FAR const void *macaddr, memcpy(pdhcpc->xid, default_xid, 4); } } +#else + memcpy(pdhcpc->xid, default_xid, 4); +#endif pdhcpc->interface = interface; pdhcpc->maclen = maclen; @@ -955,6 +959,7 @@ int dhcpc_request_async(FAR void *handle, dhcpc_callback_t callback) } pdhcpc->callback = callback; + pdhcpc->cancel = 0; ret = pthread_create(&pdhcpc->thread, NULL, dhcpc_run, pdhcpc); if (ret != 0) { diff --git a/netutils/discover/README.md b/netutils/discover/README.md deleted file mode 100644 index f5516a7e3..000000000 --- a/netutils/discover/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Network Utilities / `discover` - -This daemon is useful for discovering devices in local networks, especially with -DHCP configured devices. It listens for UDP broadcasts which also can include a -device class so that groups of devices can be discovered. It is also possible to -address all classes with a kind of broadcast discover. - -See `nuttx/tools/discover.py` for a client example. diff --git a/netutils/ftpc/README.md b/netutils/ftpc/README.md deleted file mode 100644 index b84980720..000000000 --- a/netutils/ftpc/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# Network Utilities / `ftpc` FTP Client - -## FTP Commands - -- `ABOR` – abort a file transfer -- `ACCT` – send account information -- `APPE` – append to a remote file -- `CDUP` – CWD to the parent of the current directory -- `CWD` – change working directory -- `DELE` – delete a remote file -- `HELP` – return help on using the server -- `LIST` – list remote files -- `MDTM` – return the modification time of a file -- `MKD` – make a remote directory -- `MLSD` – Standardized directory listing (instead of `LIST`) -- `MLST` – Standardized object listing (instead of `LIST`) -- `MODE` – set transfer mode -- `NLST` – name list of remote directory -- `NOOP` – do nothing -- `PASS` – send password -- `PASV` – enter passive mode -- `PORT` – open a data port -- `PWD` – print working directory -- `QUIT` – terminate the connection -- `REIN` – reinitialize the connection -- `RETR` – retrieve a remote file -- `REST` – Sets the point at which a file transfer should start -- `RMD` – remove a remote directory -- `RNFR` – rename from -- `RNTO` – rename to -- `SITE` – site-specific commands -- `SIZE` – return the size of a file -- `STOR` – store a file on the remote host -- `STOU` – store a file uniquely -- `STRU` – set file transfer structure -- `STAT` – return server status -- `SYST` – return system type -- `TYPE` – set transfer type -- `USER` – send username - -## FTP Replies - -- `110` – Restart marker reply. -- `120` – Service ready in nnn minutes. -- `125` – Data connection already open; transfer starting. -- `150` – File status okay; about to open data connection. -- `200` – Command okay. -- `202` – Command not implemented, superfluous at this site. -- `211` – System status, or system help reply. -- `212` – Directory status. -- `213` – File status. -- `214` – Help message. -- `215` – NAME system type. -- `220` – Service ready for new user. -- `221` – Service closing control connection. -- `225` – Data connection open; no transfer in progress. -- `226` – Closing data connection. -- `227` – Entering Passive Mode (`h1`, `h2`, `h3`, `h4`, `p1`, `p2`). -- `230` – User logged in, proceed. -- `250` – Requested file action okay, completed. -- `257` – `PATHNAME` created. -- `331` – User name okay, need password. -- `332` – Need account for login. -- `350` – Requested file action pending further information. -- `421` – Service not available, closing control connection. -- `425` – Can't open data connection. -- `426` – Connection closed; transfer aborted. -- `450` – Requested file action not taken. -- `451` – Requested action aborted: local error in processing. -- `452` – Requested action not taken. -- `500` – Syntax error, command unrecognized. -- `501` – Syntax error in parameters or arguments. -- `502` – Command not implemented. -- `503` – Bad sequence of commands. -- `504` – Command not implemented for that parameter. -- `530` – Not logged in. -- `532` – Need account for storing files. -- `550` – Requested action not taken. -- `551` – Requested action aborted: page type unknown. -- `552` – Requested file action aborted. -- `553` – Requested action not taken. diff --git a/netutils/ftpc/ftpc_socket.c b/netutils/ftpc/ftpc_socket.c index 0856ba255..974bd1212 100644 --- a/netutils/ftpc/ftpc_socket.c +++ b/netutils/ftpc/ftpc_socket.c @@ -260,8 +260,7 @@ int ftpc_sockaccept(FAR struct ftpc_socket_s *acceptor, } addrlen = sizeof(addr); - sock->sd = accept4(acceptor->sd, (struct sockaddr *)&addr, &addrlen, - SOCK_CLOEXEC); + sock->sd = accept(acceptor->sd, (struct sockaddr *)&addr, &addrlen); if (sock->sd == -1) { nerr("ERROR: accept() failed: %d\n", errno); diff --git a/netutils/ftpd/ftpd.c b/netutils/ftpd/ftpd.c index 9df08a1a6..0e24c1047 100644 --- a/netutils/ftpd/ftpd.c +++ b/netutils/ftpd/ftpd.c @@ -915,7 +915,7 @@ static int ftpd_accept(int sd, FAR void *addr, FAR socklen_t *addrlen, /* Accept the connection -- waiting if necessary */ - acceptsd = accept4(sd, (FAR struct sockaddr *)addr, addrlen, SOCK_CLOEXEC); + acceptsd = accept(sd, (FAR struct sockaddr *)addr, addrlen); if (acceptsd < 0) { int errval = errno; diff --git a/netutils/iperf/README.md b/netutils/iperf/README.md deleted file mode 100644 index 89d95feb1..000000000 --- a/netutils/iperf/README.md +++ /dev/null @@ -1,94 +0,0 @@ -Overview -================================================================ - -This is a NuttX port of the ESP-IDF iperf example. [1] - -It doesn't support all features in standard iperf. -It's supposed to be compatible with iperf version 2.x. [2] - -[1] https://github.com/espressif/esp-idf/tree/master/examples/wifi/iperf -[2] https://sourceforge.net/projects/iperf2/ - -Configuring NuttX to use your Wireless Router (aka Access Point) -================================================================ - - Since you are already in the root of NuttX/ repository, execute - make menuconfig to define your Wireless Router and your password: - - $ make menuconfig - - Browser the menus this way: - - Application Configuration ---> - Network Utilities ---> - Networking Configuration ---> - WAPI Configuration ---> - (myApSSID) SSID - (mySSIDpassphrase) Passprhase - - Replace the SSID from myApSSID with your wireless router name and - the Passprhase with your WiFi password. - - Exit and save your configuration. - -iperf Test Example -=================================== - -To set up, do `make menuconfig` and select the Apps > netutils > iperf example. By default, NuttX will the be the client -which sends data; and the host computer (Linux, macOS, or Windows) will be the server. - -Set up networking so the NuttX computer can ping the host, and the host can ping NuttX. Now you are ready to run the -test. - -If you are using a wireless network card, you must first connect to the router: - -On host: - - $ iperf -s -p 5471 -i 1 -w 416K - ------------------------------------------------------------ - Server listening on TCP port 5471 - TCP window size: 416 KByte - ------------------------------------------------------------ - -On NuttX: - - nsh> iperf -c 192.168.1.181 -p 5471 -i 1 -t 10 - mode=tcp-client sip=192.168.1.198:5001, dip=192.168.1.181:5471, interval=1, time=10 - - Interval Bandwidth - - 0- 1 sec, 0.39 Mbits/sec - 1- 2 sec, 0.26 Mbits/sec - 2- 3 sec, 0.39 Mbits/sec - 3- 4 sec, 0.26 Mbits/sec - 4- 5 sec, 0.26 Mbits/sec - 5- 6 sec, 0.26 Mbits/sec - 6- 7 sec, 0.26 Mbits/sec - 7- 8 sec, 0.26 Mbits/sec - 8- 9 sec, 0.26 Mbits/sec - 9- 10 sec, 0.26 Mbits/sec - 0- 10 sec, 0.28 Mbits/sec - -Now on the host you should see something like: - - $ iperf -s -p 5471 -i 1 -w 416K - ------------------------------------------------------------ - Server listening on TCP port 5471 - TCP window size: 416 KByte - ------------------------------------------------------------ - [ 5] local 192.168.1.181 port 5471 connected with 192.168.1.198 port 4210 - [ 5] 0.0- 1.0 sec 60.8 KBytes 498 Kbits/sec - [ 5] 1.0- 2.0 sec 34.9 KBytes 286 Kbits/sec - [ 5] 2.0- 3.0 sec 33.7 KBytes 276 Kbits/sec - [ 5] 3.0- 4.0 sec 33.4 KBytes 274 Kbits/sec - [ 5] 4.0- 5.0 sec 32.0 KBytes 262 Kbits/sec - [ 5] 5.0- 6.0 sec 32.0 KBytes 262 Kbits/sec - [ 5] 6.0- 7.0 sec 33.4 KBytes 274 Kbits/sec - [ 5] 7.0- 8.0 sec 32.0 KBytes 262 Kbits/sec - [ 5] 8.0- 9.0 sec 32.0 KBytes 262 Kbits/sec - [ 5] 9.0-10.0 sec 33.4 KBytes 274 Kbits/sec - [ 5] 0.0-10.3 sec 368 KBytes 292 Kbits/sec - - -This will tell you the link speed in Kbits/sec – kilobits per second. If you want kilobytes, divide by 8. - diff --git a/netutils/iperf/iperf.c b/netutils/iperf/iperf.c index 55ee3ca8e..dfd1f3b69 100644 --- a/netutils/iperf/iperf.c +++ b/netutils/iperf/iperf.c @@ -520,7 +520,7 @@ static int iperf_tcp_server(FAR struct iperf_ctrl_t *ctrl, { /* TODO need to change to non-block mode */ - sockfd = accept4(listen_socket, remote_addr, &addrlen, SOCK_CLOEXEC); + sockfd = accept(listen_socket, remote_addr, &addrlen); if (sockfd < 0) { iperf_show_socket_error_reason("tcp server listen", listen_socket); diff --git a/netutils/libcoap/Makefile b/netutils/libcoap/Makefile index e69c9be17..393bce0c2 100644 --- a/netutils/libcoap/Makefile +++ b/netutils/libcoap/Makefile @@ -22,34 +22,34 @@ include $(APPDIR)/Make.defs COAP_URL ?= "https://codeload.github.com/obgm/libcoap/zip/refs/tags" -LIBCOAP_VERSION = $(patsubst "%",%,$(strip $(CONFIG_LIBCOAP_VERSION))) -COAP_ZIP = libcoap-$(LIBCOAP_VERSION).zip +COAP_ZIP = libcoap-$(CONFIG_LIBCOAP_VERSION).zip COAP_UNPACKNAME = libcoap UNPACK ?= unzip -q -o $(COAP_ZIP): - @echo "Downloading: $(COAP_URL)/v$(LIBCOAP_VERSION)" - $(Q) curl -o $(COAP_ZIP) -L $(COAP_URL)/v$(LIBCOAP_VERSION) + @echo "Downloading: $(COAP_URL)/v$(CONFIG_LIBCOAP_VERSION)" + $(Q) curl -o $(COAP_ZIP) -L $(COAP_URL)/v$(CONFIG_LIBCOAP_VERSION) $(COAP_UNPACKNAME): $(COAP_ZIP) @echo "Unpacking: $(COAP_ZIP) -> $(COAP_UNPACKNAME)" $(Q) $(UNPACK) $(COAP_ZIP) @echo "Unpacking: $(COAP_ZIP) -> $(COAP_UNPACKNAME)" - $(Q) mv libcoap-$(LIBCOAP_VERSION) $(COAP_UNPACKNAME) + $(Q) mv libcoap-$(CONFIG_LIBCOAP_VERSION) $(COAP_UNPACKNAME) $(Q) touch $(COAP_UNPACKNAME) -context:: $(COAP_UNPACKNAME)/include/coap3/coap.h # Download and unpack tarball if no git repo found ifeq ($(wildcard $(COAP_UNPACKNAME)/.git),) +context:: $(COAP_UNPACKNAME) + distclean:: $(call DELDIR, $(COAP_UNPACKNAME)) $(call DELFILE, $(COAP_ZIP)) +endif + +context:: $(COAP_UNPACKNAME)/include/coap3/coap.h $(COAP_UNPACKNAME)/include/coap3/coap.h:: $(COAP_UNPACKNAME) -else -$(COAP_UNPACKNAME)/include/coap3/coap.h:: -endif cd $(COAP_UNPACKNAME) && ./autogen.sh && \ ./configure --disable-doxygen --disable-manpages diff --git a/netutils/libcurl4nx/curl4nx_easy_perform.c b/netutils/libcurl4nx/curl4nx_easy_perform.c index a0db57afc..0fdaa1b5a 100644 --- a/netutils/libcurl4nx/curl4nx_easy_perform.c +++ b/netutils/libcurl4nx/curl4nx_easy_perform.c @@ -522,7 +522,7 @@ int curl4nx_easy_perform(FAR struct curl4nx_s *handle) redirected = true; redircount += 1; - curl4nx_info(" + curl4nx_info("\ REDIRECTION (%d) -> %s\n", redircount, headerbuf + off); diff --git a/netutils/libwebsockets/.gitignore b/netutils/libwebsockets/.gitignore deleted file mode 100644 index 53943e1e5..000000000 --- a/netutils/libwebsockets/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/libwebsockets diff --git a/netutils/libwebsockets/CMakeLists.txt b/netutils/libwebsockets/CMakeLists.txt deleted file mode 100644 index 7977f9311..000000000 --- a/netutils/libwebsockets/CMakeLists.txt +++ /dev/null @@ -1,188 +0,0 @@ -# ############################################################################## -# apps/netutils/libwebsockets/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_NETUTILS_LIBWEBSOCKETS) - - # ############################################################################ - # Config and Fetch MbedTLS lib - # ############################################################################ - - set(LIBWEBSOCKETS_DIR ${CMAKE_CURRENT_LIST_DIR}/libwebsockets) - - if(NOT EXISTS ${LIBWEBSOCKETS_DIR}) - set(LIBWEBSOCKETS_URL "https://github.com/warmcat/libwebsockets/archive") - FetchContent_Declare( - libwebsockets_fetch - URL ${LIBWEBSOCKETS_URL}/v${CONFIG_NETUTILS_LIBWEBSOCKETS_VERSION}.zip - SOURCE_DIR ${LIBWEBSOCKETS_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/netutils/libwebsockets/libwebsockets - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(libwebsockets_fetch) - - if(NOT libwebsockets_fetch_POPULATED) - FetchContent_Populate(libwebsockets_fetch) - endif() - - execute_process( - COMMAND sh -c "patch -p0 < ${CMAKE_CURRENT_LIST_DIR}/libwebsockets.patch" - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) - message("patching done") - endif() - - # ############################################################################ - # Flags - # ############################################################################ - - string(REGEX MATCHALL "[0-9]" versions - "${CONFIG_NETUTILS_LIBWEBSOCKETS_VERSION}") - list(GET versions 0 VERSION_MAJOR) - list(GET versions 1 VERSION_MINOR) - list(GET versions 2 VERSION_PATCH) - set(FLAGS - -DLWS_LIBRARY_VERSION_MAJOR=${VERSION_MAJOR} - -DLWS_LIBRARY_VERSION_MINOR=${VERSION_MINOR} - -DLWS_LIBRARY_VERSION_PATCH=${VERSION_PATCH} - -DLWS_LIBRARY_VERSION_PATCH_ELABORATED=${VERSION_PATCH}-unknown - -DLWS_LIBRARY_VERSION="${CONFIG_NETUTILS_LIBWEBSOCKETS_VERSION}-unknown" - -Wno-shadow) - - set(INCDIR - . - ${LIBWEBSOCKETS_DIR}/lib/core - ${LIBWEBSOCKETS_DIR}/lib/plat/unix - ${LIBWEBSOCKETS_DIR}/lib/event-libs - ${LIBWEBSOCKETS_DIR}/lib/system/smd - ${LIBWEBSOCKETS_DIR}/lib/system/metrics - ${LIBWEBSOCKETS_DIR}/lib/core-net - ${LIBWEBSOCKETS_DIR}/lib/roles - ${LIBWEBSOCKETS_DIR}/lib/roles/http - ${LIBWEBSOCKETS_DIR}/lib/roles/h1 - ${LIBWEBSOCKETS_DIR}/lib/roles/h2 - ${LIBWEBSOCKETS_DIR}/lib/roles/ws - ${LIBWEBSOCKETS_DIR}/lib/tls - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/wrapper/include - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/wrapper/include/internal) - - set(CSRCS - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-caps.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-misc.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-init.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-file.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-pipe.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-service.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-sockets.c - ${LIBWEBSOCKETS_DIR}/lib/plat/unix/unix-fds.c - ${LIBWEBSOCKETS_DIR}/lib/core/alloc.c - ${LIBWEBSOCKETS_DIR}/lib/core/buflist.c - ${LIBWEBSOCKETS_DIR}/lib/core/context.c - ${LIBWEBSOCKETS_DIR}/lib/core/lws_dll2.c - ${LIBWEBSOCKETS_DIR}/lib/core/lws_map.c - ${LIBWEBSOCKETS_DIR}/lib/core/libwebsockets.c - ${LIBWEBSOCKETS_DIR}/lib/core/logs.c - ${LIBWEBSOCKETS_DIR}/lib/core/vfs.c - ${LIBWEBSOCKETS_DIR}/lib/misc/base64-decode.c - ${LIBWEBSOCKETS_DIR}/lib/misc/cache-ttl/lws-cache-ttl.c - ${LIBWEBSOCKETS_DIR}/lib/misc/cache-ttl/heap.c - ${LIBWEBSOCKETS_DIR}/lib/misc/cache-ttl/file.c - ${LIBWEBSOCKETS_DIR}/lib/misc/dir.c - ${LIBWEBSOCKETS_DIR}/lib/misc/prng.c - ${LIBWEBSOCKETS_DIR}/lib/misc/lws-ring.c - ${LIBWEBSOCKETS_DIR}/lib/misc/lwsac/lwsac.c - ${LIBWEBSOCKETS_DIR}/lib/misc/lwsac/cached-file.c - ${LIBWEBSOCKETS_DIR}/lib/misc/lejp.c - ${LIBWEBSOCKETS_DIR}/lib/misc/sha-1.c - ${LIBWEBSOCKETS_DIR}/lib/system/system.c - ${LIBWEBSOCKETS_DIR}/lib/system/smd/smd.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/dummy-callback.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/output.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/close.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/network.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/vhost.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/pollfd.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/service.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/sorted-usec-list.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/wsi.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/wsi-timeout.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/adopt.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/state.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/client.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/connect.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/connect2.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/connect3.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/connect4.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/sort-dns.c - ${LIBWEBSOCKETS_DIR}/lib/core-net/client/conmon.c - ${LIBWEBSOCKETS_DIR}/lib/roles/pipe/ops-pipe.c - ${LIBWEBSOCKETS_DIR}/lib/roles/http/header.c - ${LIBWEBSOCKETS_DIR}/lib/roles/http/date.c - ${LIBWEBSOCKETS_DIR}/lib/roles/http/parsers.c - ${LIBWEBSOCKETS_DIR}/lib/roles/http/cookie.c - ${LIBWEBSOCKETS_DIR}/lib/roles/h1/ops-h1.c - ${LIBWEBSOCKETS_DIR}/lib/roles/h2/http2.c - ${LIBWEBSOCKETS_DIR}/lib/roles/h2/hpack.c - ${LIBWEBSOCKETS_DIR}/lib/roles/h2/ops-h2.c - ${LIBWEBSOCKETS_DIR}/lib/roles/ws/ops-ws.c - ${LIBWEBSOCKETS_DIR}/lib/roles/ws/client-ws.c - ${LIBWEBSOCKETS_DIR}/lib/roles/ws/client-parser-ws.c - ${LIBWEBSOCKETS_DIR}/lib/roles/raw-skt/ops-raw-skt.c - ${LIBWEBSOCKETS_DIR}/lib/roles/raw-file/ops-raw-file.c - ${LIBWEBSOCKETS_DIR}/lib/roles/http/client/client-http.c - ${LIBWEBSOCKETS_DIR}/lib/event-libs/poll/poll.c - ${LIBWEBSOCKETS_DIR}/lib/tls/tls.c - ${LIBWEBSOCKETS_DIR}/lib/tls/tls-network.c - ${LIBWEBSOCKETS_DIR}/lib/tls/tls-sessions.c - ${LIBWEBSOCKETS_DIR}/lib/tls/tls-client.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-tls.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-extensions.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-x509.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-ssl.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-session.c - ${LIBWEBSOCKETS_DIR}/lib/tls/mbedtls/mbedtls-client.c) - - if(CONFIG_NETUTILS_MQTTC) - list(APPEND INCDIR ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt) - list( - APPEND - CSRCS - ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt/mqtt.c - ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt/ops-mqtt.c - ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt/primitives.c - ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt/client/client-mqtt.c - ${LIBWEBSOCKETS_DIR}/lib/roles/mqtt/client/client-mqtt-handshake.c) - - endif() - - # ############################################################################ - # Library Configuration - # ############################################################################ - - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${LIBWEBSOCKETS_DIR}/include) - - nuttx_add_library(libwebsockets STATIC) - target_sources(libwebsockets PRIVATE ${CSRCS}) - target_compile_options(libwebsockets PRIVATE ${FLAGS}) - target_include_directories(libwebsockets PRIVATE ${INCDIR}) - -endif() diff --git a/netutils/libwebsockets/Kconfig b/netutils/libwebsockets/Kconfig deleted file mode 100644 index 07686db68..000000000 --- a/netutils/libwebsockets/Kconfig +++ /dev/null @@ -1,19 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config NETUTILS_LIBWEBSOCKETS - bool "libwebsockets library (current version)" - default n - depends on NET && OPENSSL_MBEDTLS_WRAPPER - ---help--- - Enables the libwebsockets library. - -if NETUTILS_LIBWEBSOCKETS - -config NETUTILS_LIBWEBSOCKETS_VERSION - string "Version number" - default "4.3.1" - -endif diff --git a/netutils/libwebsockets/Make.defs b/netutils/libwebsockets/Make.defs deleted file mode 100644 index 7094809e5..000000000 --- a/netutils/libwebsockets/Make.defs +++ /dev/null @@ -1,29 +0,0 @@ -############################################################################# -# apps/netutils/libwebsockets/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################# - -ifeq ($(CONFIG_NETUTILS_LIBWEBSOCKETS),y) -CONFIGURED_APPS += $(APPDIR)/netutils/libwebsockets - -# Allows `.h>` import. - -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/netutils/libwebsockets/libwebsockets/include -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/netutils/libwebsockets/libwebsockets/include - -endif diff --git a/netutils/libwebsockets/Makefile b/netutils/libwebsockets/Makefile deleted file mode 100644 index f95e77ecb..000000000 --- a/netutils/libwebsockets/Makefile +++ /dev/null @@ -1,162 +0,0 @@ -############################################################################# -# apps/netutils/libwebsockets/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################# - -include $(APPDIR)/Make.defs - -LIBWEBSOCKETS_URL ?= "https://github.com/warmcat/libwebsockets/archive" - -LIBWEBSOCKETS_VERSION := $(patsubst "%",%,$(CONFIG_NETUTILS_LIBWEBSOCKETS_VERSION)) -LIBWEBSOCKETS_TARBALL = v$(LIBWEBSOCKETS_VERSION).tar.gz -LIBWEBSOCKETS_UNPACK = libwebsockets - -word-dot = $(word $2,$(subst ., ,$1)) - -CFLAGS += \ - -DLWS_LIBRARY_VERSION_MAJOR=$(call word-dot,$(LIBWEBSOCKETS_VERSION),1) \ - -DLWS_LIBRARY_VERSION_MINOR=$(call word-dot,$(LIBWEBSOCKETS_VERSION),2) \ - -DLWS_LIBRARY_VERSION_PATCH=$(call word-dot,$(LIBWEBSOCKETS_VERSION),3) \ - -DLWS_LIBRARY_VERSION_PATCH_ELABORATED=$(call word-dot,$(LIBWEBSOCKETS_VERSION),3)-unknown \ - -DLWS_LIBRARY_VERSION=\"$(LIBWEBSOCKETS_VERSION)-unknown\" - -CFLAGS += \ - -I. \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/core \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/plat/unix \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/event-libs \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/system/smd \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/system/metrics \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/core-net \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/roles \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/roles/http \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/roles/h1 \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/roles/h2 \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/roles/ws \ - -I$(LIBWEBSOCKETS_UNPACK)/lib/tls - -CSRCS += \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-caps.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-misc.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-init.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-file.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-pipe.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-service.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-sockets.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/plat/unix/unix-fds.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/alloc.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/buflist.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/context.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/lws_dll2.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/lws_map.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/libwebsockets.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/logs.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core/vfs.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/base64-decode.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/cache-ttl/lws-cache-ttl.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/cache-ttl/heap.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/cache-ttl/file.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/dir.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/prng.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/lws-ring.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/lwsac/lwsac.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/lwsac/cached-file.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/lejp.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/misc/sha-1.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/system/system.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/system/smd/smd.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/dummy-callback.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/output.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/close.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/network.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/vhost.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/pollfd.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/service.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/sorted-usec-list.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/wsi.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/wsi-timeout.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/adopt.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/state.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/client.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/connect.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/connect2.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/connect3.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/connect4.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/sort-dns.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/core-net/client/conmon.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/pipe/ops-pipe.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/http/header.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/http/date.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/http/parsers.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/http/cookie.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/h1/ops-h1.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/h2/http2.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/h2/hpack.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/h2/ops-h2.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/ws/ops-ws.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/ws/client-ws.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/ws/client-parser-ws.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/raw-skt/ops-raw-skt.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/raw-file/ops-raw-file.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/http/client/client-http.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/event-libs/poll/poll.c - -CSRCS += \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/tls.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/tls-network.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/tls-sessions.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/tls-client.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-tls.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-extensions.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-x509.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-ssl.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-session.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/tls/mbedtls/mbedtls-client.c \ - -ifneq ($(CONFIG_NETUTILS_MQTTC),) - CFLAGS += -I$(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt - - CSRCS += \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt/mqtt.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt/ops-mqtt.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt/primitives.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt/client/client-mqtt.c \ - $(LIBWEBSOCKETS_UNPACK)/lib/roles/mqtt/client/client-mqtt-handshake.c -endif - -ifeq ($(wildcard $(LIBWEBSOCKETS_UNPACK)/.git),) -$(LIBWEBSOCKETS_TARBALL): - $(Q) echo "Downloading libwebsockets-$(LIBWEBSOCKETS_VERSION)" - $(Q) curl -O -L $(LIBWEBSOCKETS_URL)/$(LIBWEBSOCKETS_TARBALL) - -$(LIBWEBSOCKETS_UNPACK): $(LIBWEBSOCKETS_TARBALL) - $(Q) echo "Unpacking: $(LIBWEBSOCKETS_TARBALL) -> $(LIBWEBSOCKETS_UNPACK)" - $(Q) tar zxf $(LIBWEBSOCKETS_TARBALL) - $(Q) mv libwebsockets-$(LIBWEBSOCKETS_VERSION) $(LIBWEBSOCKETS_UNPACK) - $(Q) echo "Patching $(LIBWEBSOCKETS_UNPACK)" - $(Q) patch -p0 < libwebsockets.patch - $(Q) touch $(LIBWEBSOCKETS_UNPACK) - -context:: $(LIBWEBSOCKETS_UNPACK) - -distclean:: - $(call DELFILE, $(LIBWEBSOCKETS_TARBALL)) - $(call DELDIR, $(LIBWEBSOCKETS_UNPACK)) -endif - -include $(APPDIR)/Application.mk diff --git a/netutils/libwebsockets/libwebsockets.patch b/netutils/libwebsockets/libwebsockets.patch deleted file mode 100644 index f2468fa6f..000000000 --- a/netutils/libwebsockets/libwebsockets.patch +++ /dev/null @@ -1,80 +0,0 @@ ---- libwebsockets/include/libwebsockets.h -+++ libwebsockets/include/libwebsockets.h -@@ -146,7 +146,7 @@ typedef int suseconds_t; - #include - #endif - --#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__QNX__) || defined(__OpenBSD__) -+#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__QNX__) || defined(__OpenBSD__) || defined(__NuttX__) - #include - #include - #endif - ---- libwebsockets/lib/plat/unix/private-lib-plat-unix.h -+++ libwebsockets/lib/plat/unix/private-lib-plat-unix.h -@@ -123,7 +123,7 @@ typedef pthread_mutex_t lws_mutex_t; - - #endif - --#if defined (__sun) || defined(__HAIKU__) || defined(__QNX__) || defined(__ANDROID__) -+#if defined (__sun) || defined(__HAIKU__) || defined(__QNX__) || defined(__ANDROID__) || defined(__NuttX__) - #include - - #if defined(__ANDROID__) - ---- libwebsockets/lib/plat/unix/unix-sockets.c -+++ libwebsockets/lib/plat/unix/unix-sockets.c -@@ -171,7 +171,7 @@ lws_plat_set_socket_options(struct lws_vhost *vhost, int fd, int unix_skt) - - /* Disable Nagle */ - optval = 1; --#if defined (__sun) || defined(__QNX__) -+#if defined (__sun) || defined(__QNX__) || defined(__NuttX__) - if (!unix_skt && setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&optval, optlen) < 0) - return 1; - #elif !defined(__APPLE__) && \ -@@ -237,7 +239,8 @@ lws_plat_set_socket_options_ip(lws_sockfd_type fd, uint8_t pri, int lws_flags) - !defined(__sun) && \ - !defined(__HAIKU__) && \ - !defined(__CYGWIN__) && \ -- !defined(__QNX__) -+ !defined(__QNX__) && \ -+ !defined(__NuttX__) - - /* the BSDs don't have SO_PRIORITY */ - - ---- libwebsockets/lib/roles/ws/client-ws.c -+++ libwebsockets/lib/roles/ws/client-ws.c -@@ -257,15 +257,15 @@ lws_client_ws_upgrade(struct lws *wsi, const char **cce) - } - - if (wsi->http.ah->http_response == 401) { -- lwsl_wsi_warn(wsi, "got bad HTTP response '%d'", -- wsi->http.ah->http_response); -+ lwsl_wsi_warn(wsi, "got bad HTTP response '%ld'", -+ (long)wsi->http.ah->http_response); - *cce = "HS: ws upgrade unauthorized"; - goto bail3; - } - - if (wsi->http.ah->http_response != 101) { -- lwsl_wsi_warn(wsi, "got bad HTTP response '%d'", -- wsi->http.ah->http_response); -+ lwsl_wsi_warn(wsi, "got bad HTTP response '%ld'", -+ (long)wsi->http.ah->http_response); - *cce = "HS: ws upgrade response not 101"; - goto bail3; - } - ---- libwebsockets/lib/secure-streams/system/auth-sigv4/sign.c -+++ libwebsockets/lib/secure-streams/system/auth-sigv4/sign.c -@@ -459,7 +459,7 @@ lws_ss_sigv4_set_aws_key(struct lws_context* context, uint8_t idx, - - #if defined(__linux__) || defined(__APPLE__) || defined(WIN32) || \ - defined(__FreeBSD__) || defined(__NetBSD__) || defined(__ANDROID__) || \ -- defined(__sun) || defined(__OpenBSD__) -+ defined(__sun) || defined(__OpenBSD__) || defined(__NuttX__) - - /* ie, if we have filesystem ops */ - diff --git a/netutils/libwebsockets/lws_config.h b/netutils/libwebsockets/lws_config.h deleted file mode 100644 index d4903b8a4..000000000 --- a/netutils/libwebsockets/lws_config.h +++ /dev/null @@ -1,382 +0,0 @@ -/**************************************************************************** - * apps/netutils/libwebsockets/lws_config.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_NETUTILS_LIBWEBSOCKETS_LWS_CONFIG_H -#define __APPS_NETUTILS_LIBWEBSOCKETS_LWS_CONFIG_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifndef NDEBUG - #ifndef _DEBUG - #define _DEBUG - #endif -#endif - -/* LWS_LIBRARY_VERSION_NUMBER looks like 1005001 for e.g. version 1.5.1 */ -#define LWS_LIBRARY_VERSION_NUMBER (LWS_LIBRARY_VERSION_MAJOR * 1000000) + \ - (LWS_LIBRARY_VERSION_MINOR * 1000) + \ - LWS_LIBRARY_VERSION_PATCH -#define LWS_MAX_SMP 1 - -/* #undef LWS_ESP_PLATFORM */ - -/* #undef LWS_LIBRARY_VERSION_NUMBER */ - -/* #undef LWS_EXT_PTHREAD_LIBRARIES */ - -/* #undef LWS_AVOID_SIGPIPE_IGN */ -#define LWS_BUILD_HASH "unknown" -/* #undef LWS_BUILTIN_GETIFADDRS */ -#define LWS_CLIENT_HTTP_PROXYING -/* #undef LWS_DETECTED_PLAT_IOS */ - -/* #undef LWS_FALLBACK_GETHOSTBYNAME */ -#define LWS_HAS_INTPTR_T -#define LWS_HAS_GETOPT_LONG -/* #undef LWS_HAVE__ATOI64 */ -#define LWS_HAVE_ATOLL -/* #undef LWS_HAVE_BN_bn2binpad */ -#define LWS_HAVE_CLOCK_GETTIME -/* #undef LWS_HAVE_EC_POINT_get_affine_coordinates */ - -/* #undef LWS_HAVE_EC_KEY_new_by_curve_name */ - -/* #undef LWS_HAVE_ECDSA_SIG_set0 */ - -/* #undef LWS_HAVE_EVP_MD_CTX_free */ - -/* #undef LWS_HAVE_EVP_aes_128_wrap */ - -/* #undef LWS_HAVE_EVP_aes_128_cfb8 */ - -/* #undef LWS_HAVE_EVP_aes_128_cfb128 */ - -/* #undef LWS_HAVE_EVP_aes_192_cfb8 */ - -/* #undef LWS_HAVE_EVP_aes_192_cfb128 */ - -/* #undef LWS_HAVE_EVP_aes_256_cfb8 */ - -/* #undef LWS_HAVE_EVP_aes_256_cfb128 */ - -/* #undef LWS_HAVE_EVP_aes_128_ofb */ - -/* #undef LWS_HAVE_EVP_aes_128_xts */ - -/* #undef LWS_HAVE_EVP_aes_128_ctr */ - -/* #undef LWS_HAVE_EVP_aes_128_ecb */ - -/* #undef LWS_HAVE_EVP_PKEY_new_raw_private_key */ - -/* #define LWS_HAVE_EXECVPE */ -#define LWS_HAVE_LOCALTIME_R -#define LWS_HAVE_GMTIME_R -#define LWS_HAVE_CTIME_R -#define LWS_HAVE_GETGRGID_R -#define LWS_HAVE_GETGRNAM_R -#define LWS_HAVE_GETPWUID_R -#define LWS_HAVE_GETPWNAM_R -/* #undef LWS_HAVE_LIBCAP */ - -/* #undef LWS_HAVE_HMAC_CTX_new */ -#define LWS_HAVE_MALLOC_H -/* #define LWS_HAVE_MALLOC_TRIM */ -#define LWS_HAVE_MALLOC_USABLE_SIZE -#ifdef CONFIG_CRYPTO_MBEDTLS -#define LWS_HAVE_mbedtls_md_setup -#define LWS_HAVE_mbedtls_net_init -#define LWS_HAVE_mbedtls_rsa_complete -#define LWS_HAVE_mbedtls_internal_aes_encrypt -#define LWS_HAVE_mbedtls_ssl_conf_alpn_protocols -#define LWS_HAVE_mbedtls_ssl_get_alpn_protocol -#define LWS_HAVE_mbedtls_ssl_conf_sni -#define LWS_HAVE_mbedtls_ssl_set_hs_ca_chain -#define LWS_HAVE_mbedtls_ssl_set_hs_own_cert -#define LWS_HAVE_mbedtls_ssl_set_hs_authmode -#define LWS_HAVE_mbedtls_ssl_set_verify -#define LWS_HAVE_mbedtls_x509_crt_parse_file -#define LWS_HAVE_MBEDTLS_NET_SOCKETS -/* #undef LWS_HAVE_MBEDTLS_AUTH_KEY_ID */ - -#endif -/* #undef LWS_HAVE_NEW_UV_VERSION_H */ - -/* #undef LWS_HAVE_OPENSSL_ECDH_H */ - -/* #undef LWS_HAVE_OPENSSL_STACK */ - -#ifdef CONFIG_PIPES -#define LWS_HAVE_PIPE2 -#endif -#ifdef CONFIG_EVENT_FD -#define LWS_HAVE_EVENTFD -#endif -#ifndef CONFIG_DISABLE_PTHREAD -#define LWS_HAVE_PTHREAD_H -#endif -/* #undef LWS_HAVE_RSA_SET0_KEY */ - -/* #undef LWS_HAVE_RSA_verify_pss_mgf1 */ - -/* #undef LWS_HAVE_SSL_CTX_get0_certificate */ - -/* #undef LWS_HAVE_SSL_CTX_load_verify_file */ - -/* #undef LWS_HAVE_SSL_CTX_load_verify_dir */ - -/* #undef LWS_HAVE_SSL_CTX_set1_param */ - -/* #undef LWS_HAVE_SSL_CTX_set_ciphersuites */ - -/* #undef LWS_HAVE_SSL_EXTRA_CHAIN_CERTS */ - -/* #undef LWS_HAVE_SSL_get0_alpn_selected */ - -/* #undef LWS_HAVE_SSL_CTX_EVP_PKEY_new_raw_private_key */ - -/* #undef LWS_HAVE_SSL_set_alpn_protos */ - -/* #undef LWS_HAVE_SSL_SET_INFO_CALLBACK */ - -/* #undef LWS_HAVE_SSL_SESSION_set_time */ - -/* #undef LWS_HAVE_SSL_SESSION_up_ref */ - -/* #undef LWS_HAVE__STAT32I64 */ - -#define LWS_HAVE_STDINT_H -/* #undef LWS_HAVE_SYS_CAPABILITY_H */ -#define LWS_HAVE_TIMEGM -/* #undef LWS_HAVE_TLS_CLIENT_METHOD */ - -/* #undef LWS_HAVE_TLSV1_2_CLIENT_METHOD */ -#define LWS_HAVE_SUSECONDS_T -/* #undef LWS_HAVE_UV_VERSION_H */ -#define LWS_HAVE_VFORK -/* #undef LWS_HAVE_X509_get_key_usage */ - -/* #undef LWS_HAVE_X509_VERIFY_PARAM_set1_host */ -#define LWS_LOGGING_BITFIELD_CLEAR 0 -#define LWS_LOGGING_BITFIELD_SET 0 -#define LWS_LOG_TAG_LIFECYCLE -/* #undef LWS_MINGW_SUPPORT */ - -/* #undef LWS_NO_CLIENT */ -#define LWS_NO_DAEMONIZE -#define LWS_OPENSSL_CLIENT_CERTS "/etc/ssl/certs" -#define LWS_OPENSSL_SUPPORT -/* #undef LWS_PLAT_OPTEE */ -#define LWS_PLAT_UNIX -/* #undef LWS_PLAT_FREERTOS */ - -/* #undef LWS_ROLE_CGI */ - -/* #undef LWS_ROLE_DBUS */ -#define LWS_ROLE_H1 -#define LWS_ROLE_H2 -#define LWS_ROLE_RAW -#define LWS_ROLE_RAW_FILE -/* #undef LWS_ROLE_RAW_PROXY */ -#define LWS_ROLE_WS -#ifdef CONFIG_NETUTILS_MQTTC -#define LWS_ROLE_MQTT -#endif -/* #undef LWS_SHA1_USE_OPENSSL_NAME */ -#define LWS_SSL_CLIENT_USE_OS_CA_CERTS -/* #undef LWS_SSL_SERVER_WITH_ECDH_CERT */ -#define LWS_SUPPRESS_DEPRECATED_API_WARNINGS -/* #undef LWS_TLS_LOG_PLAINTEXT_RX */ - -/* #undef LWS_TLS_LOG_PLAINTEXT_TX */ - -/* #undef LWS_WITH_ABSTRACT */ - -/* #undef LWS_WITH_ACCESS_LOG */ - -/* #undef LWS_WITH_ACME */ - -/* #undef LWS_WITH_ALSA */ - -/* #undef LWS_WITH_SYS_ASYNC_DNS */ - -/* #undef LWS_WITH_BORINGSSL */ - -/* #undef LWS_WITH_CGI */ -#define LWS_WITH_CONMON -/* #undef LWS_WITH_COSE */ -#define LWS_WITH_CUSTOM_HEADERS -/* #undef LWS_WITH_DEPRECATED_LWS_DLL */ - -/* #undef LWS_WITH_DETAILED_LATENCY */ -#define LWS_WITH_DIR -/* #undef LWS_WITH_DRIVERS */ - -/* #undef LWS_WITH_ESP32 */ - -/* #undef LWS_HAVE_EVBACKEND_LINUXAIO */ - -/* #undef LWS_HAVE_EVBACKEND_IOURING */ - -/* #undef LWS_WITH_EXTERNAL_POLL */ -#define LWS_WITH_FILE_OPS -/* #undef LWS_WITH_FSMOUNT */ - -/* #undef LWS_WITH_FTS */ - -/* #undef LWS_WITH_GENCRYPTO */ - -/* #undef LWS_WITH_GENERIC_SESSIONS */ - -/* #undef LWS_WITH_GLIB */ - -/* #undef LWS_WITH_GTK */ -#define LWS_WITH_HTTP2 -#define LWS_WITH_HTTP_BASIC_AUTH -/* #undef LWS_WITH_HTTP_BROTLI */ - -/* #undef LWS_HTTP_HEADERS_ALL */ - -/* #undef LWS_WITH_HTTP_PROXY */ - -/* #undef LWS_WITH_HTTP_STREAM_COMPRESSION */ -#define LWS_WITH_HTTP_UNCOMMON_HEADERS -#ifdef CONFIG_NET_IPv6 -#define LWS_WITH_IPV6 -#endif -/* #undef LWS_WITH_JOSE */ - -/* #undef LWS_WITH_CBOR */ -#define LWS_WITH_CBOR_FLOAT -#define LWS_WITH_LEJP -/* #undef LWS_WITH_LIBEV */ - -/* #undef LWS_WITH_LIBEVENT */ - -/* #undef LWS_WITH_LIBUV */ - -/* #undef LWS_WITH_SDEVENT */ -#define LWS_WITH_LWSAC -#define LWS_LOGS_TIMESTAMP -#ifdef CONFIG_CRYPTO_MBEDTLS -#define LWS_WITH_MBEDTLS -#endif -/* #undef LWS_WITH_MINIZ */ - -/* #undef LWS_WITH_NETLINK */ -#define LWS_WITH_NETWORK -/* #undef LWS_WITH_NO_LOGS */ -#define LWS_WITH_CACHE_NSCOOKIEJAR -#define LWS_WITH_CLIENT -#define LWS_WITHOUT_EXTENSIONS -/* #undef LWS_WITH_SERVER */ - -/* #undef LWS_WITH_SPAWN */ - -/* #undef LWS_WITH_PEER_LIMITS */ - -/* #undef LWS_WITH_PLUGINS */ - -/* #undef LWS_WITH_PLUGINS_BUILTIN */ - -/* #undef LWS_WITH_POLARSSL */ -#define LWS_WITH_POLL -/* #undef LWS_WITH_RANGES */ - -/* #undef LWS_WITH_RFC6724 */ - -/* #undef LWS_WITH_SECURE_STREAMS */ - -/* #undef LWS_WITH_SECURE_STREAMS_CPP */ - -/* #undef LWS_WITH_SECURE_STREAMS_SYS_AUTH_API_AMAZON_COM */ - -/* #undef LWS_WITH_SECURE_STREAMS_PROXY_API */ - -/* #undef LWS_WITH_SECURE_STREAMS_STATIC_POLICY_ONLY */ - -/* #undef LWS_WITH_SECURE_STREAMS_AUTH_SIGV4 */ - -/* #undef LWS_WITH_SECURE_STREAMS_BUFFER_DUMP */ - -/* #undef LWS_WITH_SS_DIRECT_PROTOCOL_STR */ - -/* #undef LWS_WITH_SELFTESTS */ - -/* #undef LWS_WITH_SEQUENCER */ - -/* #undef LWS_WITH_SERVER_STATUS */ -#define LWS_WITH_SYS_SMD -/* #undef LWS_WITH_SMTP */ - -/* #undef LWS_WITH_SOCKS5 */ - -/* #undef LWS_WITH_STATEFUL_URLDECODE */ - -/* #undef LWS_WITH_STATS */ - -/* #undef LWS_WITH_STRUCT_SQLITE3 */ - -/* #undef LWS_WITH_STRUCT_JSON */ - -/* #undef LWS_WITH_SUL_DEBUGGING */ - -/* #undef LWS_WITH_SQLITE3 */ - -/* #undef LWS_WITH_SYS_DHCP_CLIENT */ - -/* #undef LWS_WITH_SYS_FAULT_INJECTION */ - -/* #undef LWS_WITH_SYS_METRICS */ - -/* #undef LWS_WITH_SYS_NTPCLIENT */ -#define LWS_WITH_SYS_STATE -/* #undef LWS_WITH_THREADPOOL */ -#ifdef CONFIG_CRYPTO_MBEDTLS -#define LWS_WITH_TLS -/* #undef LWS_WITH_TLS_JIT_TRUST */ -#define LWS_WITH_TLS_SESSIONS -#endif -#ifdef CONFIG_NET_UDP -#define LWS_WITH_UDP -#endif -/* #undef LWS_WITH_ULOOP */ -#define LWS_WITH_UNIX_SOCK -/* #undef LWS_WITH_ZIP_FOPS */ - -/* #undef USE_OLD_CYASSL */ - -/* #undef USE_WOLFSSL */ - -/* #undef LWS_WITH_EVENT_LIBS */ - -/* #undef LWS_WITH_EVLIB_PLUGINS */ - -/* #undef LWS_WITH_LIBUV_INTERNAL */ - -/* #undef LWS_WITH_PLUGINS_API */ - -/* #define LWS_HAVE_RTA_PREF */ - -#endif diff --git a/netutils/libwebsockets/lws_config_private.h b/netutils/libwebsockets/lws_config_private.h deleted file mode 100644 index 893e02f05..000000000 --- a/netutils/libwebsockets/lws_config_private.h +++ /dev/null @@ -1,153 +0,0 @@ -/**************************************************************************** - * apps/netutils/libwebsockets/lws_config_private.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_NETUTILS_LIBWEBSOCKETS_LWS_CONFIG_PRIVATE_H -#define __APPS_NETUTILS_LIBWEBSOCKETS_LWS_CONFIG_PRIVATE_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifndef NDEBUG - #ifndef _DEBUG - #define _DEBUG - #endif -#endif -/* #undef LWIP_PROVIDE_ERRNO */ - -/* Define to 1 to use CyaSSL as a replacement for OpenSSL. - * LWS_OPENSSL_SUPPORT needs to be set also for this to work. - */ - -/* #undef USE_CYASSL */ - -/* Define to 1 if you have the `fork' function. */ -#define LWS_HAVE_FORK - -#ifndef CONFIG_DISABLE_ENVIRON -/* Define to 1 if you have the `getenv' function. */ -#define LWS_HAVE_GETENV -#endif - -/* Define to 1 if you have the header file. */ - -/* #undef LWS_HAVE_IN6ADDR_H */ - -/* Define to 1 if your system has a GNU libc compatible `malloc' function, - *and to 0 otherwise. - */ -#define LWS_HAVE_MALLOC - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_MEMORY_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_NETINET_IN_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_STDINT_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_STDLIB_H - -/* Define to 1 if you have the `strerror' function. */ -#define LWS_HAVE_STRERROR - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_STRING_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_PRCTL_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_RESOURCE_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_SOCKET_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_SOCKIO_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_SYS_TYPES_H - -/* Define to 1 if you have the header file. */ -#define LWS_HAVE_UNISTD_H - -/* #undef LWS_HAVE_TCP_USER_TIMEOUT */ - -/* Define to 1 if you have the `vfork' function. */ -#define LWS_HAVE_VFORK - -/* Define to 1 if you have the header file. */ - -/* #undef LWS_HAVE_VFORK_H */ - -/* Define to 1 if `fork' works. */ -#define LWS_HAVE_WORKING_FORK - -/* Define to 1 if `vfork' works. */ -#define LWS_HAVE_WORKING_VFORK - -/* Define to 1 if execvpe() exists */ -#define LWS_HAVE_EXECVPE - -/* Define to 1 if you have the header file. */ - -/* #undef LWS_HAVE_ZLIB_H */ - -/* #undef LWS_HAVE_GETLOADAVG */ - -/* Define to the sub-directory in which libtool stores - * uninstalled libraries. - */ - -#undef LT_OBJDIR // We're not using libtool - -/* Define to rpl_malloc if the replacement function should be used. */ - -/* #undef malloc */ - -/* Define to rpl_realloc if the replacement function should be used. */ - -/* #undef realloc */ - -/* Define to 1 if we have getifaddrs */ -#define LWS_HAVE_GETIFADDRS - -/* Define if the inline keyword doesn't exist. */ - -/* #undef inline */ - -/* #undef LWS_WITH_ZLIB */ -#define LWS_HAS_PTHREAD_SETNAME_NP - -/* Defined if you have the header file. */ -#define LWS_HAVE_INTTYPES_H - -#endif \ No newline at end of file diff --git a/netutils/mqttc/CMakeLists.txt b/netutils/mqttc/CMakeLists.txt deleted file mode 100644 index 664539d9f..000000000 --- a/netutils/mqttc/CMakeLists.txt +++ /dev/null @@ -1,121 +0,0 @@ -# -# Copyright (C) 2024 Xiaomi Corporation -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# - -if(CONFIG_NETUTILS_MQTTC) - - # ############################################################################ - # Config and Fetch MQTTC lib - # ############################################################################ - - set(MQTTC_DIR ${CMAKE_CURRENT_LIST_DIR}/MQTT-C) - - if(NOT EXISTS ${MQTTC_DIR}) - set(MQTTC_URL "https://github.com/LiamBindle/MQTT-C/archive") - FetchContent_Declare( - mqttc_fetch - URL ${MQTTC_URL}/${CONFIG_NETUTILS_MQTTC_VERSION}.tar.gz SOURCE_DIR - ${MQTTC_DIR} BINARY_DIR ${CMAKE_BINARY_DIR}/apps/netutils/mqttc/MQTT-C - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(mqttc_fetch) - - if(NOT mqttc_fetch_POPULATED) - FetchContent_Populate(mqttc_fetch) - endif() - - execute_process( - COMMAND - sh -c - "cat 0001_add_connection_status.patch | patch -s -N -d $(MQTTC_DIR) -p1" - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) - endif() - - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${MQTTC_DIR}/include) - set(CFLAGS -Wno-return-type) - if(CONFIG_NETUTILS_MQTTC_WITH_MBEDTLS) - list(APPEND CFLAGS -DMQTT_USE_MBEDTLS) - endif() - - file(GLOB CSRCS ${MQTTC_DIR}/src/*.c) - - nuttx_add_library(mqttc STATIC) - target_sources(mqttc PRIVATE ${CSRCS}) - target_compile_options(mqttc PRIVATE ${CFLAGS}) - - if(CONFIG_NETUTILS_MQTTC_EXAMPLE) - if(CONFIG_NETUTILS_MQTTC_WITH_MBEDTLS) - nuttx_add_application( - NAME - mqttc_mbedtls_pub - STACKSIZE - ${CONFIG_NETUTILS_MQTTC_EXAMPLE_STACKSIZE} - PRIORITY - ${SCHED_PRIORITY_DEFAULT} - SRCS - ${MQTTC_DIR}/examples/mbedtls_publisher.c - COMPILE_FLAGS - ${CFLAGS} - DEPENDS - mqttc) - else() - set(MQTT_PUB_CFLAGS - ${CFLAGS} - -Dopen_nb_socket=pub_open_nb_socket - -Dexit_example=pub_exit_example - -Dpublish_callback=pub_publish_callback - -Dclient_refresher=pub_client_refresher) - - set(MQTT_SUB_CFLAGS - ${CFLAGS} - -Dopen_nb_socket=sub_open_nb_socket - -Dexit_example=sub_exit_example - -Dpublish_callback=sub_publish_callback - -Dclient_refresher=sub_client_refresher) - - nuttx_add_application( - NAME - mqttc_posix_pub - STACKSIZE - ${CONFIG_NETUTILS_MQTTC_EXAMPLE_STACKSIZE} - PRIORITY - ${SCHED_PRIORITY_DEFAULT} - SRCS - ${MQTTC_DIR}/examples/simple_publisher.c - COMPILE_FLAGS - ${MQTT_PUB_CFLAGS} - DEPENDS - mqttc) - - nuttx_add_application( - NAME - mqttc_posix_sub - STACKSIZE - ${CONFIG_NETUTILS_MQTTC_EXAMPLE_STACKSIZE} - PRIORITY - ${SCHED_PRIORITY_DEFAULT} - SRCS - ${MQTTC_DIR}/examples/simple_subscriber.c - COMPILE_FLAGS - ${MQTT_SUB_CFLAGS} - DEPENDS - mqttc) - endif() - endif() -endif() diff --git a/netutils/nanopb/.gitignore b/netutils/nanopb/.gitignore new file mode 100644 index 000000000..e6b967afd --- /dev/null +++ b/netutils/nanopb/.gitignore @@ -0,0 +1 @@ +nanopb/ \ No newline at end of file diff --git a/netutils/nanopb/Kconfig b/netutils/nanopb/Kconfig new file mode 100644 index 000000000..38897b7f6 --- /dev/null +++ b/netutils/nanopb/Kconfig @@ -0,0 +1,38 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +config NETUTILS_NANOPB + tristate "Nanopb Protocol Buffers" + default n + ---help--- + Nanopb is a small code-size Protocol Buffers implementation in ansi C. + It is especially suitable for use in microcontrollers, but fits any + memory restricted system. + +if NETUTILS_NANOPB + +config NETUTILS_NANOPB_VERSION + string "Nanopb Version" + default "0.4.8" + +config NETUTILS_NANOPB_EXAMPLE + tristate "Enable Nanopb example" + default n + ---help--- + Enable Nanopb simple example + +if NETUTILS_NANOPB_EXAMPLE + +config NETUTILS_NANOPB_EXAMPLE_PRIORITY + int "Task Priority" + default 100 + +config NETUTILS_NANOPB_EXAMPLE_STACKSIZE + int "Task stack size" + default DEFAULT_TASK_STACKSIZE + +endif + +endif diff --git a/math/gemmlowp/Make.defs b/netutils/nanopb/Make.defs similarity index 89% rename from math/gemmlowp/Make.defs rename to netutils/nanopb/Make.defs index ecd7abd03..6cd3bef26 100644 --- a/math/gemmlowp/Make.defs +++ b/netutils/nanopb/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/math/gemmlowp/Make.defs +# apps/netutils/nanopb/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -18,6 +18,6 @@ # ############################################################################ -ifneq ($(CONFIG_MATH_GEMMLOWP),) -CONFIGURED_APPS += $(APPDIR)/math/gemmlowp +ifneq ($(CONFIG_NETUTILS_NANOPB),) +CONFIGURED_APPS += $(APPDIR)/netutils/nanopb endif diff --git a/netutils/nanopb/Makefile b/netutils/nanopb/Makefile new file mode 100644 index 000000000..8bc698247 --- /dev/null +++ b/netutils/nanopb/Makefile @@ -0,0 +1,78 @@ +############################################################################ +# apps/netutils/nanopb/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +NANOPB_VERSION = $(CONFIG_NETUTILS_NANOPB_VERSION) +ifeq ($(CONFIG_HOST_WINDOWS),y) + NANOPB_NAME = nanopb-$(NANOPB_VERSION)-windows-x86 +else ifeq ($(CONFIG_HOST_LINUX),y) + NANOPB_NAME = nanopb-$(NANOPB_VERSION)-linux-x86 +else + NANOPB_NAME = nanopb-$(NANOPB_VERSION)-macosx-x86 +endif + +NANOPB_TARBALL = $(NANOPB_NAME).tar.gz +NANOPB_UNPACK = nanopb +NANOPB_SRCDIR = $(NANOPB_UNPACK) + +$(NANOPB_TARBALL): + $(Q) echo "Downloading $(NANOPB_TARBALL)" + $(Q) curl -O -L https://jpa.kapsi.fi/nanopb/download/$(NANOPB_TARBALL) + +$(NANOPB_UNPACK): $(NANOPB_TARBALL) + $(Q) tar zxf $(NANOPB_TARBALL) + $(Q) mv nanopb-$(NANOPB_VERSION)-linux-x86 $(NANOPB_UNPACK) + $(Q) mv $(NANOPB_TARBALL) $(NANOPB_UNPACK) + +ifeq ($(wildcard $(NANOPB_UNPACK)),) +context:: $(NANOPB_UNPACK) +endif + +CSRCS = $(NANOPB_SRCDIR)$(DELIM)pb_common.c +CSRCS += $(NANOPB_SRCDIR)$(DELIM)pb_decode.c +CSRCS += $(NANOPB_SRCDIR)$(DELIM)pb_encode.c + +ifneq ($(CONFIG_NETUTILS_NANOPB_EXAMPLE),) +PROGNAME = nanopb_example +PRIORITY = $(CONFIG_NETUTILS_NANOPB_EXAMPLE_PRIORITY) +STACKSIZE = $(CONFIG_NETUTILS_NANOPB_EXAMPLE_STACKSIZE) +MODULE = $(CONFIG_NETUTILS_NANOPB_EXAMPLE) + +EXAMPLE_DIR = $(NANOPB_UNPACK)$(DELIM)examples$(DELIM)simple +MAINSRC = $(EXAMPLE_DIR)$(DELIM)simple.c +CSRCS += $(EXAMPLE_DIR)$(DELIM)simple.pb.c +CFLAGS += "-I$(NANOPB_UNPACK)" + +# The context below generates the simple.pb.c and simple.pb.h from the .proto +# file using the nanobpb_generator executable inside nanopb/generator-bin. +GENERATOR_EXECUTABLE = $(NANOPB_UNPACK)$(DELIM)generator-bin$(DELIM)nanopb_generator +ifeq ($(CONFIG_HOST_WINDOWS),y) +GENERATOR_EXECUTABLE += .exe +endif + +context:: + $(GENERATOR_EXECUTABLE) --output-dir=$(EXAMPLE_DIR) --options-path=$(EXAMPLE_DIR) $(EXAMPLE_DIR)$(DELIM)simple.proto +endif + +distclean:: + $(call DELDIR, $(NANOPB_UNPACK)) + +include $(APPDIR)/Application.mk diff --git a/netutils/netcat/README.md b/netutils/netcat/README.md deleted file mode 100644 index 044a700f7..000000000 --- a/netutils/netcat/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Network Utilities / `netcat` tool - -netcat TCP/IP Swiss army knife - -It was re-implemented from scratch for NuttX - - -## DEMO ## - -[![weboftwins-osvehicle-2020-rzr]( -https://files.mastodon.social/media_attachments/files/105/163/916/892/863/178/original/05468e28b4463f95.png -)]( -https://mastodon.social/@rzr/105225153152922220#weboftwins-osvehicle-2020-rzr -"weboftwins-osvehicle-2020-rzr") - - * https://purl.org/rzr/weboftwins - -## USAGE ## - -Usage is straightforward: - - nsh> help ; netcat - Usage: netcat [-l] [destination] [port] [file] - - nsh> renew eth0 ; ifconfig - - eth0 Link encap:Ethernet HWaddr 52:13:FF:FF:FF:FF at UP - inet addr:192.168.1.42 DRaddr:192.168.1.254 Mask:255.255.255.0 - -In the following examples, following configuration is used: - -- target (nuttx) is 192.168.1.42 -- host (linux) is 192.168.1.55 - -### Server ### - -As a server on NuttX and Linux's netcat as client - - nsh> netcat -l - - sh> cat /proc/version | netcat 192.168.1.42 31337 - Linux ... - -Default port is 31337 but it can changed. - - nsh> renew eth0 ; ifconfig ; netcat -l - log: net: listening on :31337 - Linux ... - -### Client ### - -Start Server on GNU/Linux: - - sh> ip addr show && netcat -l 31337 - -Client side on nuttx, we create - - nsh> help ; renew eth0 ; ifconfig - nsh> netcat 192.168.1.55 31337 /proc/version - -### Using pipes ### - - mkfifo /dev/fifo - netcat 192.168.1.55 31337 /proc/fifo - help > /dev/fifo - - fxos8700cq > /dev/fifo & - fxos8700cq [7:100] - netcat 192.168.1.55 31337 /dev/fifo - -### Resources ### - - * - * - * \ No newline at end of file diff --git a/netutils/netcat/netcat_main.c b/netutils/netcat/netcat_main.c index 155de558f..a5ba12fae 100644 --- a/netutils/netcat/netcat_main.c +++ b/netutils/netcat/netcat_main.c @@ -175,8 +175,7 @@ int netcat_server(int argc, char * argv[]) } addrlen = sizeof(struct sockaddr_in); - if ((conn = accept4(id, (struct sockaddr *)&client, &addrlen, - SOCK_CLOEXEC)) != -1) + if ((conn = accept(id, (struct sockaddr *)&client, &addrlen)) != -1) { result = do_io(conn, outfd, preallocated_iobuf, CONFIG_NETUTILS_NETCAT_BUFSIZE); diff --git a/netutils/netinit/Kconfig b/netutils/netinit/Kconfig index b0bda87a7..2031c7bae 100644 --- a/netutils/netinit/Kconfig +++ b/netutils/netinit/Kconfig @@ -1,5 +1,4 @@ # -# # For a description of the syntax of this configuration file, # see the file kconfig-language.txt in the NuttX tools repository. # @@ -119,6 +118,13 @@ config NETINIT_THREAD_PRIORITY PHY polling is CPU intensive and can interfere with the usability of of threads competing for CPU bandwidth. +config NETINIT_RETRY_MOUNTPATH + int "Network initialization retry mount path count" + default 0 + ---help--- + This should be set if the filesystem get mounted after netinit got started. + The netinit thread will check for the mount path before continuing. + endif # NETINIT_THREAD config NETINIT_DEBUG @@ -468,6 +474,14 @@ choice address to the hardware before it brings the network up. This choice allows you select the source of that MAC address. +config NETINIT_UIDMAC + bool "Board Unique ID" + depends on BOARDCTL_UNIQUEID + ---help--- + Assign a MAC address based on the board unique ID. + CONFIG_BOARDCTL_UNIQUEID_SIZE must be at least 6 bytes for + Ethernet, 8 bytes for 6LOWPAN. + config NETINIT_SWMAC bool "Fixed address" ---help--- diff --git a/netutils/netinit/netinit.c b/netutils/netinit/netinit.c index e90c7c1ab..2f4d0a78d 100644 --- a/netutils/netinit/netinit.c +++ b/netutils/netinit/netinit.c @@ -48,6 +48,7 @@ #include #include +#include #include "netutils/netlib.h" #if defined(CONFIG_NETUTILS_DHCPC) || defined(CONFIG_NETINIT_DNS) @@ -207,8 +208,13 @@ * signal indicating a change in network status. */ -#define LONG_TIME_SEC (60*60) /* One hour in seconds */ -#define SHORT_TIME_SEC (2) /* 2 seconds */ +#ifdef CONFIG_SYSTEM_TIME64 +# define LONG_TIME_SEC (60*60) /* One hour in seconds */ +#else +# define LONG_TIME_SEC (5*60) /* Five minutes in seconds */ +#endif + +#define SHORT_TIME_SEC (2) /* 2 seconds */ /**************************************************************************** * Private Data @@ -284,7 +290,9 @@ static const uint16_t g_ipv6_netmask[8] = defined(HAVE_MAC) static void netinit_set_macaddr(void) { -#if defined(CONFIG_NET_ETHERNET) +#if defined(CONFIG_NETINIT_UIDMAC) + uint8_t uid[CONFIG_BOARDCTL_UNIQUEID_SIZE]; +#elif defined(CONFIG_NET_ETHERNET) uint8_t mac[IFHWADDRLEN]; #elif defined(HAVE_EADDR) uint8_t eaddr[8]; @@ -292,7 +300,12 @@ static void netinit_set_macaddr(void) /* Many embedded network interfaces must have a software assigned MAC */ -#if defined(CONFIG_NET_ETHERNET) +#if defined(CONFIG_NETINIT_UIDMAC) + boardctl(BOARDIOC_UNIQUEID, (uintptr_t)&uid); + uid[0] = (uid[0] & 0b11110000) | 2; /* Locally Administered MAC */ + netlib_setmacaddr(NET_DEVNAME, uid); + +#elif defined(CONFIG_NET_ETHERNET) /* Use the configured, fixed MAC address */ mac[0] = (CONFIG_NETINIT_MACADDR_2 >> (8 * 1)) & 0xff; @@ -329,6 +342,30 @@ static void netinit_set_macaddr(void) # define netinit_set_macaddr() #endif +#if defined(CONFIG_NETINIT_THREAD) && CONFIG_NETINIT_RETRY_MOUNTPATH > 0 +static inline void netinit_checkpath(void) +{ + int retries = CONFIG_NETINIT_RETRY_MOUNTPATH; + while (retries > 0) + { + DIR * dir = opendir(CONFIG_IPCFG_PATH); + if (dir) + { + /* Directory exists. */ + + closedir(dir); + break; + } + else + { + usleep(100000); + } + + retries--; + } +} +#endif + /**************************************************************************** * Name: netinit_set_ipv4addrs * @@ -350,6 +387,10 @@ static inline void netinit_set_ipv4addrs(void) * file. */ +#if defined(CONFIG_NETINIT_THREAD) && CONFIG_NETINIT_RETRY_MOUNTPATH > 0 + netinit_checkpath(); +#endif + ret = ipcfg_read(NET_DEVNAME, (FAR struct ipcfg_s *)&ipv4cfg, AF_INET); #ifdef CONFIG_NETUTILS_DHCPC if (ret >= 0 && ipv4cfg.proto != IPv4PROTO_NONE) @@ -507,6 +548,10 @@ static inline void netinit_set_ipv6addrs(void) * file. */ +#if defined(CONFIG_NETINIT_THREAD) && CONFIG_NETINIT_RETRY_MOUNTPATH > 0 + netinit_checkpath(); +#endif + ret = ipcfg_read(NET_DEVNAME, (FAR struct ipcfg_s *)&ipv6cfg, AF_INET6); if (ret >= 0 && IPCFG_HAVE_STATIC(ipv6cfg.proto)) { @@ -873,6 +918,11 @@ static int netinit_monitor(void) goto errout_with_notification; } +#ifdef CONFIG_NET_ICMPv6_AUTOCONF + /* Perform ICMPv6 auto-configuration */ + + netlib_icmpv6_autoconfiguration(ifr.ifr_name); +#endif /* And wait for a short delay. We will want to recheck the * link status again soon. */ diff --git a/netutils/netlib/CMakeLists.txt b/netutils/netlib/CMakeLists.txt index ca8e48e02..bb1bacbb4 100644 --- a/netutils/netlib/CMakeLists.txt +++ b/netutils/netlib/CMakeLists.txt @@ -62,8 +62,7 @@ if(CONFIG_NETUTILS_NETLIB) list(APPEND SRCS netlib_prefix2ipv6netmask.c netlib_ipv6netmask2prefix.c) list(APPEND SRCS netlib_ipv6adaptor.c) if(CONFIG_NET_ICMPv6_AUTOCONF) - list(APPEND SRCS netlib_autoconfig.c) - list(APPEND SRCS netlib_obtainipv6addr.c) + list(APPEND SRCS netlib_autoconfig.c netlib_obtainipv6addr.c) endif() if(CONFIG_NETDB_DNSCLIENT) list(APPEND SRCS netlib_setipv6dnsaddr.c) diff --git a/netutils/netlib/netlib_obtainipv6addr.c b/netutils/netlib/netlib_obtainipv6addr.c index f5054c3e0..2aed9896b 100644 --- a/netutils/netlib/netlib_obtainipv6addr.c +++ b/netutils/netlib/netlib_obtainipv6addr.c @@ -41,20 +41,42 @@ * Private Functions ****************************************************************************/ +#ifdef CONFIG_NET_ETHERNET +static void icmpv6_linkipaddr_6(FAR const uint8_t *mac, FAR uint16_t *ipaddr) +{ + ipaddr[0] = htons(0xfe80); + ipaddr[1] = 0; + ipaddr[2] = 0; + ipaddr[3] = 0; + ipaddr[4] = htons(mac[0] << 8 | mac[1]); + ipaddr[5] = htons(mac[2] << 8 | 0x00ff); + ipaddr[6] = htons(0x00fe << 8 | mac[3]); + ipaddr[7] = htons(mac[4] << 8 | mac[5]); + ipaddr[4] ^= htons(0x0200); +} + +static void dhcpv6_set_lladdr(FAR const char *ifname) +{ + struct in6_addr addr6; + uint8_t mac[IFHWADDRLEN]; + + /* Get the MAC address of the NIC */ + + netlib_getmacaddr(ifname, mac); + + /* Set the Link Local Address of the NIC */ + + icmpv6_linkipaddr_6(mac, (uint16_t *)&addr6); + netlib_set_ipv6addr(ifname, &addr6); + netlib_prefix2ipv6netmask(64, &addr6); +} +#endif + static int dhcpv6_setup_result(FAR const char *ifname, FAR struct dhcp6c_state *presult) { int ret; -#ifdef CONFIG_NETDEV_MULTIPLE_IPv6 - ret = netlib_add_ipv6addr(ifname, &presult->addr, presult->pl); - if (ret != OK) - { - nerr("netlib_add_ipv6addr fail\n"); - return ret; - } -#else - ret = netlib_set_ipv6addr(ifname, &presult->addr); if (ret != OK) { @@ -68,7 +90,6 @@ static int dhcpv6_setup_result(FAR const char *ifname, nerr("netlib_set_ipv6netmask fail\n"); return ret; } -#endif #if defined(CONFIG_NET_IPv6) && defined(CONFIG_NETDB_DNSCLIENT) ret = netlib_set_ipv6dnsaddr(&presult->dns); @@ -89,6 +110,9 @@ static int dhcpv6_obtain_statefuladdr(FAR const char *ifname) int ret; memset(&result, 0, sizeof(result)); +#ifdef CONFIG_NET_ETHERNET + dhcpv6_set_lladdr(ifname); +#endif handle = dhcp6c_open(ifname); ret = dhcp6c_request(handle, &result); diff --git a/netutils/netlib/netlib_server.c b/netutils/netlib/netlib_server.c index 3c9bdf69c..c62bec9f5 100644 --- a/netutils/netlib/netlib_server.c +++ b/netutils/netlib/netlib_server.c @@ -92,8 +92,7 @@ void netlib_server(uint16_t portno, /* Accept the next connection */ addrlen = sizeof(struct sockaddr_in); - acceptsd = accept4(listensd, (struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (struct sockaddr *)&myaddr, &addrlen); if (acceptsd < 0) { nerr("ERROR: accept failure: %d\n", errno); diff --git a/netutils/netlib/netlib_setipv6dnsaddr.c b/netutils/netlib/netlib_setipv6dnsaddr.c old mode 100755 new mode 100644 diff --git a/netutils/nng/Makefile b/netutils/nng/Makefile index 61f06f66b..f73d2a8d3 100644 --- a/netutils/nng/Makefile +++ b/netutils/nng/Makefile @@ -34,9 +34,6 @@ CFLAGS += -DNNG_TRANSPORT_TCP CFLAGS += -DNNG_TRANSPORT_TLS CFLAGS += -DNNG_TRANSPORT_WS CFLAGS += -DNNG_TRANSPORT_WSS -CFLAGS += -DNNG_SETSTACKSIZE -CFLAGS += -DNNG_HAVE_PTHREAD_SETNAME_NP -CFLAGS += -DNNG_MAX_TASKQ_THREADS=6 CFLAGS += -DNNG_USE_EVENTFD ifeq ($(CONFIG_NETUTILS_NNG_HAVE_EPOLL),y) @@ -152,8 +149,6 @@ $(NNG_TARBALL): $(NNG_UNPACK): $(NNG_TARBALL) $(Q) tar zxf $(NNG_TARBALL) $(Q) mv nng-$(NNG_VERSION) $(NNG_UNPACK) - $(Q) echo "Patching $(NNG_UNPACK)" - $(Q) patch -p0 < nng_porting_for_nuttx.patch $(Q) touch $(NNG_UNPACK) # Download and unpack tarball if no git repo found diff --git a/netutils/nng/nng_porting_for_nuttx.patch b/netutils/nng/nng_porting_for_nuttx.patch deleted file mode 100644 index ac49d08f3..000000000 --- a/netutils/nng/nng_porting_for_nuttx.patch +++ /dev/null @@ -1,180 +0,0 @@ -diff --git nng/src/core/dialer.c nng/src/core/dialer.c -index a9674226..7b22f915 100644 ---- nng/src/core/dialer.c -+++ nng/src/core/dialer.c -@@ -63,7 +63,7 @@ nni_dialer_destroy(nni_dialer *d) - NNI_FREE_STRUCT(d); - } - --#if NNG_ENABLE_STATS -+#if defined(NNG_ENABLE_STATS) && NNG_ENABLE_STATS - static void - dialer_stat_init(nni_dialer *d, nni_stat_item *item, const nni_stat_info *info) - { -diff --git nng/src/core/listener.c nng/src/core/listener.c -index c2a5863d..9073ccc7 100644 ---- nng/src/core/listener.c -+++ nng/src/core/listener.c -@@ -513,7 +513,7 @@ nni_listener_getopt( - void - nni_listener_add_stat(nni_listener *l, nni_stat_item *item) - { --#if NNG_ENABLE_STATS -+#if defined(NNG_ENABLE_STATS) && NNG_ENABLE_STATS - nni_stat_add(&l->st_root, item); - #else - NNI_ARG_UNUSED(l); -diff --git nng/src/core/panic.c nng/src/core/panic.c -index d50664cf..5bbb6f56 100644 ---- nng/src/core/panic.c -+++ nng/src/core/panic.c -@@ -23,7 +23,7 @@ - void - nni_show_backtrace(void) - { --#if NNG_HAVE_BACKTRACE -+#if defined(NNG_HAVE_BACKTRACE) && NNG_HAVE_BACKTRACE - void *frames[50]; - int nframes; - -diff --git nng/src/core/pipe.c nng/src/core/pipe.c -index a2b6411f..3303bc2a 100644 ---- nng/src/core/pipe.c -+++ nng/src/core/pipe.c -@@ -334,7 +334,7 @@ nni_pipe_create_listener(nni_pipe **pp, nni_listener *l, void *tdata) - return (rv); - } - p->p_listener = l; --#if NNG_ENABLE_STATS -+#if defined(NNG_ENABLE_STATS) && NNG_ENABLE_STATS - static const nni_stat_info listener_info = { - .si_name = "listener", - .si_desc = "listener for pipe", -diff --git nng/src/core/socket.c nng/src/core/socket.c -index e170289d..50dddffc 100644 ---- nng/src/core/socket.c -+++ nng/src/core/socket.c -@@ -659,7 +659,7 @@ nni_sock_open(nni_sock **sockp, const nni_proto *proto) - nni_mtx_unlock(&sock_lk); - - // Set the socket name. -- (void) snprintf(s->s_name, sizeof(s->s_name), "%u", s->s_id); -+ (void) snprintf(s->s_name, sizeof(s->s_name), "%" PRIu32 "",s->s_id); - - #ifdef NNG_ENABLE_STATS - // Set up basic stat values. -diff --git nng/src/core/stream.c nng/src/core/stream.c -index 418bfb15..53905bf5 100644 ---- nng/src/core/stream.c -+++ nng/src/core/stream.c -@@ -44,6 +44,7 @@ static struct { - .listener_alloc = nni_ipc_listener_alloc, - }, - #endif -+#ifdef NNG_TRANSPORT_TCP - { - .scheme = "tcp", - .dialer_alloc = nni_tcp_dialer_alloc, -@@ -59,6 +60,7 @@ static struct { - .dialer_alloc = nni_tcp_dialer_alloc, - .listener_alloc = nni_tcp_listener_alloc, - }, -+#ifdef NNG_TRANSPORT_TLS - { - .scheme = "tls+tcp", - .dialer_alloc = nni_tls_dialer_alloc, -@@ -74,6 +76,9 @@ static struct { - .dialer_alloc = nni_tls_dialer_alloc, - .listener_alloc = nni_tls_listener_alloc, - }, -+#endif -+#endif -+#ifdef NNG_TRANSPORT_WS - { - .scheme = "ws", - .dialer_alloc = nni_ws_dialer_alloc, -@@ -89,11 +94,14 @@ static struct { - .dialer_alloc = nni_ws_dialer_alloc, - .listener_alloc = nni_ws_listener_alloc, - }, -+#endif -+#ifdef NNG_TRANSPORT_WSS - { - .scheme = "wss", - .dialer_alloc = nni_ws_dialer_alloc, - .listener_alloc = nni_ws_listener_alloc, - }, -+#endif - { - .scheme = NULL, - }, -diff --git nng/src/platform/posix/posix_file.c nng/src/platform/posix/posix_file.c -index d5fb5016..11ad4012 100644 ---- nng/src/platform/posix/posix_file.c -+++ nng/src/platform/posix/posix_file.c -@@ -289,7 +289,7 @@ nni_plat_file_lock(const char *path, nni_plat_flock *lk) - rv = 0; - #endif - if (rv < 0) { -- int rv = errno; -+ rv = errno; - close(fd); - if (rv == EAGAIN) { - return (NNG_EBUSY); -diff --git nng/src/platform/posix/posix_pollq_poll.c nng/src/platform/posix/posix_pollq_poll.c -index f6f81703..94b7c76c 100644 ---- nng/src/platform/posix/posix_pollq_poll.c -+++ nng/src/platform/posix/posix_pollq_poll.c -@@ -7,6 +7,7 @@ - // file was obtained (LICENSE.txt). A copy of the license may also be - // found online at https://opensource.org/licenses/MIT. - // -+#if !defined(NNG_HAVE_PORT) && !defined(NNG_HAVE_KQUEUE) && !defined(NNG_HAVE_EPOLL) - - #include "core/nng_impl.h" - #include "platform/posix/posix_pollq.h" -@@ -346,3 +347,4 @@ nni_posix_pollq_sysfini(void) - { - nni_posix_pollq_destroy(&nni_posix_global_pollq); - } -+#endif -diff --git nng/src/sp/protocol/pair1/pair.c nng/src/sp/protocol/pair1/pair.c -index 4a909888..1cd69460 100644 ---- nng/src/sp/protocol/pair1/pair.c -+++ nng/src/sp/protocol/pair1/pair.c -@@ -500,7 +500,7 @@ pair1_pipe_send(pair1_pipe *p, nni_msg *m) - // assumption: we have unique access to the message at this point. - NNI_ASSERT(!nni_msg_shared(m)); - --#if NNG_TEST_LIB -+#if defined(NNG_TEST_LIB) && NNG_TEST_LIB - if (s->inject_header) { - goto inject; - } -@@ -508,7 +508,7 @@ pair1_pipe_send(pair1_pipe *p, nni_msg *m) - NNI_ASSERT(nni_msg_header_len(m) == sizeof(uint32_t)); - nni_msg_header_poke_u32(m, nni_msg_header_peek_u32(m) + 1); - --#if NNG_TEST_LIB -+#if defined(NNG_TEST_LIB) && NNG_TEST_LIB - inject: - #endif - -@@ -533,7 +533,7 @@ pair1_sock_send(void *arg, nni_aio *aio) - return; - } - --#if NNG_TEST_LIB -+#if defined(NNG_TEST_LIB) && NNG_TEST_LIB - if (s->inject_header) { - goto inject; - } -@@ -556,7 +556,7 @@ pair1_sock_send(void *arg, nni_aio *aio) - nni_msg_header_append_u32(m, 0); - } - --#if NNG_TEST_LIB -+#if defined(NNG_TEST_LIB) && NNG_TEST_LIB - inject: - #endif - diff --git a/netutils/ntpclient/ntpclient.c b/netutils/ntpclient/ntpclient.c index ac48a3e09..8ec85d22e 100644 --- a/netutils/ntpclient/ntpclient.c +++ b/netutils/ntpclient/ntpclient.c @@ -409,7 +409,7 @@ static inline void ntpc_setuint64(FAR uint8_t *ptr, uint64_t value) * Name: ntp_secpart ****************************************************************************/ -static int32_t ntp_secpart(int64_t time) +static uint32_t ntp_secpart(uint64_t time) { /* NTP timestamps are represented as a 64-bit fixed-point number, in * seconds relative to 0000 UT on 1 January 1900. The integer part is @@ -434,11 +434,11 @@ static int32_t ntp_secpart(int64_t time) * Name: ntp_nsecpart ****************************************************************************/ -static int32_t ntp_nsecpart(int64_t time) +static uint32_t ntp_nsecpart(uint64_t time) { /* Get fraction part converted to nanoseconds. */ - return (((int64_t)((uint64_t)time << 32) >> 32) * NSEC_PER_SEC) >> 32; + return ((time & 0xffffffffu) * NSEC_PER_SEC) >> 32; } /**************************************************************************** @@ -527,30 +527,6 @@ static void ntpc_calculate_offset(FAR int64_t *offset, FAR int64_t *delay, (remote_xmittime - remote_recvtime); } -/**************************************************************************** - * Name: ntpc_apply_offset - ****************************************************************************/ - -static void ntpc_apply_offset(FAR struct timespec *tp, - FAR struct timespec *src, - int64_t offset) -{ - tp->tv_sec = src->tv_sec + ntp_secpart(offset); - tp->tv_nsec = src->tv_nsec + ntp_nsecpart(offset); - - while (tp->tv_nsec < 0) - { - tp->tv_nsec += NSEC_PER_SEC; - tp->tv_sec--; - } - - while (tp->tv_nsec >= NSEC_PER_SEC) - { - tp->tv_nsec -= NSEC_PER_SEC; - tp->tv_sec++; - } -} - /**************************************************************************** * Name: ntpc_settime * @@ -604,7 +580,14 @@ static void ntpc_settime(int64_t offset, FAR struct timespec *start_realtime, /* Apply offset */ - ntpc_apply_offset(&tp, &curr_realtime, offset); + tp = curr_realtime; + tp.tv_sec += ntp_secpart(offset); + tp.tv_nsec += ntp_nsecpart(offset); + while (tp.tv_nsec >= NSEC_PER_SEC) + { + tp.tv_nsec -= NSEC_PER_SEC; + tp.tv_sec++; + } /* Set the system time */ diff --git a/netutils/pppd/lcp.h b/netutils/pppd/lcp.h index a53a10dfa..c0d6951ba 100644 --- a/netutils/pppd/lcp.h +++ b/netutils/pppd/lcp.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/netutils/pppd/lpc.h + * apps/netutils/pppd/lcp.h * Link Configuration Protocol header file * * Version: .1 Original Version June 3, 2000 diff --git a/netutils/smtp/smtp.c b/netutils/smtp/smtp.c index 0b6d10514..83081361d 100644 --- a/netutils/smtp/smtp.c +++ b/netutils/smtp/smtp.c @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/netutitls/smtp/smtp.c + * apps/netutils/smtp/smtp.c * smtp SMTP E-mail sender * * Copyright (C) 2007, 2009, 2011, 2015, 2020 Gregory Nutt. All rights @@ -258,7 +258,8 @@ static inline int smtp_send_message(int sockfd, struct smtp_state *psmtp) return ERROR; } - if (send(sockfd, g_smtpcrnlperiodcrnl, strlen(g_smtpcrnlperiodcrnl), 0) < 0) + if (send(sockfd, g_smtpcrnlperiodcrnl, + strlen(g_smtpcrnlperiodcrnl), 0) < 0) { return ERROR; } @@ -350,7 +351,8 @@ int smtp_send(void *handle, const char *to, const char *cc, const char *from, net_ipv4addr_copy(server.sin_addr.s_addr, psmtp->smtpserver); server.sin_port = psmtp->port; - if (connect(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) + if (connect(sockfd, (struct sockaddr *)&server, + sizeof(struct sockaddr_in)) < 0) { close(sockfd); return ERROR; @@ -368,7 +370,8 @@ void *smtp_open(void) { /* Allocate the handle */ - struct smtp_state *psmtp = (struct smtp_state *)malloc(sizeof(struct smtp_state)); + struct smtp_state *psmtp = + (struct smtp_state *)malloc(sizeof(struct smtp_state)); if (psmtp) { /* Initialize the handle */ diff --git a/netutils/telnetd/README.md b/netutils/telnetd/README.md deleted file mode 100644 index 30135542e..000000000 --- a/netutils/telnetd/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Network Utilities / `telnetd` Telnet Daemon - -This directly contains a generic Telnet daemon. diff --git a/netutils/telnetd/telnetd_daemon.c b/netutils/telnetd/telnetd_daemon.c index b78e9f5db..8d544b52d 100644 --- a/netutils/telnetd/telnetd_daemon.c +++ b/netutils/telnetd/telnetd_daemon.c @@ -197,7 +197,7 @@ int telnetd_daemon(FAR const struct telnetd_config_s *config) ninfo("Accepting connections on port %d\n", ntohs(config->d_port)); addrlen = sizeof(addr); - acceptsd = accept4(listensd, &addr.generic, &addrlen, SOCK_CLOEXEC); + acceptsd = accept(listensd, &addr.generic, &addrlen); if (acceptsd < 0) { /* Just continue if a signal was received */ diff --git a/netutils/thttpd/cgi-src/Makefile b/netutils/thttpd/cgi-src/Makefile index 1d215c4fc..4be27bb69 100644 --- a/netutils/thttpd/cgi-src/Makefile +++ b/netutils/thttpd/cgi-src/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/netutils/cgi-src/Makefile +# apps/netutils/thttpd/cgi-src/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/netutils/thttpd/libhttpd.c b/netutils/thttpd/libhttpd.c index 697dd1d50..9c07f93e7 100644 --- a/netutils/thttpd/libhttpd.c +++ b/netutils/thttpd/libhttpd.c @@ -1854,7 +1854,7 @@ static int ls(httpd_conn *hc) char arg[16]; char *argv[1]; #if CONFIG_THTTPD_CGI_TIMELIMIT > 0 - clientdata client_data; + ClientData client_data; #endif dirp = opendir(hc->expnfilename); @@ -2355,8 +2355,7 @@ int httpd_get_conn(httpd_server *hs, int listen_fd, httpd_conn *hc) ninfo("accept() new connection on listen_fd %d\n", listen_fd); sz = sizeof(sa); - hc->conn_fd = accept4(listen_fd, (struct sockaddr *)&sa, &sz, - SOCK_CLOEXEC); + hc->conn_fd = accept(listen_fd, (struct sockaddr *)&sa, &sz); if (hc->conn_fd < 0) { if (errno == EWOULDBLOCK) diff --git a/netutils/thttpd/thttpd.c b/netutils/thttpd/thttpd.c index 94a11b841..6fe961c8d 100644 --- a/netutils/thttpd/thttpd.c +++ b/netutils/thttpd/thttpd.c @@ -96,8 +96,8 @@ struct connect_s int conn_state; httpd_conn *hc; time_t active_at; - timer *wakeup_timer; - timer *linger_timer; + Timer *wakeup_timer; + Timer *linger_timer; off_t end_offset; /* The final offset+1 of the file to send */ off_t offset; /* The current offset into the file to send */ bool eof; /* Set true when length==0 read from file */ @@ -128,10 +128,10 @@ static void handle_linger(struct connect_s *conn, struct timeval *tv); static void finish_connection(struct connect_s *conn, struct timeval *tv); static void clear_connection(struct connect_s *conn, struct timeval *tv); static void really_clear_connection(struct connect_s *conn); -static void idle(clientdata client_data, struct timeval *nowp); -static void linger_clear_connection(clientdata client_data, +static void idle(ClientData client_data, struct timeval *nowp); +static void linger_clear_connection(ClientData client_data, struct timeval *nowp); -static void occasional(clientdata client_data, struct timeval *nowp); +static void occasional(ClientData client_data, struct timeval *nowp); /**************************************************************************** * Private Functions @@ -524,7 +524,7 @@ static void finish_connection(struct connect_s *conn, struct timeval *tv) static void clear_connection(struct connect_s *conn, struct timeval *tv) { - clientdata client_data; + ClientData client_data; if (conn->wakeup_timer != NULL) { @@ -594,7 +594,7 @@ static void really_clear_connection(struct connect_s *conn) free_connections = conn; } -static void idle(clientdata client_data, struct timeval *nowp) +static void idle(ClientData client_data, struct timeval *nowp) { int cnum; struct connect_s *conn; @@ -629,7 +629,7 @@ static void idle(clientdata client_data, struct timeval *nowp) } } -static void linger_clear_connection(clientdata client_data, +static void linger_clear_connection(ClientData client_data, struct timeval *nowp) { struct connect_s *conn; @@ -640,7 +640,7 @@ static void linger_clear_connection(clientdata client_data, really_clear_connection(conn); } -static void occasional(clientdata client_data, struct timeval *nowp) +static void occasional(ClientData client_data, struct timeval *nowp) { tmr_cleanup(); } @@ -727,7 +727,7 @@ int thttpd_main(int argc, char **argv) /* Set up the occasional timer */ - if (tmr_create(NULL, occasional, junkclientdata, + if (tmr_create(NULL, occasional, JunkClientData, CONFIG_THTTPD_OCCASIONAL_MSEC * 1000L, 1) == NULL) { nerr("ERROR: tmr_create(occasional) failed\n"); @@ -736,7 +736,7 @@ int thttpd_main(int argc, char **argv) /* Set up the idle timer */ - if (tmr_create(NULL, idle, junkclientdata, 5 * 1000L, 1) == NULL) + if (tmr_create(NULL, idle, JunkClientData, 5 * 1000L, 1) == NULL) { nerr("ERROR: tmr_create(idle) failed\n"); exit(1); diff --git a/netutils/thttpd/thttpd_cgi.c b/netutils/thttpd/thttpd_cgi.c index 456350b42..8387b4213 100644 --- a/netutils/thttpd/thttpd_cgi.c +++ b/netutils/thttpd/thttpd_cgi.c @@ -717,7 +717,7 @@ static int cgi_child(int argc, char **argv) { FAR httpd_conn *hc = (FAR httpd_conn *)strtoul(argv[1], NULL, 16); #if CONFIG_THTTPD_CGI_TIMELIMIT > 0 - clientdata client_data; + ClientData client_data; #endif FAR char **argp; FAR struct cgi_conn_s *cc; @@ -1096,7 +1096,7 @@ errout_with_sem: } #if CONFIG_THTTPD_CGI_TIMELIMIT > 0 -static void cgi_kill(clientdata client_data, struct timeval *nowp) +static void cgi_kill(ClientData client_data, struct timeval *nowp) { pid_t pid = (pid_t)client_data.i; diff --git a/netutils/thttpd/thttpd_cgi.h b/netutils/thttpd/thttpd_cgi.h index 2d5c34bc1..ea83efeb3 100644 --- a/netutils/thttpd/thttpd_cgi.h +++ b/netutils/thttpd/thttpd_cgi.h @@ -7,8 +7,7 @@ * * Derived from the file libhttpd.c in the original THTTPD package: * - * Copyright (C) 1995,1998,1999,2000,2001 by Jef Poskanzer - * . + * Copyright (C) 1995,1998,1999,2000,2001 by Jef Poskanzer . * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -56,7 +55,7 @@ extern int cgi(httpd_conn *hc); #if CONFIG_THTTPD_CGI_TIMELIMIT > 0 struct timeval; -static void cgi_kill(clientdata client_data, struct timeval *now); +static void cgi_kill(ClientData client_data, struct timeval *now); #endif #endif /* CONFIG_THTTPD && CONFIG_THTTPD_CGI_PATTERN */ diff --git a/netutils/thttpd/timers.c b/netutils/thttpd/timers.c index 828756d60..074e12942 100644 --- a/netutils/thttpd/timers.c +++ b/netutils/thttpd/timers.c @@ -57,20 +57,20 @@ * Private Data ****************************************************************************/ -static timer *timers[HASH_SIZE]; -static timer *free_timers; +static Timer *timers[HASH_SIZE]; +static Timer *free_timers; /**************************************************************************** * Public Data ****************************************************************************/ -clientdata junkclientdata; +ClientData JunkClientData; /**************************************************************************** * Private Functions ****************************************************************************/ -static unsigned int hash(timer *tmr) +static unsigned int hash(Timer *tmr) { /* We can hash on the trigger time, even though it can change over the * life of a timer via the periodic bit. @@ -82,11 +82,11 @@ static unsigned int hash(timer *tmr) (unsigned int)tmr->time.tv_usec) % HASH_SIZE; } -static void l_add(timer *tmr) +static void l_add(Timer *tmr) { int h = tmr->hash; - register timer *tmr2; - register timer *tmr2prev; + register Timer *tmr2; + register Timer *tmr2prev; tmr2 = timers[h]; if (tmr2 == NULL) @@ -139,7 +139,7 @@ static void l_add(timer *tmr) } } -static void l_remove(timer *tmr) +static void l_remove(Timer *tmr) { int h = tmr->hash; @@ -158,7 +158,7 @@ static void l_remove(timer *tmr) } } -static void l_resort(timer *tmr) +static void l_resort(Timer *tmr) { /* Remove the timer from its old list. */ @@ -189,10 +189,10 @@ void tmr_init(void) free_timers = NULL; } -timer *tmr_create(struct timeval *now, timerproc *timer_proc, - clientdata client_data, long msecs, int periodic) +Timer *tmr_create(struct timeval *now, TimerProc *timer_proc, + ClientData client_data, long msecs, int periodic) { - timer *tmr; + Timer *tmr; if (free_timers != NULL) { @@ -201,7 +201,7 @@ timer *tmr_create(struct timeval *now, timerproc *timer_proc, } else { - tmr = (timer *)httpd_malloc(sizeof(timer)); + tmr = (Timer*)httpd_malloc(sizeof(Timer)); if (!tmr) { return NULL; @@ -244,7 +244,7 @@ long tmr_mstimeout(struct timeval *now) int gotone; long msecs; long m; - register timer *tmr; + register Timer *tmr; gotone = 0; msecs = 0; @@ -288,8 +288,8 @@ long tmr_mstimeout(struct timeval *now) void tmr_run(struct timeval *now) { int h; - timer *tmr; - timer *next; + Timer *tmr; + Timer *next; for (h = 0; h < HASH_SIZE; ++h) { @@ -331,7 +331,7 @@ void tmr_run(struct timeval *now) } } -void tmr_cancel(timer *tmr) +void tmr_cancel(Timer *tmr) { /* Remove it from its active list. */ @@ -346,13 +346,13 @@ void tmr_cancel(timer *tmr) void tmr_cleanup(void) { - timer *tmr; + Timer *tmr; while (free_timers != NULL) { tmr = free_timers; free_timers = tmr->next; - httpd_free((void *)tmr); + httpd_free((void*)tmr); } } diff --git a/netutils/thttpd/timers.h b/netutils/thttpd/timers.h index 4975a9809..a23462608 100644 --- a/netutils/thttpd/timers.h +++ b/netutils/thttpd/timers.h @@ -65,34 +65,34 @@ typedef union void *p; int i; long l; -} clientdata; +} ClientData; -/* The Timerproc gets called when the timer expires. It gets passed +/* The TimerProc gets called when the timer expires. It gets passed * the ClientData associated with the timer, and a timeval in case * it wants to schedule another timer. */ -typedef void timerproc(clientdata client_data, struct timeval *nowp); +typedef void TimerProc(ClientData client_data, struct timeval *nowp); /* The Timer struct. */ -typedef struct timerstruct +typedef struct TimerStruct { - timerproc *timer_proc; - clientdata client_data; + TimerProc *timer_proc; + ClientData client_data; long msecs; int periodic; struct timeval time; - struct timerstruct *prev; - struct timerstruct *next; + struct TimerStruct *prev; + struct TimerStruct *next; int hash; -} timer; +} Timer; /**************************************************************************** * Public Data ****************************************************************************/ -extern clientdata junkclientdata; /* For use when you don't care */ +extern ClientData JunkClientData; /* For use when you don't care */ /**************************************************************************** * Public Function Prototypes @@ -103,11 +103,11 @@ extern clientdata junkclientdata; /* For use when you don't care */ extern void tmr_init(void); /* Set up a timer, either periodic or one-shot. - * Returns (timer *)0 on errors. + * Returns (Timer *)0 on errors. */ -extern timer *tmr_create(struct timeval *nowp, timerproc *timer_proc, - clientdata client_data, long msecs, int periodic); +extern Timer *tmr_create(struct timeval *nowp, TimerProc *timer_proc, + ClientData client_data, long msecs, int periodic); /* Returns a timeout in milliseconds indicating how long until the next timer * triggers. You can just put the call to this routine right in your poll(). @@ -126,7 +126,7 @@ extern void tmr_run(struct timeval *nowp); * descheduled when they run, so you don't have to call this on them. */ -extern void tmr_cancel(timer *timer); +extern void tmr_cancel(Timer *timer); /* Clean up the timers package, freeing any unused storage. */ diff --git a/netutils/usrsock_rpmsg/CMakeLists.txt b/netutils/usrsock_rpmsg/CMakeLists.txt deleted file mode 100644 index 3451c4f51..000000000 --- a/netutils/usrsock_rpmsg/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# ############################################################################## -# apps/netutils/usrsock_rpmsg/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_NETUTILS_USRSOCK_RPMSG) - if(CONFIG_NET_USRSOCK) - nuttx_add_application(NAME usrsock SRCS usrsock_rpmsg_client.c) - else() - nuttx_add_application(NAME usrsock SRCS usrsock_rpmsg_server.c) - endif() -endif() diff --git a/netutils/webserver/httpd.c b/netutils/webserver/httpd.c index 5916cbc63..4602e65e9 100644 --- a/netutils/webserver/httpd.c +++ b/netutils/webserver/httpd.c @@ -768,8 +768,7 @@ static void single_server(uint16_t portno, pthread_startroutine_t handler, for (; ; ) { addrlen = sizeof(struct sockaddr_in); - acceptsd = accept4(listensd, (FAR struct sockaddr *)&myaddr, &addrlen, - SOCK_CLOEXEC); + acceptsd = accept(listensd, (FAR struct sockaddr *)&myaddr, &addrlen); if (acceptsd < 0) { diff --git a/nshlib/CMakeLists.txt b/nshlib/CMakeLists.txt index 50659a8ab..ae3b8dcd8 100644 --- a/nshlib/CMakeLists.txt +++ b/nshlib/CMakeLists.txt @@ -37,10 +37,11 @@ if(CONFIG_NSH_LIBRARY) nsh_mmcmds.c nsh_timcmds.c nsh_envcmds.c + nsh_prompt.c nsh_syscmds.c nsh_dbgcmds.c) - list(APPEND CSRCS nsh_session.c nsh_spawn.c) + list(APPEND CSRCS nsh_session.c) if(CONFIG_NSH_CONSOLE_LOGIN) list(APPEND CSRCS nsh_login.c) @@ -97,10 +98,6 @@ if(CONFIG_NSH_LIBRARY) list(APPEND CSRCS nsh_test.c) endif() - if(NOT CONFIG_NSH_DISABLE_WAIT) - list(APPEND CSRCS nsh_wait.c) - endif() - if(CONFIG_USBDEV) list(APPEND CSRCS nsh_usbconsole.c) endif() diff --git a/nshlib/Kconfig b/nshlib/Kconfig index d64773065..2a183068a 100644 --- a/nshlib/Kconfig +++ b/nshlib/Kconfig @@ -66,7 +66,31 @@ config NSH_PROMPT_STRING string "Prompt String" default "nsh> " ---help--- - Provide the shell prompt string, default is "nsh> ". + Provide the shell prompt string with size limit NSH_PROMPT_MAX. + default is "nsh> ". + +config NSH_PROMPT_MAX + int "Maximum Size of Prompt String" + default NAME_MAX + ---help--- + The maximum size of shell prompt string, including ending null. + +config NSH_PROMPT_ENV + string "Prompt String Environment Variable" + default "PS1" + depends on !DISABLE_ENVIRON + ---help--- + The environment variable name containing prompt string. + Only used when NSH_PROMPT_STRING is empty. + +config NSH_PROMPT_SUFFIX + string "Suffix used to derive fallback prompt string" + default "> " + ---help--- + When NSH_PROMPT_STRING is empty, the environment variable defined + by NSH_PROMPT_ENV or hostname will be used to derive the prompt + at runtime. This suffix is a part of the final prompt that serves + to clearly separate prompt from user inputs. config NSH_DISABLE_ECHOBACK bool "Disable echoback" @@ -382,7 +406,7 @@ config NSH_DISABLE_GET config NSH_DISABLE_HELP bool "Disable help" - default DEFAULT_SMALL + default n config NSH_DISABLE_ERROR_PRINT bool "Disable NSH Error Printing" @@ -665,10 +689,10 @@ config NSH_DISABLE_RESET_CAUSE default DEFAULT_SMALL depends on BOARDCTL_RESET_CAUSE -config NSH_DISABLE_WAIT - bool "Disable wait" +config NSH_DISABLE_IRQ_AFFINITY + bool "Disable command of irq affinity" default DEFAULT_SMALL - depends on SCHED_WAITPID + depends on BOARDCTL_IRQ_AFFINITY endmenu diff --git a/nshlib/Makefile b/nshlib/Makefile index 410085551..fb7aed89c 100644 --- a/nshlib/Makefile +++ b/nshlib/Makefile @@ -24,9 +24,9 @@ include $(APPDIR)/Make.defs CSRCS = nsh_init.c nsh_parse.c nsh_console.c nsh_script.c nsh_system.c CSRCS += nsh_command.c nsh_fscmds.c nsh_ddcmd.c nsh_proccmds.c nsh_mmcmds.c -CSRCS += nsh_timcmds.c nsh_envcmds.c nsh_syscmds.c nsh_dbgcmds.c +CSRCS += nsh_timcmds.c nsh_envcmds.c nsh_syscmds.c nsh_dbgcmds.c nsh_prompt.c -CSRCS += nsh_session.c nsh_spawn.c +CSRCS += nsh_session.c ifeq ($(CONFIG_NSH_CONSOLE_LOGIN),y) CSRCS += nsh_login.c endif @@ -82,10 +82,6 @@ ifneq ($(CONFIG_NSH_DISABLESCRIPT),y) CSRCS += nsh_test.c endif -ifneq ($(CONFIG_NSH_DISABLE_WAIT),y) -CSRCS += nsh_wait.c -endif - ifeq ($(CONFIG_USBDEV),y) CSRCS += nsh_usbconsole.c endif diff --git a/nshlib/README.md b/nshlib/README.md deleted file mode 100644 index 1e634cda8..000000000 --- a/nshlib/README.md +++ /dev/null @@ -1,2061 +0,0 @@ -# `nshlib` NuttShell (NSH) - -This directory contains the NuttShell (NSH) library. This library can be linked -with other logic to provide a simple shell application for NuttX. - -- Console/NSH Front End -- Command Overview -- Conditional Command Execution -- Looping -- Built-In Variables -- Current Working Directory - - Environment Variables -- NSH Start-Up Script -- Simple Commands -- Built-In Applications -- NSH Configuration Settings - - Command Dependencies on Configuration Settings - - Built-in Application Configuration Settings - - NSH-Specific Configuration Settings -- Common Problems - -## Console / NSH Front End - -Using settings in the configuration file, NSH may be configured to use either -the serial `stdin`/`out` or a telnet connection as the console or BOTH. When NSH -is started, you will see the following welcome on either console: - -``` -NuttShell (NSH) -nsh> -``` - -`nsh>` is the NSH prompt and indicates that you may enter a command from the -console. - -## Command Overview - -This directory contains the NuttShell (NSH). This is a simple shell-like -application. At present, NSH supports the following commands forms: - -- Simple command: - - ``` - - ``` - -- Command with re-directed output: - - ``` - > - >> - ``` - -- Background command: - - ``` - & - ``` - -- Re-directed background command: - - ``` - > & - >> & - ``` - -Where: - -- `` - is any one of the simple commands listed later. -- `` - is the full or relative path to any writeable object in the file - system name space (file or character driver). Such objects will be referred to - simply as files throughout this README. - -NSH executes at the mid-priority (`128`). Backgrounded commands can be made to -execute at higher or lower priorities using nice: - -``` -[nice [-d >]] [> |>> ] [&] -``` - -Where `` is any value between `-20` and `19` where lower (more -negative values) correspond to higher priorities. The default niceness is `10`. - -Multiple commands per line. NSH will accept multiple commands per command line -with each command separated with the semi-colon character (`;`). - -If `CONFIG_NSH_CMDPARMS` is selected, then the output from commands, from file -applications, and from NSH built-in commands can be used as arguments to other -commands. The entity to be executed is identified by enclosing the command line -in back quotes. For example, - -```shell -set FOO `myprogram $BAR` -``` - -Will execute the program named myprogram passing it the value of the environment -variable `BAR`. The value of the environment variable `FOO` is then set output -of myprogram on stdout. Because this feature commits significant resources, it -is disabled by default. - -If `CONFIG_NSH_ARGCAT` is selected, the support concatenation of strings with -environment variables or command output. For example: - -```shell -set FOO XYZ -set BAR 123 -set FOOBAR ABC_${FOO}_${BAR} -``` - -would set the environment variable `FOO` to `XYZ`, `BAR` to `123` and `FOOBAR` -to `ABC_XYZ_123`. If `NSH_ARGCAT` is not selected, then a slightly small FLASH -footprint results but then also only simple environment variables like `$FOO` -can be used on the command line. - -`CONFIG_NSH_QUOTE` enables back-slash quoting of certain characters within the -command. This option is useful for the case where an NSH script is used to -dynamically generate a new NSH script. In that case, commands must be treated as -simple text strings without interpretation of any special characters. Special -characters such as `$`, `` ` ``, `"`, and others must be retained intact as part of -the test string. This option is currently only available is `CONFIG_NSH_ARGCAT` -is also selected. - -## Conditional Command Execution - -An `if-then[-else]-fi` construct is also supported in order to support -conditional execution of commands. This works from the command line but is -primarily intended for use within NSH scripts (see the `sh` command). The syntax -is as follows: - -``` -if [!] -then - [sequence of ] -else - [sequence of ] -fi -``` - -## Looping - -`while-do-done` and `until-do-done` looping constructs are also supported. These -works from the command line but are primarily intended for use within NSH -scripts (see the `sh` command). The syntax is as follows: - -``` -while ; do ; done -``` - -(Execute `` as long as `` has an exit status of zero.) - -``` -until ; do ; done -``` - -(Execute `` as long as `` has a non-zero exit status.) - -A break command is also supported. The break command is only meaningful within -the body of the a `while` or `until` loop, between the do and done tokens. If -the break command is executed within the body of a loop, the loop will -immediately terminate and execution will continue with the next command -immediately following the done token. - -## Built-In Variables - -- `$?` - The result of the last simple command execution. - -## Current Working Directory - -All path arguments to commands may be either an absolute path or a path relative -to the current working directory. The current working directory is set using the -`cd` command and can be queried either by using the `pwd` command or by using -the `echo $PWD` command. - -### Environment Variables: - -- `PWD` - The current working directory -- `OLDPWD` - The previous working directory - -## NSH System-init And Start-Up Script - -NSH supports options to provide a system init script and start up script for NSH. -In general this capability is enabled with `CONFIG_NSH_ROMFSETC`, but has -several other related configuration options as described in the final section -of this README. This capability also depends on: - -- `CONFIG_DISABLE_MOUNTPOINT` not set -- `CONFIG_FS_ROMFS` - -### Default Script Behavior - -The implementation that is provided is intended to provide great flexibility for -the use of script files, include system init file and start-up file. This -paragraph will discuss the general behavior when all of the configuration -options are set to the default values. - -System-init script is executed before Start-up script. The system-init script -is mainly used for file system mounting and core system service startup, and the -start-up script is used for application and other system service startup. So, -Between them, some initialize can use filesystem and core system service, -Examples: Peripheral driver initialize at `boardctl(BOARDIOC_FINALINIT, 0)`. - -In this default case, enabling `CONFIG_NSH_ROMFSETC` will cause NSH to behave as -follows at NSH startup time: - -- NSH will create a read-only RAM disk (a ROM disk), containing a tiny ROMFS - file system containing the following: - - ``` - | `--init.d/ - `-- rcS - `-- rc.sysinit - ```` - - Where `rcS` is the NSH start-up script - Where `rc.sysinit` is the NSH system-init script - -- NSH will then mount the ROMFS file system at `/etc`, resulting in: - - ``` - |--dev/ - | `-- ram0 - `--etc/ - `--init.d/ - `-- rcS - `-- rc.sysinit - ``` - -- By default, the contents of `rc.sysinit` script are: - - ```shell - # Create a RAMDISK and mount it at XXXRDMOUNTPOINTXXX - - mkrd -m 1 -s 512 1024 - mkfatfs /dev/ram1 - mount -t vfat /dev/ram1 /tmp - ``` - -- NSH will execute the script at `/etc/init.d/rc.sysinit` at system init - before the first NSH prompt. After execution of the script, the root - FS will look like: - - ``` - |--dev/ - | |-- ram0 - | `-- ram1 - |--etc/ - | `--init.d/ - | `-- rcS - | `-- rc.sysinit - `--tmp/ - ``` - -### Modifying the ROMFS Image - -The contents of the `/etc` directory are retained in the file -`apps/nshlib/nsh_romfsimg.h` (OR, if `CONFIG_NSH_ARCHROMFS` is defined, -`include/arch/board/rcS.template`). In order to modify the start-up behavior, -there are three things to study: - -1. Configuration Options. - The additional `CONFIG_NSH_ROMFSETC` configuration options discussed in the - final section of this README. - -2. `tools/mkromfsimg.sh` Script. - The script `tools/mkromfsimg.sh` creates `nsh_romfsimg.h`. It is not - automatically executed. If you want to change the configuration settings - associated with creating and mounting the `/tmp` directory, then it will be - necessary to re-generate this header file using the `mkromfsimg.sh` script. - - The behavior of this script depends upon three things: - - - The configuration settings of the installed NuttX configuration. - - The genromfs tool (available from http://romfs.sourceforge.net). - - The file `apps/nshlib/rcS.template` (OR, if `CONFIG_NSH_ARCHROMFS` is - defined, `include/arch/board/rcs.template`) - -3. `rc.sysinit.template`. The file `apps/nshlib/rc.sysinit.template` contains - the general form of the `rc.sysinit.template` file; configured values - are plugged into this template file to produce the final `rc.sysinit` file. - - `rcS.template`. The file `apps/nshlib/rcS.template` contains the general form - of the `rcS` file; configured values are plugged into this template file to - produce the final `rcS` file. - -**Note**: `apps/nshlib/rc.sysinit.template` and ` apps/nshlib/rcS.template` -generates the standard, default `nsh_romfsimg.h` file. If `CONFIG_NSH_ARCHROMFS` -is defined in the NuttX configuration file, then a custom, board-specific -`nsh_romfsimg.h` file residing in `boards////include` will be -used. **Note** when the OS is configured, `include/arch/board` will be linked to -`boards////include`. - -All of the startup-behavior is contained in `rc.sysinit.template` and -`rcS.template`. The role of `mkromfsimg.sh` is to (1) apply the specific -configuration settings to `rc.sysinit.template` to create the final -`rc.sysinit.template`, and `rcS.template` to create the final `rcS` and -(2) to generate the header file `nsh_romfsimg.h` containing the ROMFS file -system image. - -## Simple Commands - -- `[ ]` - `test ` - - These are two alternative forms of the same command. They support evaluation - of a boolean expression which sets `$?`. This command is used most frequently - as the conditional command following the `if` in the `if-then[-else]-fi` - construct. - - **Expression Syntax**: - - ``` - expression = simple-expression | !expression | - expression -o expression | expression -a expression - - simple-expression = unary-expression | binary-expression - - unary-expression = string-unary | file-unary - - string-unary = -n string | -z string - - file-unary = -b file | -c file | -d file | -e file | -f file | - -r file | -s file | -w file - - binary-expression = string-binary | numeric-binary - - string-binary = string = string | string == string | string != string - - numeric-binary = integer -eq integer | integer -ge integer | - integer -gt integer | integer -le integer | - integer -lt integer | integer -ne integer - ``` - -- `addroute [] ` - `addroute default ` - - This command adds an entry in the routing table. The new entry - will map the IP address of a router on a local network(``) - to an external network characterized by the `` IP address and - a network mask `` - - The netmask may also be expressed using IPv4 CIDR or IPv6 slash - notation. In that case, the netmask need not be provided. - - **Example**: - - ``` - nsh> addroute 11.0.0.0 255.255.255.0 10.0.0.2 - ``` - - which is equivalent to - - ``` - nsh> addroute 11.0.0.0/24 10.0.0.2 - ``` - - The second form of the `addroute` command can be used to set the default - gateway. - -- `arp [-t|-a |-d |-s ]` - - Access the OS ARP table. - - - `-a ` - Will show the hardware address that the IP address `` is mapped to. - - - `-d ` - Will delete the mapping for the IP address `` from the ARP table. - - - `-s ` - Will set (or replace) the mapping of the IP address `` to the - hardware address ``. - - - `-t` - Will dump the entire content of the ARP table. This option is only - available if `CONFIG_NETLINK_ROUTE` is enabled. - - **Example**: - - ``` - nsh> arp -a 10.0.0.1 - nsh: arp: no such ARP entry: 10.0.0.1 - - nsh> arp -s 10.0.0.1 00:13:3b:12:73:e6 - nsh> arp -a 10.0.0.1 - HWAddr: 00:13:3b:12:73:e6 - - nsh> arp -d 10.0.0.1 - nsh> arp -a 10.0.0.1 - nsh: arp: no such ARP entry: 10.0.0.1 - ``` - -- `base64dec [-w] [-f] ` - -- `base64dec [-w] [-f] ` - -- `basename []` - - Extract the final string from a `` by removing the preceding path - segments and (optionally) removing any trailing ``. - -- `break` - - The `break` command is only meaningful within the body of the a `while` or - `until` loop, between the do and done tokens. Outside of a loop, `break` - command does nothing. If the break command is executed within the body of a - loop, the loop will immediately terminate and execution will continue with the - next command immediately following the done token. - -- `cat [ [ ...]]` - - This command copies and concatenates all of the files at `` to the - console (or to another file if the output is redirected). - -- `cd [|-|~|..]` - - Changes the current working directory (`PWD`). Also sets the previous working - directory environment variable (`OLDPWD`). - - **Forms**: - - - `cd ` sets the current working directory to ``. - - `cd -` sets the current working directory to the previous working directory - (`$OLDPWD`). Equivalent to `cd $OLDPWD`. - - `cd` or `cd ~` set the current working directory to the _home_ directory. - The _home_ directory can be configured by setting `CONFIG_LIBC_HOMEDIR` in - the configuration file. The default _home_ directory is `/`. - - `cd ..` sets the current working directory to the parent directory. - -- `cmp ` - - Compare of the contents of the file at `` with the contents of the file - at ``. Returns an indication only if the files differ. - -- `cp ` - - Copy of the contents of the file at `` to the location in the - file system indicated by `` - -- `date [-s "MMM DD HH:MM:SS YYYY"] [-u]` - - Show or set the current date and time. - - Only one format is used both on display and when setting the date/time: - `MMM DD HH:MM:SS YYYY`. For example, - - ```shell - data -s "Sep 1 11:30:00 2011" - ``` - - 24-hour time format is assumed. - -- `dd if= of= [bs=] [count=] [skip=]` - - Copy blocks from `` to ``. `` or `` may be - the path to a standard file, a character device, or a block device. - - **Examples**: - - 1. Read from character device, write to regular file. This will create a new - file of the specified size filled with zero. - - ```shell - nsh> dd if=/dev/zero of=/tmp/zeros bs=64 count=16 - nsh> ls -l /tmp - /tmp: - -rw-rw-rw- 1024 ZEROS - ``` - - 2. Read from character device, write to block device. This will fill the - entire block device with zeros. - - ```shell - nsh> ls -l /dev - /dev: - brw-rw-rw- 0 ram0 - crw-rw-rw- 0 zero - nsh> dd if=/dev/zero of=/dev/ram0 - ``` - - 3. Read from a block device, write to a character device. This will read the - entire block device and dump the contents in the bit bucket. - - ```shell - nsh> ls -l /dev - /dev: - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - nsh> dd if=/dev/ram0 of=/dev/null - ``` - -- `delroute []` - - This command removes an entry from the routing table. The entry removed will - be the first entry in the routing table that matches the external network - characterized by the `` IP address and the network mask `` - - The netmask may also be expressed using IPv4 CIDR or IPv6 slash notation. In - that case, the netmask need not be provided. - - **Example**: - - ``` - nsh> delroute 11.0.0.0 255.255.255.0 - ``` - - which is equivalent to - - ``` - nsh> delroute 11.0.0.0/24 - ``` - -- `df` - - Show the state of each mounted volume. - - **Example**: - - ``` - nsh> mount - /etc type romfs - /tmp type vfat - nsh> df - Block Number - Size Blocks Used Available Mounted on - 64 6 6 0 /etc - 512 985 2 983 /tmp - nsh> - ``` - -- `dirname ` - - Extract the path string leading up to the full `` by removing the final - directory or file name. - -- `dmesg` - - This command can be used to dump (and clear) the content of any buffered - syslog output messages. This command is only available if - `CONFIG_RAMLOG_SYSLOG` is enabled. In that case, syslog output will be - collected in an in-memory, circular buffer. Entering the `dmesg` command will - dump the content of that in-memory, circular buffer to the NSH console output. - `dmesg` has the side effect of clearing the buffered data so that entering - `dmesg` again will show only newly buffered data. - -- `echo [-n] [ [...]]` - - Copy the sequence of strings and expanded environment variables to console out - (or to a file if the output is re-directed). - - The `-n` option will suppress the trailing newline character. - -- `env` - - Show the current name-value pairs in the environment. **Example**: - - ``` - nsh> env - PATH=/bin - - nsh> set foo bar - nsh> env - PATH=/bin - foo=bar - - nsh> unset PATH - nsh> env - foo=bar - - nsh> - ``` - - **Note**: NSH variables are **not** shown by the `env` command. - -- `exec ` - - Execute the user logic at address ``. NSH will pause until the - execution unless the user logic is executed in background via - `exec &` - -- `exit` - - Exit NSH. Only useful if you have started some other tasks (perhaps using the - `exec` command) and you would like to have NSH out of the way. - -- `export []` - - The `export` command sets an environment variable, or promotes an NSH variable - to an environment variable. As examples: - - 1. Using `export` to promote an NSH variable to an environment variable. - - ``` - nsh> env - PATH=/bin - - nsh> set foo bar - nsh> env - PATH=/bin - - nsh> export foo - nsh> env - PATH=/bin - foo=bar - ``` - - A group-wide environment variable is created with the same value as the - local NSH variable; the local NSH variable is removed. - - **Note**: This behavior differs from the Bash shell. Bash will retain the - local Bash variable which will shadow the environment variable of the same - name and same value. - - 2. Using `export` to set an environment variable - - ``` - nsh> export dog poop - nsh> env - PATH=/bin - foo=bar - dog=poop - ``` - - The export command is not supported by NSH unless both `CONFIG_NSH_VARS=y` and - `CONFIG_DISABLE_ENVIRON` is not set. - -- `free` - - Show the current state of the memory allocator. For example, - - ``` - nsh> free - free - total used free largest - Mem: 4194288 1591552 2602736 2601584 - ``` - - Where: - - - total - This is the total size of memory allocated for use - by `malloc` in bytes. - - used - This is the total size of memory occupied by - chunks handed out by `malloc`. - - free - This is the total size of memory occupied by - free (not in use) chunks. - - largest - Size of the largest free (not in use) chunk. - -- `get [-b|-n] [-f ] -h ` - - Use TFTP to copy the file at `` from the host whose IP - address is identified by ``. Other options: - - - `-f ` - The file will be saved relative to the current working directory unless - `` is provided. - - `-b|-n` - Selects either binary (_octet_) or text (_netascii_) transfer mode. Default: - text. - -- `help [-v] []` - - Presents summary information about NSH commands to console. Options: - - - `-v` - Show verbose output will full command usage. - - - `` - Show full command usage only for this command. - -- `hexdump ` - - Dump data in hexadecimal format from a file or character device. - -- `ifconfig [nic_name [mtu ]|[address_family] [[add|del] |dhcp]] [dr|gw|gateway ] [netmask |prefixlen ] [dns ] [hw ]]` - - Show the current configuration of the network, for example: - - ``` - nsh> ifconfig - eth0 HWaddr 00:18:11:80:10:06 - IPaddr:10.0.0.2 DRaddr:10.0.0.1 Mask:255.255.255.0 - ``` - - if networking statistics are enabled (`CONFIG_NET_STATISTICS`), then - this command will also show the detailed state of transfers by protocol. - - **Note**: This commands depends upon having the `procfs` file system configured - into the system. The `procfs` file system must also have been mounted - with a command like: - - ``` - nsh> mount -t procfs /proc - ``` - -- `ifdown ` - - Take down the interface identified by the name ``. - - **Example**: - - ``` - ifdown eth0 - ``` - -- `ifup ` - - Bring up down the interface identified by the name ``. - - **Example**: - - ``` - ifup eth0 - ``` - -- `insmod ` - - Install the loadable OS module at `` as module `` - - **Example**: - - ``` - nsh> ls -l /mnt/romfs - /mnt/romfs: - dr-xr-xr-x 0 . - -r-xr-xr-x 9153 chardev - nsh> ls -l /dev - /dev: - crw-rw-rw- 0 console - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - crw-rw-rw- 0 ttyS0 - nsh> insmod /mnt/romfs/chardev mydriver - nsh> ls -l /dev - /dev: - crw-rw-rw- 0 chardev - crw-rw-rw- 0 console - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - crw-rw-rw- 0 ttyS0 - nsh> lsmod - NAME INIT UNINIT ARG TEXT SIZE DATA SIZE - mydriver 20404659 20404625 0 20404580 552 204047a8 0 - ``` - -- `irqinfo` - - Show the current count of interrupts taken on all attached interrupts. - - **Example**: - - ``` - nsh> irqinfo - IRQ HANDLER ARGUMENT COUNT RATE - 3 00001b3d 00000000 156 19.122 - 15 0000800d 00000000 817 100.000 - 30 00000fd5 20000018 20 2.490 - ``` - -- `kill - ` - - Send the `` to the task identified by ``. - -- `losetup [-d ] | [[-o ] [-r] ]` - - Setup or teardown the loop device: - - 1. Teardown the setup for the loop device at ``: - - ```shell - losetup d - ``` - - 2. Setup the loop device at `` to access the file at `` - as a block device: - - ```shell - losetup [-o ] [-r] - ``` - - **Example**: - - ``` - nsh> dd if=/dev/zero of=/tmp/image bs=512 count=512 - nsh> ls -l /tmp - /tmp: - -rw-rw-rw- 262144 IMAGE - nsh> losetup /dev/loop0 /tmp/image - nsh> ls -l /dev - /dev: - brw-rw-rw- 0 loop0 - nsh> mkfatfs /dev/loop0 - nsh> mount -t vfat /dev/loop0 /mnt/example - nsh> ls -l /mnt - ls -l /mnt - /mnt: - drw-rw-rw- 0 example/ - nsh> echo "This is a test" >/mnt/example/atest.txt - nsh> ls -l /mnt/example - /mnt/example: - -rw-rw-rw- 16 ATEST.TXT - nsh> cat /mnt/example/atest.txt - This is a test - nsh> - ``` - -- `ln [-s] ` - - The link command will create a new symbolic link at `` for the - existing file or directory, ``. This implementation is simplied - for use with NuttX in these ways: - - - Links may be created only within the NuttX top-level, pseudo file - system. No file system currently supported by NuttX provides - symbolic links. - - For the same reason, only soft links are implemented. - - File privileges are ignored. - - `c_time` is not updated. - -- `ls [-lRs] ` - - Show the contents of the directory at ``. **Note**: - `` must refer to a directory and no other file system - object. - - Options: - - - `-R` Show the constents of specified directory and all of its - sub-directories. - - `-s` Show the size of the files along with the filenames in the listing. - - `-l` Show size and mode information along with the filenames in the listing. - -- `lsmod` - - Show information about the currently installed OS modules. This information - includes: - - - The module name assigned to the module when it was installed (`NAME`, - string). - - The address of the module initialization function (`INIT`, hexadecimal). - - The address of the module un-initialization function (`UNINIT`, - hexadecimal). - - An argument that will be passed to the module un-initialization function - (`ARG`, hexadecimal). - - The start of the `.text` memory region (`TEXT`, hexadecimal). - - The size of the `.text` memory region size (`SIZE`, decimal). - - The start of the `.bss`/`.data` memory region (`DATA`, hexadecimal). - - The size of the `.bss`/`.data` memory region size (`SIZE`, decimal). - - **Example**: - - ``` - nsh> lsmod - NAME INIT UNINIT ARG TEXT SIZE DATA SIZE - mydriver 20404659 20404625 0 20404580 552 204047a8 0 - ``` - -- `md5 [-f] ` - -- `mb [=][ ]` - `mh [=][ ]` - `mw [=][ ]` - - Access memory using byte size access (`mb`), 16-bit accesses (`mh`), - or 32-bit access (`mw`). In each case, - - - ``. Specifies the address to be accessed. The current value at - that address will always be read and displayed. - - `=`. Read the value, then write `` to the - location. - - ``. Perform the `mb`, `mh`, or `mw` operation on a total of - `` bytes, increment the `` appropriately - after each access - - **Example**: - - ``` - nsh> mh 0 16 - 0 = 0x0c1e - 2 = 0x0100 - 4 = 0x0c1e - 6 = 0x0110 - 8 = 0x0c1e - a = 0x0120 - c = 0x0c1e - e = 0x0130 - 10 = 0x0c1e - 12 = 0x0140 - 14 = 0x0c1e - nsh> - ``` - -- `mkdir ` - - Create the directory at ``. All components of of `` except the - final directory name must exist on a mounted file system; the final directory - must not. - - Recall that NuttX uses a pseudo file system for its root file system. The - `mkdir` command can only be used to create directories in volumes set up with - the `mount` command; it cannot be used to create directories in the pseudo file - system. - - **Example**: - - ``` - nsh> mkdir /mnt/fs/tmp - nsh> ls -l /mnt/fs - /mnt/fs: - drw-rw-rw- 0 TESTDIR/ - drw-rw-rw- 0 TMP/ - nsh> - ``` - -- `mkfatfs [-F ] [-r ] ` - - Format a `fat` file system on the block device specified by `` - path. The FAT size may be provided as an option. Without the `` - option, mkfatfs will select either the FAT12 or FAT16 format. For historical - reasons, if you want the FAT32 format, it must be explicitly specified on the - command line. - - The `-r` option may be specified to select the the number of entries in the - root directory. Typical values for small volumes would be `112` or `224`; - `512` should be used for large volumes, such as hard disks or very large SD - cards. The default is `512` entries in all cases. - - The reported number of root directory entries used with FAT32 is zero because - the FAT32 root directory is a cluster chain. - - NSH provides this command to access the `mkfatfs()` NuttX API. This block - device must reside in the NuttX pseudo file system and must have been created - by some call to `register_blockdriver()` (see `include/nuttx/fs/fs.h`). - -- `mkfifo ` - - Creates a FIFO character device anywhere in the pseudo file system, creating - whatever pseudo directories that may be needed to complete the full path. By - convention, however, device drivers are place in the standard `/dev` - directory. After it is created, the FIFO device may be used as any other - device driver. NSH provides this command to access the `mkfifo()` NuttX API. - - **Example**: - - ``` - nsh> ls -l /dev - /dev: - crw-rw-rw- 0 console - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - nsh> mkfifo /dev/fifo - nsh> ls -l /dev - ls -l /dev - /dev: - crw-rw-rw- 0 console - crw-rw-rw- 0 fifo - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - nsh> - ``` - -- `mkrd [-m ] [-s ] ` - - Create a ramdisk consisting of ``, each of size `` (or - `512` bytes if `` is not specified). The ramdisk will be - registered as `/dev/ram`. If `` is not specified, mkrd will - attempt to register the ramdisk as `/dev/ram0`. - - **Example**: - - ``` - nsh> ls /dev - /dev: - console - null - ttyS0 - ttyS1 - nsh> mkrd 1024 - nsh> ls /dev - /dev: - console - null - ram0 - ttyS0 - ttyS1 - nsh> - ``` - - Once the ramdisk has been created, it may be formatted using the `mkfatfs` - command and mounted using the `mount` command. - - **Example**: - - ``` - nsh> mkrd 1024 - nsh> mkfatfs /dev/ram0 - nsh> mount -t vfat /dev/ram0 /tmp - nsh> ls /tmp - /tmp: - nsh> - ``` - -- `mount [-t [-o ] ]` - - The `mount` command performs one of two different operations. If no parameters - are provided on the command line after the `mount` command, then the `mount` - command will enumerate all of the current mountpoints on the console. - - If the mount parameters are provided on the command after the `mount` command, - then the `mount` command will mount a file system in the NuttX pseudo-file - system. `mount` performs a three way association, binding: - - - File system. The `-t ` option identifies the type of file system - that has been formatted on the ``. As of this writing, `vfat` - is the only supported value for `` - - - Block Device. The `` argument is the full or relative path to - a block driver inode in the pseudo file system. By convention, this is a - name under the `/dev` sub-directory. This `` must have been - previously formatted with the same file system type as specified by - `` - - - Mount Point. The mount point is the location in the pseudo file system where - the mounted volume will appear. This mount point can only reside in the - NuttX pseudo file system. By convention, this mount point is a subdirectory - under `/mnt`. The `mount` command will create whatever pseudo directories - that may be needed to complete the full path but the full path must not - already exist. - - After the volume has been mounted in the NuttX pseudo file system, it may be - access in the same way as other objects in the file system. - - **Examples**: - - ``` - nsh> ls -l /dev - /dev: - crw-rw-rw- 0 console - crw-rw-rw- 0 null - brw-rw-rw- 0 ram0 - nsh> ls /mnt - nsh: ls: no such directory: /mnt - nsh> mount -t vfat /dev/ram0 /mnt/fs - nsh> ls -l /mnt/fs/testdir - /mnt/fs/testdir: - -rw-rw-rw- 15 TESTFILE.TXT - nsh> echo "This is a test" >/mnt/fs/testdir/example.txt - nsh> ls -l /mnt/fs/testdir - /mnt/fs/testdir: - -rw-rw-rw- 15 TESTFILE.TXT - -rw-rw-rw- 16 EXAMPLE.TXT - nsh> cat /mnt/fs/testdir/example.txt - This is a test - nsh> - - nsh> mount - /etc type romfs - /tmp type vfat - /mnt/fs type vfat - ``` - -- `mv ` - - Rename the file object at `` to ``. Both paths must - reside in the same mounted file system. - -- `nfsmount ` - - Mount the remote NFS server directory `` at `` on - the target machine. `` is the IP address of the remote server. - -- `nslookup ` - - Lookup and print the IP address associated with `` - -- `passwd ` - - Set the password for the existing user `` to `` - -- `pmconfig [stay|relax] [normal|idle|standby|sleep]` - - Control power management subsystem. - -- `poweroff []` - - Shutdown and power off the system. This command depends on board- specific - hardware support to power down the system. The optional, decimal numeric - argument `` may be included to provide power off mode to board-specific - power off logic. - - **Note**: Supporting both the `poweroff` and `shutdown` commands is redundant. - -- `printf [\xNN] [\n\r\t] [ [...]]` - - Copy the sequence of strings, characters and expanded environment variables to - console out (or to a file if the output is re-directed). - - No trailing newline character is added. The escape sequences `\n`, `\r` or - `\t` can be used to add line feed, carriage return or tab character to output, - respectively. - - The hexadecimal escape sequence `\xNN` takes up to two hexadesimal digits to - specify the printed character. - -- `ps` - - Show the currently active threads and tasks. For example: - - ``` - nsh> ps - PID PRI POLICY TYPE NPX STATE EVENT SIGMASK COMMAND - 0 0 FIFO Kthread --- Ready 00000000 Idle Task - 1 128 RR Task --- Running 00000000 init - 2 128 FIFO Task --- Waiting Semaphore 00000000 nsh_telnetmain() - 3 100 RR pthread --- Waiting Semaphore 00000000 (21) - nsh> - ``` - - **Note**: This commands depends upon having the `procfs` file system - configured into the system. The procfs file system must also have been mounted - with a command like: - - ```shell - nsh> mount -t procfs /proc - ``` - -- `put [-b|-n] [-f ] -h ` - - Copy the file at to the host whose IP address is - identified by . Other options: - - - `-f ` - The file will be saved with the same name on the host unless - unless `` is provided. - - - `-b|-n` - Selects either binary (_octet_) or test (_netascii_) transfer - mode. Default: text. - -- `pwd` - - Show the current working directory. - - ``` - nsh> cd /dev - nsh> pwd - /dev - nsh> - ``` - - Same as `echo $PWD` - - ``` - nsh> echo $PWD - /dev - nsh> - ``` - -- `readlink ` - - Show target of a soft link. - -- `switchboot - - Switch to the updated or specified boot system. This command depends on - hardware support CONFIG_BOARDCTL_SWITCH_BOOT. `` point to a - partion or file which contain the firmware to boot. - -- `boot [ [
]]` - - Boot a new firmware image. This command depends on hardware support - CONFIG_BOARDCTL_BOOT_IMAGE. `` may point to a partion or file - which contain the firmware to boot. The optional, numeric argument - `
` may be useful for skipping metadata information preprended - to the firmware image. - -- `reboot []` - - Reset and reboot the system immediately. This command depends on hardware - support to reset the system. The optional, decimal numeric argument `` may - be included to provide reboot mode to board-specific reboot logic. - - **Note**: Supporting both the `reboot` and `shutdown` commands is redundant. - -- `rm ` - - Remove the specified `` name from the mounted file system. Recall - that NuttX uses a pseudo file system for its root file system. The `rm` - command can only be used to remove (`unlink`) files in volumes set up with the - `mount` command; it cannot be used to remove names from the pseudo file - system. - - **Example**: - - ``` - nsh> ls /mnt/fs/testdir - /mnt/fs/testdir: - TESTFILE.TXT - EXAMPLE.TXT - nsh> rm /mnt/fs/testdir/example.txt - nsh> ls /mnt/fs/testdir - /mnt/fs/testdir: - TESTFILE.TXT - nsh> - ``` - -- `rmdir ` - - Remove the specified `` directory from the mounted file system. - Recall that NuttX uses a pseudo file system for its root file system. The - `rmdir` command can only be used to remove directories from volumes set up - with the `mount` command; it cannot be used to remove directories from the - pseudo file system. - - **Example**: - - ``` - nsh> mkdir /mnt/fs/tmp - nsh> ls -l /mnt/fs - /mnt/fs: - drw-rw-rw- 0 TESTDIR/ - drw-rw-rw- 0 TMP/ - nsh> rmdir /mnt/fs/tmp - nsh> ls -l /mnt/fs - ls -l /mnt/fs - /mnt/fs: - drw-rw-rw- 0 TESTDIR/ - nsh> - ``` - -- `rmmod ` - - Remove the loadable OS module with the ``. **Note**: An OS module - can only be removed if it is not busy. - - **Example**: - - ``` - nsh> lsmod - NAME INIT UNINIT ARG TEXT SIZE DATA SIZE - mydriver 20404659 20404625 0 20404580 552 204047a8 0 - nsh> rmmod mydriver - nsh> lsmod - NAME INIT UNINIT ARG TEXT SIZE DATA SIZE - nsh> - ``` - -- `route ipv4|ipv6` - - Show the contents of routing table for IPv4 or IPv6. - - If only IPv4 or IPv6 is enabled, then the argument is optional but, if - provided, must match the enabled internet protocol version. - -- `rptun start|stop ` - - Start or stop the OpenAMP RPC tunnel device at ``. - -- `set [{+|-}{e|x|xe|ex}] [ ]` - - Set the variable `` to the string `` and or set NSH parser - control options. - - For example, a variable may be set like this: - - ``` - nsh> echo $foobar - - nsh> set foobar foovalue - nsh> echo $foobar - foovalue - nsh> - ``` - - If `CONFIG_NSH_VARS` is selected, the effect of this `set` command is to set - the local NSH variable. Otherwise, the group-wide environment variable will be - set. - - If the local NSH variable has already been 'promoted' to an environment - variable, then the `set` command will set the value of the environment - variable rather than the local NSH variable. - - **Note**: The Bash shell does not work this way. Bash would set the value of - both the local Bash variable and of the environment variable of the same name - to the same value. - - If `CONFIG_NSH_VARS` is selected and no arguments are provided, then the `set` - command will list all list all NSH variables. - - ``` - nsh> set - foolbar=foovalue - ``` - - Set the _exit on error control_ and/or _print a trace_ of commands when - parsing scripts in NSH. The settinngs are in effect from the point of - execution, until they are changed again, or in the case of the init script, - the settings are returned to the default settings when it exits. Included - child scripts will run with the parents settings and changes made in the child - script will effect the parent on return. - - Use `set -e` to enable and `set +e` to disable (ignore) the exit condition - on commands. The default is `-e`. Errors cause script to exit. - - Use `set -x` to enable and `set +x` to disable (silence) printing a trace of - the script commands as they are ececuted. The default is `+x`. No printing of - a trace of script commands as they are executed. - - - Example 1 - no exit on command not found - - ``` - set +e - notacommand - ``` - - - Example 2 - will exit on command not found - - ``` - set -e - notacommand - ``` - - - Example 3 - will exit on command not found, and print a trace of the script commands - - ``` - set -ex - ``` - - - Example 4 - will exit on command not found, and print a trace of the script commands - and set foobar to foovalue. - - ``` - set -ex foobar foovalue - nsh> echo $foobar - foovalue - ``` - -- `shutdown [--reboot]` - - Shutdown and power off the system or, optionally, reset and reboot the system - immediately. This command depends on hardware support to power down or reset - the system; one, both, or neither behavior may be supported. - - **Note**: The `shutdown` command duplicates the behavior of the `poweroff` and - `reboot` commands. - -- `sleep ` - - Pause execution (sleep) of `` seconds. - -- `source ` - - Execute the sequence of NSH commands in the file referred to by - ``. - -- `telnetd` - - The Telnet daemon may be started either programmatically by calling - `nsh_telnetstart()` or it may be started from the NSH command line using this - `telnetd` command. - - Normally this command would be suppressed without `CONFIG_SYSTEM_TELNETD` - because the Telnet daemon is automatically started in `nsh_main.c`. The - exception is when `CONFIG_NETINIT_NETLOCAL` is selected. IN that case, the - network is not enabled at initialization but rather must be enabled from the - NSH command line or via other applications. - - In that case, calling `nsh_telnetstart()` before the the network is - initialized will fail. - -- `time ""` - - Perform command timing. This command will execute the following `` - string and then show how much time was required to execute the command. Time - is shown with a resolution of 100 microseconds which may be beyond the - resolution of many configurations. Note that the `` must be enclosed - in quotation marks if it contains spaces or other delimiters. - - **Example**: - - ``` - nsh> time "sleep 2" - - 2.0100 sec - nsh> - ``` - - The additional 10 milliseconds in this example is due to the way that the - `sleep` command works: It always waits one system clock tick longer than - requested and this test setup used a 10 millisecond periodic system timer. - Sources of error could include various quantization errors, competing CPU - usage, and the additional overhead of the `time` command execution itself - which is included in the total. - - The reported time is the elapsed time from starting of the command to - completion of the command. This elapsed time may not necessarily be just the - processing time for the command. It may included interrupt level processing, - for example. In a busy system, command processing could be delayed if - pre-empted by other, higher priority threads competing for CPU time. So the - reported time includes all CPU processing from the start of the command to its - finish possibly including unrelated processing time during that interval. - - Notice that: - - ``` - nsh> time "sleep 2 &" - sleep [3:100] - - 0.0000 sec - nsh> - ``` - - Since the `sleep` command is executed in background, the `sleep` command - completes almost immediately. As opposed to the following where the `time` - command is run in background with the `sleep` command: - - ``` - nsh> time "sleep 2" & - time [3:100] - nsh> - 2.0100 sec - ``` - -- `truncate -s ` - - Shrink or extend the size of the regular file at `` to the - specified ``. - - A `` argument that does not exist is created. The `` option - is NOT optional. - - If a `` is larger than the specified size, the extra data is lost. - If a `` is shorter, it is extended and the extended part reads as - zero bytes. - -- `umount ` - - Un-mount the file system at mount point ``. The `umount` command can - only be used to un-mount volumes previously mounted using `mount` command. - - **Example**: - - ``` - nsh> ls /mnt/fs - /mnt/fs: - TESTDIR/ - nsh> umount /mnt/fs - nsh> ls /mnt/fs - /mnt/fs: - nsh: ls: no such directory: /mnt/fs - nsh> - ``` - -- `unset ` - - Remove the value associated with the variable ``. This will remove the - name-value pair from both the NSH local variables and the group-wide - environment variables. For example: - - ``` - nsh> echo $foobar - foovalue - nsh> unset foobar - nsh> echo $foobar - - nsh> - ``` - -- `uptime [options]` - - Display the current time, how long the system has been running, and the load - average of the system over the last 1, 5, and 15 minutes. - - options: - - -p, show uptime in pretty format - - -h, display this help and exit - - -s, system up since - - **Example**: - - ``` - nsh> uptime - 19:35:01 up 1:40, load average: 0.00, 0.00, 0.00 - nsh> - nsh> - nsh> uptime -s - 2022-09-16 17:54:26 - nsh> - nsh> - nsh> uptime -p - up 1 hour, 40 minutes - nsh> - nsh> - nsh> uptime -h - Usage: - uptime [options] - Options: - -p, show uptime in pretty format - -h, display this help and exit - -s, system up since - nsh> - ``` - -- `urldecode [-f] ` - -- `urlencode [-f] ` - -- `uname [-a | -imnoprsv]` - - Print certain system information. With no options, the output is the same as - `-s`. - - - `-a` Print all information, in the following order, except omit `-p` and - `-i` if unknown: - - `-s`, `-o`, Print the operating system name (NuttX) - - `-n` Print the network node hostname (only available if `CONFIG_NET=y`) - - `-r` Print the kernel release - - `-v` Print the kernel version - - `-m` Print the machine hardware name - - `-i` Print the machine platform name - - `-p` Print "unknown" - -- `useradd ` - - Add a new user with `` and `` - -- `userdel ` - - Delete the user with the name `` - -- `usleep ` - - Pause execution (sleep) of `` microseconds. - -- `wget [-o ] ` - - Use HTTP to copy the file at `` to the current directory. Options: - - - `-o ` The file will be saved relative to the current working - directory and with the same name as on the HTTP server unless `` - is provided. - -- `xd ` - - Dump bytes of data from address `` - - **Example**: - - ``` - nsh> xd 410e0 512 - Hex dump: - 0000: 00 00 00 00 9c 9d 03 00 00 00 00 01 11 01 10 06 ................ - 0010: 12 01 11 01 25 08 13 0b 03 08 1b 08 00 00 02 24 ....%..........$ - ... - 01f0: 08 3a 0b 3b 0b 49 13 00 00 04 13 01 01 13 03 08 .:.;.I.......... - nsh> - ``` - -## Built-In Commands - -In addition to the commands that are part of NSH listed above, there can be -additional, external _built-in_ applications that can be added to NSH. These are -separately excecuble programs but will appear much like the commands that are a -part of NSH. The primary difference from the user's perspective is that help -information about the built-in applications is not directly available from NSH. -Rather, you will need to execute the application with the -h option to get help -about using the built-in applications. - -There are several built-in appliations in the `apps/` repository. No attempt is -made here to enumerate all of them. But a few of the more common built- in -applications are listed below. - -- `ping [-c ] [-i ] ` - `ping6 [-c ] [-i ] ` - - Test the network communication with a remote peer. Example: - - ``` - nsh> 10.0.0.1 - PING 10.0.0.1 56 bytes of data - 56 bytes from 10.0.0.1: icmp_seq=1 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=2 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=3 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=4 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=5 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=6 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=7 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=8 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=9 time=0 ms - 56 bytes from 10.0.0.1: icmp_seq=10 time=0 ms - 10 packets transmitted, 10 received, 0% packet loss, time 10190 ms - nsh> - ``` - - `ping6` differs from `ping` in that it uses IPv6 addressing. - -## NSH Configuration Settings - -The availability of the above commands depends upon features that may or may not -be enabled in the NuttX configuration file. The following table indicates the -dependency of each command on NuttX configuration settings. General -configuration settings are discussed in the NuttX Porting Guide. Configuration -settings specific to NSH as discussed at the bottom of this README file. - -## Command Dependencies on Configuration Settings - - Command | Depends on Configuration -----------|-------------------------- -[ | !`CONFIG_NSH_DISABLESCRIPT` -addroute | `CONFIG_NET` && `CONFIG_NET_ROUTE` -arp | `CONFIG_NET` && `CONFIG_NET_ARP` -base64dec | `CONFIG_NETUTILS_CODECS` && `CONFIG_CODECS_BASE64` -base64enc | `CONFIG_NETUTILS_CODECS` && `CONFIG_CODECS_BASE64` -basename | - -break | !`CONFIG_NSH_DISABLESCRIPT` && !`CONFIG_NSH_DISABLE_LOOPS` -cat | - -cd | !`CONFIG_DISABLE_ENVIRON` -cp | - -dd | - -delroute | `CONFIG_NET` && `CONFIG_NET_ROUTE` -df | !`CONFIG_DISABLE_MOUNTPOINT` -dirname | - -dmesg | `CONFIG_RAMLOG_SYSLOG` -echo | - -env | `CONFIG_FS_PROCFS` && !`CONFIG_DISABLE_ENVIRON` && !`CONFIG_PROCFS_EXCLUDE_ENVIRON` -exec | - -exit | - -export | `CONFIG_NSH_VARS` && !`CONFIG_DISABLE_ENVIRON` -free | - -get | `CONFIG_NET` && `CONFIG_NET_UDP` && MTU >= 558 (see note 1) -help | - -hexdump | - -ifconfig | `CONFIG_NET` && `CONFIG_FS_PROCFS` && !`CONFIG_FS_PROCFS_EXCLUDE_NET` -ifdown | `CONFIG_NET` && `CONFIG_FS_PROCFS` && !`CONFIG_FS_PROCFS_EXCLUDE_NET` -ifup | `CONFIG_NET` && `CONFIG_FS_PROCFS` && !`CONFIG_FS_PROCFS_EXCLUDE_NET` -insmod | `CONFIG_MODULE` -irqinfo | `CONFIG_FS_PROCFS` && `CONFIG_SCHED_IRQMONITOR` -kill | - -losetup | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_DEV_LOOP` -ln | `CONFIG_PSEUDOFS_SOFTLINK` -ls | - -lsmod | `CONFIG_MODULE` && `CONFIG_FS_PROCFS` && !`CONFIG_FS_PROCFS_EXCLUDE_MODULE` -md5 | `CONFIG_NETUTILS_CODECS` && `CONFIG_CODECS_HASH_MD5` -mb,mh,mw | - -mkdir | !`CONFIG_DISABLE_MOUNTPOINT` || !`CONFIG_DISABLE_PSEUDOFS_OPERATIONS` -mkfatfs | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_FSUTILS_MKFATFS` -mkfifo | `CONFIG_PIPES` && `CONFIG_DEV_FIFO_SIZE` > 0 -mkrd | !`CONFIG_DISABLE_MOUNTPOINT` -mount | !`CONFIG_DISABLE_MOUNTPOINT` -mv | !`CONFIG_DISABLE_MOUNTPOINT` || !`CONFIG_DISABLE_PSEUDOFS_OPERATIONS` -nfsmount | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_NET` && `CONFIG_NFS` -nslookup | `CONFIG_LIBC_NETDB` && `CONFIG_NETDB_DNSCLIENT` -password | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_NSH_LOGIN_PASSWD` -pmconfig | `CONFIG_PM` && !`CONFIG_NSH_DISABLE_PMCONFIG` -poweroff | `CONFIG_BOARDCTL_POWEROFF` -printf | - -ps | `CONFIG_FS_PROCFS` && !`CONFIG_FS_PROCFS_EXCLUDE_PROC` -put | `CONFIG_NET` && `CONFIG_NET_UDP` && MTU >= 558 (see note 1,2) -pwd | !`CONFIG_DISABLE_ENVIRON` -readlink | `CONFIG_PSEUDOFS_SOFTLINK` -reboot | `CONFIG_BOARDCTL_RESET` -rm | !`CONFIG_DISABLE_MOUNTPOINT` || !`CONFIG_DISABLE_PSEUDOFS_OPERATIONS` -rmdir | !`CONFIG_DISABLE_MOUNTPOINT` || !`CONFIG_DISABLE_PSEUDOFS_OPERATIONS` -rmmod | `CONFIG_MODULE` -route | `CONFIG_FS_PROCFS` && `CONFIG_FS_PROCFS_EXCLUDE_NET` &&
!`CONFIG_FS_PROCFS_EXCLUDE_ROUTE` && `CONFIG_NET_ROUTE` &&
!`CONFIG_NSH_DISABLE_ROUTE` && (`CONFIG_NET_IPv4` || `CONFIG_NET_IPv6`) -rptun | `CONFIG_RPTUN` -set | `CONFIG_NSH_VARS` || !`CONFIG_DISABLE_ENVIRON` -shutdown | `CONFIG_BOARDCTL_POWEROFF` || `CONFIG_BOARDCTL_RESET` -sleep | - -source | !`CONFIG_NSH_DISABLESCRIPT` -test | !`CONFIG_NSH_DISABLESCRIPT` -telnetd | `CONFIG_NSH_TELNET` && `CONFIG_SYSTEM_TELNETD` -time | - -truncate | !`CONFIG_DISABLE_MOUNTPOINT` -umount | !`CONFIG_DISABLE_MOUNTPOINT` -uname | !`CONFIG_NSH_DISABLE_UNAME` -unset | `CONFIG_NSH_VARS` || !`CONFIG_DISABLE_ENVIRON` -uptime | !`CONFIG_NSH_DISABLE_UPTIME` -urldecode | `CONFIG_NETUTILS_CODECS` && `CONFIG_CODECS_URLCODE` -urlencode | `CONFIG_NETUTILS_CODECS` && `CONFIG_CODECS_URLCODE` -useradd | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_NSH_LOGIN_PASSWD` -userdel | !`CONFIG_DISABLE_MOUNTPOINT` && `CONFIG_NSH_LOGIN_PASSWD` -usleep | - -get | `CONFIG_NET` && `CONFIG_NET_TCP` -xd | - - -**Notes**: - -1. Because of hardware padding, the actual MTU required for `put` and `get` - operations size may be larger. -2. Special TFTP server start-up options will probably be required to permit - creation of file for the correct operation of the `put` command. - -In addition, each NSH command can be individually disabled via one of the -following settings. All of these settings make the configuration of NSH -potentially complex but also allow it to squeeze into very small memory -footprints. - -``` -CONFIG_NSH_DISABLE_ADDROUTE, CONFIG_NSH_DISABLE_BASE64DEC, CONFIG_NSH_DISABLE_BASE64ENC, -CONFIG_NSH_DISABLE_BASENAME, CONFIG_NSH_DISABLE_CAT, CONFIG_NSH_DISABLE_CD, -CONFIG_NSH_DISABLE_CP, CONFIG_NSH_DISABLE_DD, CONFIG_NSH_DISABLE_DELROUTE, -CONFIG_NSH_DISABLE_DF, CONFIG_NSH_DISABLE_DIRNAME, CONFIG_NSH_DISABLE_DMESG, -CONFIG_NSH_DISABLE_ECHO, CONFIG_NSH_DISABLE_ENV, CONFIG_NSH_DISABLE_EXEC, -CONFIG_NSH_DISABLE_EXIT, CONFIG_NSH_DISABLE_EXPORT, CONFIG_NSH_DISABLE_FREE, -CONFIG_NSH_DISABLE_GET, CONFIG_NSH_DISABLE_HELP, CONFIG_NSH_DISABLE_HEXDUMP, -CONFIG_NSH_DISABLE_IFCONFIG, CONFIG_NSH_DISABLE_IFUPDOWN, CONFIG_NSH_DISABLE_KILL, -CONFIG_NSH_DISABLE_LOSETUP, CONFIG_NSH_DISABLE_LN, CONFIG_NSH_DISABLE_LS, -CONFIG_NSH_DISABLE_MD5, CONFIG_NSH_DISABLE_MB, CONFIG_NSH_DISABLE_MKDIR, -CONFIG_NSH_DISABLE_MKFATFS, CONFIG_NSH_DISABLE_MKFIFO, CONFIG_NSH_DISABLE_MKRD, -CONFIG_NSH_DISABLE_MH, CONFIG_NSH_DISABLE_MODCMDS, CONFIG_NSH_DISABLE_MOUNT, -CONFIG_NSH_DISABLE_MW, CONFIG_NSH_DISABLE_MV, CONFIG_NSH_DISABLE_NFSMOUNT, -CONFIG_NSH_DISABLE_NSLOOKUP, CONFIG_NSH_DISABLE_PASSWD, CONFIG_NSH_DISABLE_PING6, -CONFIG_NSH_DISABLE_POWEROFF, CONFIG_NSH_DISABLE_PRINTF, CONFIG_NSH_DISABLE_PS, -CONFIG_NSH_DISABLE_PUT, CONFIG_NSH_DISABLE_PWD, CONFIG_NSH_DISABLE_READLINK, -CONFIG_NSH_DISABLE_REBOOT, CONFIG_NSH_DISABLE_RM, CONFIG_NSH_DISABLE_RPTUN, -CONFIG_NSH_DISABLE_RMDIR, CONFIG_NSH_DISABLE_ROUTE, CONFIG_NSH_DISABLE_SET, -CONFIG_NSH_DISABLE_SHUTDOWN, CONFIG_NSH_DISABLE_SLEEP, CONFIG_NSH_DISABLE_SOURCE, -CONFIG_NSH_DISABLE_TEST, CONFIG_NSH_DISABLE_TIME, CONFIG_NSH_DISABLE_TRUNCATE, -CONFIG_NSH_DISABLE_UMOUNT, CONFIG_NSH_DISABLE_UNSET, CONFIG_NSH_DISABLE_UPTIME, -CONFIG_NSH_DISABLE_URLDECODE, CONFIG_NSH_DISABLE_URLENCODE, CONFIG_NSH_DISABLE_USERADD, -CONFIG_NSH_DISABLE_USERDEL, CONFIG_NSH_DISABLE_USLEEP, CONFIG_NSH_DISABLE_WGET, -CONFIG_NSH_DISABLE_XD -``` - -Verbose help output can be suppressed by defining `CONFIG_NSH_HELP_TERSE`. In -that case, the `help` command is still available but will be slightly smaller. - -## Built-in Application Configuration Settings - -All built-in applications require that support for NSH built-in applications has -been enabled. This support is enabled with `CONFIG_BUILTIN=y` and -`CONFIG_NSH_BUILTIN_APPS=y`. - -Application | Depends on Configuration -------------|-------------------------- -ping | `CONFIG_NET` && `CONFIG_NET_ICMP` && `CONFIG_NET_ICMP_SOCKET` &&
`CONFIG_SYSTEM_PING` -ping6 | `CONFIG_NET` && `CONFIG_NET_ICMPv6` && `CONFIG_NET_ICMPv6_SOCKET` &&
`CONFIG_SYSTEM_PING6` - -## NSH-Specific Configuration Settings - -The behavior of NSH can be modified with the following settings in the -`boards////configs//defconfig` file: - -- `CONFIG_NSH_READLINE` – Selects the minimal implementation of `readline()`. - This minimal implementation provides on backspace for command line editing. - -- `CONFIG_NSH_CLE` - - Selects the more extensive, EMACS-like command line editor. Select this option - only if (1) you don't mind a modest increase in the FLASH footprint, and (2) - you work with a terminal that support VT100 editing commands. - - Selecting this option will add probably 1.5-2KB to the FLASH footprint. - -- `CONFIG_NSH_BUILTIN_APPS` – Support external registered, _builtin_ - applications that can be executed from the NSH command line (see - `apps/README.md` for more information). - -- `CONFIG_NSH_FILEIOSIZE` – Size of a static I/O buffer used for file access - (ignored if there is no file system). Default is `1024`. - -- `CONFIG_NSH_STRERROR` – `strerror(errno)` makes more readable output but - `strerror()` is very large and will not be used unless this setting is `y`. - This setting depends upon the `strerror()` having been enabled with - `CONFIG_LIBC_STRERROR`. - -- `CONFIG_NSH_LINELEN` – The maximum length of one command line and of one - output line. Default: `80` - -- `CONFIG_NSH_DISABLE_SEMICOLON` – By default, you can enter multiple NSH - commands on a line with each command separated by a semicolon. You can disable - this feature to save a little memory on FLASH challenged platforms. Default: - `n` - -- `CONFIG_NSH_CMDPARMS` - - If selected, then the output from commands, from file applications, and from - NSH built-in commands can be used as arguments to other commands. The entity - to be executed is identified by enclosing the command line in back quotes. For - example, - - ```shell - set FOO `myprogram $BAR` - ``` - - Will execute the program named myprogram passing it the value of the - environment variable `BAR`. The value of the environment variable FOO is then - set output of myprogram on stdout. Because this feature commits significant - resources, it is disabled by default. - - The `CONFIG_NSH_CMDPARMS` interim output will be retained in a temporary file. - Full path to a directory where temporary files can be created is taken from - `CONFIG_LIBC_TMPDIR` and it defaults to `/tmp` if `CONFIG_LIBC_TMPDIR` is not - set. - -- `CONFIG_NSH_MAXARGUMENTS` – The maximum number of NSH command arguments. - Default: `6` - -- `CONFIG_NSH_ARGCAT` - - Support concatenation of strings with environment variables or command - output. For example: - - ```shell - set FOO XYZ - set BAR 123 - set FOOBAR ABC_${FOO}_${BAR} - ``` - - would set the environment variable `FOO` to `XYZ`, `BAR` to `123` and `FOOBAR` - to `ABC_XYZ_123`. If `NSH_ARGCAT` is not selected, then a slightly small FLASH - footprint results but then also only simple environment variables like `$FOO` - can be used on the command line. - -- `CONFIG_NSH_VARS` - - By default, there are no internal NSH variables. NSH will use OS environment - variables for all variable storage. If this option, NSH will also support - local NSH variables. These variables are, for the most part, transparent and - work just like the OS environment variables. The difference is that when you - create new tasks, all of environment variables are inherited by the created - tasks. NSH local variables are not. - - If this option is enabled (and `CONFIG_DISABLE_ENVIRON` is not), then a new - command called 'export' is enabled. The export command works very must like - the set command except that is operates on environment variables. When - `CONFIG_NSH_VARS` is enabled, there are changes in the behavior of certain - commands - - Command | w/o `CONFIG_NSH_VARS` | w/`CONFIG_NSH_VARS` - -----------------|----------------------------------|--------------------- - `set ` | Set environment var `a` to `b`. | Set NSH var `a` to `b`. - `set` | Causes an error. | Lists all NSH variables. - `unset ` | Unsets environment var `a`. | Unsets both environment var and NSH var `a`. - `export ` | Causes an error. | Unsets NSH var `a`. Sets environment var `a` to `b`. - `export ` | Causes an error. | Sets environment var `a` to NSH var `b` (or `""`).
Unsets local var `a`. - `env` | Lists all environment variables. | Lists all environment variables (only). - -- `CONFIG_NSH_QUOTE` – Enables back-slash quoting of certain characters within - the command. This option is useful for the case where an NSH script is used to - dynamically generate a new NSH script. In that case, commands must be treated - as simple text strings without interpretation of any special characters. - Special characters such as `$`, `` ` ``, `"`, and others must be retained - intact as part of the test string. This option is currently only available is - `CONFIG_NSH_ARGCAT` is also selected. - -- `CONFIG_NSH_NESTDEPTH` – The maximum number of nested `if-then[-else]-fi` - sequences that are permissible. Default: `3` - -- `CONFIG_NSH_DISABLESCRIPT` – This can be set to `y` to suppress support for - scripting. This setting disables the `sh`, `test`, and `[` commands and the - `if-then[-else]-fi` construct. This would only be set on systems where a - minimal footprint is a necessity and scripting is not. - -- `CONFIG_NSH_DISABLE_ITEF` – If scripting is enabled, then then this option can - be selected to suppress support for `if-then-else-fi` sequences in scripts. - This would only be set on systems where some minimal scripting is required but - `if-then-else-fi` is not. - -- `CONFIG_NSH_DISABLE_LOOPS` – If scripting is enabled, then then this option - can be selected suppress support for `while-do-done` and `until-do-done` - sequences in scripts. This would only be set on systems where some minimal - scripting is required but looping is not. - -- `CONFIG_NSH_DISABLEBG` – This can be set to `y` to suppress support for - background commands. This setting disables the `nice` command prefix and the - `&` command suffix. This would only be set on systems where a minimal - footprint is a necessity and background command execution is not. - -- `CONFIG_NSH_MMCSDMINOR` – If the architecture supports an MMC/SD slot and if - the NSH architecture specific logic is present, this option will provide the - MMC/SD minor number, i.e., the MMC/SD block driver will be registered as - `/dev/mmcsdN` where `N` is the minor number. Default is zero. - -- `CONFIG_NSH_ROMFSETC` – Mount a ROMFS file system at `/etc` and provide a - system init script at `/etc/init.d/rc.sysinit` and a startup script at - `/etc/init.d/rcS`. The default system init script will mount a FAT FS RAMDISK - at `/tmp` but the logic is easily extensible. - -- `CONFIG_NSH_CONSOLE` - - If `CONFIG_NSH_CONSOLE` is set to `y`, then a serial console front-end is - selected. - - Normally, the serial console device is a UART and RS-232 interface. However, - if `CONFIG_USBDEV` is defined, then a USB serial device may, instead, be used - if the one of the following are defined: - - - `CONFIG_PL2303` and `CONFIG_PL2303_CONSOLE` - Sets up the Prolifics PL2303 emulation as a console device at - `/dev/console`. - - - `CONFIG_CDCACM` and `CONFIG_CDCACM_CONSOLE` - Sets up the CDC/ACM serial device as a console device at `/dev/console`. - - - `CONFIG_NSH_USBCONSOLE` – If defined, then the an arbitrary USB device may - be used to as the NSH console. In this case, `CONFIG_NSH_USBCONDEV` must be - defined to indicate which USB device to use as the console. - - - `CONFIG_NSH_USBCONDEV` – If `CONFIG_NSH_USBCONSOLE` is set to `y`, then - `CONFIG_NSH_USBCONDEV` must also be set to select the USB device used to - support the NSH console. This should be set to the quoted name of a - read-/write-able USB driver. Default: `/dev/ttyACM0`. - - If there are more than one USB devices, then a USB device minor number may - also need to be provided: - - - `CONFIG_NSH_USBDEV_MINOR` – The minor device number of the USB device. - Default: `0` - - - `CONFIG_NSH_USBKBD` – Normally NSH uses the same device for `stdin`, - `stdout`, and `stderr`. By default, that device is `/dev/console`. If this - option is selected, then NSH will use a USB HID keyboard for stdin. In this - case, the keyboard is connected directly to the target (via a USB host - interface) and the data from the keyboard will drive NSH. NSH output - (`stdout` and `stderr`) will still go to `/dev/console`. - - - `CONFIG_NSH_USBKBD_DEVNAME` – If `NSH_USBKBD` is set to `y`, then - `NSH_USBKBD_DEVNAME` must also be set to select the USB keyboard device used - to support the NSH console input. This should be set to the quoted name of a - read- able keyboard driver. Default: `/dev/kbda`. - - - `CONFIG_NSH_USBDEV_TRACE` – If USB tracing is enabled - (`CONFIG_USBDEV_TRACE`), then NSH can be configured to show the buffered USB - trace data after each NSH command: - - If `CONFIG_NSH_USBDEV_TRACE` is selected, then USB trace data can be - filtered as follows. Default: Only USB errors are traced. - - - `CONFIG_NSH_USBDEV_TRACEINIT` - Show initialization events - - `CONFIG_NSH_USBDEV_TRACECLASS` - Show class driver events - - `CONFIG_NSH_USBDEV_TRACETRANSFERS` - Show data transfer events - - `CONFIG_NSH_USBDEV_TRACECONTROLLER` - Show controller events - - `CONFIG_NSH_USBDEV_TRACEINTERRUPTS` - Show interrupt-related events. - -- `CONFIG_NSH_ALTCONDEV` and `CONFIG_NSH_CONDEV` - - If `CONFIG_NSH_CONSOLE` is set to `y`, then `CONFIG_NSH_ALTCONDEV` may also be - selected to enable use of an alternate character device to support the NSH - console. If `CONFIG_NSH_ALTCONDEV` is selected, then `CONFIG_NSH_CONDEV` holds - the quoted name of a readable/write-able character driver such as: - `CONFIG_NSH_CONDEV="/dev/ttyS1"`. This is useful, for example, to separate the - NSH command line from the system console when the system console is used to - provide debug output. Default: stdin and stdout (probably `/dev/console`) - - **Note 1**: When any other device other than `/dev/console` is used for a - user interface, (1) linefeeds (`\n`) will not be expanded to carriage return - / linefeeds (`\r\n`). You will need to configure your terminal program to - account for this. And (2) input is not automatically echoed so you will have - to turn local echo on. - - **Note 2**: This option forces the console of all sessions to use - `NSH_CONDEV`. Hence, this option only makes sense for a system that supports - only a single session. This option is, in particular, incompatible with - Telnet sessions because each Telnet session must use a different console - device. - -- `CONFIG_NSH_TELNET` – If `CONFIG_NSH_TELNET` is set to `y`, then a TELENET - server front-end is selected. When this option is provided, you may log into - NuttX remotely using telnet in order to access NSH. - -- `CONFIG_NSH_ARCHINIT` – Set if your board provides architecture specific - initialization via the board-interface function `boardctl()`. This function - will be called early in NSH initialization to allow board logic to do such - things as configure MMC/SD slots. - -If Telnet is selected for the NSH console, then we must configure the resources -used by the Telnet daemon and by the Telnet clients. - -- `CONFIG_SYSTEM_TELNETD_PORT` – The telnet daemon will listen on this TCP port - number for connections. Default: `23` -- `CONFIG_SYSTEM_TELNETD_PRIORITY` – Priority of the Telnet daemon. Default: - `SCHED_PRIORITY_DEFAULT` -- `CONFIG_SYSTEM_TELNETD_STACKSIZE` – Stack size allocated for the Telnet - daemon. Default: `2048` -- `CONFIG_SYSTEM_TELNETD_SESSION_PRIORITY` – Priority of the Telnet client. Default: - `SCHED_PRIORITY_DEFAULT` -- `CONFIG_SYSTEM_TELNETD_SESSION_STACKSIZE` – Stack size allocated for the Telnet - client. Default: `3072` - -One or both of CONFIG_NSH_CONSOLE and `CONFIG_NSH_TELNET` must be defined. If -`CONFIG_NSH_TELNET` is selected, then there some other configuration settings -that apply: - -- `CONFIG_NET=y` – Of course, networking must be enabled -- `CONFIG_NET_TCP=y` – TCP/IP support is required for telnet (as well as various - other TCP-related configuration settings). -- `CONFIG_NETINIT_DHCPC` – Obtain the IP address via DHCP. -- `CONFIG_NETINIT_IPADDR` – If `CONFIG_NETINIT_DHCPC` is NOT set, then the - static IP address must be provided. -- `CONFIG_NETINIT_DRIPADDR` – Default router IP address. -- `CONFIG_NETINIT_NETMASK` – Network mask. -- `CONFIG_NETINIT_NOMAC` – Set if your ethernet hardware has no built-in MAC - address. If set, a bogus MAC will be assigned. - -If you use DHCPC, then some special configuration network options are required. -These include: - -- `CONFIG_NET=y` – Of course, networking must be enabled. -- `CONFIG_NET_UDP=y` – UDP support is required for DHCP (as well as various other - UDP-related configuration settings). -- `CONFIG_NET_BROADCAST=y` – UDP broadcast support is needed. -- `CONFIG_NET_ETH_PKTSIZE=650` (or larger). Per RFC2131 (p. 9), the DHCP client - must be prepared to receive DHCP messages of up to `576` bytes (excluding - Ethernet, IP, or UDP headers and FCS). **Note**: Note that the actual MTU - setting will depend upon the specific link protocol. Here Ethernet is - indicated. - -If `CONFIG_NSH_ROMFSETC` is selected, then the following additional -configuration setting apply: - -- `CONFIG_NSH_ROMFSMOUNTPT` – The default mountpoint for the ROMFS volume is - `/etc`, but that can be changed with this setting. This must be a absolute - path beginning with `/`. - -- `CONFIG_NSH_SYSINITSCRIPT` – This is the relative path to the system init - script within the mountpoint. The default is `init.d/rc.sysinit`. This - is a relative path and must not start with `/`. - -- `CONFIG_NSH_INITSCRIPT` – This is the relative path to the startup script - within the mountpoint. The default is `init.d/rcS`. This is a relative path - and must not start with `/`. - -- `CONFIG_NSH_ROMFSDEVNO` – This is the minor number of the ROMFS block device. - The default is `0` corresponding to `/dev/ram0`. - -- `CONFIG_NSH_ROMFSSECTSIZE` – This is the sector size to use with the ROMFS - volume. Since the default volume is very small, this defaults to `64` but - should be increased if the ROMFS volume were to be become large. Any value - selected must be a power of `2`. - -When the default rcS file used when `CONFIG_NSH_ROMFSETC` is selected, it will -mount a FAT FS under `/tmp`. The following selections describe that FAT FS. - -- `CONFIG_NSH_FATDEVNO` – This is the minor number of the FAT FS block device. - The default is `1` corresponding to `/dev/ram1`. - -- `CONFIG_NSH_FATSECTSIZE` – This is the sector size use with the FAT FS. - Default is `512`. - -- `CONFIG_NSH_FATNSECTORS` – This is the number of sectors to use with the FAT - FS. Default is `1024`. The amount of memory used by the FAT FS will be - `CONFIG_NSH_FATSECTSIZE` * `CONFIG_NSH_FATNSECTORS` bytes. - -- `CONFIG_NSH_FATMOUNTPT` – This is the location where the FAT FS will be - mounted. Default is `/tmp`. - -## Common Problems - -Problem: - -``` -The function 'readline' is undefined. -``` - -Usual Cause: - -The following is missing from your `defconfig` file: - -```conf -CONFIG_SYSTEM_READLINE=y -``` diff --git a/nshlib/nsh.h b/nshlib/nsh.h index 561feac85..574150247 100644 --- a/nshlib/nsh.h +++ b/nshlib/nsh.h @@ -658,11 +658,6 @@ struct nsh_parser_s #endif bool np_redirect; /* true: Output from the last command was re-directed */ bool np_fail; /* true: The last command failed */ - pid_t np_lastpid; /* Pid of the last command executed */ -#ifdef NSH_HAVE_VARS - char np_pids[32]; /* String representation of the last pid */ -#endif - #ifndef CONFIG_NSH_DISABLESCRIPT uint8_t np_flags; /* See nsh_npflags_e above */ #endif @@ -753,7 +748,6 @@ extern const char g_loginsuccess[]; extern const char g_badcredentials[]; extern const char g_loginfailure[]; #endif -extern const char g_nshprompt[]; extern const char g_fmtsyntax[]; extern const char g_fmtargrequired[]; extern const char g_fmtnomatching[]; @@ -830,6 +824,11 @@ int nsh_session(FAR struct console_stdio_s *pstate, int login, int argc, FAR char *argv[]); int nsh_parse(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline); +/* Prompt string handling */ + +FAR const char *nsh_prompt(void); +void nsh_update_prompt(void); + /**************************************************************************** * Name: nsh_login * @@ -1146,6 +1145,11 @@ int cmd_switchboot(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv); FAR char **argv); #endif +#if defined(CONFIG_BOARDCTL_IRQ_AFFINITY) && !defined(CONFIG_NSH_DISABLE_IRQ_AFFINITY) + int cmd_irq_affinity(FAR struct nsh_vtbl_s *vtbl, int argc, + FAR char **argv); +#endif + #if defined(CONFIG_RPMSG) && !defined(CONFIG_NSH_DISABLE_RPMSG) int cmd_rpmsg(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv); #endif @@ -1216,10 +1220,6 @@ int cmd_alias(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv); int cmd_unalias(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv); #endif -#if !defined(CONFIG_NSH_DISABLE_WAIT) && defined(CONFIG_SCHED_WAITPID) -int cmd_wait(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv); -#endif - /**************************************************************************** * Name: nsh_extmatch_count * diff --git a/nshlib/nsh_alias.c b/nshlib/nsh_alias.c index 0024548da..b14847cd1 100644 --- a/nshlib/nsh_alias.c +++ b/nshlib/nsh_alias.c @@ -392,6 +392,7 @@ int cmd_unalias(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) { FAR struct nsh_alias_s *alias; FAR char **arg; + int option; int ret = OK; /* Init, if necessary */ @@ -407,7 +408,7 @@ int cmd_unalias(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) /* If '-a' is provided, then just wipe them all */ - if (getopt(argc, argv, "a") == 'a') + if ((option = getopt(argc, argv, "a")) == 'a') { alias_removeall(vtbl); return ret; diff --git a/nshlib/nsh_builtin.c b/nshlib/nsh_builtin.c index 32dc953e1..49c0fd5d9 100644 --- a/nshlib/nsh_builtin.c +++ b/nshlib/nsh_builtin.c @@ -120,7 +120,6 @@ int nsh_builtin(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, * foreground */ - vtbl->np.np_lastpid = ret; #ifdef CONFIG_SCHED_WAITPID /* CONFIG_SCHED_WAITPID is selected, so we may run the command in diff --git a/nshlib/nsh_command.c b/nshlib/nsh_command.c index 86a1edd7a..a505b1faa 100644 --- a/nshlib/nsh_command.c +++ b/nshlib/nsh_command.c @@ -188,7 +188,7 @@ static const struct cmdmap_s g_cmdmap[] = #ifndef CONFIG_NSH_DISABLE_DD CMD_MAP("dd", cmd_dd, 3, 7, "if= of= [bs=] [count=] " - "[skip=] [seek=] [verify] [conv=]"), + "[skip=] [seek=] [verify]"), #endif #if defined(CONFIG_NET) && defined(CONFIG_NET_ROUTE) && !defined(CONFIG_NSH_DISABLE_DELROUTE) @@ -456,6 +456,7 @@ static const struct cmdmap_s g_cmdmap[] = #if defined(CONFIG_BOARDCTL_POWEROFF) && !defined(CONFIG_NSH_DISABLE_POWEROFF) CMD_MAP("poweroff", cmd_poweroff, 1, 2, NULL), + CMD_MAP("quit", cmd_poweroff, 1, 2, NULL), #endif #ifndef CONFIG_NSH_DISABLE_PRINTF @@ -469,8 +470,7 @@ static const struct cmdmap_s g_cmdmap[] = #endif #ifndef CONFIG_NSH_DISABLE_PS - CMD_MAP("ps", cmd_ps, 1, CONFIG_NSH_MAXARGUMENTS, - "<-heap> "), + CMD_MAP("ps", cmd_ps, 1, 1, NULL), #endif #ifdef CONFIG_NET_UDP @@ -498,9 +498,14 @@ static const struct cmdmap_s g_cmdmap[] = CMD_MAP("resetcause", cmd_reset_cause, 1, 1, NULL), #endif +#if defined(CONFIG_BOARDCTL_IRQ_AFFINITY) && !defined(CONFIG_NSH_DISABLE_IRQ_AFFINITY) + CMD_MAP("irqaff", cmd_irq_affinity, 3, 3, + "irqaff [IRQ Number] [Core Mask]"), +#endif + #ifdef NSH_HAVE_DIROPTS # ifndef CONFIG_NSH_DISABLE_RM - CMD_MAP("rm", cmd_rm, 2, 3, "[-rf] "), + CMD_MAP("rm", cmd_rm, 2, 3, "[-r] "), # endif #endif @@ -657,10 +662,6 @@ static const struct cmdmap_s g_cmdmap[] = #ifndef CONFIG_NSH_DISABLE_XD CMD_MAP("xd", cmd_xd, 3, 3, " "), -#endif -#if !defined(CONFIG_NSH_DISABLE_WAIT) && defined(CONFIG_SCHED_WAITPID) - CMD_MAP("wait", cmd_wait, 1, CONFIG_NSH_MAXARGUMENTS, - "pid1 [pid2 [pid3] ...]"), #endif CMD_MAP(NULL, NULL, 1, 1, NULL) }; @@ -1251,7 +1252,6 @@ int nsh_command(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char *argv[]) } ret = handler(vtbl, argc, argv); - vtbl->np.np_lastpid = getpid(); return ret; } diff --git a/nshlib/nsh_ddcmd.c b/nshlib/nsh_ddcmd.c index 703f86086..5e7ebe957 100644 --- a/nshlib/nsh_ddcmd.c +++ b/nshlib/nsh_ddcmd.c @@ -76,8 +76,8 @@ struct dd_s uint32_t nsectors; /* Number of sectors to transfer */ uint32_t skip; /* The number of sectors skipped on input */ uint32_t seek; /* The number of bytes skipped on output */ - int oflags; /* The open flags on output deivce */ bool eof; /* true: The end of the input or output file has been hit */ + bool verify; /* true: Verify infile and outfile correctness */ size_t sectsize; /* Size of one sector */ size_t nbytes; /* Number of valid bytes in the buffer */ FAR uint8_t *buffer; /* Buffer of data to write to the output file */ @@ -170,7 +170,8 @@ static inline int dd_infopen(FAR const char *name, FAR struct dd_s *dd) static inline int dd_outfopen(FAR const char *name, FAR struct dd_s *dd) { - dd->outfd = open(name, dd->oflags, 0644); + dd->outfd = open(name, (dd->verify ? O_RDWR : O_WRONLY) | + O_CREAT | O_TRUNC, 0644); if (dd->outfd < 0) { FAR struct nsh_vtbl_s *vtbl = dd->vtbl; @@ -184,6 +185,7 @@ static inline int dd_outfopen(FAR const char *name, FAR struct dd_s *dd) static int dd_verify(FAR const char *infile, FAR const char *outfile, FAR struct dd_s *dd) { + FAR struct nsh_vtbl_s *vtbl = dd->vtbl; FAR uint8_t *buffer; unsigned sector = 0; int ret = OK; @@ -194,7 +196,7 @@ static int dd_verify(FAR const char *infile, FAR const char *outfile, ret = lseek(dd->infd, dd->skip ? dd->skip * dd->sectsize : 0, SEEK_SET); if (ret < 0) { - nsh_error(dd->vtbl, g_fmtcmdfailed, g_dd, "lseek", NSH_ERRNO); + nsh_error(vtbl, g_fmtcmdfailed, g_dd, "lseek", NSH_ERRNO); return ret; } @@ -202,7 +204,7 @@ static int dd_verify(FAR const char *infile, FAR const char *outfile, ret = lseek(dd->outfd, 0, SEEK_SET); if (ret < 0) { - nsh_error(dd->vtbl, g_fmtcmdfailed, g_dd, "lseek", NSH_ERRNO); + nsh_error(vtbl, g_fmtcmdfailed, g_dd, "lseek", NSH_ERRNO); return ret; } @@ -223,7 +225,7 @@ static int dd_verify(FAR const char *infile, FAR const char *outfile, ret = read(dd->outfd, buffer, dd->nbytes); if (ret != dd->nbytes) { - nsh_error(dd->vtbl, g_fmtcmdfailed, g_dd, "read", NSH_ERRNO); + nsh_error(vtbl, g_fmtcmdfailed, g_dd, "read", NSH_ERRNO); break; } @@ -231,10 +233,10 @@ static int dd_verify(FAR const char *infile, FAR const char *outfile, { char msg[32]; snprintf(msg, sizeof(msg), "infile sector %d", sector); - nsh_dumpbuffer(dd->vtbl, msg, dd->buffer, dd->nbytes); + nsh_dumpbuffer(vtbl, msg, dd->buffer, dd->nbytes); snprintf(msg, sizeof(msg), "\noutfile sector %d", sector); - nsh_dumpbuffer(dd->vtbl, msg, buffer, dd->nbytes); - nsh_output(dd->vtbl, "\n"); + nsh_dumpbuffer(vtbl, msg, buffer, dd->nbytes); + nsh_output(vtbl, "\n"); ret = ERROR; break; } @@ -244,7 +246,7 @@ static int dd_verify(FAR const char *infile, FAR const char *outfile, if (ret < 0) { - nsh_error(dd->vtbl, g_fmtcmdfailed, g_dd, "dd_verify", ret); + nsh_error(vtbl, g_fmtcmdfailed, g_dd, "dd_verify", ret); } free(buffer); @@ -280,7 +282,6 @@ int cmd_dd(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) dd.vtbl = vtbl; /* For nsh_output */ dd.sectsize = DEFAULT_SECTSIZE; /* Sector size if 'bs=' not provided */ dd.nsectors = 0xffffffff; /* MAX_UINT32 */ - dd.oflags = O_WRONLY | O_CREAT | O_TRUNC; /* If no IF= option is provided on the command line, then read * from stdin. @@ -338,18 +339,7 @@ int cmd_dd(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) } else if (strncmp(argv[i], "verify", 6) == 0) { - dd.oflags |= O_RDONLY; - } - else if (strncmp(argv[i], "conv=", 5) == 0) - { - if (strstr(argv[i], "nocreat") != NULL) - { - dd.oflags &= ~(O_CREAT | O_TRUNC); - } - else if (strstr(argv[i], "notrunc") != NULL) - { - dd.oflags &= ~O_TRUNC; - } + dd.verify = true; } } @@ -453,14 +443,14 @@ int cmd_dd(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) total = ((uint64_t)sector * (uint64_t)dd.sectsize); - nsh_output(vtbl, "%" PRIu64 "bytes copied, %" PRIu64 " usec, ", - total, elapsed); + nsh_output(vtbl, "%llu bytes copied, %u usec, ", + total, (unsigned int)elapsed); nsh_output(vtbl, "%u KB/s\n" , (unsigned int)(((double)total / 1024) / ((double)elapsed / USEC_PER_SEC))); #endif - if (ret == 0 && (dd.oflags & O_RDONLY) != 0) + if (ret == 0 && dd.verify) { ret = dd_verify(infile, outfile, &dd); } diff --git a/nshlib/nsh_fileapps.c b/nshlib/nsh_fileapps.c index 858eac05f..e279ea2d4 100644 --- a/nshlib/nsh_fileapps.c +++ b/nshlib/nsh_fileapps.c @@ -31,6 +31,7 @@ #include #include +#include #include #include #include @@ -38,7 +39,6 @@ #include "nsh.h" #include "nsh_console.h" -#include "nshlib/nshlib.h" #ifdef CONFIG_NSH_FILE_APPS @@ -70,8 +70,8 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, FAR char **argv, FAR const char *redirfile, int oflags) { - int priority = CONFIG_SYSTEM_NSH_PRIORITY; - size_t stacksize = CONFIG_SYSTEM_NSH_STACKSIZE; + posix_spawn_file_actions_t file_actions; + posix_spawnattr_t attr; pid_t pid; int rc = 0; int ret; @@ -80,6 +80,49 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, int index; #endif + /* Initialize the attributes file actions structure */ + + ret = posix_spawn_file_actions_init(&file_actions); + if (ret != 0) + { + /* posix_spawn_file_actions_init returns a positive errno value on + * failure. + */ + + nsh_error(vtbl, g_fmtcmdfailed, cmd, "posix_spawn_file_actions_init", + NSH_ERRNO_OF(ret)); + goto errout; + } + + ret = posix_spawnattr_init(&attr); + if (ret != 0) + { + /* posix_spawnattr_init returns a positive errno value on failure. */ + + nsh_error(vtbl, g_fmtcmdfailed, cmd, "posix_spawnattr_init", + NSH_ERRNO); + goto errout_with_actions; + } + + /* Handle re-direction of output */ + + if (redirfile) + { + ret = posix_spawn_file_actions_addopen(&file_actions, 1, redirfile, + oflags, 0644); + if (ret != 0) + { + /* posix_spawn_file_actions_addopen returns a positive errno + * value on failure. + */ + + nsh_error(vtbl, g_fmtcmdfailed, cmd, + "posix_spawn_file_actions_addopen", + NSH_ERRNO); + goto errout_with_attrs; + } + } + #ifdef CONFIG_BUILTIN /* Check if a builtin application with this name exists */ @@ -88,33 +131,41 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, if (index >= 0) { FAR const struct builtin_s *builtin; + struct sched_param param; /* Get information about the builtin */ builtin = builtin_for_index(index); if (builtin == NULL) { - errno = ENOENT; - return ERROR; + ret = ENOENT; + goto errout_with_actions; } /* Set the correct task size and priority */ - priority = builtin->priority; - stacksize = builtin->stacksize; + param.sched_priority = builtin->priority; + ret = posix_spawnattr_setschedparam(&attr, ¶m); + if (ret != 0) + { + goto errout_with_actions; + } + + ret = posix_spawnattr_setstacksize(&attr, builtin->stacksize); + if (ret != 0) + { + goto errout_with_actions; + } } #endif - /* Execute the program. nsh_spawn returns a pid when no wait + /* Execute the program. posix_spawnp returns a positive errno value on + * failure. */ - ret = nsh_spawn(cmd, NULL, argv, priority, stacksize, - redirfile, oflags, false); - if (ret >= 0) + ret = posix_spawnp(&pid, cmd, &file_actions, &attr, argv, environ); + if (ret == OK) { - pid = ret; - ret = 0; - /* The application was successfully started with pre-emption disabled. * In the simplest cases, the application will not have run because the * the scheduler is locked. But in the case where I/O was redirected, @@ -131,7 +182,6 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, * foreground */ - vtbl->np.np_lastpid = pid; #ifdef CONFIG_SCHED_WAITPID /* CONFIG_SCHED_WAITPID is selected, so we may run the command in * foreground unless we were specifically requested to run the command @@ -227,7 +277,9 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, #if !defined(CONFIG_SCHED_WAITPID) || !defined(CONFIG_NSH_DISABLEBG) { - nsh_output(vtbl, "%s [%d:%d]\n", cmd, ret, priority); + struct sched_param param; + sched_getparam(ret, ¶m); + nsh_output(vtbl, "%s [%d:%d]\n", cmd, ret, param.sched_priority); /* Backgrounded commands always 'succeed' as long as we can start * them. @@ -238,7 +290,35 @@ int nsh_fileapp(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, #endif /* !CONFIG_SCHED_WAITPID || !CONFIG_NSH_DISABLEBG */ } - if (rc != 0) + /* Free attributes and file actions. Ignoring return values in the case + * of an error. + */ + +errout_with_actions: + posix_spawn_file_actions_destroy(&file_actions); + +errout_with_attrs: + posix_spawnattr_destroy(&attr); + +errout: + /* Most posix_spawn interfaces return a positive errno value on failure + * and do not set the errno variable. + */ + + if (ret > 0) + { + /* Set the errno value and return -1 */ + + errno = ret; + ret = ERROR; + } + else if (ret < 0) + { + /* Return -1 on failure. errno should have been set. */ + + ret = ERROR; + } + else if (rc != 0) { /* We can't return the exact status (nsh has nowhere to put it) * so just pass back zero/nonzero in a fashion that doesn't look diff --git a/nshlib/nsh_fscmds.c b/nshlib/nsh_fscmds.c index 9ae283d56..5b7b1c088 100644 --- a/nshlib/nsh_fscmds.c +++ b/nshlib/nsh_fscmds.c @@ -163,8 +163,8 @@ static int cp_handler(FAR struct nsh_vtbl_s *vtbl, FAR const char *srcpath, for (; ; ) { - ssize_t nbyteswritten; - ssize_t nbytesread; + int nbytesread; + int nbyteswritten; FAR char *iobuffer = vtbl->iobuffer; nbytesread = read(rdfd, iobuffer, IOBUFFERSIZE); @@ -413,7 +413,7 @@ static int ls_handler(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, details[0] = 'f'; } #endif -#ifdef CONFIG_FS_SHM +#ifdef CONFIG_FS_SHMFS else if (S_ISSHM(buf.st_mode)) { details[0] = 'h'; @@ -516,7 +516,6 @@ static int ls_handler(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, if ((lsflags & LSFLAGS_SIZE) != 0) { -#ifdef CONFIG_HAVE_FLOAT if (lsflags & LSFLAGS_HUMANREADBLE && buf.st_size >= KB) { if (buf.st_size >= GB) @@ -533,7 +532,6 @@ static int ls_handler(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, } } else -#endif { nsh_output(vtbl, "%12" PRIdOFF, buf.st_size); } @@ -1518,11 +1516,10 @@ int cmd_ls(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) lsflags |= LSFLAGS_SIZE; break; -#ifdef CONFIG_HAVE_FLOAT case 'h': lsflags |= LSFLAGS_HUMANREADBLE; break; -#endif + case '?': default: nsh_error(vtbl, g_fmtarginvalid, argv[0]); @@ -2104,20 +2101,21 @@ int cmd_readlink(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) #ifdef NSH_HAVE_DIROPTS #ifndef CONFIG_NSH_DISABLE_RM -static int unlink_recursive(FAR char *path, FAR struct stat *stat) +static int unlink_recursive(FAR char *path) { struct dirent *d; + struct stat stat; size_t len; int ret; DIR *dp; - ret = lstat(path, stat); + ret = lstat(path, &stat); if (ret < 0) { return ret; } - if (!S_ISDIR(stat->st_mode)) + if (!S_ISDIR(stat.st_mode)) { return unlink(path); } @@ -2142,7 +2140,7 @@ static int unlink_recursive(FAR char *path, FAR struct stat *stat) } snprintf(&path[len], PATH_MAX - len, "/%s", d->d_name); - ret = unlink_recursive(path, stat); + ret = unlink_recursive(path); if (ret < 0) { closedir(dp); @@ -2162,65 +2160,31 @@ static int unlink_recursive(FAR char *path, FAR struct stat *stat) int cmd_rm(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) { - bool recursive = false; - bool force = false; + bool recursive = (strcmp(argv[1], "-r") == 0); FAR char *fullpath; char buf[PATH_MAX]; - struct stat stat; int ret = ERROR; - int c; - while ((c = getopt(argc, argv, "rf")) != ERROR) + if (recursive && argc == 2) { - switch (c) - { - case 'r': - recursive = true; - break; - case 'f': - force = true; - break; - case '?': - nsh_output(vtbl, "Unknown option 0x%x\n", optopt); - return ret; - default: - nsh_error(vtbl, g_fmtargrequired, argv[0]); - return ret; - } - } - - if (optind >= argc) - { - if (force) - { - ret = OK; - } - else - { - nsh_error(vtbl, g_fmtargrequired, argv[0]); - } - + nsh_error(vtbl, g_fmtargrequired, argv[0]); return ret; } - fullpath = nsh_getfullpath(vtbl, argv[optind]); + fullpath = nsh_getfullpath(vtbl, recursive ? argv[2] : argv[1]); + if (fullpath != NULL) { if (recursive) { strlcpy(buf, fullpath, PATH_MAX); - ret = unlink_recursive(buf, &stat); + ret = unlink_recursive(buf); } else { ret = unlink(fullpath); } - if (force && errno == ENOENT) - { - ret = 0; - } - if (ret < 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "unlink", NSH_ERRNO); diff --git a/nshlib/nsh_fsutils.c b/nshlib/nsh_fsutils.c index 309f24dc2..4dd8f4141 100644 --- a/nshlib/nsh_fsutils.c +++ b/nshlib/nsh_fsutils.c @@ -82,7 +82,7 @@ static int getpid_callback(FAR struct nsh_vtbl_s *vtbl, snprintf(buffer, sizeof(buffer), "%s/%s/cmdline", dirpath, entryp->d_name); - fd = open(buffer, O_RDONLY | O_CLOEXEC); + fd = open(buffer, O_RDONLY); if (fd < 0) { return 0; @@ -137,7 +137,7 @@ int nsh_catfile(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, /* Open the file for reading */ - fd = open(filepath, O_RDONLY | O_CLOEXEC); + fd = open(filepath, O_RDONLY); if (fd < 0) { #if defined(CONFIG_NSH_PROC_MOUNTPOINT) @@ -282,7 +282,7 @@ int nsh_readfile(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, /* Open the file */ - fd = open(filepath, O_RDONLY | O_CLOEXEC); + fd = open(filepath, O_RDONLY); if (fd < 0) { nsh_error(vtbl, g_fmtcmdfailed, cmd, "open", NSH_ERRNO); @@ -381,7 +381,7 @@ int nsh_writefile(FAR struct nsh_vtbl_s *vtbl, FAR const char *cmd, /* Open the file for reading */ - fd = open(filepath, O_WRONLY | O_CLOEXEC); + fd = open(filepath, O_WRONLY); if (fd < 0) { #if defined(CONFIG_NSH_PROC_MOUNTPOINT) diff --git a/nshlib/nsh_init.c b/nshlib/nsh_init.c index b84b06d3e..5904269e4 100644 --- a/nshlib/nsh_init.c +++ b/nshlib/nsh_init.c @@ -110,10 +110,14 @@ void nsh_initialize(void) FAR struct console_stdio_s *pstate; #endif -#if defined(CONFIG_NSH_READLINE) && defined(CONFIG_READLINE_TABCOMPLETION) - /* Configure the NSH prompt */ + /* populate NSH prompt string */ - readline_prompt(g_nshprompt); + nsh_update_prompt(); + +#if defined(CONFIG_NSH_READLINE) && defined(CONFIG_READLINE_TABCOMPLETION) + /* Configure readline prompt */ + + readline_prompt(nsh_prompt()); # ifdef CONFIG_READLINE_HAVE_EXTMATCH /* Set up for tab completion on NSH commands */ diff --git a/nshlib/nsh_parse.c b/nshlib/nsh_parse.c index 053f735e4..4709bd901 100644 --- a/nshlib/nsh_parse.c +++ b/nshlib/nsh_parse.c @@ -125,6 +125,18 @@ * Private Types ****************************************************************************/ +/* These structure describes the parsed command line */ + +#ifndef CONFIG_NSH_DISABLEBG +struct cmdarg_s +{ + FAR struct nsh_vtbl_s *vtbl; /* For front-end interaction */ + int fd; /* FD for output redirection */ + int argc; /* Number of arguments in argv */ + FAR char *argv[MAX_ARGV_ENTRIES]; /* Argument list */ +}; +#endif + /* This structure describes the allocation list */ #ifdef HAVE_MEMLIST @@ -160,6 +172,13 @@ static void nsh_alist_free(FAR struct nsh_vtbl_s *vtbl, FAR struct nsh_alist_s *alist); #endif +#ifndef CONFIG_NSH_DISABLEBG +static void nsh_releaseargs(struct cmdarg_s *arg); +static pthread_addr_t nsh_child(pthread_addr_t arg); +static struct cmdarg_s *nsh_cloneargs(FAR struct nsh_vtbl_s *vtbl, + int fd, int argc, FAR char *argv[]); +#endif + static int nsh_saveresult(FAR struct nsh_vtbl_s *vtbl, bool result); static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char *argv[], FAR const char *redirfile, @@ -260,7 +279,6 @@ static const char g_redirect1[] = ">"; static const char g_redirect2[] = ">>"; #ifdef NSH_HAVE_VARS static const char g_exitstatus[] = "?"; -static const char g_lastpid[] = "!"; static const char g_success[] = "0"; static const char g_failure[] = "1"; #endif @@ -303,10 +321,6 @@ const char g_badcredentials[] = "\nInvalid username or password\n"; const char g_loginfailure[] = "Login failed!\n"; #endif -/* The NSH prompt */ - -const char g_nshprompt[] = CONFIG_NSH_PROMPT_STRING; - /* Common, message formats */ const char g_fmtsyntax[] = "nsh: %s: syntax error\n"; @@ -425,25 +439,88 @@ static void nsh_alist_free(FAR struct nsh_vtbl_s *vtbl, } #endif +/**************************************************************************** + * Name: nsh_releaseargs + ****************************************************************************/ + +#ifndef CONFIG_NSH_DISABLEBG +static void nsh_releaseargs(struct cmdarg_s *arg) +{ + FAR struct nsh_vtbl_s *vtbl = arg->vtbl; + int i; + + /* If the output was redirected, then file descriptor should + * be closed. The created task has its one, independent copy of + * the file descriptor + */ + + if (vtbl->np.np_redirect) + { + close(arg->fd); + } + + /* Released the cloned vtbl instance */ + + nsh_release(vtbl); + + /* Release the cloned args */ + + for (i = 0; i < arg->argc; i++) + { + free(arg->argv[i]); + } + + free(arg); +} +#endif + /**************************************************************************** * Name: nsh_child ****************************************************************************/ #ifndef CONFIG_NSH_DISABLEBG -static CODE int nsh_child(int argc, FAR char *argv[]) +static pthread_addr_t nsh_child(pthread_addr_t arg) { - FAR struct console_stdio_s *pstate = nsh_newconsole(false); + struct cmdarg_s *carg = (struct cmdarg_s *)arg; int ret; - DEBUGASSERT(pstate != NULL); + _info("BG %s\n", carg->argv[0]); - /* Execute the session */ + /* Execute the specified command on the child thread */ - ret = nsh_execute(&pstate->cn_vtbl, argc - 1, &argv[1], NULL, 0); + ret = nsh_command(carg->vtbl, carg->argc, carg->argv); - /* Exit upon return */ + /* Released the cloned arguments */ + + _info("BG %s complete\n", carg->argv[0]); + nsh_releaseargs(carg); + return (pthread_addr_t)((uintptr_t)ret); +} +#endif + +/**************************************************************************** + * Name: nsh_cloneargs + ****************************************************************************/ + +#ifndef CONFIG_NSH_DISABLEBG +static struct cmdarg_s *nsh_cloneargs(FAR struct nsh_vtbl_s *vtbl, + int fd, int argc, FAR char *argv[]) +{ + struct cmdarg_s *ret = (struct cmdarg_s *)zalloc(sizeof(struct cmdarg_s)); + int i; + + if (ret) + { + ret->vtbl = vtbl; + ret->fd = fd; + ret->argc = argc; + + for (i = 0; i < argc; i++) + { + ret->argv[i] = strdup(argv[i]); + } + } - nsh_exit(&pstate->cn_vtbl, ret); return ret; } #endif @@ -519,6 +596,7 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char *argv[], FAR const char *redirfile, int oflags) { + int fd = -1; int ret; /* DO NOT CHANGE THE ORDERING OF THE FOLLOWING STEPS @@ -612,6 +690,24 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, #endif + /* Redirected output? */ + + if (vtbl->np.np_redirect) + { + /* Open the redirection file. This file will eventually + * be closed by a call to either nsh_release (if the command + * is executed in the background) or by nsh_undirect if the + * command is executed in the foreground. + */ + + fd = open(redirfile, oflags, 0666); + if (fd < 0) + { + nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open", NSH_ERRNO); + goto errout; + } + } + /* Handle the case where the command is executed in background. * However is app is to be started as built-in new process will * be created anyway, so skip this step. @@ -621,15 +717,50 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, if (vtbl->np.np_bg) { struct sched_param param; - FAR char *spawn_argv[MAX_ARGV_ENTRIES + 1]; - int i; + struct nsh_vtbl_s *bkgvtbl; + struct cmdarg_s *args; + pthread_attr_t attr; + pthread_t thread; + + /* Get a cloned copy of the vtbl with reference count=1. + * after the command has been processed, the nsh_release() call + * at the end of nsh_child() will destroy the clone. + */ + + bkgvtbl = nsh_clone(vtbl); + if (!bkgvtbl) + { + goto errout_with_redirect; + } + + /* Create a container for the command arguments */ + + args = nsh_cloneargs(bkgvtbl, fd, argc, argv); + if (!args) + { + nsh_release(bkgvtbl); + goto errout_with_redirect; + } + + /* Handle redirection of output via a file descriptor */ + + if (vtbl->np.np_redirect) + { + nsh_redirect(bkgvtbl, fd, NULL); + } + + /* Get the execution priority of this task */ ret = sched_getparam(0, ¶m); if (ret != 0) { nsh_error(vtbl, g_fmtcmdfailed, argv[0], "sched_getparm", NSH_ERRNO); - return nsh_saveresult(vtbl, true); + + /* NOTE: bkgvtbl is released in nsh_relaseargs() */ + + nsh_releaseargs(args); + goto errout; } /* Determine the priority to execute the command */ @@ -657,49 +788,42 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, param.sched_priority = priority; } - spawn_argv[0] = "nsh_child"; - for (i = 0; i < argc; i++) + /* Set up the thread attributes */ + + pthread_attr_init(&attr); + pthread_attr_setschedpolicy(&attr, SCHED_NSH); + pthread_attr_setschedparam(&attr, ¶m); + + /* Execute the command as a separate thread at the appropriate + * priority. + */ + + ret = pthread_create(&thread, &attr, nsh_child, (pthread_addr_t)args); + if (ret != 0) { - spawn_argv[1 + i] = argv[i]; + nsh_error(vtbl, g_fmtcmdfailed, argv[0], "pthread_create", + NSH_ERRNO_OF(ret)); + + /* NOTE: bkgvtbl is released in nsh_relaseargs() */ + + nsh_releaseargs(args); + goto errout; } - spawn_argv[++i] = NULL; + /* Detach from the pthread since we are not going to join with it. + * Otherwise, we would have a memory leak. + */ - ret = nsh_spawn(spawn_argv[0], nsh_child, - spawn_argv, param.sched_priority, - CONFIG_SYSTEM_NSH_STACKSIZE, - redirfile, oflags, false); - nsh_output(vtbl, "%s [%d:%d]\n", argv[0], ret, + pthread_detach(thread); + + nsh_output(vtbl, "%s [%d:%d]\n", argv[0], thread, param.sched_priority); - if (ret < 0) - { - return nsh_saveresult(vtbl, true); - } } else #endif { - int fd = -1; uint8_t save[SAVE_SIZE]; - /* Redirected output? */ - - if (vtbl->np.np_redirect) - { - /* Open the redirection file. This file will eventually - * be closed by a call to either nsh_release (if the command - * is executed in the background) or by nsh_undirect if the - * command is executed in the foreground. - */ - - fd = open(redirfile, oflags, 0666); - if (fd < 0) - { - nsh_error(vtbl, g_fmtcmdfailed, argv[0], "open", NSH_ERRNO); - return nsh_saveresult(vtbl, true); - } - } - /* Handle redirection of output via a file descriptor */ if (vtbl->np.np_redirect) @@ -731,7 +855,7 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, if (ret < 0) { - return nsh_saveresult(vtbl, true); + goto errout; } } @@ -740,6 +864,17 @@ static int nsh_execute(FAR struct nsh_vtbl_s *vtbl, */ return nsh_saveresult(vtbl, false); + +#ifndef CONFIG_NSH_DISABLEBG +errout_with_redirect: + if (vtbl->np.np_redirect) + { + close(fd); + } +#endif + +errout: + return nsh_saveresult(vtbl, true); } /**************************************************************************** @@ -1089,11 +1224,6 @@ static FAR char *nsh_envexpand(FAR struct nsh_vtbl_s *vtbl, return (FAR char *)g_success; } } - else if (strcmp(varname, g_lastpid) == 0) - { - itoa(vtbl->np.np_lastpid, vtbl->np.np_pids, 10); - return vtbl->np.np_pids; - } else { FAR char *value; @@ -2413,12 +2543,6 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) int argc; int ret; bool redirect_save = false; -#ifdef CONFIG_SCHED_INSTRUMENTATION_DUMP - char tracebuf[CONFIG_NSH_LINELEN + 1]; - - strlcpy(tracebuf, cmdline, sizeof(tracebuf)); - sched_note_beginex(NOTE_TAG_APP, tracebuf); -#endif /* Initialize parser state */ @@ -2583,7 +2707,7 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) { redirect_save = vtbl->np.np_redirect; vtbl->np.np_redirect = true; - oflags = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; + oflags = O_WRONLY | O_CREAT | O_TRUNC; redirfile = nsh_getfullpath(vtbl, argv[argc - 1]); argc -= 2; } @@ -2594,7 +2718,7 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) { redirect_save = vtbl->np.np_redirect; vtbl->np.np_redirect = true; - oflags = O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC; + oflags = O_WRONLY | O_CREAT | O_APPEND; redirfile = nsh_getfullpath(vtbl, argv[argc - 1]); argc -= 2; } @@ -2628,9 +2752,6 @@ static int nsh_parse_command(FAR struct nsh_vtbl_s *vtbl, FAR char *cmdline) dynlist_free: NSH_ALIASLIST_FREE(vtbl, &alist); NSH_MEMLIST_FREE(&memlist); -#ifdef CONFIG_SCHED_INSTRUMENTATION_DUMP - sched_note_endex(NOTE_TAG_APP, tracebuf); -#endif return ret; } diff --git a/nshlib/nsh_proccmds.c b/nshlib/nsh_proccmds.c index 5a350ed1a..f1ce2c11b 100644 --- a/nshlib/nsh_proccmds.c +++ b/nshlib/nsh_proccmds.c @@ -115,7 +115,7 @@ static const char g_priority[] = "Priority:"; static const char g_scheduler[] = "Scheduler:"; static const char g_sigmask[] = "SigMask:"; -#ifdef PS_SHOW_HEAPSIZE +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) static const char g_heapsize[] = "AllocSize:"; #endif /* CONFIG_DEBUG _MM && !CONFIG_NSH_DISABLE_PSHEAPUSAGE */ @@ -249,15 +249,16 @@ static void nsh_parse_statusline(FAR char *line, static int ps_callback(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, FAR struct dirent *entryp, FAR void *pvarg) { + UNUSED(pvarg); + struct nsh_taskstatus_s status; FAR char *filepath; FAR char *line; FAR char *nextline; int ret; int i; -#ifdef PS_SHOW_HEAPSIZE - bool heap = *(FAR bool *)pvarg; - char heapsize[10] = ""; +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) + unsigned long heap_size = 0; #endif #if !defined(CONFIG_NSH_DISABLE_PSSTACKUSAGE) unsigned long stack_size = 0; @@ -367,66 +368,62 @@ static int ps_callback(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, status.td_flags, status.td_state, status.td_event, status.td_sigmask); -#ifdef PS_SHOW_HEAPSIZE - if (heap) +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) + /* Get the Heap AllocSize */ + + filepath = NULL; + ret = asprintf(&filepath, "%s/%s/heap", dirpath, entryp->d_name); + if (ret < 0 || filepath == NULL) { - /* Get the Heap AllocSize */ + nsh_error(vtbl, g_fmtcmdfailed, "ps", "asprintf", NSH_ERRNO); + vtbl->iobuffer[0] = '\0'; + } + else + { + ret = nsh_readfile(vtbl, "ps", filepath, vtbl->iobuffer, + IOBUFFERSIZE); + free(filepath); - filepath = NULL; - ret = asprintf(&filepath, "%s/%s/heap", dirpath, entryp->d_name); - if (ret < 0 || filepath == NULL) + if (ret >= 0) { - nsh_error(vtbl, g_fmtcmdfailed, "ps", "asprintf", NSH_ERRNO); - vtbl->iobuffer[0] = '\0'; - } - else - { - ret = nsh_readfile(vtbl, "ps", filepath, vtbl->iobuffer, - IOBUFFERSIZE); - free(filepath); - - if (ret >= 0) + nextline = vtbl->iobuffer; + do { - nextline = vtbl->iobuffer; - do + /* Find the beginning of the next line and NUL-terminate the + * current line. + */ + + line = nextline; + for (nextline++; + *nextline != '\n' && *nextline != '\0'; + nextline++); + + if (*nextline == '\n') { - /* Find the beginning of the next line and NUL-terminate - * the current line. - */ - - line = nextline; - for (nextline++; - *nextline != '\n' && *nextline != '\0'; - nextline++); - - if (*nextline == '\n') - { - *nextline++ = '\0'; - } - else - { - nextline = NULL; - } - - /* Parse the current line - * - * Format: - * - * 111111111122222222223 - * 123456789012345678901234567890 - * AllocSize: xxxx - * AllocBlks: xxxx - */ - - if (strncmp(line, g_heapsize, strlen(g_heapsize)) == 0) - { - snprintf(heapsize, sizeof(heapsize), "%8s ", - &line[12]); - break; - } + *nextline++ = '\0'; + } + else + { + nextline = NULL; + } + + /* Parse the current line + * + * Format: + * + * 111111111122222222223 + * 123456789012345678901234567890 + * AllocSize: xxxx + * AllocBlks: xxxx + */ + + if (strncmp(line, g_heapsize, strlen(g_heapsize)) == 0) + { + heap_size = strtoul(&line[12], NULL, 0); + break; } - while (nextline != NULL); } + while (nextline != NULL); } } @@ -534,20 +531,20 @@ static int ps_callback(FAR struct nsh_vtbl_s *vtbl, FAR const char *dirpath, defined (PS_SHOW_STACKUSAGE) || defined (NSH_HAVE_CPULOAD) nsh_output(vtbl, #ifdef PS_SHOW_HEAPSIZE - "%s" + "%08lu " #endif #ifdef PS_SHOW_STACKSIZE - "%07lu " + "%06lu " #endif #ifdef PS_SHOW_STACKUSAGE - "%07lu " + "%06lu " "%3lu.%lu%%%c " #endif #ifdef NSH_HAVE_CPULOAD "%6s " #endif -#ifdef PS_SHOW_HEAPSIZE - , heapsize +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) + , heap_size #endif #if !defined(CONFIG_NSH_DISABLE_PSSTACKUSAGE) , stack_size @@ -623,20 +620,8 @@ int cmd_exec(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) #ifndef CONFIG_NSH_DISABLE_PS int cmd_ps(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) { - FAR const char *heapprompt = ""; - bool heap = false; - int i; - -#ifdef PS_SHOW_HEAPSIZE - for (i = 1; i < argc; i++) - { - if (strcmp(argv[i], "-heap") == 0) - { - heap = true; - heapprompt = " HEAP "; - } - } -#endif + UNUSED(argc); + UNUSED(argv); nsh_output(vtbl, "%5s %5s " #ifdef CONFIG_SMP @@ -644,7 +629,9 @@ int cmd_ps(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) #endif "%3s %-8s %-7s %3s %-8s %-9s " "%-16s " - "%s" +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) + "%8s " +#endif #if !defined(CONFIG_NSH_DISABLE_PSSTACKUSAGE) "%6s " #ifdef CONFIG_STACK_COLORATION @@ -662,7 +649,9 @@ int cmd_ps(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) #endif "PRI", "POLICY", "TYPE", "NPX", "STATE", "EVENT", "SIGMASK", - heapprompt, +#if CONFIG_MM_BACKTRACE >= 0 && !defined(CONFIG_NSH_DISABLE_PSHEAPUSAGE) + "HEAP", +#endif #if !defined(CONFIG_NSH_DISABLE_PSSTACKUSAGE) "STACK", #ifdef CONFIG_STACK_COLORATION @@ -676,28 +665,8 @@ int cmd_ps(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) "COMMAND" ); - if (argc - heap > 1) - { - for (i = 1; i < argc; i++) - { - struct dirent entry; - if (!isdigit(*argv[i])) - { - continue; - } - - entry.d_type = DT_DIR; - strcpy(entry.d_name, argv[i]); - ps_callback(vtbl, CONFIG_NSH_PROC_MOUNTPOINT, &entry, &heap); - } - - return 0; - } - else - { - return nsh_foreach_direntry(vtbl, "ps", CONFIG_NSH_PROC_MOUNTPOINT, - ps_callback, &heap); - } + return nsh_foreach_direntry(vtbl, "ps", CONFIG_NSH_PROC_MOUNTPOINT, + ps_callback, NULL); } #endif diff --git a/nshlib/nsh_prompt.c b/nshlib/nsh_prompt.c new file mode 100644 index 000000000..964534e1c --- /dev/null +++ b/nshlib/nsh_prompt.c @@ -0,0 +1,105 @@ +/**************************************************************************** + * apps/nshlib/nsh_prompt.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include + +#include "nsh.h" + +/**************************************************************************** + * Preprocessor Macros + ****************************************************************************/ + +#define NSH_PROMPT_SIZE (CONFIG_NSH_PROMPT_MAX + 1 - \ + sizeof(CONFIG_NSH_PROMPT_SUFFIX)) + +/**************************************************************************** + * Private Variables + ****************************************************************************/ + +static char g_nshprompt[CONFIG_NSH_PROMPT_MAX] = CONFIG_NSH_PROMPT_STRING; + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: nsh_update_prompt + * + * Description: + * This updates g_nshprompt from multiple sources, in the following order: + * + * - non-empty NSH_PROMPT_ENV variable and suffix + * - non-empty NSH_PROMPT_STRING + * - non-empty HOSTNAME and suffix + * + * Note that suffix has higher priority when used to help clearly separate + * prompts from command line inputs. + * + * Results: + * - updated g_nsh_prompt value. + * + ****************************************************************************/ + +void nsh_update_prompt(void) +{ + static_assert(CONFIG_NSH_PROMPT_MAX > sizeof(CONFIG_NSH_PROMPT_STRING), + "NSH_PROMPT_STRING too long!"); + static_assert(CONFIG_NSH_PROMPT_MAX > sizeof(CONFIG_NSH_PROMPT_SUFFIX), + "NSH_PROMPT_SUFFIX too long!"); + #ifndef CONFIG_DISABLE_ENVIRON + if (getenv(CONFIG_NSH_PROMPT_ENV)) + { + strlcpy(g_nshprompt, getenv(CONFIG_NSH_PROMPT_ENV), NSH_PROMPT_SIZE); + strcat(g_nshprompt, CONFIG_NSH_PROMPT_SUFFIX); + } + else + #endif + if (CONFIG_NSH_PROMPT_STRING[0]) + { + strcpy(g_nshprompt, CONFIG_NSH_PROMPT_STRING); + } + else + { + gethostname(g_nshprompt, NSH_PROMPT_SIZE); + strcat(g_nshprompt, CONFIG_NSH_PROMPT_SUFFIX); + } +} + +/**************************************************************************** + * Name: nsh_prompt + * + * Description: + * This function returns latest prompt string. + * It is needed as g_nshprompt is no longer public. + * + ****************************************************************************/ + +FAR const char *nsh_prompt(void) +{ + return g_nshprompt; +} diff --git a/nshlib/nsh_script.c b/nshlib/nsh_script.c index 35b9df8a9..e49ac1951 100644 --- a/nshlib/nsh_script.c +++ b/nshlib/nsh_script.c @@ -111,7 +111,7 @@ int nsh_script(FAR struct nsh_vtbl_s *vtbl, FAR const FAR char *cmd, /* Open the file containing the script */ - vtbl->np.np_fd = open(fullpath, O_RDOK | O_CLOEXEC); + vtbl->np.np_fd = open(fullpath, O_RDOK); if (vtbl->np.np_fd < 0) { if (log) diff --git a/nshlib/nsh_session.c b/nshlib/nsh_session.c index 8327df7c2..b9ac839c0 100644 --- a/nshlib/nsh_session.c +++ b/nshlib/nsh_session.c @@ -207,7 +207,7 @@ int nsh_session(FAR struct console_stdio_s *pstate, * occurs. Either will cause the session to terminate. */ - ret = cle_fd(pstate->cn_line, g_nshprompt, CONFIG_NSH_LINELEN, + ret = cle_fd(pstate->cn_line, nsh_prompt(), CONFIG_NSH_LINELEN, INFD(pstate), OUTFD(pstate)); if (ret < 0) { @@ -218,7 +218,7 @@ int nsh_session(FAR struct console_stdio_s *pstate, #else /* Display the prompt string */ - write(OUTFD(pstate), g_nshprompt, strlen(g_nshprompt)); + write(OUTFD(pstate), nsh_prompt(), strlen(nsh_prompt())); /* readline() normally returns the number of characters read, but * will return EOF on end of file or if an error occurs. EOF @@ -243,6 +243,7 @@ int nsh_session(FAR struct console_stdio_s *pstate, /* Parse process the command */ nsh_parse(vtbl, pstate->cn_line); + nsh_update_prompt(); } return ret; diff --git a/nshlib/nsh_spawn.c b/nshlib/nsh_spawn.c deleted file mode 100644 index e5da87e0a..000000000 --- a/nshlib/nsh_spawn.c +++ /dev/null @@ -1,221 +0,0 @@ -/**************************************************************************** - * apps/nshlib/nsh_spawn.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#ifdef CONFIG_SCHED_WAITPID -# include -# include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include "nsh.h" -#include "nshlib/nshlib.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/**************************************************************************** - * Name: nsh_spawn - * - * Description: - * Attempt to execute the application task foreground or background - * - * Returned Value: - * 0 (OK) if the application task corresponding to 'appname' was - * and successfully started. - * If wait enabled, indicates that the - * application returned successful status (EXIT_SUCCESS) - * If wait not enabled, should not be here. - * >0 If wait enabled, PID of the exec'ed module. - * If wait not enabled, indicates the application - * returned status. - * - ****************************************************************************/ - -int nsh_spawn(FAR const char *appname, FAR main_t main, - FAR char * const *argv, int priority, size_t stacksize, - FAR const char *redirfile, int oflags, bool wait) -{ - posix_spawnattr_t attr; - posix_spawn_file_actions_t file_actions; - struct sched_param param; - pid_t pid = -1; - int ret; - - /* Initialize attributes for task_spawn(). */ - - ret = posix_spawnattr_init(&attr); - if (ret != 0) - { - goto errout_with_errno; - } - - ret = posix_spawn_file_actions_init(&file_actions); - if (ret != 0) - { - goto errout_with_attrs; - } - - /* Set the correct task size and priority */ - - param.sched_priority = priority; - ret = posix_spawnattr_setschedparam(&attr, ¶m); - if (ret != 0) - { - goto errout_with_actions; - } - - ret = posix_spawnattr_setstacksize(&attr, stacksize); - if (ret != 0) - { - goto errout_with_actions; - } - - /* If robin robin scheduling is enabled, then set the scheduling policy - * of the new task to SCHED_RR before it has a chance to run. - */ - -#if CONFIG_RR_INTERVAL > 0 - ret = posix_spawnattr_setschedpolicy(&attr, SCHED_RR); - if (ret != 0) - { - goto errout_with_actions; - } - - ret = posix_spawnattr_setflags(&attr, - POSIX_SPAWN_SETSCHEDPARAM | - POSIX_SPAWN_SETSCHEDULER); - if (ret != 0) - { - goto errout_with_actions; - } - -#else - ret = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSCHEDPARAM); - if (ret != 0) - { - goto errout_with_actions; - } - -#endif - - /* Is output being redirected? */ - - if (redirfile) - { - /* Set up to close open redirfile and set to stdout (1) */ - - ret = posix_spawn_file_actions_addopen(&file_actions, 1, - redirfile, oflags, 0644); - if (ret != 0) - { - serr("ERROR: posix_spawn_file_actions_addopen failed: %d\n", ret); - goto errout_with_actions; - } - } - -#ifdef CONFIG_LIBC_EXECFUNCS - /* Load and execute the application. */ - - ret = posix_spawnp(&pid, appname, &file_actions, &attr, argv, NULL); -# ifndef CONFIG_BUILD_KERNEL - if (ret != 0 && main != NULL) -# endif -#endif -#ifndef CONFIG_BUILD_KERNEL - { - /* Start the built-in */ - - pid = task_spawn(appname, main, &file_actions, - &attr, argv ? &argv[1] : NULL, NULL); - if (pid < 0) - { - ret = -pid; - } - else - { - ret = OK; - } - } -#endif - - if (ret != 0) - { - serr("ERROR: app spawn failed: %d\n", ret); - goto errout_with_actions; - } - - /* Free attributes and file actions. Ignoring return values in the case - * of an error. - */ - - /* Return the task ID of the new task if the task was successfully - * started. Otherwise, ret will be ERROR (and the errno value will - * be set appropriately). - */ - - posix_spawn_file_actions_destroy(&file_actions); - posix_spawnattr_destroy(&attr); - -#if defined(CONFIG_SCHED_WAITPID) - if (wait) - { - int rc; - ret = waitpid(pid, &rc, 0); - if (ret < 0) - { - ret = ERROR; - } - else - { - ret = rc; - } - } - else -#endif - { - ret = pid; - } - - return ret; - -errout_with_actions: - posix_spawn_file_actions_destroy(&file_actions); - -errout_with_attrs: - posix_spawnattr_destroy(&attr); - -errout_with_errno: - errno = ret; - return ERROR; -} diff --git a/nshlib/nsh_syscmds.c b/nshlib/nsh_syscmds.c index 981dac49a..f635a4064 100644 --- a/nshlib/nsh_syscmds.c +++ b/nshlib/nsh_syscmds.c @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -119,7 +118,6 @@ static FAR const char * const g_resetflag[] = "panic", "bootloader", "recovery", - "restore", "factory", NULL }; @@ -292,7 +290,7 @@ int cmd_pmconfig(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) if (argc == 4) { ctrl.domain = atoi(argv[3]); - if (ctrl.domain >= CONFIG_PM_NDOMAINS) + if (ctrl.domain < 0 || ctrl.domain >= CONFIG_PM_NDOMAINS) { nsh_error(vtbl, g_fmtargrange, argv[3]); return ERROR; @@ -521,6 +519,32 @@ int cmd_reset_cause(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) } #endif +/**************************************************************************** + * Name: cmd_irq_affinity + ****************************************************************************/ + +#if defined(CONFIG_BOARDCTL_IRQ_AFFINITY) && !defined(CONFIG_NSH_DISABLE_IRQ_AFFINITY) +int cmd_irq_affinity(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) +{ + unsigned int affinity[2]; + + if (argc == 3) + { + affinity[0] = strtoul(argv[1], NULL, 0); + affinity[1] = strtoul(argv[2], NULL, 0); + + if (affinity[1] == 0) + { + affinity[1] = 0x1; + } + + return boardctl(BOARDIOC_IRQ_AFFINITY, (uintptr_t)affinity); + } + + return ERROR; +} +#endif + /**************************************************************************** * Name: cmd_rpmsg ****************************************************************************/ @@ -574,7 +598,7 @@ static int cmd_rpmsg_once(FAR struct nsh_vtbl_s *vtbl, return ERROR; } - fd = open(path, O_CLOEXEC); + fd = open(path, 0); if (fd < 0) { nsh_output(vtbl, g_fmtarginvalid, path); @@ -615,16 +639,18 @@ static int cmd_rpmsg_help(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) { nsh_output(vtbl, "%s \n", argv[0]); +#ifdef CONFIG_RPMSG_PING nsh_output(vtbl, "%s ping " "\n\n", argv[0]); - nsh_output(vtbl, " Times of rptun ping.\n"); + nsh_output(vtbl, " Number of ping operations.\n"); nsh_output(vtbl, " The length of each ping packet.\n"); nsh_output(vtbl, " Whether the peer acknowlege or " "check data.\n"); nsh_output(vtbl, " 0 - No acknowledge and check.\n"); nsh_output(vtbl, " 1 - Acknowledge, no data check.\n"); nsh_output(vtbl, " 2 - Acknowledge and data check.\n"); - nsh_output(vtbl, " ping period (ms) \n"); + nsh_output(vtbl, " Sleep interval between two operations.\n"); +#endif nsh_output(vtbl, " Rpmsg device path.\n\n"); return OK; } @@ -740,8 +766,8 @@ int cmd_uname(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) { FAR const char *str; struct lib_memoutstream_s stream; - char buf[sizeof(struct utsname)]; struct utsname info; + struct utsname output; unsigned int set; int option; bool badarg; @@ -832,8 +858,7 @@ int cmd_uname(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) /* Process each option */ first = true; - lib_memoutstream(&stream, buf, sizeof(buf)); - + lib_memoutstream(&stream, (FAR char *)&output, sizeof(output)); for (i = 0; set != 0; i++) { unsigned int mask = (1 << i); diff --git a/nshlib/nsh_timcmds.c b/nshlib/nsh_timcmds.c index 2f28ac11d..08d9716d4 100644 --- a/nshlib/nsh_timcmds.c +++ b/nshlib/nsh_timcmds.c @@ -431,7 +431,6 @@ int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) return ret; errout: - optind = 0; nsh_error(vtbl, errfmt, argv[0]); return ERROR; } @@ -514,6 +513,7 @@ int cmd_timedatectl(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) nsh_output(vtbl, "Universal time: %s %s\n", timbuf, tm.tm_zone); +#ifdef CONFIG_RTC_DRIVER ret = open("/dev/rtc0", O_RDONLY); if (ret > 0) { @@ -535,6 +535,7 @@ int cmd_timedatectl(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) nsh_output(vtbl, " RTC time: %s\n", timbuf); } +#endif /* CONFIG_RTC_DRIVER */ } return ret; diff --git a/nshlib/nsh_wait.c b/nshlib/nsh_wait.c deleted file mode 100644 index 382a522c1..000000000 --- a/nshlib/nsh_wait.c +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** - * apps/nshlib/nsh_wait.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -#include -#include -#include - -#include "nsh.h" -#include "nsh_console.h" - -#if !defined(CONFIG_NSH_DISABLE_WAIT) && defined(CONFIG_SCHED_WAITPID) - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/**************************************************************************** - * Name: cmd_wait - * - * Description: - * Handle 'cmd_wait' command from terminal. - * wait pid1 [pid2 [pid3] ..] - wait for a pid to exit. - * - * Input Parameters: - * vtbl - The NSH console. - * argc - Amount of argument strings in command. - * argv - The argument strings. - * - * Returned Value: - * Zero (OK) on success; a negated errno value on failure. - * - ****************************************************************************/ - -int cmd_wait(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv) -{ - FAR struct tcb_s *ptcb; - FAR struct tcb_s *ctcb; - int status = 0; - int ret = OK; - pid_t pid; - - if (argc == 1) - { - return OK; - } - - ptcb = nxsched_self(); - for (int i = 1; i < argc; i++) - { - pid = atoi(argv[i]); - if (pid == 0) - { - continue; - } - - ctcb = nxsched_get_tcb(pid); - if (ctcb == NULL) - { - continue; - } - - if (ctcb->group == ptcb->group) - { - ret = pthread_join(pid, (FAR pthread_addr_t *)&status); - } - else - { - ret = waitpid(pid, &status, 0); - } - - if (ret < 0) - { - nsh_error(vtbl, g_fmtcmdfailed, - argv[0], "wait", NSH_ERRNO); - continue; - } - } - - return ret < 0 ? ret : status; -} - -#endif /* CONFIG_NSH_DISABLE_WAIT */ diff --git a/system/adb/Kconfig b/system/adb/Kconfig index 172e50444..fdf452520 100644 --- a/system/adb/Kconfig +++ b/system/adb/Kconfig @@ -113,39 +113,6 @@ config ADBD_USB_SERVER ---help--- Run adb daemon on USB bus -choice - prompt "Check usb hotplug" - default ADBD_USB_HOTPLUG_BYTIMER - -config ADBD_USB_HOTPLUG_BYTIMER - bool "Using 1s timer to check usb hotplug" - depends on ADBD_USB_SERVER - ---help--- - Using 1s timer to check usb hotplug - -config ADBD_USB_HOTPLUG_BYNOTIFY - bool "Using fs notify to check usb hotplug" - depends on ADBD_USB_SERVER - depends on FS_NOTIFY - ---help--- - Using fs notify to monitor usb hotplug - -endchoice # Check usb hotplug - -config ADBD_QEMU_SERVER - bool "QEMU pipe transport support" - depends on GOLDFISH_PIPE - default n - ---help--- - Run adb daemon on qemu pipe - -config ADBD_QEMU_SERVER_PORT - int "QEMU pipe transport port" - depends on ADBD_QEMU_SERVER - default 5555 - ---help--- - Port used by adb daemon qemu pipe server - config ADBD_LOGCAT_SERVICE bool "ADB logcat support" depends on RAMLOG_SYSLOG @@ -161,17 +128,17 @@ config ADBD_FILE_SERVICE config ADBD_FILE_SYMLINK bool "File service symlink support" - default n depends on ADBD_FILE_SERVICE depends on PSEUDOFS_SOFTLINKS + default PSEUDOFS_SOFTLINKS ---help--- Enable fs symlink support. config ADBD_SHELL_SERVICE bool "ADB shell support" depends on SYSTEM_NSH - select LIBC_EXECFUNCS - select PSEUDOTERM + depends on LIBC_EXECFUNCS + depends on PSEUDOTERM default n ---help--- Enable "adb shell" feature. diff --git a/system/adb/Makefile b/system/adb/Makefile index 9c8716557..7e536d9c2 100644 --- a/system/adb/Makefile +++ b/system/adb/Makefile @@ -20,8 +20,8 @@ include $(APPDIR)/Make.defs -ADBD_URL ?= "https://github.com/spiriou/microADB/archive" -ADBD_VERSION ?= b0bc09a7612000186df723f2fe55705b1c2fe873 +ADB_URL ?= "https://github.com/spiriou/microADB/archive" +ADB_VERSION ?= master ADB_DIR := $(APPDIR)/system/adb ADB_UNPACKNAME := microADB @@ -29,17 +29,17 @@ ADB_UNPACKDIR := $(ADB_DIR)/$(ADB_UNPACKNAME) $(ADB_UNPACKDIR): @echo "Downloading: $(ADB_UNPACKNAME)" - $(Q) curl -O -L $(ADBD_URL)/$(ADBD_VERSION).zip - $(Q) unzip -o $(ADBD_VERSION).zip - $(call DELFILE, $(ADBD_VERSION).zip) - $(call MOVEFILE, $(ADB_UNPACKNAME)-$(ADBD_VERSION), $(ADB_UNPACKDIR)) + $(Q) curl -O -L $(ADB_URL)/$(ADB_VERSION).zip + $(Q) unzip -o $(ADB_VERSION).zip + $(call DELFILE, $(ADB_VERSION).zip) + $(call MOVEFILE, $(ADB_UNPACKNAME)-$(ADB_VERSION), $(ADB_UNPACKDIR)) # adb server app PROGNAME := $(CONFIG_ADBD_PROGNAME) PRIORITY := $(CONFIG_ADBD_PRIORITY) STACKSIZE := $(CONFIG_ADBD_STACKSIZE) -MODULE := $(CONFIG_ADB_SERVER) +MODULE := $(CONFIG_SYSTEM_ADBD) # Files @@ -61,10 +61,6 @@ ifeq ($(CONFIG_ADBD_USB_SERVER),y) CSRCS += $(ADB_UNPACKNAME)/hal/hal_uv_client_usb.c endif -ifeq ($(CONFIG_ADBD_QEMU_SERVER),y) -CSRCS += $(ADB_UNPACKNAME)/hal/hal_uv_client_qemu.c -endif - ifeq ($(CONFIG_ADBD_AUTHENTICATION),y) CSRCS += $(ADB_UNPACKNAME)/adb_auth_key.c endif diff --git a/system/adb/adb_banner.c b/system/adb/adb_banner.c index 5228abc09..6983b7135 100644 --- a/system/adb/adb_banner.c +++ b/system/adb/adb_banner.c @@ -57,8 +57,7 @@ int adb_fill_connect_data(char *buf, size_t bufsize) { /* FIXME only keep first 4 bytes */ - len = snprintf(buf, remaining, - "device:%" PRIx32 ":", *(uint32_t *)board_id); + len = snprintf(buf, remaining, "device:%x:", *(uint32_t *)board_id); } #else len = snprintf(buf, remaining, "device:" CONFIG_ADBD_DEVICE_ID ":"); diff --git a/system/adb/adb_main.c b/system/adb/adb_main.c index 901d40376..080f5324a 100644 --- a/system/adb/adb_main.c +++ b/system/adb/adb_main.c @@ -24,8 +24,8 @@ #include "adb.h" +#include #include -#include #if defined(CONFIG_ADBD_BOARD_INIT) || defined (CONFIG_BOARDCTL_RESET) || \ defined(CONFIG_ADBD_USB_BOARDCTL) @@ -33,7 +33,7 @@ #endif #ifdef CONFIG_ADBD_NET_INIT -#include "netutils/netinit.h" +# include "netutils/netinit.h" #endif /**************************************************************************** @@ -70,7 +70,7 @@ void adb_log_impl(int priority, FAR const char *func, int line, va_end(ap); } -void adb_reboot_impl(const char *target) +void adb_reboot_impl(FAR const char *target) { #ifdef CONFIG_BOARDCTL_RESET if (strcmp(target, "recovery") == 0) @@ -94,6 +94,17 @@ int main(int argc, FAR char **argv) { adb_context_t *ctx; +#ifdef CONFIG_ADBD_USB_BOARDCTL + struct boardioc_usbdev_ctrl_s ctrl; +# ifdef CONFIG_USBDEV_COMPOSITE + uint8_t usbdev = BOARDIOC_USBDEV_COMPOSITE; +# else + uint8_t usbdev = BOARDIOC_USBDEV_ADB; +# endif + FAR void *handle; + int ret; +#endif + #ifdef CONFIG_ADBD_BOARD_INIT boardctl(BOARDIOC_INIT, 0); #endif /* CONFIG_ADBD_BOARD_INIT */ @@ -102,15 +113,6 @@ int main(int argc, FAR char **argv) /* Setup USBADB device */ - struct boardioc_usbdev_ctrl_s ctrl; -#ifdef CONFIG_USBDEV_COMPOSITE - uint8_t usbdev = BOARDIOC_USBDEV_COMPOSITE; -#else - uint8_t usbdev = BOARDIOC_USBDEV_ADB; -#endif - FAR void *handle; - int ret; - /* Perform architecture-specific initialization */ ctrl.usbdev = usbdev; @@ -151,7 +153,7 @@ int main(int argc, FAR char **argv) ctx = adb_hal_create_context(); if (!ctx) { - return -1; + return 1; } adb_hal_run(ctx); diff --git a/system/adb/logcat_service.c b/system/adb/logcat_service.c index c26455a54..37405c2eb 100644 --- a/system/adb/logcat_service.c +++ b/system/adb/logcat_service.c @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -67,9 +66,7 @@ static void logcat_on_kick(struct adb_service_s *service) logcat_service_t *svc = container_of(service, logcat_service_t, service); if (!svc->wait_ack) { - int ret; - ret = uv_poll_start(&svc->poll, UV_READABLE, logcat_on_data_available); - assert(ret == 0); + uv_poll_start(&svc->poll, UV_READABLE, logcat_on_data_available); } } @@ -91,12 +88,9 @@ static void close_cb(uv_handle_t *handle) static void logcat_on_close(struct adb_service_s *service) { int fd; - int ret; logcat_service_t *svc = container_of(service, logcat_service_t, service); - ret = uv_fileno((uv_handle_t *)&svc->poll, &fd); - assert(ret == 0); - + uv_fileno((uv_handle_t *)&svc->poll, &fd); close(fd); uv_close((uv_handle_t *)&svc->poll, close_cb); } @@ -181,9 +175,7 @@ exit_stop_service: adb_service_t * logcat_service(adb_client_t *client, const char *params) { - int fd; int ret; - logcat_service_t *service = (logcat_service_t *)malloc(sizeof(logcat_service_t)); @@ -197,25 +189,17 @@ adb_service_t * logcat_service(adb_client_t *client, const char *params) /* TODO parse params string to extract logcat parameters */ - fd = open(CONFIG_SYSLOG_DEVPATH, O_RDONLY | O_CLOEXEC); - if (fd < 0) + ret = open(CONFIG_SYSLOG_DEVPATH, O_RDONLY | O_CLOEXEC); + + if (ret < 0) { adb_err("failed to open %s (%d)\n", CONFIG_SYSLOG_DEVPATH, errno); free(service); return NULL; } - ret = ioctl(fd, PIPEIOC_POLLINTHRD, 1); - if (ret < 0) - { - adb_err("failed to control %s (%d)\n", CONFIG_SYSLOG_DEVPATH, errno); - close(fd); - free(service); - return NULL; - } - uv_handle_t *handle = adb_uv_get_client_handle(client); - ret = uv_poll_init(handle->loop, &service->poll, fd); + ret = uv_poll_init(handle->loop, &service->poll, ret); assert(ret == 0); service->poll.data = client; diff --git a/system/batterydump/Make.defs b/system/batterydump/Make.defs deleted file mode 100644 index 07126ab10..000000000 --- a/system/batterydump/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/system/batterydump/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_SYSTEM_BATTERYDUMP),) -CONFIGURED_APPS += $(APPDIR)/system/batterydump -endif diff --git a/system/cdcacm/README.md b/system/cdcacm/README.md deleted file mode 100644 index 61fc9cab6..000000000 --- a/system/cdcacm/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# System / `cdcacm` USB CDC/ACM serial - -This very simple add-on allows the USB CDC/ACM serial device can be dynamically -connected and disconnected from a host. This add-on can only be used as an NSH -built-in command. If built-in, then two new NSH commands will be supported: - -1. `sercon` – Connect the CDC/ACM serial device -2. `serdis` – Disconnect the CDC/ACM serial device - -Configuration prerequisites (not complete): - -- `CONFIG_USBDEV=y` – USB device support must be enabled -- `CONFIG_CDCACM=y` – The CDC/ACM driver must be built - -Configuration options specific to this add-on: - -- `CONFIG_SYSTEM_CDCACM_DEVMINOR` – The minor number of the CDC/ACM device, - i.e., the `x` in `/dev/ttyACMx`. - -If `CONFIG_USBDEV_TRACE` is enabled (or `CONFIG_DEBUG_FEATURES` and -`CONFIG_DEBUG_USB`, or `CONFIG_USBDEV_TRACE`), then the add-on code will also -initialize the USB trace output. The amount of trace output can be controlled -using: - -- `CONFIG_SYSTEM_CDCACM_TRACEINIT` – Show initialization events. -- `CONFIG_SYSTEM_CDCACM_TRACECLASS` – Show class driver events. -- `CONFIG_SYSTEM_CDCACM_TRACETRANSFERS` – Show data transfer events. -- `CONFIG_SYSTEM_CDCACM_TRACECONTROLLER` – Show controller events. -- `CONFIG_SYSTEM_CDCACM_TRACEINTERRUPTS` – Show interrupt-related events. - -**Note**: This add-on is only enables or disable USB CDC/ACM via the NSH -`sercon` and `serdis` command. It will enable and disable tracing per the -settings before enabling and after disabling the CDC/ACM device. It will not, -however, monitor buffered trace data in the interim. If `CONFIG_USBDEV_TRACE` is -defined (and the debug options are not), other application logic will need to -monitor the buffered trace data. diff --git a/system/cfgdata/README.md b/system/cfgdata/README.md deleted file mode 100644 index f3768019f..000000000 --- a/system/cfgdata/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# System / `cfgdata` - -``` -Author: Ken Pettit - Date: 18 December 2018 -``` - -This application provides a command line interface for managing platform -specific configdata within the `/dev/config` device. - -**Usage**: - -```shell -config [arguments] -``` - -Where `` is one of: - -- `all` – show all config entries -- `print` – display a specific config entry -- `set` – set or change a config entry -- `unset` – delete a config entry diff --git a/system/composite/README.md b/system/composite/README.md deleted file mode 100644 index 6e4d89bb8..000000000 --- a/system/composite/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# System / `composite` USB Composite - -This logic adds a NSH command to control a USB composite device. The only -supported devices in the composite are CDC/ACM serial and a USB mass storage -device. Which devices are enclosed in a composite device is configured with an -array of configuration-structs, handed over to the function -`composite_initialize()`. - -Required overall configuration: - -Enable the USB Support of your Hardware / Processor e.g. `SAMV7_USBDEVHS=y` - -- `CONFIG_USBDEV=y` – USB device support. -- `CONFIG_USBDEV_COMPOSITE=y` – USB composite device support. -- `CONFIG_COMPOSITE_IAD=y` – Interface associate descriptor needed. -- `CONFIG_CDCACM=y` – USB CDC/ACM serial device support. -- `CONFIG_CDCACM_COMPOSITE=y` – USB CDC/ACM serial composite device support. - -The interface-, string-descriptor- and endpoint-numbers are configured via the -configuration-structs as noted above. The CDC/ACM serial device needs three -endpoints; one interrupt-driven and two bulk endpoints. - -- `CONFIG_USBMSC=y` – USB mass storage device support. -- `CONFIG_USBMSC_COMPOSITE=y` – USB mass storage composite device support. - -Like the configuration for the CDC/ACM, the descriptor- and endpoint-numbers are -configured via the configuration struct. - -Depending on the configuration struct you need to configure different vendor- -and product-IDs. Each `VID`/`PID` is unique to a device and thus to a dedicated -configuration. - -Linux tries to detect the device types and installs default drivers if the -`VID`/`PID` pair is unknown. - -Windows insists on a known and installed configuration. With an Atmel hardware -and Atmel-Studio or the Atmel-USB-drivers installed, you can test your -configuration with Atmel Example Vendor- and Product-IDs. - -If you have a USBMSC and a CDC/ACM configured in your combo, then you can try to -use - -- `VID = 0x03EB` (ATMEL) -- `PID = 0x2424` (ASF Example with MSC and CDC) - -If for example you try to test a configuration with up to seven CDCs, then - -- `VID = 0x03EB` (ATMEL) -- `PID = 0x2426` (ASF Example with up to seven CDCs) - -This add-on can be built as two NSH _built-in_ commands: - -- `CONFIG_NSH_BUILTIN_APPS` – if this option is selected: `conn` will connect - the USB composite device; `disconn` will disconnect the USB composite device. - -Configuration options unique to this add-on: - -- `CONFIG_SYSTEM_COMPOSITE_DEBUGMM` – Enables some debug tests to check for - memory usage and memory leaks. - -If `CONFIG_USBDEV_TRACE` is enabled (or `CONFIG_DEBUG_FEATURES` and -`CONFIG_DEBUG_USB`), then the add-on code will also manage the USB trace output. -The amount of trace output can be controlled using: - -- `CONFIG_SYSTEM_COMPOSITE_TRACEINIT` – Show initialization events. -- `CONFIG_SYSTEM_COMPOSITE_TRACECLASS` – Show class driver events. -- `CONFIG_SYSTEM_COMPOSITE_TRACETRANSFERS` – Show data transfer events. -- `CONFIG_SYSTEM_COMPOSITE_TRACECONTROLLER` – Show controller events. -- `CONFIG_SYSTEM_COMPOSITE_TRACEINTERRUPTS` – Show interrupt-related events. diff --git a/system/coredump/Kconfig b/system/coredump/Kconfig index 4ab9f6955..5f8673565 100644 --- a/system/coredump/Kconfig +++ b/system/coredump/Kconfig @@ -22,10 +22,4 @@ config SYSTEM_COREDUMP_PRIORITY ---help--- This is the task priority that will be used when starting the coredump. -config SYSTEM_COREDUMP_SWAPBUFFER_NUMS - int "coredump read/write swap buffer nums" - default 64 - ---help--- - The coredump read/write swap buffer nums. swap buffer size = sectorsize * nums - endif # SYSTEM_COREDUMP diff --git a/system/coredump/coredump.c b/system/coredump/coredump.c index 039dc81e0..2dfc61f5a 100644 --- a/system/coredump/coredump.c +++ b/system/coredump/coredump.c @@ -101,15 +101,10 @@ static void dumpfile_delete(FAR char *path, FAR const char *filename, FAR void *arg) { FAR char *dumppath = arg; - int ret; sprintf(dumppath, "%s/%s", path, filename); printf("Remove %s\n", dumppath); - ret = remove(dumppath); - if (ret < 0) - { - printf("Remove %s fail\n", dumppath); - } + remove(dumppath); } /**************************************************************************** @@ -119,12 +114,8 @@ static void dumpfile_delete(FAR char *path, FAR const char *filename, static void coredump_restore(FAR char *savepath, size_t maxfile) { FAR struct coredump_info_s *info; - char dumppath[PATH_MAX] = - { - 0 - }; - unsigned char *swap; + char dumppath[PATH_MAX]; struct geometry geo; ssize_t writesize; ssize_t readsize; @@ -133,7 +124,6 @@ static void coredump_restore(FAR char *savepath, size_t maxfile) size_t max = 0; int dumpfd; int blkfd; - off_t off; int ret; blkfd = open(CONFIG_BOARD_COREDUMP_BLKDEV_PATH, O_RDWR); @@ -154,20 +144,8 @@ static void coredump_restore(FAR char *savepath, size_t maxfile) goto blkfd_err; } - off = lseek(blkfd, (geo.geo_nsectors - 1) * geo.geo_sectorsize, SEEK_SET); - if (off < 0) - { - printf("Seek %s fail\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); - goto info_err; - } - - readsize = read(blkfd, info, geo.geo_sectorsize); - if (readsize != geo.geo_sectorsize) - { - printf("Read %s fail\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); - goto info_err; - } - + lseek(blkfd, (geo.geo_nsectors - 1) * geo.geo_sectorsize, SEEK_SET); + read(blkfd, info, geo.geo_sectorsize); if (info->magic != COREDUMP_MAGIC) { printf("%s coredump not found!\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); @@ -222,8 +200,7 @@ static void coredump_restore(FAR char *savepath, size_t maxfile) goto info_err; } - swap = malloc(geo.geo_sectorsize * - CONFIG_SYSTEM_COREDUMP_SWAPBUFFER_NUMS); + swap = malloc(geo.geo_sectorsize); if (swap == NULL) { printf("Malloc fail\n"); @@ -233,8 +210,7 @@ static void coredump_restore(FAR char *savepath, size_t maxfile) lseek(blkfd, 0, SEEK_SET); while (offset < info->size) { - readsize = read(blkfd, swap, geo.geo_sectorsize * - CONFIG_SYSTEM_COREDUMP_SWAPBUFFER_NUMS); + readsize = read(blkfd, swap, geo.geo_sectorsize); if (readsize < 0) { printf("Read %s fail\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); @@ -253,20 +229,8 @@ static void coredump_restore(FAR char *savepath, size_t maxfile) printf("Coredump finish [%s][%zu]\n", dumppath, info->size); info->magic = 0; - off = lseek(blkfd, (geo.geo_nsectors - 1) * geo.geo_sectorsize, SEEK_SET); - if (off < 0) - { - printf("Seek %s fail\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); - goto swap_err; - } - - writesize = write(blkfd, info, geo.geo_sectorsize); - if (writesize != geo.geo_sectorsize) - { - printf("Write %s fail\n", CONFIG_BOARD_COREDUMP_BLKDEV_PATH); - } - -swap_err: + lseek(blkfd, (geo.geo_nsectors - 1) * geo.geo_sectorsize, SEEK_SET); + write(blkfd, info, geo.geo_sectorsize); free(swap); fd_err: close(dumpfd); diff --git a/system/critmon/critmon.c b/system/critmon/critmon.c index c18de9dd6..8a67dd22b 100644 --- a/system/critmon/critmon.c +++ b/system/critmon/critmon.c @@ -261,10 +261,10 @@ static int critmon_process_directory(FAR struct dirent *entryp) /* Finally, output the stack info that we gleaned from the procfs */ #if CONFIG_TASK_NAME_SIZE > 0 - printf("%-29s %-29s %11s %-16s %-5s %s\n", + printf("%11s %11s %11s %-16s %-5s %s\n", maxpreemp, maxcrit, maxrun, runtime, entryp->d_name, name); #else - printf("%-29s %-29s %11s %16s %5s\n", + printf("%11s %11s %11s %16s %5s\n", maxpreemp, maxcrit, maxrun, runtime, entryp->d_name); #endif @@ -386,7 +386,7 @@ static void critmon_global_crit(void) /* Finally, output the stack info that we gleaned from the procfs */ - printf("%-29s %-29s ----------- ---------------- ---- CPU %s\n", + printf("%11s %11s ----------- ---------------- ---- CPU %s\n", maxpreemp, maxcrit, cpu); } @@ -410,12 +410,10 @@ static int critmon_list_once(void) /* Output a Header */ #if CONFIG_TASK_NAME_SIZE > 0 - printf("PRE-EMPTION CALLER CSECTION CALLER " - "RUN TIME PID DESCRIPTION\n"); + printf("PRE-EMPTION CSECTION RUN TIME " + "PID DESCRIPTION\n"); #else - printf("PRE-EMPTION CALLER CSECTION CALLER " - printf("PRE-EMPTION CSECTION RUN " - "RUN TIME PID\n"); + printf("PRE-EMPTION CSECTION RUN TIME PID\n"); #endif /* Should global usage first */ diff --git a/system/cu/cu_main.c b/system/cu/cu_main.c index 7524b32a1..986d31fa4 100644 --- a/system/cu/cu_main.c +++ b/system/cu/cu_main.c @@ -133,7 +133,7 @@ static int set_termios(FAR struct cu_globals_s *cu, int nocrlf) int ret; struct termios tio; - if (isatty(cu->devfd) && isatty(cu->stdfd)) + if (isatty(cu->devfd)) { tio = cu->devtio; @@ -182,31 +182,38 @@ static int set_termios(FAR struct cu_globals_s *cu, int nocrlf) cu_error("set_termios: ERROR during tcsetattr(): %d\n", errno); return ret; } - - /* Let the remote machine to handle all crlf/echo except Ctrl-C */ - - tio = cu->stdtio; - - tio.c_iflag = 0; - tio.c_oflag = 0; - tio.c_lflag &= ~ECHO; - - ret = tcsetattr(cu->stdfd, TCSANOW, &tio); - if (ret) - { - cu_error("set_termios: ERROR during tcsetattr(): %d\n", errno); - return ret; - } } + /* Let the remote machine to handle all crlf/echo except Ctrl-C */ + + if (cu->stdfd >= 0) + { + tio = cu->stdtio; + + tio.c_iflag = 0; + tio.c_oflag = 0; + tio.c_lflag &= ~ECHO; + + ret = tcsetattr(cu->stdfd, TCSANOW, &tio); + if (ret) + { + cu_error("set_termios: ERROR during tcsetattr(): %d\n", errno); + return ret; + } + } + return 0; } static void retrieve_termios(FAR struct cu_globals_s *cu) { - if (isatty(cu->devfd) && isatty(cu->stdfd)) + if (isatty(cu->devfd)) { tcsetattr(cu->devfd, TCSANOW, &cu->devtio); + } + + if (cu->stdfd >= 0) + { tcsetattr(cu->stdfd, TCSANOW, &cu->stdtio); } } diff --git a/system/dhcp6c/CMakeLists.txt b/system/dhcp6c/CMakeLists.txt index c75a046f6..4db36c901 100644 --- a/system/dhcp6c/CMakeLists.txt +++ b/system/dhcp6c/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/system/dhcpc/CMakeLists.txt +# apps/system/dhcp6c/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -21,7 +21,7 @@ if(CONFIG_SYSTEM_DHCPC_RENEW6) nuttx_add_application( NAME - ${CONFIG_DHCPC_RENEW6_PROGNAME} + dhcpc6 SRCS renew6_main.c STACKSIZE diff --git a/system/dhcp6c/Make.defs b/system/dhcp6c/Make.defs index aaebe0cf4..336ac6ed0 100644 --- a/system/dhcp6c/Make.defs +++ b/system/dhcp6c/Make.defs @@ -1,5 +1,5 @@ ############################################################################ -# apps/system/dhcpc/Make.defs +# apps/system/dhcp6c/Make.defs # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/system/dhcp6c/Makefile b/system/dhcp6c/Makefile index 275d31fba..dcd4c852a 100644 --- a/system/dhcp6c/Makefile +++ b/system/dhcp6c/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/system/dhcpc/Makefile +# apps/system/dhcp6c/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with diff --git a/system/fastboot/Kconfig b/system/fastboot/Kconfig index 181405ee4..d05875c23 100644 --- a/system/fastboot/Kconfig +++ b/system/fastboot/Kconfig @@ -24,11 +24,4 @@ config SYSTEM_FASTBOOTD_DOWNLOAD_MAX int "USB-fastboot download buffer size" default 40960 -config FASTBOOTD_USB_BOARDCTL - bool "USB Board Control" - depends on BOARDCTL - depends on BOARDCTL_USBDEVCTRL - ---help--- - Connect usbdev before running fastboot daemon. - endif # SYSTEM_FASTBOOTD diff --git a/system/fastboot/fastboot.c b/system/fastboot/fastboot.c index 8ca2090c5..26766cfee 100644 --- a/system/fastboot/fastboot.c +++ b/system/fastboot/fastboot.c @@ -23,7 +23,6 @@ ****************************************************************************/ #include -#include #include #include @@ -33,16 +32,12 @@ #include #include #include -#include -#include #include #include #include -#include #include #include -#include /**************************************************************************** * Pre-processor Definitions @@ -51,10 +46,8 @@ #define FASTBOOT_USBDEV "/dev/fastboot" #define FASTBOOT_BLKDEV "/dev/%s" -#define FASTBOOT_EP_BULKIN_IDX 1 -#define FASTBOOT_EP_BULKOUT_IDX 2 -#define FASTBOOT_EP_RETRY_TIMES 100 -#define FASTBOOT_EP_RETRY_DELAY_MS 10 +#define FASTBOOT_EP_BULKIN_IDX 0 +#define FASTBOOT_EP_BULKOUT_IDX 1 #define FASTBOOT_MSG_LEN 64 @@ -72,9 +65,6 @@ ((uint32_t)(p)[1] << 8) | \ (uint32_t)(p)[0]) -#define fb_info(...) syslog(LOG_INFO, ##__VA_ARGS__); -#define fb_err(...) syslog(LOG_ERR, ##__VA_ARGS__); - /**************************************************************************** * Private types ****************************************************************************/ @@ -114,12 +104,10 @@ struct fastboot_ctx_s { int usbdev_in; int usbdev_out; - int flash_fd; size_t download_max; size_t download_size; size_t download_offset; size_t total_imgsize; - int wait_ms; FAR void *download_buffer; FAR struct fastboot_var_s *varlist; }; @@ -232,10 +220,10 @@ static void fastboot_okay(FAR struct fastboot_ctx_s *context, static int fastboot_flash_open(FAR const char *name) { - int fd = open(name, O_RDWR | O_CLOEXEC); + int fd = open(name, O_RDWR); if (fd < 0) { - fb_err("Open %s error\n", name); + printf("Open %s error\n", name); return -errno; } @@ -246,7 +234,6 @@ static void fastboot_flash_close(int fd) { if (fd >= 0) { - fsync(fd); close(fd); } } @@ -260,14 +247,14 @@ static int fastboot_flash_write(int fd, off_t offset, offset = lseek(fd, offset, SEEK_SET); if (offset < 0) { - fb_err("Seek error:%d\n", errno); + printf("Seek error:%d\n", errno); return -errno; } ret = fastboot_write(fd, data, size); if (ret < 0) { - fb_err("Flash write error:%d\n", -ret); + printf("Flash write error:%d\n", -ret); } return ret; @@ -285,7 +272,7 @@ static int ffastboot_flash_fill(int fd, off_t offset, buffer = malloc(blk_sz); if (buffer == NULL) { - fb_err("Flash bwrite malloc fail\n"); + printf("Flash bwrite malloc fail\n"); return -ENOMEM; } @@ -309,15 +296,7 @@ out: static int fastboot_flash_erase(int fd) { - int ret; - - ret = ioctl(fd, MTDIOC_BULKERASE, 0); - if (ret < 0) - { - fb_err("Erase device failed\n"); - } - - return ret < 0 ? -errno : ret; + return OK; } static int @@ -389,7 +368,7 @@ fastboot_flash_program(FAR struct fastboot_ctx_s *context, int fd) case FASTBOOT_CHUNK_CRC32: break; default: - fb_err("Error chunk type:%d, skip\n", chunk->chunk_type); + printf("Error chunk type:%d, skip\n", chunk->chunk_type); break; } } @@ -407,44 +386,9 @@ static void fastboot_flash(FAR struct fastboot_ctx_s *context, FAR const char *arg) { char blkdev[PATH_MAX]; - - snprintf(blkdev, PATH_MAX, FASTBOOT_BLKDEV, arg); - - if (context->flash_fd < 0) - { - context->flash_fd = fastboot_flash_open(blkdev); - if (context->flash_fd < 0) - { - fastboot_fail(context, "Flash open failure"); - return; - } - } - - if (fastboot_flash_program(context, context->flash_fd) < 0) - { - fastboot_fail(context, "Image flash failure"); - } - else - { - fastboot_okay(context, ""); - } - - if (context->total_imgsize == 0) - { - fastboot_flash_close(context->flash_fd); - context->flash_fd = -1; - } -} - -static void fastboot_erase(FAR struct fastboot_ctx_s *context, - FAR const char *arg) -{ - char blkdev[PATH_MAX]; - int ret; int fd; snprintf(blkdev, PATH_MAX, FASTBOOT_BLKDEV, arg); - fb_info("Erase %s\n", blkdev); fd = fastboot_flash_open(blkdev); if (fd < 0) @@ -453,32 +397,35 @@ static void fastboot_erase(FAR struct fastboot_ctx_s *context, return; } - ret = fastboot_flash_erase(fd); - if (ret == -ENOTTY) + if (fastboot_flash_program(context, fd) < 0) { - struct stat sb; - - ret = fstat(fd, &sb); - if (ret >= 0) - { - memset(context->download_buffer, 0xff, context->download_max); - - while (sb.st_size > 0) - { - size_t len = MIN(sb.st_size, context->download_max); - - ret = fastboot_write(fd, context->download_buffer, len); - if (ret < 0) - { - break; - } - - sb.st_size -= len; - } - } + fastboot_fail(context, "Image flash failure"); + } + else + { + fastboot_okay(context, ""); } - if (ret < 0) + fastboot_flash_close(fd); +} + +static void fastboot_erase(FAR struct fastboot_ctx_s *context, + FAR const char *arg) +{ + char blkdev[PATH_MAX]; + int fd; + + snprintf(blkdev, PATH_MAX, FASTBOOT_BLKDEV, arg); + printf("Erase %s\n", blkdev); + + fd = fastboot_flash_open(blkdev); + if (fd < 0) + { + fastboot_fail(context, "Flash open failure"); + return; + } + + if (fastboot_flash_erase(fd) < 0) { fastboot_fail(context, "Flash erase failure"); } @@ -509,7 +456,7 @@ static void fastboot_download(FAR struct fastboot_ctx_s *context, ret = fastboot_write(context->usbdev_out, response, strlen(response)); if (ret < 0) { - fb_err("Reponse error [%d]\n", -ret); + printf("Reponse error [%d]\n", -ret); return; } @@ -521,7 +468,7 @@ static void fastboot_download(FAR struct fastboot_ctx_s *context, download, len); if (r < 0) { - fb_err("fastboot_download usb read error\n"); + printf("fastboot_download usb read error\n"); return; } @@ -564,10 +511,7 @@ static void fastboot_reboot(FAR struct fastboot_ctx_s *context, FAR const char *arg) { #ifdef CONFIG_BOARDCTL_RESET - fastboot_okay(context, ""); boardctl(BOARDIOC_RESET, BOARDIOC_SOFTRESETCAUSE_USER_REBOOT); -#else - fastboot_fail(context, "Operation not supported"); #endif } @@ -575,28 +519,12 @@ static void fastboot_reboot_bootloader(FAR struct fastboot_ctx_s *context, FAR const char *arg) { #ifdef CONFIG_BOARDCTL_RESET - fastboot_okay(context, ""); boardctl(BOARDIOC_RESET, BOARDIOC_SOFTRESETCAUSE_ENTER_BOOTLOADER); -#else - fastboot_fail(context, "Operation not supported"); #endif } static void fastboot_command_loop(FAR struct fastboot_ctx_s *context) { - if (context->wait_ms > 0) - { - struct pollfd fds[1]; - - fds[0].fd = context->usbdev_in; - fds[0].events = POLLIN; - - if (poll(fds, 1, context->wait_ms) <= 0) - { - return; - } - } - while (1) { char buffer[FASTBOOT_MSG_LEN]; @@ -607,7 +535,7 @@ static void fastboot_command_loop(FAR struct fastboot_ctx_s *context) buffer, FASTBOOT_MSG_LEN); if (r < 0) { - fb_err("USB read error\n"); + printf("USB read error\n"); break; } @@ -637,17 +565,14 @@ static void fastboot_publish(FAR struct fastboot_ctx_s *context, FAR struct fastboot_var_s *var; var = malloc(sizeof(*var)); - if (var == NULL) + if (var) { - fb_err("ERROR: Could not allocate the memory.\n"); - return; + var->name = name; + var->string = string; + var->data = data; + var->next = context->varlist; + context->varlist = var; } - - var->name = name; - var->string = string; - var->data = data; - var->next = context->varlist; - context->varlist = var; } static void fastboot_create_publish(FAR struct fastboot_ctx_s *context) @@ -672,117 +597,44 @@ static void fastboot_free_publish(FAR struct fastboot_ctx_s *context) } } -static int fastboot_open_usb(int index, int flags) -{ - int try = FASTBOOT_EP_RETRY_TIMES; - char usbdev[32]; - int ret; - - snprintf(usbdev, sizeof(usbdev), - "%s/ep%d", FASTBOOT_USBDEV, index); - do - { - ret = open(usbdev, flags); - if (ret >= 0) - { - return ret; - } - - usleep(FASTBOOT_EP_RETRY_DELAY_MS * 1000); - } - while (try--); - - fb_err("open [%s] error %d\n", usbdev, errno); - - return -errno; -} - /**************************************************************************** * Public Functions ****************************************************************************/ int main(int argc, FAR char **argv) { - struct fastboot_ctx_s context; + FAR struct fastboot_ctx_s context; FAR void *buffer = NULL; + char usbdev[32]; int ret = OK; -#ifdef CONFIG_FASTBOOTD_USB_BOARDCTL - struct boardioc_usbdev_ctrl_s ctrl; -# ifdef CONFIG_USBDEV_COMPOSITE - uint8_t dev = BOARDIOC_USBDEV_COMPOSITE; -# else - uint8_t dev = BOARDIOC_USBDEV_FASTBOOT; -# endif - FAR void *handle; - - ctrl.usbdev = dev; - ctrl.action = BOARDIOC_USBDEV_INITIALIZE; - ctrl.instance = 0; - ctrl.config = 0; - ctrl.handle = NULL; - - ret = boardctl(BOARDIOC_USBDEV_CONTROL, (uintptr_t)&ctrl); - if (ret < 0) - { - fb_err("boardctl(BOARDIOC_USBDEV_CONTROL) failed: %d\n", ret); - return ret; - } - - ctrl.usbdev = dev; - ctrl.action = BOARDIOC_USBDEV_CONNECT; - ctrl.instance = 0; - ctrl.config = 0; - ctrl.handle = &handle; - - ret = boardctl(BOARDIOC_USBDEV_CONTROL, (uintptr_t)&ctrl); - if (ret < 0) - { - fb_err("boardctl(BOARDIOC_USBDEV_CONTROL) failed: %d\n", ret); - return ret; - } -#endif /* FASTBOOTD_USB_BOARDCTL */ - - if (argc > 1) - { - if (strcmp(argv[1], "-h") == 0) - { - fb_err("Usage: fastbootd [wait_ms]\n"); - return 0; - } - - context.wait_ms = atoi(argv[1]); - } - else - { - context.wait_ms = 0; - } - buffer = malloc(CONFIG_SYSTEM_FASTBOOTD_DOWNLOAD_MAX); if (buffer == NULL) { - fb_err("ERROR: Could not allocate the memory.\n"); + printf("ERROR: Could not allocate the memory.\n"); return -ENOMEM; } - context.usbdev_in = - fastboot_open_usb(FASTBOOT_EP_BULKOUT_IDX, O_RDONLY | O_CLOEXEC); + snprintf(usbdev, sizeof(usbdev), "%s/ep%d", + FASTBOOT_USBDEV, FASTBOOT_EP_BULKOUT_IDX + 1); + context.usbdev_in = open(usbdev, O_RDONLY); if (context.usbdev_in < 0) { + printf("open [%s] error\n", usbdev); ret = -errno; goto err_with_mem; } - context.usbdev_out = - fastboot_open_usb(FASTBOOT_EP_BULKIN_IDX, O_WRONLY | O_CLOEXEC); + snprintf(usbdev, sizeof(usbdev), "%s/ep%d", + FASTBOOT_USBDEV, FASTBOOT_EP_BULKIN_IDX + 1); + context.usbdev_out = open(usbdev, O_WRONLY); if (context.usbdev_out < 0) { + printf("open [%s] error\n", usbdev); ret = -errno; goto err_with_in; } - context.varlist = NULL; - context.flash_fd = -1; context.download_buffer = buffer; context.download_size = 0; context.download_offset = 0; diff --git a/system/flash_eraseall/README.md b/system/flash_eraseall/README.md deleted file mode 100644 index 64d485def..000000000 --- a/system/flash_eraseall/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# System / `flash_eraseall` Flash Erase-All - -``` -Author: Ken Pettit - Date: 5 May 2013 -``` - -This application erases the FLASH of an MTD flash block. It is simply a wrapper -that calls the NuttX `flash_eraseall` interface. - -**Usage**: - -```shell -flash_eraseall -``` diff --git a/system/flatbuffers/.gitignore b/system/flatbuffers/.gitignore deleted file mode 100644 index 266005cbb..000000000 --- a/system/flatbuffers/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/flatbuffers diff --git a/system/flatbuffers/CMakeLists.txt b/system/flatbuffers/CMakeLists.txt deleted file mode 100644 index 06e5d13fd..000000000 --- a/system/flatbuffers/CMakeLists.txt +++ /dev/null @@ -1,54 +0,0 @@ -# ############################################################################## -# apps/system/flatbuffers/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_SYSTEM_FLATBUFFERS) - - # ############################################################################ - # Config and Fetch flatbuffers lib - # ############################################################################ - - set(FLATBUFFERS_DIR ${CMAKE_CURRENT_LIST_DIR}/flatbuffers) - - if(NOT EXISTS ${FLATBUFFERS_DIR}) - set(FLATBUFFERS_URL - https://github.com/google/flatbuffers/archive/v23.5.26.tar.gz) - FetchContent_Declare( - flatbuffers_fetch - URL ${FLATBUFFERS_URL} SOURCE_DIR ${FLATBUFFERS_DIR} BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/math/flatbuffers/flatbuffers - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(flatbuffers_fetch) - - if(NOT flatbuffers_fetch_POPULATED) - FetchContent_Populate(flatbuffers_fetch) - - # Apply the patch after fetching the content - execute_process( - COMMAND ${CMAKE_COMMAND} -E echo "Applying patch to flatbuffers" - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}) - - execute_process(COMMAND patch -d ${FLATBUFFERS_DIR} -p1 < - ${CMAKE_CURRENT_LIST_DIR}/flatbuffers.patch) - endif() - endif() - -endif() diff --git a/system/flatbuffers/Kconfig b/system/flatbuffers/Kconfig deleted file mode 100644 index 7ece716ba..000000000 --- a/system/flatbuffers/Kconfig +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/system/flatbuffers/Kconfig -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -config SYSTEM_FLATBUFFERS - bool "flatbuffers" - default n - ---help--- - Enable flatbuffers. diff --git a/system/flatbuffers/Make.defs b/system/flatbuffers/Make.defs deleted file mode 100644 index 7c313e524..000000000 --- a/system/flatbuffers/Make.defs +++ /dev/null @@ -1,25 +0,0 @@ -############################################################################ -# apps/system/flatbuffers/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_SYSTEM_FLATBUFFERS),) -CONFIGURED_APPS += $(APPDIR)/system/flatbuffers -CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/system/flatbuffers/flatbuffers/include -CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/system/flatbuffers/flatbuffers/include -endif diff --git a/system/flatbuffers/flatbuffers.patch b/system/flatbuffers/flatbuffers.patch deleted file mode 100644 index 2017775aa..000000000 --- a/system/flatbuffers/flatbuffers.patch +++ /dev/null @@ -1,100 +0,0 @@ -diff --git a/include/flatbuffers/base.h b/include/flatbuffers/base.h -index 5c4cae79..1a631641 100644 ---- a/include/flatbuffers/base.h -+++ b/include/flatbuffers/base.h -@@ -1,6 +1,16 @@ - #ifndef FLATBUFFERS_BASE_H_ - #define FLATBUFFERS_BASE_H_ - -+// For TFLM, we always want FLATBUFFERS_LOCALE_INDEPENDENT to be defined as 0. -+// We could achieve this by adding -DFLATBUFFERS_LOCALE_INDEPENDENT=0 to the -+// TFLM Makefile. However, for (at least) the Arduino, adding additional build -+// flags during the compilation can be a bit awkward. As such, we have instead -+// made a decision to change the default to be FLATBUFFERS_LOCALE_INDEPENDENT=0 -+// for TFLM to make it easier for external IDE integration. -+#ifndef FLATBUFFERS_LOCALE_INDEPENDENT -+#define FLATBUFFERS_LOCALE_INDEPENDENT 0 -+#endif -+ - // clang-format off - - // If activate should be declared and included first. -diff --git a/include/flatbuffers/default_allocator.h b/include/flatbuffers/default_allocator.h -index d4724122..975d9380 100644 ---- a/include/flatbuffers/default_allocator.h -+++ b/include/flatbuffers/default_allocator.h -@@ -39,24 +39,18 @@ class DefaultAllocator : public Allocator { - // This is to avoid having a statically or dynamically allocated default - // allocator, or having to move it between the classes that may own it. - inline uint8_t *Allocate(Allocator *allocator, size_t size) { -- return allocator ? allocator->allocate(size) -- : DefaultAllocator().allocate(size); -+ return allocator->allocate(size); - } - - inline void Deallocate(Allocator *allocator, uint8_t *p, size_t size) { -- if (allocator) -- allocator->deallocate(p, size); -- else -- DefaultAllocator().deallocate(p, size); -+ allocator->deallocate(p, size); - } - - inline uint8_t *ReallocateDownward(Allocator *allocator, uint8_t *old_p, - size_t old_size, size_t new_size, - size_t in_use_back, size_t in_use_front) { -- return allocator ? allocator->reallocate_downward(old_p, old_size, new_size, -- in_use_back, in_use_front) -- : DefaultAllocator().reallocate_downward( -- old_p, old_size, new_size, in_use_back, in_use_front); -+ return allocator->reallocate_downward(old_p, old_size, new_size, in_use_back, -+ in_use_front); - } - - } // namespace flatbuffers -diff --git a/include/flatbuffers/flexbuffers.h b/include/flatbuffers/flexbuffers.h -index 8e8cac14..52dae316 100644 ---- a/include/flatbuffers/flexbuffers.h -+++ b/include/flatbuffers/flexbuffers.h -@@ -495,9 +495,24 @@ class Reference { - return static_cast(ReadUInt64(Indirect(), byte_width_)); - case FBT_NULL: return 0.0; - case FBT_STRING: { -+#if 1 -+#if !defined( _MSC_VER) -+#pragma GCC diagnostic push -+#pragma GCC diagnostic ignored "-Wnull-dereference" -+#endif -+ // See b/173239141 for additional context. Patched via -+ // micro/tools/make/flexbuffers_download.sh -+ // Introduce a segfault for an unsupported code path for TFLM. -+ return *(static_cast(nullptr)); -+#if !defined( _MSC_VER) -+#pragma GCC diagnostic pop -+#endif -+#else -+ // This is the original code - double d; - flatbuffers::StringToNumber(AsString().c_str(), &d); - return d; -+#endif - } - case FBT_VECTOR: return static_cast(AsVector().size()); - case FBT_BOOL: -diff --git a/include/flatbuffers/util.h b/include/flatbuffers/util.h -index 1ccf3517..34a75193 100644 ---- a/include/flatbuffers/util.h -+++ b/include/flatbuffers/util.h -@@ -23,6 +23,12 @@ - #include "flatbuffers/base.h" - #include "flatbuffers/stl_emulation.h" - -+// For TFLM we always want to use FLATBUFFERS_PREFER_PRINTF=1. See -+// http://b/211811553 for more context. -+#ifndef FLATBUFFERS_PREFER_PRINTF -+#define FLATBUFFERS_PREFER_PRINTF 1 -+#endif -+ - #ifndef FLATBUFFERS_PREFER_PRINTF - # include - # include diff --git a/system/gcov/Kconfig b/system/gcov/Kconfig index 5eca78114..6c951954d 100644 --- a/system/gcov/Kconfig +++ b/system/gcov/Kconfig @@ -5,7 +5,7 @@ config SYSTEM_GCOV tristate "gcov tool" - depends on SCHED_GCOV + depends on ARCH_COVERAGE ---help--- Enable support for the 'gcov' command. diff --git a/system/gcov/gcov.c b/system/gcov/gcov.c index 9506cadb1..bf4dbf549 100644 --- a/system/gcov/gcov.c +++ b/system/gcov/gcov.c @@ -23,7 +23,6 @@ ****************************************************************************/ #include -#include #include /**************************************************************************** @@ -36,13 +35,11 @@ static void show_usage(FAR const char *progname) { - printf("\nUsage: %s [-d path] [-t strip] [-r] [-h]\n", progname); + printf("\nUsage: %s [-d] [-r] [-h]\n", progname); printf("\nWhere:\n"); - printf(" -d dump the coverage, path is the path to the coverage file\n"); - printf(" -t strip the path prefix number\n"); + printf(" -d dump the coverage.\n"); printf(" -r reset the coverage\n"); printf(" -h show this text and exits.\n"); - exit(EXIT_FAILURE); } /**************************************************************************** @@ -52,31 +49,12 @@ static void show_usage(FAR const char *progname) void __gcov_dump(void); void __gcov_reset(void); -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void gcov_dump(FAR const char * path, FAR const char *strip) -{ - if (path == NULL || access(path, F_OK) != 0 || atoi(strip) <= 0) - { - fprintf(stderr, "ERROR: Invalid parameter\n"); - return; - } - - setenv("GCOV_PREFIX_STRIP", strip, 1); - setenv("GCOV_PREFIX", path, 1); - __gcov_dump(); -} - /**************************************************************************** * Public Functions ****************************************************************************/ int main(int argc, FAR char *argv[]) { - FAR const char *strip = "99"; - FAR const char *path; int option; if (argc < 2) @@ -84,17 +62,12 @@ int main(int argc, FAR char *argv[]) show_usage(argv[0]); } - while ((option = getopt(argc, argv, "d:t:rh")) != ERROR) + while ((option = getopt(argc, argv, "drh")) != ERROR) { switch (option) { case 'd': - path = optarg; - break; - - case 't': - strip = optarg; - + __gcov_dump(); break; case 'r': @@ -110,6 +83,5 @@ int main(int argc, FAR char *argv[]) } } - gcov_dump(path, strip); return 0; } diff --git a/system/gdbstub/gdbstub.c b/system/gdbstub/gdbstub.c index 9fe1b7c03..9f7abc6c0 100644 --- a/system/gdbstub/gdbstub.c +++ b/system/gdbstub/gdbstub.c @@ -188,7 +188,7 @@ int main(int argc, FAR char *argv[]) } reconnect: - if (((fd = accept4(sock, NULL, NULL, SOCK_CLOEXEC)) < 0)) + if (((fd = accept(sock, NULL, NULL)) < 0)) { fprintf(stderr, "ERROR: Failed to accept socket: %d\n", errno); return -errno; diff --git a/system/gprof/Kconfig b/system/gprof/Kconfig deleted file mode 100644 index 4e4e8d701..000000000 --- a/system/gprof/Kconfig +++ /dev/null @@ -1,23 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config SYSTEM_GPROF - tristate "gprof tool" - default n - depends on SCHED_GPROF || SIM_GPROF - ---help--- - Enable support for the 'gprof' command. - -if SYSTEM_GPROF - -config SYSTEM_GPROF_PRIORITY - int "gprof task priority" - default 100 - -config SYSTEM_GPROF_STACKSIZE - int "gprof stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/system/gprof/Make.defs b/system/gprof/Make.defs deleted file mode 100644 index ee8214abb..000000000 --- a/system/gprof/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/system/gprof/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_SYSTEM_GPROF),) -CONFIGURED_APPS += $(APPDIR)/system/gprof -endif diff --git a/system/gprof/gprof.c b/system/gprof/gprof.c deleted file mode 100644 index 61f4637f6..000000000 --- a/system/gprof/gprof.c +++ /dev/null @@ -1,83 +0,0 @@ -/**************************************************************************** - * apps/system/gprof/gprof.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -#include - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -extern uint8_t _stext[]; -extern uint8_t _etext[]; - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int main(int argc, FAR char *argv[]) -{ - if (argc < 2) - { - goto help; - } - - if (strcmp(argv[1], "dump") == 0) - { -#ifndef CONFIG_DISABLE_ENVIRON - FAR const char *output = argc < 3 ? "gmon.out" : argv[2]; - setenv("GMON_OUT_PREFIX", output, true); -#else - fprintf(stderr, "gprof: Environment not supported\n"); -#endif - _mcleanup(); - } - else if (strcmp(argv[1], "start") == 0) - { - monstartup((uintptr_t)&_stext, (uintptr_t)&_etext); - moncontrol(1); - } - else if (strcmp(argv[1], "stop") == 0) - { - moncontrol(0); - } - else - { - goto help; - } - - return EXIT_SUCCESS; - -help: - printf("Usage: gprof []\n" - " gprof dump [output]\n" - " gprof start\n" - " gprof stop\n"); - return EXIT_FAILURE; -} - diff --git a/system/hexed/src/hexcopy.c b/system/hexed/src/hexcopy.c index b735dda88..99b94c5f5 100644 --- a/system/hexed/src/hexcopy.c +++ b/system/hexed/src/hexcopy.c @@ -1,10 +1,12 @@ /**************************************************************************** - * apps/system/hexed/src/hexcopy.c - hexed copy command + * apps/system/hexed/src/hexcopy.c + * hexed copy command * * Copyright (c) 2011, B.ZaaR, All rights reserved. * * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: + * modification, are permitted provided that the following conditions are + * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. @@ -17,17 +19,17 @@ * products derived from this software without specific prior written * permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ @@ -131,32 +133,30 @@ static int setcopy(FAR struct command_s *cmd, int optc, char *opt) switch (optc) { - case 0: - /* Set source */ + case 0: /* Set source */ + { + cmd->opts.src = v; + optc++; + } + break; - cmd->opts.src = v; - optc++; - break; + case 1: /* Set destination */ + { + cmd->opts.dest = v; + optc++; + } + break; - case 1: - /* Set destination */ + case 2: /* Set length */ + { + cmd->opts.len = v; + cmd->opts.bytes = cmd->opts.len * cmd->opts.word; + optc = 0; + } + break; - cmd->opts.dest = v; - optc++; - break; - - case 2: - /* Set length */ - - cmd->opts.len = v; - cmd->opts.bytes = cmd->opts.len * cmd->opts.word; - optc = 0; - break; - - default: - /* Too many options specified */ - - return -E2BIG; + default: /* Too many options specified */ + return -E2BIG; } return optc; diff --git a/system/i2c/README.md b/system/i2c/README.md deleted file mode 100644 index 0d005664c..000000000 --- a/system/i2c/README.md +++ /dev/null @@ -1,387 +0,0 @@ -# System / `i2c` I2C Tool - -The I2C tool provides a way to debug I2C related problems. This README file will -provide usage information for the I2C tools. - -## Contents - -- System Requirements - - I2C Driver - - Configuration Options -- Help -- Common Line Form -- Common Command Options - - _Sticky_ Options - - Environment variables - - Common Option Summary -- Command summary - - `bus` - - `dev` - - `get` - - `set` - - `verf` -- I2C Build Configuration - - NuttX Configuration Requirements - - I2C Tool Configuration Options - -## System Requirements - -The I2C tool is designed to be implemented as a NuttShell (NSH) add-on. Read the -`apps/nshlib/README.md` file for information about add-ons. - -### Configuration Options - -- `CONFIG_NSH_BUILTIN_APPS` – Build the tools as an NSH built-in command. -- `CONFIG_I2CTOOL_MINBUS` – Smallest bus index supported by the hardware - (default `0`). -- `CONFIG_I2CTOOL_MAXBUS` – Largest bus index supported by the hardware - (default `3`). -- `CONFIG_I2CTOOL_MINADDR` – Minimum device address (default: `0x03`). -- `CONFIG_I2CTOOL_MAXADDR` – Largest device address (default: `0x77`). -- `CONFIG_I2CTOOL_MAXREGADDR` – Largest register address (default: `0xff`). -- `CONFIG_I2CTOOL_DEFFREQ` – Default frequency (default: `4000000`). - -## Help - -First of all, the I2C tools supports a pretty extensive help output. That help -output can be view by entering either: - -``` -nsh> i2c help -``` - -or - -``` -nsh> i2c ? -``` - -Here is an example of the help output. I shows the general form of the command -line, the various I2C commands supported with their unique command line options, -and a more detailed summary of the command I2C command options. - -``` -nsh> i2c help - -Usage: i2c [arguments] -Where is one of: - - Show help : ? - List buses : bus - List devices : dev [OPTIONS] - Read register : get [OPTIONS] [] - Show help : help - Write register: set [OPTIONS] [] - Verify access : verf [OPTIONS] [] - - Where common _sticky_ OPTIONS include: - [-a addr] is the I2C device address (hex). Default: 03 Current: 03 - [-b bus] is the I2C bus number (decimal). Default: 1 Current: 1 - [-r regaddr] is the I2C device register address (hex). Default: 00 Current: 00 - [-w width] is the data width (8 or 16 decimal). Default: 8 Current: 8 - [-s|n], send/don't send start between command and data. Default: -n Current: -n - [-i|j], Auto increment|don't increment regaddr on repetitions. Default: NO Current: NO - [-f freq] I2C frequency. Default: 100000 Current: 100000 -``` - -**Notes**: - -- An environment variable like `$PATH` may be used for any argument. -- Arguments are _sticky_. For example, once the I2C address is specified, that - address will be re-used until it is changed. - -**Warning**: - -- The I2C dev command may have bad side effects on your I2C devices. Use only at - your own risk. - -## Command Line Form - -The I2C is started from NSH by invoking the `i2c` command from the NSH command -line. The general form of the `i2c` command is: - -```shell -i2c [arguments] -``` - -Where `` is a _sub-command_ and identifies one I2C operations supported by -the tool. `[arguments]` represents the list of arguments needed to perform the -I2C operation. Those arguments vary from command to command as described below. -However, there is also a core set of common `OPTIONS` supported by all commands. -So perhaps a better representation of the general I2C command would be: - -```shell -i2c [OPTIONS] [arguments] -``` - -Where `[OPTIONS]` represents the common options and and arguments represent the -operation-specific arguments. - -## Common Command Options - -### _Sticky_ Options - -In order to interact with I2C devices, there are a number of I2C parameters that -must be set correctly. One way to do this would be to provide to set the value -of each separate command for each I2C parameter. The I2C tool takes a different -approach, instead: The I2C configuration can be specified as a (potentially -long) sequence of command line arguments. - -These arguments, however, are _sticky_. They are sticky in the sense that once -you set the I2C parameter, that value will remain until it is reset with a new -value (or until you reset the board). - -### Environment Variables - -**Note** also that if environment variables are not disabled (by -`CONFIG_DISABLE_ENVIRON=y`), then these options may also be environment -variables. Environment variables must be preceded with the special character -`$`. For example, `PWD` is the variable that holds the current working directory -and so `$PWD` could be used as a command line argument. The use of environment -variables on the I2C tools command is really only useful if you wish to write -NSH scripts to execute a longer, more complex series of I2C commands. - -### Common Option Summary - -- `[-a addr]` is the I2C device address (hex). Default: `03` Current: `03` - - The `[-a addr]` sets the I2C device address. The valid range is `0x03` through - `0x77` (this valid range is controlled by the configuration settings - `CONFIG_I2CTOOL_MINADDR` and `CONFIG_I2CTOOL_MAXADDR`). If you are working - with the same device, the address needs to be set only once. - - All I2C address are 7-bit, hexadecimal values. - - **Note 1**: Notice in the `help` output above it shows both default value of the - I2C address (`03` hex) and the current address value (also `03` hex). - - **Note 2**: Sometimes I2C addresses are represented as 8-bit values (with bit zero - indicating a read or write operation). The I2C tool uses a 7-bit - representation of the address with bit 7 unused and no read/write indication - in bit 0. Essentially, the 7-bit address is like the 8-bit address shifted - right by 1. - - **Note 3**: Most I2C bus controllers will also support 10-bit addressing. That - capability has not been integrated into the I2C tool as of this writing. - -- `[-b bus]` is the I2C bus number (decimal). Default: `1` Current: `1` - - Most devices support multiple I2C devices and also have unique bus numbering. - This option identifies which bus you are working with now. The valid range of - bus numbers is controlled by the configuration settings - `CONFIG_I2CTOOL_MINBUS` and `CONFIG_I2CTOOL_MAXBUS`. - - The bus numbers are small, decimal numbers. - -- `[-r regaddr]` is the I2C device register address (hex). Default: `00` - Current: `00` - - The I2C set and get commands will access registers on the I2C device. This - option selects the device register address (sometimes called the sub-address). - This is an 8-bit hexadecimal value. The maximum value is determined by the - configuration setting `CONFIG_I2CTOOL_MAXREGADDR`. - -- `[-w width] `is the data width (8 or 16 decimal). Default: `8` Current: `8` - - Device register data may be 8-bit or 16-bit. This options selects one of those - two data widths. - -- `[-s|n]`, send/don't send start between command and data. Default: `-n` - Current: `-n` - - This determines whether or not there should be a new I2C START between sending - of the register address and sending/receiving of the register data. - -- `[-i|j]`, Auto increment|don't increment `regaddr` on repetitions. Default: - `NO` Current: `NO` - - On commands that take a optional number of repetitions, the option can be used - to temporarily increment the `regaddr` value by one on each repetition. - -- `[-f freq]` I2C frequency. Default: `400000` Current: `400000` - - The `[-f freq]` sets the frequency of the I2C device. - -## Command Summary - -We have already seen the I2C help (or `?`) commands above. This section will -discuss the remaining commands. - -### List buses: `bus [OPTIONS]` - -This command will simply list all of the configured I2C buses and indicate which -are supported by the driver and which are not: - -``` -BUS EXISTS? -Bus 1: YES -Bus 2: NO -``` - -The valid range of bus numbers is controlled by the configuration settings -`CONFIG_I2CTOOL_MINBUS` and `CONFIG_I2CTOOL_MAXBUS`. - -### List devices: `dev [OPTIONS] ` - -The `dev` command will attempt to identify all of the I2C devices on the -selected bus. The `` and `` arguments are 7-bit, hexadecimal I2C -addresses. This command will examine a range of addresses beginning with -`` and continuing through ``. It will request the value of register -address zero from each device. - -The register address of zero is always used by default. The previous _sticky_ -register address is ignored. Some devices may not respond to ergister address -zero, however. To work around this, you can provide a new _sticky_ register -address on the command as an option to the 'dev' command. Then that new _sticky_ -register address will be used instead of the address zero. - -If the device at an I2C address responds to the read request, then the `dev` -command will display the I2C address of the device. If the device does not -respond, this command will display `--`. The resulting display looks like: - -```shell -nsh> i2c dev 03 77 -``` - -``` - 0 1 2 3 4 5 6 7 8 9 a b c d e f -00: -- -- -- -- -- -- -- -- -- -- -- -- -- -10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -40: -- -- -- -- -- -- -- -- -- 49 -- -- -- -- -- -- -50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -70: -- -- -- -- -- -- -- -- -``` - -Warnings: -- The I2C dev command may have bad side effects on certain I2C devices. For - example, if could cause data loss in an EEPROM device. -- The I2C dev command also depends upon the underlying behavior of the I2C - driver. How does the driver respond to addressing failures? - -### Read register: `get [OPTIONS]` - -This command will read the value of the I2C register using the selected I2C -parameters in the common options. No other arguments are required. - -This command with write the 8-bit address value then read an 8- or 16-bit data -value from the device. Optionally, it may re-start the transfer before obtaining -the data. - -An optional `` argument can be supplied to repeat the read -operation an arbitrary number of times (up to 2 billion). If auto-increment is -select (`-i`), then the register address will be temporarily incremented on each -repetitions. The increment is temporary in the since that it will not alter the -_sticky_ value of the register address. - -On success, the output will look like the following (the data value read will be -shown as a 4-character hexadecimal number if the 16-bit data width option is -selected). - -``` -READ Bus: 1 Addr: 49 Subaddr: 04 Value: 96 -``` - -All values (except the bus numbers) are hexadecimal. - -### Write register: `set [OPTIONS] ` - -This command will write a value to an I2C register using the selected I2C -parameters in the common options. The value to write must be provided as the -final, hexadecimal value. This value may be an 8-bit value (in the range -`00`-`ff`) or a 16-bit value (in the range `0000`-`ffff`), depending upon the -selected data width. - -This command will write the 8-bit address value then write the 8- or 16-bit data -value to the device. Optionally, it may re-start the transfer before writing the -data. - -An optional `` argument can be supplied to repeat the write -operation an arbitrary number of times (up to 2 billion). If auto-increment is -select (`-i`), then the register address will be temporarily incremented on each -repetitions. The increment is temporary in the since that it will not alter the -_sticky_ value of the register address. - -On success, the output will look like the following (the data value written will -be shown as a 4-character hexadecimal number if the 16-bit data width option is -selected). - -``` -WROTE Bus: 1 Addr: 49 Subaddr: 04 Value: 96 -``` - -All values (except the bus numbers) are hexadecimal. - -### Verify access: `verf [OPTIONS] []` - - -This command combines writing and reading from an I2C device register. It will -write a value to an will write a value to an I2C register using the selected I2C -parameters in the common options just as described for tie `set` command. Then -this command will read the value back just as described with the `get` command. -Finally, this command will compare the value read and against the value written -and emit an error message if they do not match. - -If no value is provided, then this command will use the register address itself -as the data, providing for a address-in-address test. - -An optional `` argument can be supplied to repeat the verify -operation an arbitrary number of times (up to 2 billion). If auto-increment is -select (`-i`), then the register address will be temporarily incremented on each -repetitions. The increment is temporary in the since that it will not alter the -`sticky` value of the register address. - -On success, the output will look like the following (the data value written will -be shown as a 4-character hexadecimal number if the 16-bit data width option is -selected). - -``` -VERIFY Bus: 1 Addr: 49 Subaddr: 04 Wrote: 96 Read: 92 FAILURE -``` - -All values (except the bus numbers) are hexadecimal. - -## I2C Build Configuration - -### NuttX Configuration Requirements - -The I2C tools requires the following in your NuttX configuration: - -1. Application configuration. - - Using `make menuconfig`, select the i2c tool. The following definition should - appear in your `.config` file: - - ```conf - CONFIG_SYSTEM_I2C=y - ``` - -2. Device-specific I2C driver support must be enabled: - - ```conf - CONFIG_I2C_DRIVER=y - ``` - - The I2C tool will then use the I2C character driver to access the I2C bus. - These devices will reside at `/dev/i2cN` where `N` is the I2C bus number. - - **Note**: The I2C driver `ioctl` interface is defined in - `include/nuttx/i2c/i2c_master.h`. - -### I2C Tool Configuration Options - -The default behavior of the I2C tool can be modified by the setting the options -in the NuttX configuration. This configuration is the `defconfig` file in your -configuration directory that is copied to the NuttX top-level directory as -`.config` when NuttX is configured. - -- `CONFIG_NSH_BUILTIN_APPS` – Build the tools as an NSH built-in command. -- `CONFIG_I2CTOOL_MINBUS` – Smallest bus index supported by the hardware - (default `0`). -- `CONFIG_I2CTOOL_MAXBUS` – Largest bus index supported by the hardware - (default `3`). -- `CONFIG_I2CTOOL_MINADDR` – Minimum device address (default: `0x03`). -- `CONFIG_I2CTOOL_MAXADDR` – Largest device address (default: `0x77`). -- `CONFIG_I2CTOOL_MAXREGADDR` – Largest register address (default: `0xff`). -- `CONFIG_I2CTOOL_DEFFREQ` – Default frequency (default: `4000000`). diff --git a/system/input/input.c b/system/input/input.c index de7022caa..ecb64127d 100644 --- a/system/input/input.c +++ b/system/input/input.c @@ -224,7 +224,7 @@ static int input_utouch_swipe(int argc, char **argv) DELAY_MS(interval); } - input_utouch_move(fd, x1, y1, TOUCH_UP); + input_utouch_move(fd, 0, 0, TOUCH_UP); close(fd); return 0; } diff --git a/system/libuv/.gitignore b/system/libuv/.gitignore index f33ff0339..95c8049c9 100644 --- a/system/libuv/.gitignore +++ b/system/libuv/.gitignore @@ -1,3 +1,2 @@ libuv* *.zip -ext diff --git a/system/libuv/Android.bp b/system/libuv/Android.bp deleted file mode 100644 index b26180021..000000000 --- a/system/libuv/Android.bp +++ /dev/null @@ -1,57 +0,0 @@ -cc_library_static { - name: "libuv", - - srcs: [ - "libuv/src/fs-poll.c", - "libuv/src/idna.c", - "libuv/src/inet.c", - "libuv/src/random.c", - "libuv/src/strscpy.c", - "libuv/src/strtok.c", - "libuv/src/thread-common.c", - "libuv/src/threadpool.c", - "libuv/src/timer.c", - "libuv/src/uv-data-getter-setters.c", - "libuv/src/uv-common.c", - "libuv/src/version.c", - "libuv/src/unix/async.c", - "libuv/src/unix/core.c", - "libuv/src/unix/dl.c", - "libuv/src/unix/fs.c", - "libuv/src/unix/getaddrinfo.c", - "libuv/src/unix/getnameinfo.c", - "libuv/src/unix/loop-watcher.c", - "libuv/src/unix/loop.c", - "libuv/src/unix/pipe.c", - "libuv/src/unix/poll.c", - "libuv/src/unix/process.c", - "libuv/src/unix/random-devurandom.c", - "libuv/src/unix/signal.c", - "libuv/src/unix/stream.c", - "libuv/src/unix/tcp.c", - "libuv/src/unix/thread.c", - "libuv/src/unix/tty.c", - "libuv/src/unix/udp.c", - "libuv/src/unix/linux.c", - "libuv/src/unix/procfs-exepath.c", - "libuv/src/unix/proctitle.c", - "libuv/src/unix/random-getrandom.c", - "libuv/src/unix/random-getentropy.c", - "libuv/src/unix/random-sysctl-linux.c", - ], - - local_include_dirs: [ - "libuv/include", - "libuv/src", - ], - - cflags: [ - //"-DANDROID", - "-D_GNU_SOURCE", // For LibUV on Android/Linux - "-Werror", - "-Wno-missing-field-initializers", - "-Wno-unused-parameter", - "-Wno-sometimes-uninitialized", - ], -} - diff --git a/system/libuv/CMakeLists.txt b/system/libuv/CMakeLists.txt deleted file mode 100644 index 1bfae0833..000000000 --- a/system/libuv/CMakeLists.txt +++ /dev/null @@ -1,251 +0,0 @@ -# ############################################################################## -# apps/system/libuv/CMakeLists.txt -# -# Licensed to the Apache Software Foundation (ASF) under one or more contributor -# license agreements. See the NOTICE file distributed with this work for -# additional information regarding copyright ownership. The ASF licenses this -# file to you under the Apache License, Version 2.0 (the "License"); you may not -# use this file except in compliance with the License. You may obtain a copy of -# the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations under -# the License. -# -# ############################################################################## - -if(CONFIG_LIBUV) - - # ############################################################################ - # Config and Fetch libuv - # ############################################################################ - - set(LIBUV_DIR ${CMAKE_CURRENT_LIST_DIR}/libuv) - - if(NOT EXISTS ${LIBUV_DIR}) - set(LIBUV_URL https://github.com/libuv/libuv/archive/refs/tags/v1.46.0/zip) - FetchContent_Declare( - libuv_fetch - URL ${LIBUV_URL} SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/libuv BINARY_DIR - ${CMAKE_BINARY_DIR}/apps/system/libuv/libuv - PATCH_COMMAND patch -p0 -d ${CMAKE_CURRENT_LIST_DIR}/libuv < - ${CMAKE_CURRENT_LIST_DIR}/0001-libuv-port-for-nuttx.patch - DOWNLOAD_NO_PROGRESS true - TIMEOUT 30) - - FetchContent_GetProperties(libuv_fetch) - - if(NOT libuv_fetch_POPULATED) - FetchContent_Populate(libuv_fetch) - endif() - endif() - - if(NOT DEFINED GCCVER) - execute_process(COMMAND ${CMAKE_C_COMPILER} --version - OUTPUT_VARIABLE GCC_VERSION_OUTPUT) - string(REGEX MATCH "\\+\\+.* ([0-9]+)\\.[0-9]+" GCC_VERSION_REGEX - "${GCC_VERSION_OUTPUT}") - set(GCCVER ${CMAKE_MATCH_1}) - endif() - # ############################################################################ - # Flags - # ############################################################################ - - set(CFLAGS - -Wno-shadow - -DDEF_THREADPOOL_SIZE=CONFIG_LIBUV_THREADPOOL_SIZE - -DDEF_THREADPOOL_STACKSIZE=CONFIG_LIBUV_THREAD_STACKSIZE - -DDEF_THREADPOOL_PRIORITY=CONFIG_LIBUV_THREADPOOL_PRIORITY - -DMAX_EPOLL_EVENTS=CONFIG_LIBUV_MAX_EPOLL_EVENTS - -DPREP_EVENT_SIZE=CONFIG_LIBUV_PREP_EVENT_SIZE - -DDEF_STREAM_READ_BUF_SIZE=CONFIG_LIBUV_STREAM_READ_BUF_SIZE) - - if(GCCVER EQUAL 12) - list(APPEND CFLAGS -Wno-dangling-pointer) - endif() - # ############################################################################ - # Sources - # ############################################################################ - set(LIBUV_SRC_DIR ${LIBUV_DIR}/src) - set(LIBUV_UNIX_DIR ${LIBUV_DIR}/src/unix) - set(LIBUV_TEST_DIR ${LIBUV_DIR}/test) - - set(SRCS - ${LIBUV_UNIX_DIR}/core.c ${LIBUV_UNIX_DIR}/poll.c - ${LIBUV_UNIX_DIR}/loop.c ${LIBUV_UNIX_DIR}/thread.c - ${LIBUV_SRC_DIR}/thread-common.c ${LIBUV_UNIX_DIR}/posix-hrtime.c) - - if(CONFIG_LIBUV_BACKEND_EPOLL) - list(APPEND SRCS ${LIBUV_UNIX_DIR}/linux.c) - else() - list(APPEND SRCS ${LIBUV_UNIX_DIR}/posix-poll.c - ${LIBUV_UNIX_DIR}/no-fsevents.c) - endif() - - list(APPEND SRCS ${LIBUV_SRC_DIR}/uv-data-getter-setters.c - ${LIBUV_SRC_DIR}/version.c) - - if(NOT CONFIG_LIBUV_UTILS_TEST) - list(APPEND SRCS ${LIBUV_SRC_DIR}/idna.c ${LIBUV_SRC_DIR}/strscpy.c - ${LIBUV_SRC_DIR}/strtok.c) - endif() - - list( - APPEND - SRCS - ${LIBUV_SRC_DIR}/uv-common.c - ${LIBUV_UNIX_DIR}/random-devurandom.c - ${LIBUV_SRC_DIR}/random.c - ${LIBUV_UNIX_DIR}/nuttx.c - ${LIBUV_UNIX_DIR}/tty.c - ${LIBUV_UNIX_DIR}/loop-watcher.c - ${LIBUV_UNIX_DIR}/signal.c - ${LIBUV_UNIX_DIR}/stream.c - ${LIBUV_SRC_DIR}/threadpool.c - ${LIBUV_UNIX_DIR}/async.c - ${LIBUV_UNIX_DIR}/pipe.c - ${LIBUV_UNIX_DIR}/fs.c - ${LIBUV_SRC_DIR}/fs-poll.c - ${LIBUV_SRC_DIR}/timer.c - ${LIBUV_UNIX_DIR}/process-spawn.c - ${LIBUV_UNIX_DIR}/sysinfo-loadavg.c - ${LIBUV_UNIX_DIR}/sysinfo-memory.c) - - if(CONFIG_LIBC_DLFCN) - list(APPEND SRCS ${LIBUV_UNIX_DIR}/dl.c) - endif() - - if(CONFIG_LIBC_NETDB) - list(APPEND SRCS ${LIBUV_UNIX_DIR}/getaddrinfo.c - ${LIBUV_UNIX_DIR}/getnameinfo.c) - endif() - - if(CONFIG_NET) - list(APPEND SRCS ${LIBUV_SRC_DIR}/inet.c) - endif() - - if(CONFIG_NET_TCP) - list(APPEND SRCS ${LIBUV_UNIX_DIR}/tcp.c) - endif() - - if(CONFIG_NET_UDP) - list(APPEND SRCS ${LIBUV_UNIX_DIR}/udp.c) - endif() - # ############################################################################ - # Include Directory - # ############################################################################ - - set(EXPORT_INCDIR ${CMAKE_CURRENT_LIST_DIR}/libuv/include) - set(INTER_INCDIR ${LIBUV_DIR}/src ${LIBUV_DIR}/src/unix ${LIBUV_DIR}/test) - - # ############################################################################ - # Library Configuration - # ############################################################################ - - # import libuv ext - if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/ext/CMakeLists.txt) - set(EXT_SRCS) - set(EXT_INCDIR) - set(EXT_EXPORT_INCDIR) - include(${CMAKE_CURRENT_LIST_DIR}/ext/CMakeLists.txt) - list(APPEND EXPORT_INCDIR ${EXT_EXPORT_INCDIR}) - list(APPEND INTER_INCDIR ${EXT_INCDIR}) - list(APPEND SRCS ${EXT_SRCS}) - endif() - - set(INCDIR ${EXPORT_INCDIR} ${INTER_INCDIR}) - - nuttx_add_library(libuv STATIC) - target_sources(libuv PRIVATE ${SRCS}) - target_include_directories(libuv PRIVATE ${INCDIR}) - target_compile_options(libuv PRIVATE ${CFLAGS}) - - # Global FLAG - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_COMPILE_OPTIONS - -DUV_HANDLE_BACKTRACE=CONFIG_LIBUV_HANDLE_BACKTRACE) - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${EXPORT_INCDIR}) - - # ############################################################################ - # Applications Configuration - # ############################################################################ - - if(EXISTS ${CMAKE_CURRENT_LIST_DIR}/ext/tests/CMakeLists.txt) - add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/ext/tests) - endif() - - if(CONFIG_LIBUV_UTILS_TEST) - set(LIBUV_UTILS_TEST_SRCS - ${LIBUV_TEST_DIR}/run-tests.c ${LIBUV_TEST_DIR}/runner.c - ${LIBUV_TEST_DIR}/runner-unix.c ${LIBUV_TEST_DIR}/echo-server.c) - file(GLOB TEST_CSRCS ${LIBUV_TEST_DIR}/test-*.c) - list(APPEND LIBUV_UTILS_TEST_SRCS ${TEST_CSRCS}) - nuttx_add_application( - NAME - uv_run_tests - STACKSIZE - ${CONFIG_LIBUV_UTILS_STACKSIZE} - PRIORITY - ${CONFIG_LIBUV_UTILS_PRIORITY} - SRCS - ${LIBUV_UTILS_TEST_SRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - COMPILE_FLAGS - ${CFLAGS} - DEPENDS - libuv) - endif() - - if(CONFIG_LIBUV_UTILS_BENCHMARK) - set(LIBUV_UTILS_BENCHMARK_SRCS - ${LIBUV_TEST_DIR}/run-benchmarks.c - ${LIBUV_TEST_DIR}/runner.c - ${LIBUV_TEST_DIR}/runner-unix.c - ${LIBUV_TEST_DIR}/echo-server.c - ${LIBUV_TEST_DIR}/blackhole-server.c - ${LIBUV_TEST_DIR}/benchmark-async-pummel.c - ${LIBUV_TEST_DIR}/benchmark-async.c - ${LIBUV_TEST_DIR}/benchmark-fs-stat.c - ${LIBUV_TEST_DIR}/benchmark-getaddrinfo.c - ${LIBUV_TEST_DIR}/benchmark-loop-count.c - ${LIBUV_TEST_DIR}/benchmark-million-async.c - ${LIBUV_TEST_DIR}/benchmark-million-timers.c - ${LIBUV_TEST_DIR}/benchmark-multi-accept.c - ${LIBUV_TEST_DIR}/benchmark-ping-pongs.c - ${LIBUV_TEST_DIR}/benchmark-ping-udp.c - ${LIBUV_TEST_DIR}/benchmark-pound.c - ${LIBUV_TEST_DIR}/benchmark-pump.c - ${LIBUV_TEST_DIR}/benchmark-sizes.c - ${LIBUV_TEST_DIR}/benchmark-spawn.c - ${LIBUV_TEST_DIR}/benchmark-tcp-write-batch.c - ${LIBUV_TEST_DIR}/benchmark-thread.c - ${LIBUV_TEST_DIR}/benchmark-udp-pummel.c) - - nuttx_add_application( - NAME - uv_run_benchmarks - STACKSIZE - ${CONFIG_LIBUV_UTILS_STACKSIZE} - PRIORITY - ${CONFIG_LIBUV_UTILS_PRIORITY} - SRCS - ${LIBUV_UTILS_BENCHMARK_SRCS} - INCLUDE_DIRECTORIES - ${INCDIR} - COMPILE_FLAGS - ${CFLAGS} - DEPENDS - libuv) - endif() - -endif() diff --git a/system/libuv/Kconfig b/system/libuv/Kconfig index 9f55d2a4b..56f30bc90 100644 --- a/system/libuv/Kconfig +++ b/system/libuv/Kconfig @@ -6,6 +6,7 @@ config LIBUV bool "libuv asynchronous I/O Library" default n + select PIPES ---help--- Enable build for libuv asynchronous I/O Library @@ -19,41 +20,6 @@ config LIBUV_THREAD_STACKSIZE int "libuv worker thread stack size" default PTHREAD_STACK_DEFAULT -config LIBUV_THREADPOOL_PRIORITY - int "libuv default thread pool priority" - default 100 - -config LIBUV_BACKEND_EPOLL - bool "Using epoll backend in libuv" - default y - depends on FS_NOTIFY - -config LIBUV_STREAM_READ_BUF_SIZE - int "libuv stream read buffer size" - default 4096 - -if LIBUV_BACKEND_EPOLL - -config LIBUV_MAX_EPOLL_EVENTS - int "libuv max epoll events" - default 8 - -config LIBUV_PREP_EVENT_SIZE - int "libuv prep event size" - default 1 - -endif - -config LIBUV_HANDLE_BACKTRACE - int "the depth of libuv handle backtrace" - default 0 - ---help--- - Config the depth of backtrace for libuv handle creation by specified this - config: disable backtrace by 0 - when enabled, uv_print_all_handles & uv_print_active_handles will print - handle alloc backtrace additionally. - it's useful for libuv handle leak debugging - choice prompt "libuv utils" default LIBUV_UTILS_NONE @@ -81,5 +47,3 @@ config LIBUV_UTILS_STACKSIZE endif endif - -osource "$APPSDIR/system/libuv/ext/Kconfig" diff --git a/system/libuv/Make.defs b/system/libuv/Make.defs index 0a60fb9fe..740c5ef84 100644 --- a/system/libuv/Make.defs +++ b/system/libuv/Make.defs @@ -26,10 +26,4 @@ CONFIGURED_APPS += $(APPDIR)/system/libuv CFLAGS += ${INCDIR_PREFIX}$(APPDIR)/system/libuv/libuv/include CXXFLAGS += ${INCDIR_PREFIX}$(APPDIR)/system/libuv/libuv/include --include $(APPDIR)/system/libuv/ext/Make.defs - -# define UV_HANDLE_BACKTRACE -CFLAGS += -DUV_HANDLE_BACKTRACE=CONFIG_LIBUV_HANDLE_BACKTRACE -CXXFLAGS += -DUV_HANDLE_BACKTRACE=CONFIG_LIBUV_HANDLE_BACKTRACE - endif diff --git a/system/libuv/Makefile b/system/libuv/Makefile index 118af0811..bb2b50bcc 100644 --- a/system/libuv/Makefile +++ b/system/libuv/Makefile @@ -19,7 +19,6 @@ ############################################################################ include $(APPDIR)/Make.defs --include ./ext/Makefile LIBUV_PATCHS ?= $(sort $(wildcard 000*.patch)) @@ -29,6 +28,7 @@ LIBUV_TARBALL = v$(LIBUV_VERSION).zip LIBUV_URL_BASE = https://github.com/libuv/libuv/archive/refs/tags LIBUV_URL = $(LIBUV_URL_BASE)/$(LIBUV_TARBALL) + $(LIBUV_TARBALL): @echo "Downloading: $(LIBUV_TARBALL)" $(Q) curl -L $(LIBUV_URL) -o $(LIBUV_TARBALL) @@ -51,10 +51,6 @@ CFLAGS += -I$(LIBUV_UNPACK)/test CFLAGS += -Wno-shadow CFLAGS += -DDEF_THREADPOOL_SIZE=CONFIG_LIBUV_THREADPOOL_SIZE CFLAGS += -DDEF_THREADPOOL_STACKSIZE=CONFIG_LIBUV_THREAD_STACKSIZE -CFLAGS += -DDEF_THREADPOOL_PRIORITY=CONFIG_LIBUV_THREADPOOL_PRIORITY -CFLAGS += -DMAX_EPOLL_EVENTS=CONFIG_LIBUV_MAX_EPOLL_EVENTS -CFLAGS += -DPREP_EVENT_SIZE=CONFIG_LIBUV_PREP_EVENT_SIZE -CFLAGS += -DDEF_STREAM_READ_BUF_SIZE=CONFIG_LIBUV_STREAM_READ_BUF_SIZE ifeq ($(GCCVER),) export GCCVER = $(shell $(CC) --version | grep gcc | sed -r 's/.* ([0-9]+\.[0-9]+).*/\1/' | cut -d'.' -f1) @@ -78,12 +74,7 @@ CSRCS += loop.c CSRCS += thread.c CSRCS += thread-common.c CSRCS += posix-hrtime.c -ifneq ($(CONFIG_LIBUV_BACKEND_EPOLL),) -CSRCS += linux.c -else CSRCS += posix-poll.c -CSRCS += no-fsevents.c -endif CSRCS += uv-data-getter-setters.c CSRCS += version.c ifeq ($(CONFIG_LIBUV_UTILS_TEST),) @@ -91,6 +82,7 @@ CSRCS += idna.c CSRCS += strscpy.c CSRCS += strtok.c endif +CSRCS += no-fsevents.c CSRCS += uv-common.c CSRCS += random-devurandom.c CSRCS += random.c @@ -105,7 +97,9 @@ CSRCS += pipe.c CSRCS += fs.c CSRCS += fs-poll.c CSRCS += timer.c +ifneq ($(CONFIG_LIBC_EXECFUNCS),) CSRCS += process-spawn.c +endif CSRCS += sysinfo-loadavg.c CSRCS += sysinfo-memory.c diff --git a/system/libuv/README.md b/system/libuv/README.md deleted file mode 100644 index 9d853f207..000000000 --- a/system/libuv/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# `libuv` - -Most features of libuv are supported by current port, except SIGPROF relative function (loop_configure). - -Nearly full libuv's test suite avaliable on NuttX, but some known case can't run on sim: - -* loop_update_time -* idle_starvation -* signal_multiple_loops -* signal_pending_on_close -* metrics_idle_time -* metrics_idle_time_thread -* metrics_idle_time_zero - -And some will cause crash by some reason: - -* fs_poll_ref diff --git a/system/lm75/lm75.c b/system/lm75/lm75.c index 9edb8f2f0..57595fcbe 100644 --- a/system/lm75/lm75.c +++ b/system/lm75/lm75.c @@ -41,12 +41,12 @@ #ifndef CONFIG_SYSTEM_LM75_DEVNAME # warning CONFIG_SYSTEM_LM75_DEVNAME is not defined -# define CONFIG_SYSTEM_LM75_DEVNAME "/dev/temp" +# define CONFIG_SYSTEM_LM75_DEVNAME "/dev/temp0" #endif #if !defined(CONFIG_SYSTEM_LM75_FAHRENHEIT) && !defined(CONFIG_SYSTEM_LM75_CELSIUS) # warning one of CONFIG_SYSTEM_LM75_FAHRENHEIT or CONFIG_SYSTEM_LM75_CELSIUS must be defined -# defeind CONFIG_SYSTEM_LM75_FAHRENHEIT 1 +# define CONFIG_SYSTEM_LM75_FAHRENHEIT 1 #endif #if defined(CONFIG_SYSTEM_LM75_FAHRENHEIT) && defined(CONFIG_SYSTEM_LM75_CELSIUS) diff --git a/system/nsh/README.md b/system/nsh/README.md deleted file mode 100644 index 8d3998b01..000000000 --- a/system/nsh/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# System / `nsh` NuttShell (NSH) - -## Basic Configuration - -This directory provides an example of how to configure and use the NuttShell -(NSH) application. NSH is a simple shell application. NSH is described in its -own README located at `apps/nshlib/README.md`. This function is enabled with: - -```conf -CONFIG_SYSTEM_NSH=y -``` - -Applications using this example will need to provide an `defconfig` file in the -configuration directory with instruction to build the NSH library like: - -```conf -CONFIG_NSH_LIBRARY=y -``` - -## Other Configuration Requirements - -**Note**: If the NSH serial console is used, then following is also required to -build the `readline()` library: - -```conf -CONFIG_SYSTEM_READLINE=y -``` - -And if networking is included: - -```conf -CONFIG_NETUTILS_NETLIB=y -CONFIG_NETUTILS_DHCPC=y -CONFIG_NETDB_DNSCLIENT=y -CONFIG_NETUTILS_TFTPC=y -CONFIG_NETUTILS_WEBCLIENT=y -``` - -If the Telnet console is enabled, then the defconfig file should also include: - -```conf -CONFIG_NETUTILS_TELNETD=y -``` - -Also if the Telnet console is enabled, make sure that you have the following set -in the NuttX configuration file or else the performance will be very bad -(because there will be only one character per TCP transfer): - -- `CONFIG_STDIO_BUFFER_SIZE` - Some value `>= 64` -- `CONFIG_STDIO_LINEBUFFER=y` diff --git a/system/ntpc/Kconfig b/system/ntpc/Kconfig index 30be27a06..a8137ab86 100644 --- a/system/ntpc/Kconfig +++ b/system/ntpc/Kconfig @@ -11,7 +11,6 @@ config SYSTEM_NTPC ---help--- Enable the NTP client 'start' and 'stop' commands - if SYSTEM_NTPC config SYSTEM_NTPC_PRIORITY diff --git a/system/nxcodec/Kconfig b/system/nxcodec/Kconfig deleted file mode 100644 index f7850dccf..000000000 --- a/system/nxcodec/Kconfig +++ /dev/null @@ -1,30 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config SYSTEM_NXCODEC - bool "NxCodec test application" - default n - ---help--- - Enable support for the NxCodec test application and optional - command line interface. - -if SYSTEM_NXCODEC - -config SYSTEM_NXCODEC_PROGNAME - string "Program name" - default "nxcodec" - ---help--- - This is the name of the program that will be used when the NSH ELF - program is installed. - -config SYSTEM_NXCODEC_PRIORITY - int "nxcodec task priority" - default 100 - -config SYSTEM_NXCODEC_STACKSIZE - int "nxcodec stack size" - default DEFAULT_TASK_STACKSIZE - -endif # SYSTEM_NXCODEC diff --git a/system/nxcodec/Make.defs b/system/nxcodec/Make.defs deleted file mode 100644 index ba0768549..000000000 --- a/system/nxcodec/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/system/nxcodec/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_SYSTEM_NXCODEC),) -CONFIGURED_APPS += $(APPDIR)/system/nxcodec -endif diff --git a/system/nxcodec/nxcodec.c b/system/nxcodec/nxcodec.c deleted file mode 100644 index d6a99e4de..000000000 --- a/system/nxcodec/nxcodec.c +++ /dev/null @@ -1,259 +0,0 @@ -/**************************************************************************** - * apps/system/nxcodec/nxcodec.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include "nxcodec.h" - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static inline bool nxcodec_splane_video(FAR struct v4l2_capability *cap) -{ - return (cap->capabilities & V4L2_CAP_VIDEO_M2M) || - ((cap->capabilities & V4L2_CAP_STREAMING) && - (cap->capabilities & (V4L2_CAP_VIDEO_OUTPUT | - V4L2_CAP_VIDEO_CAPTURE))); -} - -static inline bool nxcodec_mplane_video(FAR struct v4l2_capability *cap) -{ - return (cap->capabilities & V4L2_CAP_VIDEO_M2M_MPLANE) || - ((cap->capabilities & V4L2_CAP_STREAMING) && - (cap->capabilities & (V4L2_CAP_VIDEO_OUTPUT_MPLANE | - V4L2_CAP_VIDEO_CAPTURE_MPLANE))); -} - -static int nxcodec_prepare_contexts(FAR nxcodec_t *codec) -{ - struct v4l2_capability cap; - int ret; - - memset(&cap, 0, sizeof(cap)); - ret = ioctl(codec->fd, VIDIOC_QUERYCAP, &cap); - if (ret < 0) - { - return -errno; - } - - if (nxcodec_mplane_video(&cap)) - { - codec->capture.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; - codec->output.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; - return 0; - } - - if (nxcodec_splane_video(&cap)) - { - codec->capture.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; - codec->output.type = V4L2_BUF_TYPE_VIDEO_OUTPUT; - return 0; - } - - return -EINVAL; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int nxcodec_init(FAR nxcodec_t *codec) -{ - int ret; - - codec->fd = open(codec->devname, O_RDWR | O_NONBLOCK); - if (codec->fd < 0) - { - return -errno; - } - - ret = nxcodec_prepare_contexts(codec); - if (ret < 0) - { - goto err0; - } - - ret = nxcodec_context_get_format(&codec->output); - if (ret < 0) - { - printf("v4l2 output format not supported\n"); - goto err0; - } - - ret = nxcodec_context_get_format(&codec->capture); - if (ret < 0) - { - printf("v4l2 capture format not supported\n"); - goto err0; - } - - if (codec->output.fdesc.pixelformat != - codec->output.format.fmt.pix.pixelformat) - { - ret = -EINVAL; - goto err0; - } - - codec->output.format.type = codec->output.type; - - ret = nxcodec_context_set_format(&codec->output); - if (ret < 0) - { - printf("can't set v4l2 output format\n"); - goto err0; - } - - codec->output.fd = open(codec->output.filename, O_RDONLY); - if (codec->output.fd < 0) - { - printf("Failed to open input file %s \n", codec->output.filename); - ret = -errno; - goto err0; - } - - if (codec->capture.fdesc.pixelformat != - codec->capture.format.fmt.pix.pixelformat) - { - ret = -EINVAL; - goto err1; - } - - codec->capture.format.type = codec->capture.type; - - ret = nxcodec_context_set_format(&codec->capture); - if (ret < 0) - { - printf("can't to set v4l2 capture format\n"); - goto err1; - } - - codec->capture.fd = open(codec->capture.filename, - O_WRONLY | O_CREAT, 0644); - if (codec->capture.fd < 0) - { - printf("Failed to open input file %s \n", codec->capture.filename); - ret = -errno; - goto err1; - } - - return 0; - -err1: - close(codec->output.fd); -err0: - close(codec->fd); - return ret; -} - -int nxcodec_start(FAR nxcodec_t *codec) -{ - int ret; - - ret = nxcodec_context_init(&codec->output); - if (ret < 0) - { - printf("can't request output buffers\n"); - return ret; - } - - ret = nxcodec_context_set_status(&codec->output, VIDIOC_STREAMON); - if (ret < 0) - { - printf("set output VIDIOC_STREAMON failed\n"); - goto err0; - } - - ret = nxcodec_context_init(&codec->capture); - if (ret < 0) - { - printf("can't request capture buffers\n"); - goto err0; - } - - ret = nxcodec_context_set_status(&codec->capture, VIDIOC_STREAMON); - if (ret < 0) - { - printf("set capture VIDIOC_STREAMON failed\n"); - goto err1; - } - - ret = nxcodec_context_enqueue_frame(&codec->output); - if (ret < 0 && ret != -EAGAIN) - { - goto err1; - } - - return 0; - -err1: - nxcodec_context_uninit(&codec->capture); -err0: - nxcodec_context_uninit(&codec->output); - return ret; -} - -int nxcodec_stop(FAR nxcodec_t *codec) -{ - int ret; - - if (!codec) - { - return 0; - } - - nxcodec_context_uninit(&codec->output); - - ret = nxcodec_context_set_status(&codec->output, VIDIOC_STREAMOFF); - if (ret < 0) - { - printf("set output VIDIOC_STREAMOFF failed\n"); - return ret; - } - - nxcodec_context_uninit(&codec->capture); - - ret = nxcodec_context_set_status(&codec->capture, VIDIOC_STREAMOFF); - if (ret < 0) - { - printf("set capture VIDIOC_STREAMOFF failed\n"); - return ret; - } - - return 0; -} - -int nxcodec_uninit(FAR nxcodec_t *codec) -{ - close(codec->capture.fd); - close(codec->output.fd); - close(codec->fd); - - return 0; -} diff --git a/system/nxcodec/nxcodec.h b/system/nxcodec/nxcodec.h deleted file mode 100644 index a3e89217b..000000000 --- a/system/nxcodec/nxcodec.h +++ /dev/null @@ -1,51 +0,0 @@ -/**************************************************************************** - * apps/system/nxcodec/nxcodec.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_NXCODEC_NXCODEC_H -#define __APPS_SYSTEM_NXCODEC_NXCODEC_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include "nxcodec_context.h" - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef struct nxcodec_s -{ - char devname[PATH_MAX]; - int fd; - nxcodec_context_t capture; - nxcodec_context_t output; -} nxcodec_t; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int nxcodec_init(FAR nxcodec_t *codec); -int nxcodec_start(FAR nxcodec_t *codec); -int nxcodec_stop(FAR nxcodec_t *codec); -int nxcodec_uninit(FAR nxcodec_t *codec); - -#endif /* __APPS_SYSTEM_NXCODEC_NXCODEC_H */ diff --git a/system/nxcodec/nxcodec_context.c b/system/nxcodec/nxcodec_context.c deleted file mode 100644 index 16514d94a..000000000 --- a/system/nxcodec/nxcodec_context.c +++ /dev/null @@ -1,383 +0,0 @@ -/**************************************************************************** - * apps/system/nxcodec/nxcodec_context.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "nxcodec_context.h" -#include "nxcodec.h" - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define NXCODEC_CONTEXT_BUFNUMBER 3 - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static inline FAR nxcodec_t * -nxcodec_context_to_nxcodec(FAR nxcodec_context_t *ctx) -{ - return V4L2_TYPE_IS_OUTPUT(ctx->type) ? - container_of(ctx, nxcodec_t, output) : - container_of(ctx, nxcodec_t, capture); -} - -static FAR nxcodec_context_buf_t * -nxcodec_context_dequeue_buf(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - struct v4l2_buffer buf; - int ret; - - memset(&buf, 0, sizeof(buf)); - buf.memory = V4L2_MEMORY_MMAP; - buf.type = ctx->type; - - ret = ioctl(codec->fd, VIDIOC_DQBUF, &buf); - if (ret < 0) - { - printf("type: %d VIDIOC_DQBUF, err: %s\n", ctx->type, strerror(errno)); - return NULL; - } - - ctx->buf[buf.index].free = true; - ctx->buf[buf.index].buf = buf; - - return &ctx->buf[buf.index]; -} - -static FAR nxcodec_context_buf_t * -nxcodec_context_get_freebuf(FAR nxcodec_context_t *ctx) -{ - int i; - - if (V4L2_TYPE_IS_OUTPUT(ctx->type)) - { - while (nxcodec_context_dequeue_buf(ctx)); - } - - for (i = 0; i < ctx->nbuffers; i++) - { - if (ctx->buf[i].free) - { - return &ctx->buf[i]; - } - } - - return NULL; -} - -static int nxcodec_context_write_data(FAR nxcodec_context_t *ctx, - FAR const char *buf, int size) -{ - return write(ctx->fd, buf, size) < 0 ? -errno : 0; -} - -static int nxcodec_context_read_yuv_data(FAR nxcodec_context_t *ctx, - FAR char *buf, - FAR uint32_t *bytesused) -{ - size_t buflen = ctx->format.fmt.pix.width * - ctx->format.fmt.pix.height * 3 / 2; - ssize_t ret; - - ret = read(ctx->fd, buf, buflen); - if (ret <= 0) - { - return -errno; - } - - *bytesused = ret; - return 0; -} - -static int nxcodec_context_read_h264_data(FAR nxcodec_context_t *ctx, - FAR char *buf, - FAR uint32_t *bytesused) -{ - char start_code[4]; - ssize_t ret; - int size; - - memset(start_code, 0, 4); - - ret = read(ctx->fd, buf, 4); - if (ret <= 0) - { - return -errno; - } - - if (buf[0] == 0x00 && buf[1] == 0x00 && - buf[2] == 0x00 && buf[3] == 0x01) - { - size = 4; - while (1) - { - ret = read(ctx->fd, buf + size, 1); - if (ret < 0) - { - return -errno; - } - else if (ret == 0) - { - break; - } - - start_code[0] = start_code[1]; - start_code[1] = start_code[2]; - start_code[2] = start_code[3]; - start_code[3] = *(buf + size); - size++; - - if (start_code[0] == 0x00 && start_code[1] == 0x00 && - start_code[2] == 0x00 && start_code[3] == 0x01) - { - size -= 4; - lseek(ctx->fd, -4, SEEK_CUR); - break; - } - } - } - else - { - return -EINVAL; - } - - *bytesused = size; - - return 0; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int nxcodec_context_set_status(FAR nxcodec_context_t *ctx, uint32_t cmd) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - - return ioctl(codec->fd, cmd, &ctx->type) < 0 ? -errno : 0; -} - -int nxcodec_context_enqueue_frame(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - FAR nxcodec_context_buf_t *buf; - int ret; - - buf = nxcodec_context_get_freebuf(ctx); - if (!buf) - { - return -EAGAIN; - } - - if (ctx->format.fmt.pix.pixelformat == V4L2_PIX_FMT_H264) - { - ret = nxcodec_context_read_h264_data(ctx, - buf->addr, - &buf->buf.bytesused); - if (ret < 0) - { - return ret; - } - } - else if (ctx->format.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) - { - ret = nxcodec_context_read_yuv_data(ctx, - buf->addr, - &buf->buf.bytesused); - if (ret < 0) - { - return ret; - } - } - - ret = ioctl(codec->fd, VIDIOC_QBUF, &buf->buf); - if (ret < 0) - { - return -errno; - } - - buf->free = false; - return 0; -} - -int nxcodec_context_dequeue_frame(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - FAR nxcodec_context_buf_t *buf; - int ret; - - buf = nxcodec_context_dequeue_buf(ctx); - if (!buf) - { - return -EAGAIN; - } - - if (buf->buf.length > 0) - { - nxcodec_context_write_data(ctx, buf->addr, buf->buf.bytesused); - } - - ret = ioctl(codec->fd, VIDIOC_QBUF, &buf->buf); - if (ret < 0) - { - return -errno; - } - - buf->free = false; - return 0; -} - -int nxcodec_context_get_format(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - - memset(&ctx->fdesc, 0, sizeof(ctx->fdesc)); - ctx->fdesc.type = ctx->type; - - return ioctl(codec->fd, VIDIOC_ENUM_FMT, &ctx->fdesc) < 0 ? -errno : 0; -} - -int nxcodec_context_set_format(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - - return ioctl(codec->fd, VIDIOC_S_FMT, &ctx->format) < 0 ? -errno : 0; -} - -int nxcodec_context_init(FAR nxcodec_context_t *ctx) -{ - FAR nxcodec_t *codec = nxcodec_context_to_nxcodec(ctx); - struct v4l2_requestbuffers req; - int ret; - int i; - - memset(&req, 0, sizeof(req)); - req.count = NXCODEC_CONTEXT_BUFNUMBER; - req.memory = V4L2_MEMORY_MMAP; - req.type = ctx->type; - - ret = ioctl(codec->fd, VIDIOC_REQBUFS, &req); - if (ret < 0) - { - printf("type: %d VIDIOC_REQBUFS failed: %s\n", - ctx->type, strerror(errno)); - return -errno; - } - - ctx->nbuffers = req.count; - ctx->buf = calloc(ctx->nbuffers, sizeof(nxcodec_context_buf_t)); - if (!ctx->buf) - { - printf("type: %d malloc enomem\n", ctx->type); - return -ENOMEM; - } - - for (i = 0; i < ctx->nbuffers; i++) - { - FAR nxcodec_context_buf_t *buf = &ctx->buf[i]; - - buf->buf.memory = V4L2_MEMORY_MMAP; - buf->buf.type = ctx->type; - buf->buf.index = i; - - ret = ioctl(codec->fd, VIDIOC_QUERYBUF, &buf->buf); - if (ret < 0) - { - goto error; - } - - buf->length = buf->buf.length; - buf->addr = mmap(NULL, - buf->buf.length, - PROT_READ | PROT_WRITE, - MAP_SHARED, - codec->fd, - buf->buf.m.offset); - - if (buf->addr == MAP_FAILED) - { - goto error; - } - - buf->free = true; - - if (V4L2_TYPE_IS_OUTPUT(ctx->type)) - { - continue; - } - - ret = ioctl(codec->fd, VIDIOC_QBUF, &buf->buf); - if (ret < 0) - { - munmap(buf->addr, buf->length); - goto error; - } - - buf->free = false; - } - - return 0; - -error: - free(ctx->buf); - return -errno; -} - -void nxcodec_context_uninit(FAR nxcodec_context_t *ctx) -{ - int i; - - if (!ctx->buf) - { - return; - } - - for (i = 0; i < ctx->nbuffers; i++) - { - FAR nxcodec_context_buf_t *buf = &ctx->buf[i]; - - if (buf->addr && buf->length) - { - if (munmap(buf->addr, buf->length) < 0) - { - printf("type: %d unmap plane (%s))\n", - ctx->type, strerror(errno)); - } - } - } - - free(ctx->buf); -} diff --git a/system/nxcodec/nxcodec_context.h b/system/nxcodec/nxcodec_context.h deleted file mode 100644 index 09319e6ff..000000000 --- a/system/nxcodec/nxcodec_context.h +++ /dev/null @@ -1,65 +0,0 @@ -/**************************************************************************** - * apps/system/nxcodec/nxcodec_context.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APP_SYSTEM_NXCODEC_NXCODEC_CONTEXT_H -#define __APP_SYSTEM_NXCODEC_NXCODEC_CONTEXT_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Types - ****************************************************************************/ - -typedef struct nxcodec_context_buf_s -{ - FAR void *addr; - size_t length; - struct v4l2_buffer buf; - bool free; -} nxcodec_context_buf_t; - -typedef struct nxcodec_context_s -{ - char filename[PATH_MAX]; - int fd; - enum v4l2_buf_type type; - struct v4l2_format format; - struct v4l2_fmtdesc fdesc; - FAR nxcodec_context_buf_t *buf; - int nbuffers; -} nxcodec_context_t; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int nxcodec_context_init(FAR nxcodec_context_t *ctx); -int nxcodec_context_set_status(FAR nxcodec_context_t *ctx, uint32_t cmd); -int nxcodec_context_enqueue_frame(FAR nxcodec_context_t *ctx); -int nxcodec_context_dequeue_frame(FAR nxcodec_context_t *ctx); -int nxcodec_context_get_format(FAR nxcodec_context_t *ctx); -int nxcodec_context_set_format(FAR nxcodec_context_t *ctx); -void nxcodec_context_uninit(FAR nxcodec_context_t *ctx); - -#endif /* __APP_SYSTEM_NXCODEC_NXCODEC_CONTEXT_H */ diff --git a/system/nxcodec/nxcodec_main.c b/system/nxcodec/nxcodec_main.c deleted file mode 100644 index d25f57180..000000000 --- a/system/nxcodec/nxcodec_main.c +++ /dev/null @@ -1,206 +0,0 @@ -/**************************************************************************** - * apps/system/nxcodec/nxcodec_main.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include - -#include "nxcodec.h" - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static const char g_short_options[] = "d:s:hf:i:o:"; - -static const struct option g_long_options[] = -{ - { "device", required_argument, NULL, 'd' }, - { "size", required_argument, NULL, 's' }, - { "help", no_argument, NULL, 'h' }, - { "format", required_argument, NULL, 'f' }, - { "infile", required_argument, NULL, 'i' }, - { "outfile", required_argument, NULL, 'o' }, - { NULL, 0, NULL, 0 } -}; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void usage(FAR const char *progname) -{ - printf("Usage: %s [options]\n\n" - "Version 1.3\n" - "Options:\n" - "-d | --device Video device name\n" - "-s | --size Size of stream\n" - "-h | --help Print this message\n" - "-f | --format Format of stream\n" - "-i | --infile Input filename for M2M devices\n" - "-o | --outfile Outputs stream to filename\n\n" - "eg: nxcodec -d /dev/video1 -s 256x144 \ - -f H264 -i input.h264 -f YU12 -o output.yuv\n", - progname); - - exit(EXIT_SUCCESS); -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -/**************************************************************************** - * nxcodec_main - ****************************************************************************/ - -int main(int argc, FAR char **argv) -{ - nxcodec_t codec; - int ret; - char cc[5] = - { - 0 - }; - - memset(&codec, 0, sizeof(codec)); - - while (1) - { - int idx; - int c; - - c = getopt_long(argc, argv, g_short_options, g_long_options, &idx); - if (-1 == c) - { - break; - } - - switch (c) - { - case 0: /* getopt_long() flag */ - break; - - case 'd': - memset(codec.devname, 0, sizeof(codec.devname)); - snprintf(codec.devname, sizeof(codec.devname), "%s", optarg); - break; - - case 's' : - sscanf(optarg, "%"SCNu32"x%"SCNu32"", - &codec.capture.format.fmt.pix.width, - &codec.capture.format.fmt.pix.height); - - codec.output.format.fmt.pix.width = - codec.capture.format.fmt.pix.width; - codec.output.format.fmt.pix.height = - codec.capture.format.fmt.pix.height; - break; - - case 'h': - usage(argv[0]); - - case 'f': - memset(cc, 0, 5); - snprintf(cc, sizeof(cc), "%s", optarg); - break; - - case 'i': - memset(codec.output.filename, 0, sizeof(codec.output.filename)); - snprintf(codec.output.filename, - sizeof(codec.output.filename), "%s", optarg); - - codec.output.format.fmt.pix.pixelformat = - v4l2_fourcc(cc[0], cc[1], cc[2], cc[3]); - break; - - case 'o': - memset(codec.capture.filename, 0, - sizeof(codec.capture.filename)); - snprintf(codec.capture.filename, - sizeof(codec.capture.filename), "%s", optarg); - - codec.capture.format.fmt.pix.pixelformat = - v4l2_fourcc(cc[0], cc[1], cc[2], cc[3]); - break; - - default: - usage(argv[0]); - break; - } - } - - if (argc != optind) - { - printf("Too few input parameter!\n\n"); - usage(argv[0]); - } - - ret = nxcodec_init(&codec); - if (ret < 0) - { - return ret; - } - - ret = nxcodec_start(&codec); - if (ret < 0) - { - goto end0; - } - - while (1) - { - struct pollfd pfd = - { - .events = POLLIN | POLLOUT, - .fd = codec.fd, - }; - - poll(&pfd, 1, -1); - - if (pfd.revents & POLLIN) - { - if (nxcodec_context_dequeue_frame(&codec.capture) < 0) - { - break; - } - } - - if (pfd.revents & POLLOUT) - { - if (nxcodec_context_enqueue_frame(&codec.output) < 0) - { - break; - } - } - } - - nxcodec_stop(&codec); - -end0: - nxcodec_uninit(&codec); - return ret; -} diff --git a/system/nxdiag/Makefile b/system/nxdiag/Makefile index 73efc4edd..743610166 100644 --- a/system/nxdiag/Makefile +++ b/system/nxdiag/Makefile @@ -80,7 +80,7 @@ INFO_DEPS += espressif_prepare espressif_prepare: ifeq ($(HALDIR),$(ARCH_ESP_HALDIR)) @echo "Unshallowing Espressif HAL..." - (cd ${HALDIR} && git fetch --depth=10000 && git fetch --tags) + (cd ${HALDIR} && git fetch && git fetch --tags) endif ifdef ESPTOOL_BINDIR diff --git a/system/nxplayer/README.md b/system/nxplayer/README.md deleted file mode 100644 index a17730d53..000000000 --- a/system/nxplayer/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# System / `nxplayer` NXPlayer - -``` -Author: Ken Pettit - Date: 11 Sept 2013 -``` - -This application implements a command-line media player which uses the NuttX -Audio system to play files (`mp3`, `wav`, etc.) from the file system. - -Usage: - -```shell -nxplayer -``` - -The application presents an command line for specifying player commands, such as -`play filename`, `pause`, `volume 50%`, etc. diff --git a/system/nxplayer/nxplayer.c b/system/nxplayer/nxplayer.c index 1221935b7..a0d10e590 100644 --- a/system/nxplayer/nxplayer.c +++ b/system/nxplayer/nxplayer.c @@ -1121,13 +1121,6 @@ static FAR void *nxplayer_playthread(pthread_addr_t pvarg) audinfo("Play complete. outstanding=%d\n", outstanding); DEBUGASSERT(outstanding == 0); #endif - -#ifdef CONFIG_AUDIO_MULTI_SESSION - ioctl(pplayer->dev_fd, AUDIOIOC_STOP, - (unsigned long)pplayer->session); -#else - ioctl(pplayer->dev_fd, AUDIOIOC_STOP, 0); -#endif running = false; break; diff --git a/system/nxrecorder/nxrecorder.c b/system/nxrecorder/nxrecorder.c index 10f4806e9..674baf1a6 100644 --- a/system/nxrecorder/nxrecorder.c +++ b/system/nxrecorder/nxrecorder.c @@ -110,12 +110,7 @@ static const struct nxrecorder_ext_fmt_s g_known_ext[] = #ifdef CONFIG_AUDIO_FORMAT_OGG_VORBIS { "ogg", AUDIO_FMT_OGG_VORBIS, NULL }, #endif -#ifdef CONFIG_AUDIO_FORMAT_AMR - { "amr", AUDIO_FMT_AMR, NULL }, -#endif -#ifdef CONFIG_AUDIO_FORMAT_OPUS - { "opus", AUDIO_FMT_OPUS, NULL } -#endif + { "amr", AUDIO_FMT_AMR, NULL } }; static const int g_known_ext_count = sizeof(g_known_ext) / @@ -133,16 +128,6 @@ static const struct nxrecorder_enc_ops_s g_enc_ops[] = AUDIO_FMT_PCM, NULL, nxrecorder_write_common, - }, - { - AUDIO_FMT_MP3, - NULL, - nxrecorder_write_common, - }, - { - AUDIO_FMT_OPUS, - NULL, - nxrecorder_write_common, } }; @@ -201,32 +186,12 @@ static int nxrecorder_opendevice(FAR struct nxrecorder_s *precorder, if (ioctl(precorder->dev_fd, AUDIOIOC_GETCAPS, (uintptr_t)&cap) == cap.ac_len) { - if (((cap.ac_format.hw & (1 << (format - 1))) || - (cap.ac_format.hw & (1 << (AUDIO_FMT_OTHER - 1)))) && + if (((cap.ac_format.hw & (1 << (format - 1))) != 0) && (cap.ac_controls.b[0] & AUDIO_TYPE_INPUT)) { - if (!(cap.ac_format.hw & (1 << (format - 1)))) - { - /* Get the format supported by the driver - * through cap.ac_controls.w - */ - - cap.ac_len = sizeof(cap); - cap.ac_type = AUDIO_TYPE_QUERY; - cap.ac_subtype = AUDIO_FMT_OTHER; - if (ioctl(precorder->dev_fd, AUDIOIOC_GETCAPS, - (uintptr_t)&cap) == cap.ac_len) - { - if (!(cap.ac_controls.w & (1 << (format - 1)))) - { - supported = false; - } - } - } - /* Test if subformat needed and detected */ - if (subfmt != AUDIO_FMT_UNDEF && supported) + if (subfmt != AUDIO_FMT_UNDEF) { /* Prepare to get sub-formats for * this main format @@ -1132,7 +1097,6 @@ int nxrecorder_recordinternal(FAR struct nxrecorder_s *precorder, if (!precorder->ops) { - ret = -ENOSYS; goto err_out; } @@ -1320,7 +1284,6 @@ FAR struct nxrecorder_s *nxrecorder_create(void) precorder->mq = 0; precorder->record_id = 0; precorder->crefs = 1; - precorder->ops = NULL; #ifdef CONFIG_AUDIO_MULTI_SESSION precorder->session = NULL; diff --git a/system/perf-tools/Kconfig b/system/perf-tools/Kconfig deleted file mode 100644 index 90cd77de0..000000000 --- a/system/perf-tools/Kconfig +++ /dev/null @@ -1,22 +0,0 @@ -# -# For a description of the syntax of this configuration file, -# see the file kconfig-language.txt in the NuttX tools repository. -# - -config PERF_TOOLS - tristate "Performance analysis utility" - default n - ---help--- - Performance analysis utility - -if PERF_TOOLS - -config PERF_TOOLS_PRIORITY - int "Perf tools task priority" - default 100 - -config PERF_TOOLS_STACKSIZE - int "Perf tools stack size" - default DEFAULT_TASK_STACKSIZE - -endif diff --git a/system/perf-tools/Make.defs b/system/perf-tools/Make.defs deleted file mode 100644 index 458d4d4e1..000000000 --- a/system/perf-tools/Make.defs +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################ -# apps/system/perf-tools/Make.defs -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -ifneq ($(CONFIG_PERF_TOOLS),) -CONFIGURED_APPS += $(APPDIR)/system/perf-tools -endif diff --git a/system/perf-tools/Makefile b/system/perf-tools/Makefile deleted file mode 100644 index eccab6227..000000000 --- a/system/perf-tools/Makefile +++ /dev/null @@ -1,32 +0,0 @@ -############################################################################ -# apps/system/perf-tools/Makefile -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. -# -############################################################################ - -include $(APPDIR)/Make.defs - -PROGNAME = perf -PRIORITY = $(CONFIG_PERF_TOOLS_PRIORITY) -STACKSIZE = $(CONFIG_PERF_TOOLS_STACKSIZE) -MODULE = $(CONFIG_PERF_TOOLS) - -MAINSRC += perf.c builtin-help.c builtin-list.c builtin-record.c \ - builtin-stat.c builtin-version.c evlist.c evsel.c \ - parse-options.c - -include $(APPDIR)/Application.mk diff --git a/system/perf-tools/builtin-list.c b/system/perf-tools/builtin-list.c deleted file mode 100644 index 14da4d33b..000000000 --- a/system/perf-tools/builtin-list.c +++ /dev/null @@ -1,156 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/builtin-list.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#include "evsel.h" - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static const char list_usage[] = "perf list [hw|sw|cache]"; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void default_print_start(void) -{ - printf("List of pre-defined events (to be used in -e):\n\n"); -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -bool is_event_supported(uint8_t type, uint64_t config) -{ - bool ret = false; - struct evsel_s *evsel; - struct perf_event_attr_s attr = - { - .type = type, - .config = config, - .disabled = 1, - }; - - evsel = evsel_new(&attr); - if (evsel) - { - ret = evsel_open(evsel, NULL) >= 0; - evsel_delete(evsel); - } - - return ret; -} - -void print_hwcache_events(void) -{ - int type; - int op; - int res; - int ret; - uint64_t config; - - for (type = 0; type < PERF_COUNT_HW_CACHE_MAX; type++) - { - for (op = 0; op < PERF_COUNT_HW_CACHE_OP_MAX; op++) - { - if (!evsel_is_cache_op_valid(type, op)) - { - continue; - } - - for (res = 0; res < PERF_COUNT_HW_CACHE_RESULT_MAX; res++) - { - char name[64]; - evsel_hw_cache_type_op_res_name(type, op, res, - name, sizeof(name)); - ret = parse_hw_cache_events(name, &config); - if (ret || !is_event_supported(PERF_TYPE_HW_CACHE, config)) - { - continue; - } - - printf(" %-32s\t [Hardware cache event]\n", name); - } - } - } - - printf("\n"); -} - -void print_hw_events(void) -{ - int i; - - for (i = 0; i < PERF_COUNT_HW_MAX; i++) - { - if (!is_event_supported(PERF_TYPE_HARDWARE, i)) - { - continue; - } - - printf(" %-32s\t [Hardware event]\n", evsel_hw_names[i]); - } - - printf("\n"); -} - -int cmd_list(int argc, FAR const char **argv) -{ - char *type = NULL; - - if (argc > 1) - { - type = (char *)argv[1]; - } - else - { - default_print_start(); - print_hw_events(); - print_hwcache_events(); - return 0; - } - - if (strcmp(type, "hw") == 0 || - strcmp(type, "hardware") == 0) - { - default_print_start(); - print_hw_events(); - } - else if (strcmp(type, "cache") == 0) - { - default_print_start(); - print_hwcache_events(); - } - else - { - printf("\n Usage: %s\n\n", list_usage); - } - - return 0; -} diff --git a/system/perf-tools/builtin-record.c b/system/perf-tools/builtin-record.c deleted file mode 100644 index aea7ff56f..000000000 --- a/system/perf-tools/builtin-record.c +++ /dev/null @@ -1,39 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/builtin-record.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int cmd_record(int argc, FAR const char **argv) -{ - /* Delete the print after implementing the function */ - - printf("perf record is not implemented yet!\n"); - - return 0; -} diff --git a/system/perf-tools/builtin-stat.c b/system/perf-tools/builtin-stat.c deleted file mode 100644 index c231b5783..000000000 --- a/system/perf-tools/builtin-stat.c +++ /dev/null @@ -1,594 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/builtin-stat.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "builtin.h" -#include "evlist.h" -#include "evsel.h" -#include "parse-options.h" - -/**************************************************************************** - * Private Definitions - ****************************************************************************/ - -#define PERF_STAT_DEFAULT_MAX_EVSTR 64 -#define PERF_STAT_DEFAULT_MAX_CMDSTR 128 - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static const char stat_usage[] = - "perf stat [] []"; - -static const struct option_s stat_options[] = -{ - OPT_STRING('a', "all-cpus", "system-wide collection from all CPUs"), - OPT_STRING('C', "cpu ", "list of cpus to monitor in system-wide"), - OPT_STRING('e', "event ", - "event selector. use 'perf list' to list available events"), - OPT_STRING('p', "pid ", "stat events on existing process id"), -}; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void stat_cmds_help(int sname) -{ - unsigned int i = 0; - unsigned int longest = 0; - - printf("\n Usage: %s\n\n", stat_usage); - - for (i = 0; i < nitems(stat_options); i++) - { - if (longest < strlen(stat_options[i].long_name)) - { - longest = strlen(stat_options[i].long_name); - } - } - - for (i = 0; i < nitems(stat_options); i++) - { - if (!sname || sname == stat_options[i].short_name) - { - printf(" -%c, --%-*s %s\n", stat_options[i].short_name, - longest, stat_options[i].long_name, - stat_options[i].help); - } - } - - printf("\n"); -} - -static void print_counters(FAR struct evlist_s *evlist, - FAR struct timespec *ts) -{ - printf("\n Performance counter stats\n\n"); - - evlist_print_counters(evlist); - - printf("\n %ld.%09ld seconds time elapsed\n", ts->tv_sec, ts->tv_nsec); -} - -static int check_raw_event(FAR char *evstr) -{ - char buf[PERF_STAT_DEFAULT_MAX_EVSTR]; - int evnum = 0; - int cnum = 0; - int i; - int len = strlen(evstr); - - if (len == 1) - { - return 0; - } - - for (i = 0; i <= len; i++) - { - if (evstr[i] == ',' || evstr[i] == '\0') - { - if (strncmp(evstr + cnum, "r", 1)) - { - return 0; - } - - memset(buf, 0, sizeof(buf)); - if (i - cnum > sizeof(buf)) - { - printf("The event name is too long, %d\n", i - cnum); - return 0; - } - - strncpy(buf, evstr + cnum + 1, i - cnum - 1); - if (strlen(buf) == 0) - { - return 0; - } - - if (strspn(buf, "0123456789abcdefABCDEF") != strlen(buf)) - { - return 0; - } - - cnum = i + 1; - evnum++; - } - } - - return evnum; -} - -static int check_hw_cache_event(FAR char *evstr) -{ - char buf[PERF_STAT_DEFAULT_MAX_EVSTR]; - int evnum = 0; - int cnum = 0; - int i; - int len = strlen(evstr); - - for (i = 0; i <= len; i++) - { - if (evstr[i] == ',' || evstr[i] == '\0') - { - memset(buf, 0, sizeof(buf)); - if (i - cnum > sizeof(buf)) - { - printf("The event name is too long, %d\n", i - cnum); - return 0; - } - - strncpy(buf, evstr + cnum, i - cnum); - if (parse_hw_cache_events(buf, NULL) < 0) - { - return 0; - } - - cnum = i + 1; - evnum++; - } - } - - return evnum; -} - -static int check_hw_event(FAR char *evstr) -{ - char buf[PERF_STAT_DEFAULT_MAX_EVSTR]; - int evnum = 0; - int cnum = 0; - int i; - int j; - int len = strlen(evstr); - - for (i = 0; i <= len; i++) - { - if (evstr[i] == ',' || evstr[i] == '\0') - { - memset(buf, 0, sizeof(buf)); - if (i - cnum > sizeof(buf)) - { - printf("The event name is too long, %d\n", i - cnum); - return 0; - } - - strncpy(buf, evstr + cnum, i - cnum); - for (j = 0; j < PERF_COUNT_HW_MAX; j++) - { - if (!strcmp(evsel_hw_names[j], buf)) - { - break; - } - } - - if (j >= PERF_COUNT_HW_MAX) - { - return 0; - } - - cnum = i + 1; - evnum++; - } - } - - return evnum; -} - -static int check_event(FAR char *evstr, FAR int *evnum) -{ - *evnum = check_hw_event(evstr); - if (!(*evnum)) - { - *evnum = check_hw_cache_event(evstr); - if (!(*evnum)) - { - *evnum = check_raw_event(evstr); - if (!(*evnum)) - { - printf("Event syntax error: %s\n", evstr); - return -EINVAL; - } - - return PERF_TYPE_RAW; - } - else - { - return PERF_TYPE_HW_CACHE; - } - } - else - { - return PERF_TYPE_HARDWARE; - } -} - -static int set_specified_raw_attributes(FAR char *evstr, - FAR struct perf_event_attr_s *attrs) -{ - char *ptr = evstr; - int evnum = 0; - - for (ptr++; ; ptr += 2) - { - attrs[evnum].type = PERF_TYPE_RAW; - attrs[evnum].config = strtol(ptr, &ptr, 16); - attrs[evnum].size = sizeof(struct perf_event_attr_s); - attrs[evnum].disabled = 1; - attrs[evnum].inherit = 1; - if (*ptr == '\0') - { - break; - } - - evnum++; - } - - return 0; -} - -static int set_specified_hw_cache_attributes(FAR char *evstr, - FAR struct perf_event_attr_s *attrs) -{ - char buf[PERF_STAT_DEFAULT_MAX_EVSTR]; - uint64_t config; - int evnum = 0; - int cnum = 0; - int i; - int len = strlen(evstr); - - for (i = 0; i <= len; i++) - { - if (evstr[i] == ',' || evstr[i] == '\0') - { - memset(buf, 0, sizeof(buf)); - if (i - cnum > sizeof(buf)) - { - printf("The event name is too long, %d\n", i - cnum); - return -EINVAL; - } - - strncpy(buf, evstr + cnum, i - cnum); - parse_hw_cache_events(buf, &config); - attrs[evnum].type = PERF_TYPE_HW_CACHE; - attrs[evnum].config = config; - attrs[evnum].size = sizeof(struct perf_event_attr_s); - attrs[evnum].disabled = 1; - attrs[evnum].inherit = 1; - cnum = i + 1; - evnum++; - } - } - - return 0; -} - -static int set_specified_hw_attributes(FAR char *evstr, - FAR struct perf_event_attr_s *attrs) -{ - char buf[PERF_STAT_DEFAULT_MAX_EVSTR]; - int evnum = 0; - int cnum = 0; - int i; - int j; - int len = strlen(evstr); - - for (i = 0; i <= len; i++) - { - if (evstr[i] == ',' || evstr[i] == '\0') - { - memset(buf, 0, sizeof(buf)); - if (i - cnum > sizeof(buf)) - { - printf("The event name is too long, %d\n", i - cnum); - return -EINVAL; - } - - strncpy(buf, evstr + cnum, i - cnum); - for (j = 0; j < PERF_COUNT_HW_MAX; j++) - { - if (!strcmp(evsel_hw_names[j], buf)) - { - attrs[evnum].type = PERF_TYPE_HARDWARE; - attrs[evnum].config = j; - attrs[evnum].size = sizeof(struct perf_event_attr_s); - attrs[evnum].disabled = 1; - attrs[evnum].inherit = 1; - break; - } - } - - cnum = i + 1; - evnum++; - } - } - - return 0; -} - -static int add_specified_attributes(FAR struct evlist_s *evlist, - FAR char *evstr) -{ - int i; - int status; - int evnum = 0; - - if (!evstr) - { - return -EINVAL; - } - - status = check_event(evstr, &evnum); - if (status < 0) - { - return -EINVAL; - } - - evlist->attrs = zalloc(evnum * sizeof(struct perf_event_attr_s)); - if (!evlist->attrs) - { - printf("Zalloc attrs failed!\n"); - return -ENOMEM; - } - - if (status == PERF_TYPE_HARDWARE) - { - set_specified_hw_attributes(evstr, evlist->attrs); - } - else if (status == PERF_TYPE_HW_CACHE) - { - set_specified_hw_cache_attributes(evstr, evlist->attrs); - } - else if (status == PERF_TYPE_RAW) - { - set_specified_raw_attributes(evstr, evlist->attrs); - } - - if (evlist->system_wide) - { - for (i = 0; i < CONFIG_SMP_NCPUS; i++) - { - status = evlist_add_attrs(evlist, evlist->attrs, evnum, i); - } - } - else - { - status = evlist_add_attrs(evlist, evlist->attrs, evnum, evlist->cpu); - } - - return status; -} - -static int set_default_attributes(FAR int *config, int nr, - FAR struct perf_event_attr_s *attrs) -{ - int i; - - for (i = 0; i < nr; i++) - { - attrs[i].type = PERF_TYPE_HARDWARE; - attrs[i].config = config[i]; - attrs[i].size = sizeof(struct perf_event_attr_s); - attrs[i].disabled = 1; - attrs[i].inherit = 1; - } - - return 0; -} - -static int add_default_attributes(FAR struct evlist_s *evlist) -{ - int i; - int status = 0; - int evnum = nitems(default_hw_config); - - evlist->attrs = zalloc(evnum * sizeof(struct perf_event_attr_s)); - if (!evlist->attrs) - { - printf("Zalloc attrs failed!\n"); - return -ENOMEM; - } - - set_default_attributes(default_hw_config, evnum, evlist->attrs); - - if (evlist->system_wide) - { - for (i = 0; i < CONFIG_SMP_NCPUS; i++) - { - status = evlist_add_attrs(evlist, evlist->attrs, evnum, i); - } - } - else - { - status = evlist_add_attrs(evlist, evlist->attrs, evnum, evlist->cpu); - } - - return status; -} - -int perf_stat_handle(FAR struct evlist_s *evlist) -{ - int status = 0; - - evlist_for_each_evsel(evlist, node, evsel_count_start, status); - if (status) - { - return status; - } - - if (evlist->cmd_str) - { - status = system(evlist->cmd_str); - if (status) - { - return status; - } - } - else - { - sleep(evlist->sec); - } - - evlist_for_each_evsel(evlist, node, evsel_read_counter, status); - - evlist_for_each_evsel(evlist, node, evsel_count_end, status); - - return status; -} - -static int run_perf_stat(FAR struct evlist_s *evlist, - FAR struct stat_args_s *stat_args) -{ - int status = 0; - int i; - char cmd_str[PERF_STAT_DEFAULT_MAX_CMDSTR]; - struct timespec start_time; - struct timespec end_time; - struct timespec run_time; - - memset(cmd_str, '\0', sizeof(cmd_str)); - - evlist->cpu = stat_args->cpu; - evlist->pid = stat_args->pid; - - if (stat_args->cmd_nr > 0) - { - for (i = 0; i < stat_args->cmd_nr; i++) - { - strcat(cmd_str, stat_args->cmd_args[i]); - strcat(cmd_str, " "); - } - - evlist->cmd_str = cmd_str; - } - - if (stat_args->events) - { - evlist->defult_attrs = false; - status = add_specified_attributes(evlist, stat_args->events); - if (status) - { - stat_cmds_help(0); - return status; - } - } - else - { - evlist->defult_attrs = true; - status = add_default_attributes(evlist); - if (status) - { - return status; - } - } - - clock_gettime(CLOCK_MONOTONIC, &start_time); - - status = perf_stat_handle(evlist); - if (status) - { - return status; - } - - clock_gettime(CLOCK_MONOTONIC, &end_time); - - run_time.tv_sec = end_time.tv_sec - start_time.tv_sec; - run_time.tv_nsec = end_time.tv_nsec - start_time.tv_nsec; - - print_counters(evlist, &run_time); - - return status; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int cmd_stat(int argc, FAR const char **argv) -{ - FAR static struct evlist_s *evlist; - int status = 0; - struct stat_args_s stat_args; - - memset(&stat_args, 0, sizeof(struct stat_args_s)); - - status = parse_stat_options(argc, (char **)argv, &stat_args); - if (status || stat_args.type == STAT_ARGS_HELP) - { - stat_cmds_help(0); - return status; - } - - evlist = evlist_new(); - if (evlist == NULL) - { - return -ENOMEM; - } - - evlist->sec = stat_args.sec; - evlist->type = stat_args.type; - if (stat_args.pid == -1 && stat_args.cpu == -1) - { - evlist->system_wide = true; - } - else - { - evlist->system_wide = false; - } - - status = run_perf_stat(evlist, &stat_args); - - evlist_delete(evlist); - - return status; -} diff --git a/system/perf-tools/builtin.h b/system/perf-tools/builtin.h deleted file mode 100644 index 5550bbf09..000000000 --- a/system/perf-tools/builtin.h +++ /dev/null @@ -1,47 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/builtin.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_PERF_TOOLS_BUILTIN_H -#define __APPS_SYSTEM_PERF_TOOLS_BUILTIN_H - -/**************************************************************************** - * Public Definitions - ****************************************************************************/ - -#define PERF_DEFAULT_RUN_TIME 5 - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -extern const char perf_usage_string[]; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -void cmd_list_help(void); -int cmd_help(int argc, FAR const char **argv); -int cmd_list(int argc, FAR const char **argv); -int cmd_record(int argc, FAR const char **argv); -int cmd_stat(int argc, FAR const char **argv); -int cmd_version(int argc, FAR const char **argv); - -#endif /* __APPS_SYSTEM_PERF_TOOLS_BUILTIN_H */ diff --git a/system/perf-tools/evlist.c b/system/perf-tools/evlist.c deleted file mode 100644 index 911ed87aa..000000000 --- a/system/perf-tools/evlist.c +++ /dev/null @@ -1,176 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/evlist.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -#include "evlist.h" -#include "evsel.h" - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void perf_evlist_init(FAR struct perf_evlist_s *evlist) -{ - list_initialize(&evlist->entries); - evlist->nr_entries = 0; -} - -static void perf_evlist_add(FAR struct perf_evlist_s *evlist, - FAR struct perf_evsel_s *evsel) -{ - list_add_tail(&evlist->entries, &evsel->node); - evlist->nr_entries += 1; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -void evlist_init(FAR struct evlist_s *evlist) -{ - perf_evlist_init(&evlist->core); -} - -FAR struct evlist_s *evlist_new(void) -{ - FAR struct evlist_s *evlist = zalloc(sizeof(struct evlist_s)); - - if (evlist != NULL) - { - evlist_init(evlist); - } - - return evlist; -} - -int evlist_delete(FAR struct evlist_s *evlist) -{ - if (evlist == NULL) - { - return -EINVAL; - } - - evlist->core.nr_entries = 0; - - free(evlist->attrs); - free(evlist); - - return 0; -} - -void evlist_add(FAR struct evlist_s *evlist, FAR struct evsel_s *entry) -{ - perf_evlist_add(&evlist->core, &entry->core); - entry->evlist = evlist; -} - -int evlist_add_attrs(FAR struct evlist_s *evlist, - FAR struct perf_event_attr_s *attrs, - size_t nr_attrs, int cpu) -{ - FAR struct evsel_s *evsel; - FAR struct list_node *node; - size_t i; - - for (i = 0; i < nr_attrs; i++) - { - evsel = evsel_new(attrs + i); - if (evsel == NULL) - { - goto out_delete; - } - - evsel->core.cpu = cpu; - evsel->core.pid = evlist->pid; - evlist_add(evlist, evsel); - } - - return 0; - -out_delete: - list_for_every(&(evlist->core.entries), node) - { - FAR struct perf_evsel_s *psel; - psel = container_of(node, struct perf_evsel_s, node); - evsel = container_of(psel, struct evsel_s, core); - evsel_delete(evsel); - } - - return -ENOMEM; -} - -int evlist_print_counters(FAR struct evlist_s *evlist) -{ - FAR struct perf_evsel_s *psel = NULL; - FAR struct evsel_s *evsel = NULL; - FAR struct list_node *node = NULL; -#if (CONFIG_SMP_NCPUS > 1) - struct evlist_count_s *evcnt = NULL; - int i = 0; - - if (evlist->system_wide) - { - int num = evlist->core.nr_entries / CONFIG_SMP_NCPUS; - evcnt = zalloc(num * sizeof(struct evlist_count_s)); - if (!evcnt) - { - return -ENOMEM; - } - - list_for_every(&(evlist->core.entries), node) - { - psel = container_of(node, struct perf_evsel_s, node); - evsel = container_of(psel, struct evsel_s, core); - evcnt[i % num].count += evsel->core.count; - if (i < num) - { - evcnt[i].name = evsel_name(evsel); - } - - i++; - } - - for (i = 0; i < num; i++) - { - printf("%10ld\t %s\n", evcnt[i].count, evcnt[i].name); - } - - free(evcnt); - } - else -#endif - { - list_for_every(&(evlist->core.entries), node) - { - psel = container_of(node, struct perf_evsel_s, node); - evsel = container_of(psel, struct evsel_s, core); - printf("%10ld\t %s\n", evsel->core.count, evsel_name(evsel)); - } - } - - return 0; -} diff --git a/system/perf-tools/evlist.h b/system/perf-tools/evlist.h deleted file mode 100644 index ee3ecb7a5..000000000 --- a/system/perf-tools/evlist.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/evlist.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_PERF_TOOLS_EVLIST_H -#define __APPS_SYSTEM_PERF_TOOLS_EVLIST_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -#include "builtin.h" -#include "evsel.h" - -/**************************************************************************** - * Public Definitions - ****************************************************************************/ - -struct perf_evlist_s -{ - struct list_node entries; - int nr_entries; -}; - -struct evlist_s -{ - struct perf_evlist_s core; - int sec; - int cpu; - int pid; - FAR char *cmd_str; - int type; - bool system_wide; - bool defult_attrs; - FAR struct perf_event_attr_s *attrs; -}; - -struct evlist_count_s -{ - uint64_t count; - FAR const char *name; -}; - -#define evlist_for_each_evsel(evlist, node, func, status) \ - do { \ - FAR struct perf_evsel_s *psel = NULL; \ - FAR struct evsel_s *evsel = NULL; \ - FAR struct list_node *node; \ - FAR struct list_node *list = &(evlist->core.entries); \ - for(node = (list)->next; node != (list); node = node->next) \ - { \ - psel = container_of(node, struct perf_evsel_s, node), \ - evsel = container_of(psel, struct evsel_s, core); \ - status = func(evsel, evlist); \ - } \ - } while(0) - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int evlist_delete(FAR struct evlist_s *evlist); -FAR struct evlist_s *evlist_new(void); -int evlist_add_attrs(FAR struct evlist_s *evlist, - FAR struct perf_event_attr_s *attrs, - size_t nr_attrs, int cpu); -int evlist_print_counters(FAR struct evlist_s *evlist); - -#endif /* __APPS_SYSTEM_PERF_TOOLS_EVLIST_H */ diff --git a/system/perf-tools/evsel.c b/system/perf-tools/evsel.c deleted file mode 100644 index 5961966b6..000000000 --- a/system/perf-tools/evsel.c +++ /dev/null @@ -1,470 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/evsel.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include -#include -#include - -#include "evsel.h" - -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define C(x) PERF_COUNT_HW_CACHE_##x -#define CACHE_READ (1 << C(OP_READ)) -#define CACHE_WRITE (1 << C(OP_WRITE)) -#define CACHE_PREFETCH (1 << C(OP_PREFETCH)) -#define COP(x) (1 << x) - -/**************************************************************************** - * Private data - ****************************************************************************/ - -/**************************************************************************** - * cache operation stat - * L1I : Read and prefetch only - * ITLB and BPU : Read-only - ****************************************************************************/ - -const unsigned long evsel_hw_cache_stat[C(MAX)] = -{ - [C(L1D)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH), - [C(L1I)] = (CACHE_READ | CACHE_PREFETCH), - [C(LL)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH), - [C(DTLB)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH), - [C(ITLB)] = (CACHE_READ), - [C(BPU)] = (CACHE_READ), - [C(NODE)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH), -}; - -FAR const char *evsel_hw_cache[PERF_COUNT_HW_CACHE_MAX] = -{ - [PERF_COUNT_HW_CACHE_L1D] = "L1-dcache", - [PERF_COUNT_HW_CACHE_L1I] = "L1-icache", - [PERF_COUNT_HW_CACHE_LL] = "LLC", - [PERF_COUNT_HW_CACHE_DTLB] = "dTLB", - [PERF_COUNT_HW_CACHE_ITLB] = "iTLB", - [PERF_COUNT_HW_CACHE_BPU] = "branch", - [PERF_COUNT_HW_CACHE_NODE] = "node", -}; - -FAR const char *evsel_hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX] = -{ - [PERF_COUNT_HW_CACHE_OP_READ] = "load", - [PERF_COUNT_HW_CACHE_OP_WRITE] = "store", - [PERF_COUNT_HW_CACHE_OP_PREFETCH] = "prefetch", -}; - -const char *evsel_hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX] = -{ - [PERF_COUNT_HW_CACHE_RESULT_ACCESS] = "refs", - [PERF_COUNT_HW_CACHE_RESULT_MISS] = "misses", -}; - -/**************************************************************************** - * Public data - ****************************************************************************/ - -FAR const char *const evsel_hw_names[PERF_COUNT_HW_MAX] = -{ - "cycles", - "instructions", - "cache-references", - "cache-misses", - "branches", - "branch-misses", - "bus-cycles", - "stalled-cycles-frontend", - "stalled-cycles-backend", - "ref-cycles", -}; - -int default_hw_config[DEFAULT_HW_CONFIG_NUM] = -{ - PERF_COUNT_HW_CPU_CYCLES, - PERF_COUNT_HW_INSTRUCTIONS, - PERF_COUNT_HW_BRANCH_INSTRUCTIONS, - PERF_COUNT_HW_BRANCH_MISSES, -}; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static void perf_evsel_init(FAR struct perf_evsel_s *evsel, - FAR struct perf_event_attr_s *attr) -{ - list_initialize(&evsel->node); - evsel->attr = *attr; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int parse_aliases(FAR const char *str, - FAR const char *const names[], - int size, FAR int *longest) -{ - int n; - int i; - - *longest = -1; - for (i = 0; i < size; i++) - { - n = strlen(names[i]); - if (n > *longest && !strncasecmp(str, names[i], n)) - { - *longest = n; - } - - if (*longest > 0) - { - return i; - } - } - - return -1; -} - -int parse_hw_cache_events(FAR const char *name, FAR uint64_t *config) -{ - int len; - int cache_type = -1; - int cache_op = -1; - int cache_result = -1; - const char *str = name; - const char *name_end = &name[strlen(name) + 1]; - - cache_type = parse_aliases(str, evsel_hw_cache, - PERF_COUNT_HW_CACHE_MAX, &len); - if (cache_type == -1) - { - return -EINVAL; - } - - str += len + 1; - if (str < name_end) - { - cache_op = parse_aliases(str, evsel_hw_cache_op, - PERF_COUNT_HW_CACHE_OP_MAX, &len); - if (cache_op >= 0) - { - if (!evsel_is_cache_op_valid(cache_type, cache_op)) - { - return -EINVAL; - } - - str += len + 1; - } - else - { - return -EINVAL; - } - } - - if (str < name_end) - { - cache_result = parse_aliases(str, evsel_hw_cache_result, - PERF_COUNT_HW_CACHE_RESULT_MAX, &len); - if (cache_result < 0) - { - return -EINVAL; - } - } - - if (cache_op == -1) - { - cache_op = PERF_COUNT_HW_CACHE_OP_READ; - } - - if (cache_result == -1) - { - cache_result = PERF_COUNT_HW_CACHE_RESULT_ACCESS; - } - - if (config) - { - *config = cache_type | (cache_op << 8) | (cache_result << 16); - } - - return 0; -} - -int evsel_hw_cache_type_op_res_name(uint8_t type, uint8_t op, uint8_t result, - FAR char *bf, size_t size) -{ - if (result) - { - return snprintf(bf, size, "%s-%s-%s", evsel_hw_cache[type], - evsel_hw_cache_op[op], - evsel_hw_cache_result[result]); - } - - return snprintf(bf, size, "%s-%s", evsel_hw_cache[type], - evsel_hw_cache_op[op]); -} - -bool evsel_is_cache_op_valid(uint8_t type, uint8_t op) -{ - if (evsel_hw_cache_stat[type] & COP(op)) - { - return true; - } - else - { - return false; - } -} - -int evsel_hw_cache_name(FAR struct evsel_s *evsel, FAR char *buf, - size_t size) -{ - uint64_t config = evsel->core.attr.config; - uint8_t op; - uint8_t result; - uint8_t type = (config >> 0) & 0xff; - const char *err = "unknown-ext-hardware-cache-type"; - - if (type >= PERF_COUNT_HW_CACHE_MAX) - { - goto out_err; - } - - op = (config >> 8) & 0xff; - err = "unknown-ext-hardware-cache-op"; - if (op >= PERF_COUNT_HW_CACHE_OP_MAX) - { - goto out_err; - } - - result = (config >> 16) & 0xff; - err = "unknown-ext-hardware-cache-result"; - if (result >= PERF_COUNT_HW_CACHE_RESULT_MAX) - { - goto out_err; - } - - err = "invalid-cache"; - if (!evsel_is_cache_op_valid(type, op)) - { - goto out_err; - } - - return evsel_hw_cache_type_op_res_name(type, op, result, buf, size); - -out_err: - return snprintf(buf, size, "%s", err); -} - -int evsel_raw_name(FAR struct evsel_s *evsel, FAR char *buf, - size_t size) -{ - return snprintf(buf, size, "r%" PRIx64, evsel->core.attr.config); -} - -int evsel_hw_name(FAR struct evsel_s *evsel, FAR char *buf, - size_t size) -{ - uint64_t config = evsel->core.attr.config; - - if (config < PERF_COUNT_HW_MAX && evsel_hw_names[config]) - { - return snprintf(buf, size, "%s", evsel_hw_names[config]); - } - else - { - return snprintf(buf, size, "%s", "unknown-hardware"); - } -} - -FAR const char *evsel_name(FAR struct evsel_s *evsel) -{ - char buf[128]; - - if (!evsel) - { - goto out_unknown; - } - - switch (evsel->core.attr.type) - { - case PERF_TYPE_HARDWARE: - evsel_hw_name(evsel, buf, sizeof(buf)); - break; - case PERF_TYPE_HW_CACHE: - evsel_hw_cache_name(evsel, buf, sizeof(buf)); - break; - case PERF_TYPE_RAW: - evsel_raw_name(evsel, buf, sizeof(buf)); - break; - default: - snprintf(buf, sizeof(buf), "unknown attr type: %d", - evsel->core.attr.type); - break; - } - - evsel->name = strdup(buf); - if (evsel->name) - { - return evsel->name; - } - -out_unknown: - return "unknown"; -} - -void evsel_init(FAR struct evsel_s *evsel, - FAR struct perf_event_attr_s *attr) -{ - perf_evsel_init(&evsel->core, attr); - evsel->evlist = NULL; -} - -FAR struct evsel_s *evsel_new(FAR struct perf_event_attr_s *attr) -{ - FAR struct evsel_s *evsel = zalloc(sizeof(struct evsel_s)); - - if (!evsel) - { - return NULL; - } - - evsel_init(evsel, attr); - - return evsel; -} - -void evsel_delete(FAR struct evsel_s *evsel) -{ - if (!evsel) - { - return; - } - - free(evsel); -} - -int evsel_read_counter(FAR struct evsel_s *evsel, - FAR struct evlist_s *evlist) -{ - uint64_t count; - - if (read(evsel->core.evfd, &count, sizeof(count)) < 0) - { - return -EINVAL; - } - - evsel->core.count = count; - - return 0; -} - -int evsel_open(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - evsel->core.evfd = perf_event_open(&evsel->core.attr, evsel->core.pid, - evsel->core.cpu, -1, O_CLOEXEC); - if (evsel->core.evfd < 0) - { - return -ENOENT; - } - - return 0; -} - -int evsel_close(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - if (evsel->core.evfd < 0) - { - return -EINVAL; - } - - close(evsel->core.evfd); - - return 0; -} - -int evsel_reset(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - if (evsel->core.evfd < 0) - { - return -EINVAL; - } - - ioctl(evsel->core.evfd, PERF_EVENT_IOC_RESET, 0); - - return 0; -} - -int evsel_enable(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - if (evsel->core.evfd < 0) - { - return -EINVAL; - } - - ioctl(evsel->core.evfd, PERF_EVENT_IOC_ENABLE, 0); - - return 0; -} - -int evsel_disable(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - if (evsel->core.evfd < 0) - { - return -EINVAL; - } - - ioctl(evsel->core.evfd, PERF_EVENT_IOC_DISABLE, 0); - - return 0; -} - -int evsel_count_start(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - int status; - - status = evsel_open(evsel, evlist); - if (status) - { - return status; - } - - evsel_reset(evsel, evlist); - evsel_enable(evsel, evlist); - - return status; -} - -int evsel_count_end(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist) -{ - evsel_disable(evsel, evlist); - evsel_close(evsel, evlist); - - return 0; -} diff --git a/system/perf-tools/evsel.h b/system/perf-tools/evsel.h deleted file mode 100644 index 4805aa945..000000000 --- a/system/perf-tools/evsel.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/evsel.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_PERF_TOOLS_EVSEL_H -#define __APPS_SYSTEM_PERF_TOOLS_EVSEL_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include - -#include "evlist.h" - -/**************************************************************************** - * Public Definitions - ****************************************************************************/ - -struct perf_evsel_s -{ - struct list_node node; - struct perf_event_attr_s attr; - int evfd; - int cpu; - int pid; - uint64_t count; -}; - -struct evsel_s -{ - struct perf_evsel_s core; - FAR struct evlist_s *evlist; - FAR char *name; -}; - -#define DEFAULT_HW_CONFIG_NUM 4 - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -FAR extern const char *const evsel_hw_names[PERF_COUNT_HW_MAX]; -extern int default_hw_config[DEFAULT_HW_CONFIG_NUM]; -FAR extern const char *evsel_hw_cache[PERF_COUNT_HW_CACHE_MAX]; -FAR extern const char *evsel_hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX]; -FAR extern const char *evsel_hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX]; - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int parse_hw_cache_events(FAR const char *name, FAR uint64_t *config); -int evsel_hw_cache_type_op_res_name(uint8_t type, uint8_t op, uint8_t result, - FAR char *bf, size_t size); -bool evsel_is_cache_op_valid(uint8_t type, uint8_t op); -int evsel_hw_cache_name(FAR struct evsel_s *evsel, FAR char *buf, - size_t size); -FAR const char *evsel_name(FAR struct evsel_s *evsel); -FAR struct evsel_s *evsel_new(FAR struct perf_event_attr_s *attr); -void evsel_delete(FAR struct evsel_s *evsel); -int evsel_read_counter(FAR struct evsel_s *evsel, - FAR struct evlist_s *evlist); -int evsel_open(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); -int evsel_close(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); -int evsel_reset(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); -int evsel_enable(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); -int evsel_disable(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); -int evsel_count_start(FAR struct evsel_s *evsel, - FAR struct evlist_s *evlist); -int evsel_count_end(FAR struct evsel_s *evsel, FAR struct evlist_s *evlist); - -#endif /* __APPS_SYSTEM_PERF_TOOLS_EVSEL_H */ diff --git a/system/perf-tools/parse-options.c b/system/perf-tools/parse-options.c deleted file mode 100644 index bf58f6c66..000000000 --- a/system/perf-tools/parse-options.c +++ /dev/null @@ -1,241 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/parse-options.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include - -#include "builtin.h" -#include "parse-options.h" - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int check_and_atoi(char *arg) -{ - int i; - - for (i = 0; arg[i] != '\0'; i++) - { - if (!isdigit(arg[i])) - { - return -EINVAL; - } - } - - return atoi(arg); -} - -int parse_stat_options(int argc, FAR char **argv, - FAR struct stat_args_s *stat_args) -{ - int opt; - int ret; - - stat_args->cmd_nr = argc; - - while ((opt = getopt(argc, argv, ":aC:p:e:")) != -1) - { - switch (opt) - { - case 'a': - if (stat_args->type == STAT_ARGS_NONE || - stat_args->type == STAT_ARGS_CPU) - { - stat_args->type = STAT_ARGS_ALL; - stat_args->cpu = -1; - stat_args->pid = -1; - stat_args->events = NULL; - } - - stat_args->cmd_nr -= 2; - break; - case 'C': - if (stat_args->type == STAT_ARGS_NONE) - { - stat_args->type = STAT_ARGS_CPU; - stat_args->cpu = check_and_atoi(optarg); - stat_args->pid = -1; - stat_args->events = NULL; - } - else if (stat_args->type == STAT_ARGS_EVENT) - { - stat_args->cpu = check_and_atoi(optarg); - stat_args->pid = -1; - stat_args->cmd_nr += 1; - } - else if (stat_args->type == STAT_ARGS_TASK) - { - printf("PID/TID switch overriding CPU\n"); - stat_args->cpu = check_and_atoi(optarg); - stat_args->cmd_nr += 1; - } - - stat_args->cmd_nr -= 3; - break; - case 'p': - if (stat_args->type == STAT_ARGS_NONE) - { - stat_args->type = STAT_ARGS_TASK; - stat_args->pid = check_and_atoi(optarg); - stat_args->cpu = -1; - stat_args->events = NULL; - } - else if (stat_args->type == STAT_ARGS_EVENT) - { - stat_args->pid = check_and_atoi(optarg); - stat_args->cpu = -1; - stat_args->cmd_nr += 1; - } - else if (stat_args->type == STAT_ARGS_CPU) - { - printf("PID/TID switch overriding CPU\n"); - stat_args->type = STAT_ARGS_TASK; - stat_args->pid = check_and_atoi(optarg); - stat_args->cmd_nr += 1; - } - - stat_args->cmd_nr -= 3; - break; - case 'e': - if (stat_args->type == STAT_ARGS_NONE || - stat_args->type == STAT_ARGS_ALL) - { - stat_args->cpu = -1; - stat_args->pid = -1; - } - else if (stat_args->type == STAT_ARGS_CPU) - { - stat_args->pid = -1; - stat_args->cmd_nr += 1; - } - else if (stat_args->type == STAT_ARGS_TASK) - { - stat_args->cmd_nr += 1; - } - - stat_args->type = STAT_ARGS_EVENT; - stat_args->events = optarg; - stat_args->cmd_nr -= 3; - break; - case 'h': - stat_args->type = STAT_ARGS_HELP; - break; - default: - return -EINVAL; - } - } - - stat_args->sec = PERF_DEFAULT_RUN_TIME; - stat_args->cmd = argv[optind]; - stat_args->cmd_args = &argv[optind]; - - if (argc == 1) - { - stat_args->type = STAT_ARGS_ALL; - stat_args->cpu = -1; - stat_args->pid = -1; - stat_args->events = NULL; - stat_args->cmd_nr -= 1; - } - else if (stat_args->cmd_nr > 0) - { - if (!strcmp(stat_args->cmd, "sleep")) - { - if (stat_args->type == STAT_ARGS_NONE) - { - stat_args->cpu = -1; - stat_args->pid = -1; - stat_args->events = NULL; - stat_args->cmd_nr -= 1; - } - - if (stat_args->cmd_nr == 2) - { - stat_args->sec = check_and_atoi(stat_args->cmd_args[1]); - if (stat_args->sec < 0) - { - return -EINVAL; - } - } - else - { - printf("sleep: invalid time interval\n"); - return -EINVAL; - } - - stat_args->cmd = NULL; - stat_args->cmd_nr = 0; - } - else - { - if (stat_args->type == STAT_ARGS_NONE) - { - stat_args->type = STAT_ARGS_FORK; - stat_args->cpu = -1; - stat_args->pid = _SCHED_GETPID(); - stat_args->events = NULL; - stat_args->cmd_nr -= 1; - } - else if (stat_args->type == STAT_ARGS_CPU || - stat_args->type == STAT_ARGS_EVENT) - { - stat_args->type = STAT_ARGS_FORK; - stat_args->pid = _SCHED_GETPID(); - } - else if (stat_args->type == STAT_ARGS_TASK) - { - stat_args->cmd = NULL; - stat_args->cmd_nr = 0; - } - } - } - - if (stat_args->cpu >= CONFIG_SMP_NCPUS || stat_args->cpu < -1) - { - printf(" Perf can support %d CPUs.\n", CONFIG_SMP_NCPUS); - return -EINVAL; - } - - if (stat_args->pid > 0) - { - ret = kill(stat_args->pid, 0); - if (ret == -1 && errno == ESRCH) - { - printf("The specified process does not exist\n"); - return -EINVAL; - } - else if (ret != 0) - { - printf("Error trying to determine whether the process exists\n"); - } - } - else if (stat_args->pid != -1) - { - return -EINVAL; - } - - return 0; -} diff --git a/system/perf-tools/parse-options.h b/system/perf-tools/parse-options.h deleted file mode 100644 index 5d49942eb..000000000 --- a/system/perf-tools/parse-options.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/parse-options.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_PERF_TOOLS_PARSE_OPTIONS_H -#define __APPS_SYSTEM_PERF_TOOLS_PARSE_OPTIONS_H - -/**************************************************************************** - * Public Definitions - ****************************************************************************/ - -enum parse_opt_type_e -{ - OPTION_END, - OPTION_ARGUMENT, - OPTION_STRING, -}; - -struct option_s -{ - enum parse_opt_type_e type; - int short_name; - FAR const char *long_name; - FAR const char *help; -}; - -enum args_type_e -{ - STAT_ARGS_NONE, - STAT_ARGS_ALL, - STAT_ARGS_CPU, - STAT_ARGS_EVENT, - STAT_ARGS_TASK, - STAT_ARGS_FORK, - STAT_ARGS_HELP, -}; - -struct stat_args_s -{ - enum args_type_e type; - int cpu; - int pid; - FAR char *events; - FAR char *cmd; - FAR char **cmd_args; - int cmd_nr; - int sec; -}; - -#define OPT_ARGUMENT(l, h) \ - { .type = OPTION_ARGUMENT, .long_name = (l), .help = (h) } -#define OPT_STRING(s, l, h) \ - { .type = OPTION_STRING, .short_name = (s), .long_name = (l), .help = (h) } - -/**************************************************************************** - * Public Function Prototypes - ****************************************************************************/ - -int parse_stat_options(int argc, FAR char **argv, - FAR struct stat_args_s *stat_args); - -#endif /* __APPS_SYSTEM_PERF_TOOLS_PARSE_OPTIONS_H */ diff --git a/system/perf-tools/perf.c b/system/perf-tools/perf.c deleted file mode 100644 index f1095ad81..000000000 --- a/system/perf-tools/perf.c +++ /dev/null @@ -1,213 +0,0 @@ -/**************************************************************************** - * apps/system/perf-tools/perf.c - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include -#include -#include -#include - -#include - -#include "builtin.h" -#include "parse-options.h" - -/**************************************************************************** - * Private Types - ****************************************************************************/ - -struct cmd_struct_s -{ - FAR const char *cmd; - FAR int (*fn)(int, FAR const char **); - int option; -}; - -/**************************************************************************** - * Private Data - ****************************************************************************/ - -static struct cmd_struct_s commands[] = -{ - { "help", cmd_help, 0 }, - { "list", cmd_list, 0 }, - { "record", cmd_record, 0 }, - { "stat", cmd_stat, 0 }, - { "version", cmd_version, 0 }, -}; - -static struct option_s options[] = -{ - OPT_ARGUMENT("help", "help"), - OPT_ARGUMENT("version", "version"), - OPT_ARGUMENT("list-cmds", "list-cmds"), - OPT_ARGUMENT("list-opts", "list-opts"), -}; - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -const char perf_usage_string[] = - "perf [--version] [--help] [OPTIONS] COMMAND [ARGS]"; - -/**************************************************************************** - * Private Functions - ****************************************************************************/ - -static inline bool strstarts(FAR const char *str, FAR const char *prefix) -{ - return strncmp(str, prefix, strlen(prefix)) == 0; -} - -static int run_argv(int argc, FAR const char **argv) -{ - FAR const char *cmd = argv[0]; - unsigned int i; - - /* Turn "perf cmd --help" into "perf help cmd" */ - - if (argc > 1 && !strcmp(argv[1], "--help")) - { - argv[1] = argv[0]; - argv[0] = cmd = "help"; - } - - for (i = 0; i < nitems(commands); i++) - { - FAR struct cmd_struct_s *p = commands + i; - if (p->fn == NULL) - { - continue; - } - - if (strcmp(p->cmd, cmd)) - { - continue; - } - - exit(p->fn(argc, argv)); - } - - printf("perf: '%s' is not a perf-command. See 'perf --help'.\n", cmd); - exit(-EINVAL); -} - -static int handle_options(FAR const char ***argv, FAR int *argc) -{ - int handled = 0; - - while (*argc > 0) - { - const char *cmd = (*argv)[0]; - if (cmd[0] != '-') - { - break; - } - - if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version")) - { - break; - } - - if (!strcmp(cmd, "-h")) - { - (*argv)[0] = "--help"; - break; - } - - if (!strcmp(cmd, "-v")) - { - (*argv)[0] = "--version"; - break; - } - - if (!strcmp(cmd, "--list-cmds")) - { - unsigned int i; - - for (i = 0; i < nitems(commands); i++) - { - FAR struct cmd_struct_s *p = commands + i; - printf("%s ", p->cmd); - } - - printf("\n"); - exit(0); - } - else if (!strcmp(cmd, "--list-opts")) - { - unsigned int i; - - for (i = 0; i < nitems(options); i++) - { - FAR struct option_s *p = options + i; - printf("--%s ", p->long_name); - } - - printf("\n"); - exit(0); - } - else - { - fprintf(stderr, "Unknown option: %s\n", cmd); - fprintf(stderr, "\n Usage: %s\n", perf_usage_string); - exit(-EINVAL); - } - - (*argv)++; - (*argc)--; - handled++; - } - - return handled; -} - -/**************************************************************************** - * Public Functions - ****************************************************************************/ - -int main(int argc, FAR const char **argv) -{ - argv++; - argc--; - handle_options(&argv, &argc); - - if (argc == 0) - { - cmd_list_help(); - return 0; - } - - if (strstarts(argv[0], "--")) - { - argv[0] += 2; - } - - while (1) - { - run_argv(argc, argv); - } - - return 0; -} diff --git a/system/popen/popen.c b/system/popen/popen.c index a873f3864..254f86ae6 100644 --- a/system/popen/popen.c +++ b/system/popen/popen.c @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -323,7 +322,7 @@ FILE *popen(FAR const char *command, FAR const char *mode) if (strchr(mode, 'e') == NULL) { - ioctl(retfd, FIOCLEX, 0); + fcntl(retfd, F_SETFD, 0); } /* Finale and return input input/output stream */ diff --git a/system/psmq/README.md b/system/psmq/README.md deleted file mode 100644 index 0e0d585a6..000000000 --- a/system/psmq/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# System / `psmq` Publish Subscribe Message Queue - -`psmq` is publish subscribe message queue. It's a set of programs and libraries -to implement publish/subscribe way of inter-process communication on top of -POSIX message queue. - -Manuals, source code and more info at: https://psmq.bofc.pl - -Little demo using `psmqd` broker, `psmq_pub` and `psmq_sub`: - -Start broker and make it log to file - -``` -nsh> psmqd -b/brok -p/sd/psmqd/psmqd.log & -``` - -Start subscribe thread that will read all messages send on `/can/*` and -`/adc/*` topic, and dump all readings to file - -``` -nsh> psmq_sub -n/sub -b/brok -t/can/* -t/adc/* -o/sd/psmq-sub/can.log & -n/connected to broker /brok -n/subscribed to: /can/* -n/subscribed to: /adc/* -n/start receiving data -n/reply timeout set 100 -``` - -Publish some messages - -``` -nsh> psmq_pub -b/brok -t/can/engine/rpm -m50 -nsh> psmq_pub -b/brok -t/adc/volt -m30 -nsh> psmq_pub -b/brok -t/can/room/10/temp -m23 -nsh> psmq_pub -b/brok -t/pwm/fan1/speed -m300 -``` - -Check out subscribe thread logs - -``` -nsh> cat /sd/psmq-sub/can.log -``` - -``` -[2021-05-23 17:53:59] p:0 l: 3 /can/engine/rpm 50 -[2021-05-23 17:53:59] p:0 l: 3 /adc/volt 30 -[2021-05-23 17:53:59] p:0 l: 3 /can/room/10/temp 23 -``` - -As you can see `/pwm/fan1/speed` hasn't been received by subscribe thread, -since we didn't subscribe to it. - -Content: - -- `psmqd` – broker, relays messages between clients. -- `psmq_sub` – listens to specified topics, can be used as logger for - communication (optional). -- `psmq_pub` – publishes messages directly from shell. Can send binary data, but - requires pipes, so on nuttx it can only send ASCII. -- `libpsmq` – library used to communicate with the broker and send/receive - messages. diff --git a/system/ptpd/Kconfig b/system/ptpd/Kconfig index d65216c61..e213b132a 100644 --- a/system/ptpd/Kconfig +++ b/system/ptpd/Kconfig @@ -10,7 +10,6 @@ config SYSTEM_PTPD ---help--- Enable 'ptpd' command to start the PTP daemon - if SYSTEM_PTPD config SYSTEM_PTPD_PRIORITY diff --git a/system/sched_note/note_main.c b/system/sched_note/note_main.c index 2f0691796..661af30ba 100644 --- a/system/sched_note/note_main.c +++ b/system/sched_note/note_main.c @@ -36,6 +36,15 @@ #include +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +# define syslog_time(priority, fmt, ...) \ + syslog(priority, "%08lx: " fmt, \ + (unsigned long)systime, \ + __VA_ARGS__) + /**************************************************************************** * Private Data ****************************************************************************/ @@ -43,6 +52,723 @@ static bool g_note_daemon_started; static uint8_t g_note_buffer[CONFIG_SYSTEM_NOTE_BUFFERSIZE]; +/* Names of task/thread states */ + +#ifdef CONFIG_SCHED_INSTRUMENTATION_SWITCH +static FAR const char *g_statenames[] = +{ + "Invalid", + "Waiting for Unlock", + "Ready", + "Running", + "Inactive", + "Waiting for Semaphore", + "Waiting for Signal", +#ifndef CONFIG_DISABLE_MQUEUE + "Waiting for MQ empty", + "Waiting for MQ full" +#endif +}; + +#define NSTATES (sizeof(g_statenames)/sizeof(FAR const char *)) +#endif + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: trace_dump_unflatten + ****************************************************************************/ + +static void trace_dump_unflatten(FAR void *dst, + FAR uint8_t *src, size_t len) +{ +#ifdef CONFIG_ENDIAN_BIG + FAR uint8_t *end = (FAR uint8_t *)dst + len - 1; + while (len-- > 0) + { + *end-- = *src++; + } +#else + memcpy(dst, src, len); +#endif +} + +/**************************************************************************** + * Name: dump_notes + ****************************************************************************/ + +static void dump_notes(size_t nread) +{ + FAR struct note_common_s *note; + uint32_t systime_sec; + uint32_t systime_nsec; + pid_t pid; + off_t offset; + + offset = 0; + while (offset < nread) + { + note = (FAR struct note_common_s *)&g_note_buffer[offset]; + trace_dump_unflatten(&pid, note->nc_pid, sizeof(pid)); + trace_dump_unflatten(&systime_nsec, + note->nc_systime_nsec, sizeof(systime_nsec)); + trace_dump_unflatten(&systime_sec, + note->nc_systime_sec, sizeof(systime_sec)); + + switch (note->nc_type) + { + case NOTE_START: + { + FAR struct note_start_s *note_start = + (FAR struct note_start_s *)note; + + if (note->nc_length < sizeof(struct note_start_s)) + { + syslog(LOG_ERR, + "Note too small for \"Start\" note: %d\n", + note->nc_length); + return; + } + +#ifdef CONFIG_SMP +#if CONFIG_TASK_NAME_SIZE > 0 + syslog_time(LOG_INFO, + "Task %u \"%s\" started, CPU%u, priority %u\n", + (unsigned int)pid, + note_start->nst_name, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); +#else + syslog_time(LOG_INFO, + "Task %u started, CPU%u, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); +#endif +#else +#if CONFIG_TASK_NAME_SIZE > 0 + syslog_time(LOG_INFO, + "Task %u \"%s\" started, priority %u\n", + (unsigned int)pid, + note_start->nst_name, (unsigned int)note->nc_priority); +#else + syslog_time(LOG_INFO, + "Task %u started, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority); +#endif +#endif + } + break; + + case NOTE_STOP: + { + if (note->nc_length != sizeof(struct note_stop_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"Stop\" note: %d\n", + note->nc_length); + return; + } + +#ifdef CONFIG_SMP + syslog_time(LOG_INFO, + "Task %u stopped, CPU%u, priority %u\n", + (unsigned int)pid, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); +#else + syslog_time(LOG_INFO, + "Task %u stopped, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority); +#endif + } + break; + +#ifdef CONFIG_SCHED_INSTRUMENTATION_SWITCH + case NOTE_SUSPEND: + { + FAR struct note_suspend_s *note_suspend = + (FAR struct note_suspend_s *)note; + FAR const char *statename; + + if (note->nc_length != sizeof(struct note_suspend_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"Suspend\" note: %d\n", + note->nc_length); + return; + } + + if (note_suspend->nsu_state < NSTATES) + { + statename = g_statenames[note_suspend->nsu_state]; + } + else + { + statename = "ERROR"; + } + +#ifdef CONFIG_SMP + syslog_time(LOG_INFO, + "Task %u suspended, CPU%u, priority %u, state \"%s\"\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority, statename); +#else + syslog_time(LOG_INFO, + "Task %u suspended, priority %u, state \"%s\"\n", + (unsigned int)pid, + (unsigned int)note->nc_priority, statename); +#endif + } + break; + + case NOTE_RESUME: + { + if (note->nc_length != sizeof(struct note_resume_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"Resume\" note: %d\n", + note->nc_length); + return; + } + +#ifdef CONFIG_SMP + syslog_time(LOG_INFO, + "Task %u resumed, CPU%u, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); +#else + syslog_time(LOG_INFO, + "Task %u resumed, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority); +#endif + } + break; +#endif + +#ifdef CONFIG_SMP + case NOTE_CPU_START: + { + FAR struct note_cpu_start_s *note_start = + (FAR struct note_cpu_start_s *)note; + + if (note->nc_length != sizeof(struct note_cpu_start_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU Start\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u requests CPU%u to start, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note_start->ncs_target, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_CPU_STARTED: + { + if (note->nc_length != sizeof(struct note_cpu_started_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU started\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u has started, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); + } + break; + +#ifdef CONFIG_SCHED_INSTRUMENTATION_SWITCH + case NOTE_CPU_PAUSE: + { + FAR struct note_cpu_pause_s *note_pause = + (FAR struct note_cpu_pause_s *)note; + + if (note->nc_length != sizeof(struct note_cpu_pause_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU pause\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u requests CPU%u to pause, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note_pause->ncp_target, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_CPU_PAUSED: + { + if (note->nc_length != sizeof(struct note_cpu_paused_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU paused\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u has paused, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_CPU_RESUME: + { + FAR struct note_cpu_resume_s *note_resume = + (FAR struct note_cpu_resume_s *)note; + + if (note->nc_length != sizeof(struct note_cpu_resume_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU resume\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u requests CPU%u to resume, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note_resume->ncr_target, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_CPU_RESUMED: + { + if (note->nc_length != sizeof(struct note_cpu_resumed_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"CPU resumed\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u CPU%u has resumed, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority); + } + break; +#endif +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_PREEMPTION + case NOTE_PREEMPT_LOCK: + case NOTE_PREEMPT_UNLOCK: + { + FAR struct note_preempt_s *note_preempt = + (FAR struct note_preempt_s *)note; + uint16_t count; + + if (note->nc_length != sizeof(struct note_preempt_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"Preemption\" note: %d\n", + note->nc_length); + return; + } + + trace_dump_unflatten(&count, note_preempt->npr_count, + sizeof(count)); + + if (note->nc_type == NOTE_PREEMPT_LOCK) + { +#ifdef CONFIG_SMP + syslog_time(LOG_INFO, + "Task %u locked, CPU%u, priority %u, count=%u\n", + (unsigned int)pid, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority, + (unsigned int)count); +#else + syslog_time(LOG_INFO, + "Task %u locked, priority %u, count=%u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority, + (unsigned int)count); +#endif + } + else + { +#ifdef CONFIG_SMP + syslog_time(LOG_INFO, + "Task %u unlocked, CPU%u, priority %u, count=%u\n", + (unsigned int)pid, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority, + (unsigned int)count); +#else + syslog_time(LOG_INFO, + "Task %u unlocked, priority %u, count=%u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority, + (unsigned int)count); +#endif + } + } + break; + +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_CSECTION + case NOTE_CSECTION_ENTER: + case NOTE_CSECTION_LEAVE: + { +#ifdef CONFIG_SMP + FAR struct note_csection_s *note_csection = + (FAR struct note_csection_s *)note; + uint16_t count; +#endif + + if (note->nc_length != sizeof(struct note_csection_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"csection\" note: %d\n", + note->nc_length); + return; + } + +#ifdef CONFIG_SMP + trace_dump_unflatten(&count, note_csection->ncs_count, + sizeof(count)); + + if (note->nc_type == NOTE_CSECTION_ENTER) + { + syslog_time(LOG_INFO, + "Task %u enter csection, CPU%u, priority %u, " + "count=%u\n", + (unsigned int)pid, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority, + (unsigned int)count); + } + else + { + syslog_time(LOG_INFO, + "Task %u leave csection, CPU%u, priority %u, " + "count=%u\n", + (unsigned int)pid, (unsigned int)note->nc_cpu, + (unsigned int)note->nc_priority, + (unsigned int)count); + } +#else + if (note->nc_type == NOTE_CSECTION_ENTER) + { + syslog_time(LOG_INFO, + "Task %u enter csection, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority); + } + else + { + syslog_time(LOG_INFO, + "Task %u leave csection, priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_priority); + } +#endif + } + break; +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_SPINLOCKS + case NOTE_SPINLOCK_LOCK: + case NOTE_SPINLOCK_LOCKED: + case NOTE_SPINLOCK_UNLOCK: + case NOTE_SPINLOCK_ABORT: + { + FAR struct note_spinlock_s *note_spinlock = + (FAR struct note_spinlock_s *)note; + FAR void *spinlock; + + if (note->nc_length != sizeof(struct note_spinlock_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"Spinlock\" note: %d\n", + note->nc_length); + return; + } + + trace_dump_unflatten(&spinlock, + note_spinlock->nsp_spinlock, + sizeof(spinlock)); + + switch (note->nc_type) + { +#ifdef CONFIG_SMP + case NOTE_SPINLOCK_LOCK: + { + syslog_time(LOG_INFO, + "Task %u CPU%u wait for spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_LOCKED: + { + syslog_time(LOG_INFO, + "Task %u CPU%u has spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_UNLOCK: + { + syslog_time(LOG_INFO, + "Task %u CPU%u unlocking spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_ABORT: + { + syslog_time(LOG_INFO, + "Task %u CPU%u abort wait on spinlock=%p " + "value=%u priority %u\n", + (unsigned int)pid, + (unsigned int)note->nc_cpu, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; +#else + case NOTE_SPINLOCK_LOCK: + { + syslog_time(LOG_INFO, + "Task %u wait for spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_LOCKED: + { + syslog_time(LOG_INFO, + "Task %u has spinlock=%p value=%u priority %u\n", + (unsigned int)pid, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_UNLOCK: + { + syslog_time(LOG_INFO, + "Task %u unlocking spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; + + case NOTE_SPINLOCK_ABORT: + { + syslog_time(LOG_INFO, + "Task %u abort wait on spinlock=%p value=%u " + "priority %u\n", + (unsigned int)pid, + spinlock, + (unsigned int)note_spinlock->nsp_value, + (unsigned int)note->nc_priority); + } + break; +#endif + } + break; + } +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_SYSCALL + case NOTE_SYSCALL_ENTER: + { + FAR struct note_syscall_enter_s *note_sysenter = + (FAR struct note_syscall_enter_s *)note; + + if (note->nc_length < SIZEOF_NOTE_SYSCALL_ENTER(0)) + { + syslog(LOG_ERR, + "Size incorrect for \"SYSCALL enter\" note: " + "%d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u Enter SYSCALL %d\n", + (unsigned int)pid, + note_sysenter->nsc_nr); + } + break; + + case NOTE_SYSCALL_LEAVE: + { + FAR struct note_syscall_leave_s *note_sysleave = + (FAR struct note_syscall_leave_s *)note; + uintptr_t result; + + if (note->nc_length != + sizeof(struct note_syscall_leave_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"SYSCALL leave\" note: " + "%d\n", + note->nc_length); + return; + } + + trace_dump_unflatten(&result, + note_sysleave->nsc_result, + sizeof(result)); + + syslog_time(LOG_INFO, + "Task %u Leave SYSCALL %d: %" PRIdPTR "\n", + (unsigned int)pid, + note_sysleave->nsc_nr, result); + } + break; +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_IRQHANDLER + case NOTE_IRQ_ENTER: + case NOTE_IRQ_LEAVE: + { + FAR struct note_irqhandler_s *note_irq = + (FAR struct note_irqhandler_s *)note; + + if (note->nc_length != sizeof(struct note_irqhandler_s)) + { + syslog(LOG_ERR, + "Size incorrect for \"IRQ\" note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u %s IRQ %d\n", + (unsigned int)pid, + note->nc_type == NOTE_IRQ_ENTER ? "Enter" : "Leave", + note_irq->nih_irq); + } + break; +#endif + +#ifdef CONFIG_SCHED_INSTRUMENTATION_DUMP + case NOTE_DUMP_STRING: + { + FAR struct note_string_s *note_string = + (FAR struct note_string_s *)note; + + if (note->nc_length < sizeof(struct note_string_s)) + { + syslog(LOG_INFO, + "ERROR: note too small for string note: %d\n", + note->nc_length); + return; + } + + syslog_time(LOG_INFO, + "Task %u priority %u, string:%s\n", + (unsigned int)pid, + (unsigned int)note->nc_priority, + note_string->nst_data); + } + break; + + case NOTE_DUMP_BINARY: + { + FAR struct note_binary_s *note_binary = + (FAR struct note_binary_s *)note; + uintptr_t ip; + char out[1280]; + int count; + int ret = 0; + int i; + + count = + note->nc_length - sizeof(struct note_binary_s) + 1; + + if (count < 0) + { + syslog(LOG_INFO, + "ERROR: note too small for binary note: %d\n", + note->nc_length); + return; + } + + for (i = 0; i < count; i++) + { + snprintf(&out[ret], sizeof(out) - ret, + " 0x%x", note_binary->nbi_data[i]); + ret += strlen(&out[ret]); + } + + trace_dump_unflatten(&ip, note_binary->nbi_ip, + sizeof(ip)); + + syslog_time(LOG_INFO, + "Task %u priority %u, ip=0x%" PRIdPTR + " event=%u count=%u%s\n", + (unsigned int)pid, + (unsigned int)note->nc_priority, + note_binary->nbi_ip, + note_binary->nbi_event, + count, + out); + } + break; +#endif + + default: + syslog(LOG_INFO, "Unrecognized note type: %d\n", note->nc_type); + return; + } + + offset += note->nc_length; + } +} + /**************************************************************************** * Name: note_daemon ****************************************************************************/ @@ -77,7 +803,7 @@ static int note_daemon(int argc, char *argv[]) nread = read(fd, g_note_buffer, CONFIG_SYSTEM_NOTE_BUFFERSIZE); if (nread > 0) { - syslog(LOG_INFO, "%.*s", (int)nread, g_note_buffer); + dump_notes(nread); } usleep(CONFIG_SYSTEM_NOTE_DELAY * 1000L); diff --git a/testing/fftest/CMakeLists.txt b/system/sensorscope/CMakeLists.txt similarity index 82% rename from testing/fftest/CMakeLists.txt rename to system/sensorscope/CMakeLists.txt index b91f1c3ac..554114ff2 100644 --- a/testing/fftest/CMakeLists.txt +++ b/system/sensorscope/CMakeLists.txt @@ -1,5 +1,5 @@ # ############################################################################## -# apps/testing/fftest/CMakeLists.txt +# apps/system/sensorscope/CMakeLists.txt # # Licensed to the Apache Software Foundation (ASF) under one or more contributor # license agreements. See the NOTICE file distributed with this work for @@ -18,16 +18,14 @@ # # ############################################################################## -if(CONFIG_TESTING_FF) +if(CONFIG_SYSTEM_SENSORSCOPE) nuttx_add_application( NAME - ${CONFIG_TESTING_FF_PROGNAME} - PRIORITY - ${CONFIG_TESTING_FF_PRIORITY} - STACKSIZE - ${CONFIG_TESTING_FF_STACKSIZE} - MODULE - ${CONFIG_TESTING_FF} + ${CONFIG_SYSTEM_SENSORSCOPE_PROGNAME} SRCS - fftest.c) + sensorscope_main.c + STACKSIZE + ${CONFIG_SYSTEM_SENSORSCOPE_STACKSIZE} + PRIORITY + ${CONFIG_SYSTEM_SENSORSCOPE_PRIORITY}) endif() diff --git a/system/sensorscope/Kconfig b/system/sensorscope/Kconfig new file mode 100644 index 000000000..a8dd84ec1 --- /dev/null +++ b/system/sensorscope/Kconfig @@ -0,0 +1,72 @@ +# +# For a description of the syntax of this configuration file, +# see the file kconfig-language.txt in the NuttX tools repository. +# + +menuconfig SYSTEM_SENSORSCOPE + bool "NxScope sensors stream app" + default n + depends on LOGGING_NXSCOPE + select LOGGING_NXSCOPE_INTF_SERIAL + select LOGGING_NXSCOPE_PROTO_SER + +if SYSTEM_SENSORSCOPE + +config SYSTEM_SENSORSCOPE_PROGNAME + string "Program name" + default "sensorscope" + +config SYSTEM_SENSORSCOPE_PRIORITY + int "nxscope task priority" + default 100 + +config SYSTEM_SENSORSCOPE_STACKSIZE + int "nxscope stack size" + default DEFAULT_TASK_STACKSIZE + +config SYSTEM_SENSORSCOPE_SERIAL_PATH + string "nxscope serial path" + default "/dev/ttyUSB0" + +config SYSTEM_SENSORSCOPE_SERIAL_BAUD + int "nxscope serial baud" + default 115200 + ---help--- + Ignored if set to 0 (for example for RTT interface) + +config SYSTEM_SENSORSCOPE_CDCACM + bool "nxscope CDCACM device support" + depends on CDCACM + default n + +config SYSTEM_SENSORSCOPE_FORCE_ENABLE + bool "nxscope force enable" + default n + +config SYSTEM_SENSORSCOPE_STREAMBUF_LEN + int "nxscope stream buffer length" + default 512 + +config SYSTEM_SENSORSCOPE_RXBUF_LEN + int "nxscope RX buffer length" + default 32 + +config SYSTEM_SENSORSCOPE_RX_PADDING + int "nxscope RX padding" + default 0 + +config SYSTEM_SENSORSCOPE_MAIN_INTERVAL + int "nxscope main interval (microseconds)" + default 100000 + ---help--- + This value is responsible for the frequency at which stream + frames will be sent and incoming frames will be received. + +config SYSTEM_SENSORSCOPE_FETCH_INTERVAL + int "nxscope sensor fetch interval (microseconds)" + default 1000 + ---help--- + This value is responsible for the frequency at which the sensors + are read + +endif # SYSTEM_SENSORSCOPE diff --git a/system/sensorscope/Make.defs b/system/sensorscope/Make.defs new file mode 100644 index 000000000..2e7664771 --- /dev/null +++ b/system/sensorscope/Make.defs @@ -0,0 +1,23 @@ +############################################################################ +# apps/systen/sensorscope/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_SYSTEM_SENSORSCOPE),) +CONFIGURED_APPS += $(APPDIR)/system/sensorscope +endif diff --git a/system/sensorscope/Makefile b/system/sensorscope/Makefile new file mode 100644 index 000000000..18ee63133 --- /dev/null +++ b/system/sensorscope/Makefile @@ -0,0 +1,34 @@ +############################################################################ +# apps/system/sensorscope/Makefile +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +include $(APPDIR)/Make.defs + +# sensorscope built-in application info + +PROGNAME = $(CONFIG_SYSTEM_SENSORSCOPE_PROGNAME) +PRIORITY = $(CONFIG_SYSTEM_SENSORSCOPE_PRIORITY) +STACKSIZE = $(CONFIG_SYSTEM_SENSORSCOPE_STACKSIZE) +MODULE = $(CONFIG_SYSTEM_SENSORSCOPE) + +MAINSRC = sensorscope_main.c + +CSRCS = + +include $(APPDIR)/Application.mk diff --git a/system/sensorscope/sensorscope_main.c b/system/sensorscope/sensorscope_main.c new file mode 100644 index 000000000..ab80be527 --- /dev/null +++ b/system/sensorscope/sensorscope_main.c @@ -0,0 +1,555 @@ +/**************************************************************************** + * apps/system/sensorscope/sensorscope_main.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "logging/nxscope/nxscope.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define SENSOR_PATH "/dev/uorb/" +#define SENSOR_PATH_MAX 62 +#define SENSOR_CHNAME_MAX 16 + +/**************************************************************************** + * Private Type Definition + ****************************************************************************/ + +struct nxsensor_info_s +{ + FAR const char *name; + size_t data_size; /* Sensor read data size */ + size_t data_offset; /* Read data offset (no timestamp) */ + size_t dim; /* Data vector dimenstion */ + int dtype; /* Data vector type */ +}; + +struct listen_object_s +{ + /* Node of object info list */ + + struct list_node node; + + /* Sensor data */ + + int fd; + FAR uint8_t *data; + + /* Sensor info */ + + FAR struct nxsensor_info_s *info; + + /* nxscope channel data */ + + int chanid; + char chname[SENSOR_CHNAME_MAX]; +}; + +struct nxscope_thr_env_s +{ + struct nxscope_s nxs; + struct list_node objlist; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* This array defines supported sensors. */ + +struct nxsensor_info_s g_nxsensor[] = +{ + {"accel", sizeof(struct sensor_accel), 0, 3, NXSCOPE_TYPE_FLOAT}, + {"mag", sizeof(struct sensor_mag), 0, 3, NXSCOPE_TYPE_FLOAT}, + {"gyro", sizeof(struct sensor_gyro), 0, 3, NXSCOPE_TYPE_FLOAT}, + {"light", sizeof(struct sensor_light), 0, 2, NXSCOPE_TYPE_FLOAT}, + {"baro", sizeof(struct sensor_baro), 0, 2, NXSCOPE_TYPE_FLOAT}, + {"prox", sizeof(struct sensor_prox), 0, 1, NXSCOPE_TYPE_FLOAT}, + {"humi", sizeof(struct sensor_humi), 0, 1, NXSCOPE_TYPE_FLOAT}, + {"temp", sizeof(struct sensor_temp), 0, 1, NXSCOPE_TYPE_FLOAT}, + {"rgb", sizeof(struct sensor_rgb), 0, 3, NXSCOPE_TYPE_FLOAT}, + {"hall", sizeof(struct sensor_hall), 0, 1, NXSCOPE_TYPE_INT32}, + {"ir", sizeof(struct sensor_ir), 0, 1, NXSCOPE_TYPE_FLOAT}, + {"gas", sizeof(struct sensor_gas), 0, 1, NXSCOPE_TYPE_FLOAT}, +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: nxscope_samples_thr + ****************************************************************************/ + +static FAR void *nxscope_samples_thr(FAR void *arg) +{ + FAR struct nxscope_thr_env_s *envp = arg; + FAR struct listen_object_s *tmp; + FAR float *data; + int ret; + size_t offset; + + DEBUGASSERT(envp); + + printf("nxscope_samples_thr\n"); + + while (1) + { + list_for_every_entry(&envp->objlist, tmp, struct listen_object_s, node) + { + /* Read data from sensor */ + + ret = read(tmp->fd, tmp->data, tmp->info->data_size); + if (ret < 0) + { + printf("ERROR: read failed %d\n", -errno); + } + else + { + /* Get vector from a given offset */ + + offset = tmp->info->data_offset + sizeof(uint64_t); + data = (float *)&tmp->data[offset]; + + nxscope_put_vfloat(&envp->nxs, tmp->chanid, data, + tmp->info->dim); + } + } + + usleep(CONFIG_SYSTEM_SENSORSCOPE_FETCH_INTERVAL); + } + + return NULL; +} + +#ifdef CONFIG_SYSTEM_SENSORSCOPE_CDCACM +/**************************************************************************** + * Name: nxscope_cdcacm_init + ****************************************************************************/ + +static int nxscope_cdcacm_init(void) +{ + struct boardioc_usbdev_ctrl_s ctrl; + FAR void *handle; + int ret; + + ctrl.usbdev = BOARDIOC_USBDEV_CDCACM; + ctrl.action = BOARDIOC_USBDEV_CONNECT; + ctrl.instance = 0; + ctrl.handle = &handle; + + ret = boardctl(BOARDIOC_USBDEV_CONTROL, (uintptr_t)&ctrl); + if (ret < 0) + { + printf("ERROR: BOARDIOC_USBDEV_CONTROL failed %d\n", ret); + goto errout; + } + +errout: + return ret; +} +#endif + +/**************************************************************************** + * Name: listener_add_object + ****************************************************************************/ + +static FAR struct listen_object_s * +listener_add_object(FAR struct list_node *objlist, + FAR struct nxsensor_info_s *info, + int fd, int chanid, FAR char *chname) +{ + FAR struct listen_object_s *tmp; + + tmp = malloc(sizeof(struct listen_object_s)); + if (tmp == NULL) + { + return NULL; + } + + /* Initialize object */ + + strncpy(tmp->chname, chname, SENSOR_CHNAME_MAX); + + tmp->info = info; + tmp->chanid = chanid; + tmp->fd = fd; + + /* Allocate space for data */ + + tmp->data = malloc(info->data_size); + + /* Add node to list */ + + list_add_tail(objlist, &tmp->node); + + return tmp; +} + +/**************************************************************************** + * Name: listener_delete_object_list + ****************************************************************************/ + +static void listener_delete_object_list(FAR struct list_node *objlist) +{ + FAR struct listen_object_s *tmp; + FAR struct listen_object_s *next; + + list_for_every_entry_safe(objlist, tmp, next, struct listen_object_s, node) + { + free(tmp->data); + list_delete(&tmp->node); + free(tmp); + } + + list_initialize(objlist); +} + +/**************************************************************************** + * Name: sensorscope_chinfo + ****************************************************************************/ + +static int sensorscope_chinfo(FAR char *path, + FAR struct nxsensor_info_s **info) +{ + int i; + + for (i = 0; i < nitems(g_nxsensor); i++) + { + if (strstr(path, g_nxsensor[i].name) != NULL) + { + *info = &g_nxsensor[i]; + return OK; + } + } + + return -EINVAL; +} + +/**************************************************************************** + * Name: nxscope_channels_num + ****************************************************************************/ + +static int nxscope_channels_num(void) +{ + FAR struct dirent *entry; + FAR DIR *dir; + int i = 0; + + dir = opendir(SENSOR_PATH); + if (!dir) + { + return 0; + } + + while ((entry = readdir(dir)) != NULL) + { + if (entry->d_type == DT_CHR) + { + i++; + } + } + + closedir(dir); + + return i; +} + +/**************************************************************************** + * Name: nxscope_channels + ****************************************************************************/ + +static int nxscope_channels(FAR struct nxscope_thr_env_s *envp) +{ + union nxscope_chinfo_type_u u; + FAR struct nxsensor_info_s *info; + FAR struct dirent *entry; + FAR struct listen_object_s *obj; + FAR DIR *dir; + int chanid; + int ret; + int fd; + char path[SENSOR_PATH_MAX]; + + /* Initialize objects list */ + + list_initialize(&envp->objlist); + + /* Open sensors direcotry */ + + dir = opendir(SENSOR_PATH); + if (!dir) + { + return 0; + } + + /* Get available sensors */ + + chanid = 0; + while ((entry = readdir(dir)) != NULL) + { + if (entry->d_type != DT_CHR) + { + continue; + } + + /* Get sensor info */ + + ret = sensorscope_chinfo(entry->d_name, &info); + if (ret != OK) + { + printf("ERROR: not supported sensor %s\n", entry->d_name); + } + else + { + snprintf(path, SENSOR_PATH_MAX, SENSOR_PATH"%s", entry->d_name); + fd = open(path, O_CLOEXEC | O_RDWR | O_NONBLOCK); + if (fd < 0) + { + printf("ERROR: failed to open %s %d\n", entry->d_name, -errno); + } + else + { + /* Add new object */ + + obj = listener_add_object(&envp->objlist, + info, fd, chanid, + basename(entry->d_name)); + if (obj == NULL) + { + printf("ERROR: failed to add listener object %d\n", + chanid); + return -ENOMEM; + } + + /* Register nxscope channel */ + + u.s.dtype = NXSCOPE_TYPE_FLOAT; + u.s._res = 0; + u.s.cri = 0; + + nxscope_chan_init(&envp->nxs, obj->chanid, obj->chname, + u.u8, obj->info->dim, 0); + + /* Next channel */ + + chanid++; + } + } + } + + return OK; +} + +/**************************************************************************** + * Name: nxscope_cb_start + ****************************************************************************/ + +static int nxscope_cb_start(FAR void *priv, bool start) +{ + UNUSED(priv); + + printf("--> nxscope_cb_start: start=%d\n", start); + + return OK; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: nxscope_main + ****************************************************************************/ + +int main(int argc, FAR char *argv[]) +{ + struct nxscope_thr_env_s env; + struct nxscope_cfg_s nxs_cfg; + struct nxscope_intf_s intf; + struct nxscope_proto_s proto; + struct nxscope_ser_cfg_s nxs_ser_cfg; + struct nxscope_callbacks_s cbs; + pthread_t thread; + int ret; + +#ifndef CONFIG_NSH_ARCHINIT + /* Perform architecture-specific initialization (if configured) */ + + boardctl(BOARDIOC_INIT, 0); + +# ifdef CONFIG_BOARDCTL_FINALINIT + /* Perform architecture-specific final-initialization (if configured) */ + + boardctl(BOARDIOC_FINALINIT, 0); +# endif +#endif + +#ifdef CONFIG_SYSTEM_SENSORSCOPE_CDCACM + /* Initialize the USB CDCACM device */ + + ret = nxscope_cdcacm_init(); + if (ret < 0) + { + printf("ERROR: nxscope_cdcacm_init failed %d\n", ret); + goto errout_noproto; + } +#endif + + /* Default serial protocol */ + + ret = nxscope_proto_ser_init(&proto, NULL); + if (ret < 0) + { + printf("ERROR: nxscope_proto_ser_init failed %d\n", ret); + goto errout_noproto; + } + + /* Configuration */ + + nxs_ser_cfg.path = CONFIG_SYSTEM_SENSORSCOPE_SERIAL_PATH; + nxs_ser_cfg.nonblock = true; + nxs_ser_cfg.baud = CONFIG_SYSTEM_SENSORSCOPE_SERIAL_BAUD; + + /* Initialize serial interface */ + + ret = nxscope_ser_init(&intf, &nxs_ser_cfg); + if (ret < 0) + { + printf("ERROR: nxscope_ser_init failed %d\n", ret); + goto errout_nointf; + } + + /* Connect callbacks */ + + cbs.start_priv = NULL; + cbs.start = nxscope_cb_start; + + /* Initialize nxscope */ + + nxs_cfg.intf_cmd = &intf; + nxs_cfg.intf_stream = &intf; + nxs_cfg.proto_cmd = &proto; + nxs_cfg.proto_stream = &proto; + nxs_cfg.callbacks = &cbs; + nxs_cfg.channels = nxscope_channels_num(); + nxs_cfg.streambuf_len = CONFIG_SYSTEM_SENSORSCOPE_STREAMBUF_LEN; + nxs_cfg.rxbuf_len = CONFIG_SYSTEM_SENSORSCOPE_RXBUF_LEN; + nxs_cfg.rx_padding = CONFIG_SYSTEM_SENSORSCOPE_RX_PADDING; + + ret = nxscope_init(&env.nxs, &nxs_cfg); + if (ret < 0) + { + printf("ERROR: nxscope_init failed %d\n", ret); + goto errout_nonxscope; + } + + /* Create channels */ + + ret = nxscope_channels(&env); + if (ret != OK) + { + printf("ERROR: nxscope_channels failed %d\n", ret); + goto errout; + } + + /* Create samples thread */ + + ret = pthread_create(&thread, NULL, nxscope_samples_thr, &env); + if (ret != OK) + { + printf("ERROR: pthread_create failed %d\n", ret); + goto errout; + } + +#ifdef CONFIG_SYSTEM_SENSORSCOPE_FORCE_ENABLE + /* Enable channels and enable stream */ + + nxscope_chan_all_en(&nxs, true); + nxscope_stream_start(&nxs, true); +#endif + + /* Main loop */ + + while (1) + { + /* Flush stream data */ + + ret = nxscope_stream(&env.nxs); + if (ret < 0) + { + printf("ERROR: nxscope_stream failed %d\n", ret); + } + + /* Handle recv data */ + + ret = nxscope_recv(&env.nxs); + if (ret < 0) + { + printf("ERROR: nxscope_recv failed %d\n", ret); + } + + usleep(CONFIG_SYSTEM_SENSORSCOPE_MAIN_INTERVAL); + } + +errout: + + /* Delete objects */ + + listener_delete_object_list(&env.objlist); + + /* Deinit nxscope */ + + nxscope_deinit(&env.nxs); + +errout_nonxscope: + + /* Deinit interface */ + + nxscope_ser_deinit(&intf); + +errout_nointf: + + /* Deinit protocol */ + + nxscope_proto_ser_deinit(&proto); + +errout_noproto: + return 0; +} diff --git a/system/settings/Kconfig b/system/settings/Kconfig new file mode 100644 index 000000000..351897ce9 --- /dev/null +++ b/system/settings/Kconfig @@ -0,0 +1,85 @@ +# +# Settings Storage Configuration +# + +config SYSTEM_SETTINGS + bool "Settings Functions" + default n + ---help--- + The settings storage can be used to store and retrieve various + configurable parameters. This storage is a RAM-based map (for fast access) + but one or more files can be used too (so values can persist across system + reboots). + +if SYSTEM_SETTINGS + +config SYSTEM_SETTINGS_MAP_SIZE + int "Settings storage size" + default 20 + ---help--- + The size of the settings storage, i.e. the + maximum number of settings that can be created. + +config SYSTEM_SETTINGS_KEY_SIZE + int "Settings key size" + default 20 + ---help--- + Maximum size of a setting key. + +config SYSTEM_SETTINGS_VALUE_SIZE + int "Settings value size" + default 20 + ---help--- + Maximum size of a string setting value. + +config SYSTEM_SETTINGS_MAX_STORAGES + int "Settings files" + default 2 + ---help--- + Maximum number of supported settings files. + +config SYSTEM_SETTINGS_MAX_FILENAME + int "Settings filename size" + default 50 + ---help--- + Maximum size of settings filename. + +config SYSTEM_SETTINGS_CACHED_SAVES + bool "Cache save operations" + default y + ---help--- + If enabled saving to the storages will be cached. + + Whenever a save is triggered, the settings will only + be saved in the RAM map (and will be immediately + effective). Writes to the storages though will + happen after a small delay. + + This improves performance greatly when multiple + successive saves are to be performed, as the actual + write will happen only once, asynchronously. + +if SYSTEM_SETTINGS_CACHED_SAVES + +config SYSTEM_SETTINGS_CACHE_TIME_MS + int "Cache Delay (ms)" + default 100 + ---help--- + Sets the delay after a setting is changed before they are written +endif # SYSTEM_SETTINGS_CACHED_SAVES + +config SYSTEM_SETTINGS_MAX_SIGNALS + int "Max. settings signals" + default 2 + ---help--- + Maximum number of signals that can be registered + on the settings storage. + +config SYSTEM_SETTINGS_SIGNO + int "Signal Number to use" + default 32 + range 32 63 + ---help--- + The Signal number to use for notifies + +endif # SYSTEM_SETTINGS diff --git a/system/settings/Make.defs b/system/settings/Make.defs new file mode 100644 index 000000000..9092af73f --- /dev/null +++ b/system/settings/Make.defs @@ -0,0 +1,24 @@ +############################################################################ +# apps/system/settings/Make.defs +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. The +# ASF licenses this file to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance with the +# License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. +# +############################################################################ + +ifneq ($(CONFIG_SYSTEM_SETTINGS),) +CONFIGURED_APPS += $(APPDIR)/system/settings +endif + diff --git a/examples/module/chardev/Makefile b/system/settings/Makefile similarity index 88% rename from examples/module/chardev/Makefile rename to system/settings/Makefile index 070247a01..318b2278d 100644 --- a/examples/module/chardev/Makefile +++ b/system/settings/Makefile @@ -1,5 +1,5 @@ ############################################################################ -# apps/examples/module/chardev/Makefile +# apps/system/settings/Makefile # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with @@ -20,9 +20,9 @@ include $(APPDIR)/Make.defs -PROGNAME = chardev -DYNLIB = y - -MAINSRC = chardev.c +ifneq ($CONFIG_SYSTEM_UTILS_SETTINGS,) +CSRCS += settings.c storage_bin.c storage_text.c +endif include $(APPDIR)/Application.mk + diff --git a/system/settings/readme.md b/system/settings/readme.md new file mode 100644 index 000000000..4016adff6 --- /dev/null +++ b/system/settings/readme.md @@ -0,0 +1,94 @@ +# Introduction + +The settings storage can be used to store and retrieve various configurable parameters. This storage is a RAM-based map (for fast access), but one or more files can be used too (so values can persist across system reboots). + +This is a thread-safe implementation. Different threads may access the settings simultaneously. + +# Setting Definition + +Each setting is a key/value pair. + +The key is always a string, while there are many value types supported. + +## Strings + +All strings, whether they represent a key or a string value, must use a specific format. They must be ASCII, NULL-terminated strings, and they are always case-sensitive. They must obey to the following rules: + +- they cannot start with a number. +- they cannot contain the characters '=', ';'. +- they cannot contain the characters '\n', '\r'. + +## Setting Type + +Since each setting has its own type, it is the user's responsibility to access the setting using the correct type. Some "casts" are possible (e.g. between bool and int), but generally reading with the wrong type will lead to failure. + +The following types are currently supported. + +- String. +- int +- bool +- ip address +- float + +### Setting Storage Size + +Kconfig is used to determine the size of the various fields used: + +- CONFIG_SYSTEM_SETTINGS_MAP_SIZE     the total number settings allowed +- CONFIG_SYSTEM_SETTINGS_MAX_STORAGES the number of storage files that can be used +- CONFIG_SYSTEM_SETTINGS_VALUE_SIZE   the storage size of a STRING value +- CONFIG_SYSTEM_SETTINGS_KEY_SIZE     the size of the KEY field +- CONFIG_SYSTEM_SETTINGS_MAX_FILENAME the maximum filename size + +# Signal + +A POSIX signal can be chosen via Kconfig and is used to send notifications when a setting has been changed. is used to determine the maximum number of signals that can be registered for the settings storage functions. + +# Files + +There are also various types of files that can be used. Each file type is using a different data format to parse the stored data. Every type is expected to be best suited for a specific file system or medium type, or be better performing while used with external systems. In any case, all configured files are automatically synchronized whenever a value changes. + +## Cached Saves + +It is possible to enable cached saves, via Kconfig, along with the time (in ms) that should elapse after the last storage value was updated before a write to the file or files should be initiated. + +## Storage Types +The current storage types are defined in and are as follows. + +### STORAGE_BINARY + +Data is stored as "raw" binary. Bool, int and float data are stored using the maximum number of bytes needed, as determined by the size of the union used for these settings; this will be architecture dependent. + +### STORAGE_TEXT + +All data is converted to ASCII characters making the storage easily human-readable. + +# Usage + +## Most common + +This is the usual sequence of calls to use the settings utility. + +1. Call settings_init(); +2. Call settings_setstorage("path", storage_type); for every/any file storage in use + - for example settings_setstorage("/dev/eeprom", STORAGE_EPROM); +3. Call settings_create(key_name, settings_type, default value) for every setting required +4. settings_notify(). + - for example settings_create("KEY1", SETTINGS_STRING, "Hello"); +5. If a settings value needs to be read, call the variadic function settings_get(key_name, settings_type, &variable, size);. "size" is only needed for STRING types. + - for example settings_get("KEY1", SETTINGS_STRING, &read_str, sizeof(readstr)); +6. If a settings value needs to be changed, call the variadic function settings_set(key_name, settings_type, &value, size); "size" is only needed for STRING types. + - for example settings_set("KEY1", SETTINGS_STRING, &new_string); + +## Other functions +Other functions exist to assist the user program. +1. settings_sync(wait_dump). This will synchronise the settings between file storages if more than 1 are in use. if cached saves are enabled, the wait_dump parameter, if true, will force the sync function to wait until any saves are actually written out. +2. settings_iterate(idx, &setting). This gets a copy of a setting at the specified position. It can be used to iterate over the entire settings map, by using successive values of idx. +3. settings_type(key_name, &type). Gets the type of a given setting. +4. settings_clear(). Clears all settings and sata in all storages is purged. +5. settings_hash(&hash). Gets the hash of the settings storage. This hash represents the internal state of the settings map. A unique number is calculated based on the contents of the whole map. This hash can be used to check the settings for any alterations: i.e. any setting that may had its value changed since last check. +## Error codes +The settings functions provide negated error return codes that can be used as required by the user application to deal with unexpected behaviour. + +## Example App +There is an example app available to demonstrate the usage of many of the settings features CONFIG_EXAMPLES_SETTINGS. diff --git a/system/settings/settings.c b/system/settings/settings.c new file mode 100644 index 000000000..78eeac5ee --- /dev/null +++ b/system/settings/settings.c @@ -0,0 +1,1598 @@ +/**************************************************************************** + * apps/system/settings/settings.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "storage.h" +#include "system/settings.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifdef CONFIG_SYSTEM_SETTINGS_CACHED_SAVES +# define TIMER_SIGNAL SIGRTMIN +#endif + +#ifndef CONFIG_SYSTEM_SETTINGS_CACHE_TIME_MS +# define CONFIG_SYSTEM_SETTINGS_CACHE_TIME_MS 100 +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static int sanity_check(FAR char *str); +static uint32_t hash_calc(void); +static int get_setting(FAR char *key, FAR setting_t **setting); +static size_t get_string(FAR setting_t *setting, FAR char *buffer, + size_t size); +static int set_string(FAR setting_t *setting, FAR char *str); +static int get_int(FAR setting_t *setting, FAR int *i); +static int set_int(FAR setting_t *setting, int i); +static int get_bool(FAR setting_t *setting, FAR int *i); +static int set_bool(FAR setting_t *setting, int i); +static int get_float(FAR setting_t *setting, FAR double *f); +static int set_float(FAR setting_t *setting, FAR double f); +static int get_ip(FAR setting_t *setting, FAR struct in_addr *ip); +static int set_ip(FAR setting_t *setting, FAR struct in_addr *ip); +static int load(void); +static void save(void); +static void signotify(void); +static void dump_cache(union sigval ptr); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static struct +{ + pthread_mutex_t mtx; + uint32_t hash; + bool wrpend; + bool initialized; + storage_t store[CONFIG_SYSTEM_SETTINGS_MAX_STORAGES]; + struct notify_s notify[CONFIG_SYSTEM_SETTINGS_MAX_SIGNALS]; +#if defined(CONFIG_SYSTEM_SETTINGS_CACHED_SAVES) + struct sigevent sev; + struct itimerspec trigger; + timer_t timerid; +#endif +} g_settings; + +setting_t map[CONFIG_SYSTEM_SETTINGS_MAP_SIZE]; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: hash_calc + * + * Description: + * Gets a setting for a string value + * + * Input Parameters: + * none + * Returned Value: + * crc32 hash of all the settings + * + ****************************************************************************/ + +static uint32_t hash_calc(void) +{ + return crc32((FAR uint8_t *)map, sizeof(map)); +} + +/**************************************************************************** + * Name: get_setting + * + * Description: + * Gets a setting for a given key + * + * Input Parameters: + * key - key of the required setting + * setting - pointer to pointer for the setting + * + * Returned Value: + * The value of the setting for the given key + * + ****************************************************************************/ + +static int get_setting(FAR char *key, FAR setting_t **setting) +{ + int i; + int ret = OK; + + assert(*setting == NULL); + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; i++) + { + if (map[i].type == SETTING_EMPTY) + { + ret = -ENOENT; + goto exit; + } + + if (strcmp(map[i].key, key) == 0) + { + *setting = &map[i]; + goto exit; + } + } + + *setting = NULL; + ret = -ENOENT; + +exit: + return ret; +} + +/**************************************************************************** + * Name: get_string + * + * Description: + * Gets a setting for a string value + * + * Input Parameters: + * setting - pointer to the setting type + * str - pointer to return the string value + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static size_t get_string(FAR setting_t *setting, FAR char *buffer, + size_t size) +{ + assert(setting); + if ((setting->type != SETTING_STRING) && + (setting->type != SETTING_IP_ADDR)) + { + return -EACCES; + } + + if (setting->type == SETTING_STRING) + { + FAR const char *s = setting->val.s; + size_t len = strlen(s); + + assert(len < size); + if (len >= size) + { + return 0; + } + + strncpy(buffer, s, size); + buffer[size - 1] = '\0'; + + return len; + } + else if (setting->type == SETTING_IP_ADDR) + { + assert(INET_ADDRSTRLEN < size); + + inet_ntop(AF_INET, &setting->val.ip, buffer, size); + buffer[size - 1] = '\0'; + + return strlen(buffer); + } + + return 0; +} + +/**************************************************************************** + * Name: set_string + * + * Description: + * Creates a setting for a string value setting->type != set_ + * + * Input Parameters: + * setting - pointer to the setting type + * str - the string value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int set_string(FAR setting_t *setting, FAR char *str) +{ + assert(setting); + + if ((setting->type != SETTING_STRING) && + (setting->type != SETTING_IP_ADDR)) + { + return -EACCES; + } + + ASSERT(strlen(str) < CONFIG_SYSTEM_SETTINGS_VALUE_SIZE); + if (strlen(str) >= CONFIG_SYSTEM_SETTINGS_VALUE_SIZE) + { + return -EINVAL; + } + + if (strlen(str) && (sanity_check(str) < 0)) + { + return -EINVAL; + } + + setting->type = SETTING_STRING; + strncpy(setting->val.s, str, CONFIG_SYSTEM_SETTINGS_VALUE_SIZE); + setting->val.s[CONFIG_SYSTEM_SETTINGS_VALUE_SIZE - 1] = '\0'; + + return OK; +} + +/**************************************************************************** + * Name: get_int + * + * Description: + * Gets a setting for an integer value + * + * Input Parameters: + * setting - pointer to the setting type + * i - pointer to return the integer value + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int get_int(FAR setting_t *setting, FAR int *i) +{ + assert(setting); + if ((setting->type != SETTING_INT) && + (setting->type != SETTING_BOOL) && + (setting->type != SETTING_FLOAT)) + { + return -EACCES; + } + + if (setting->type == SETTING_INT) + { + *i = setting->val.i; + } + else if (setting->type == SETTING_BOOL) + { + *i = !!setting->val.i; + } + else if (setting->type == SETTING_FLOAT) + { + *i = (int)setting->val.f; + } + else + { + return -EINVAL; + } + + return OK; +} + +/**************************************************************************** + * Name: set_int + * + * Description: + * Creates a setting for an integer value + * + * Input Parameters: + * setting - pointer to the setting type + * i - the integer value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int set_int(FAR setting_t *setting, int i) +{ + assert(setting); + if ((setting->type != SETTING_INT) && + (setting->type != SETTING_BOOL) && + (setting->type != SETTING_FLOAT)) + { + return -EACCES; + } + + setting->type = SETTING_INT; + setting->val.i = i; + + return OK; +} + +/**************************************************************************** + * Name: get_bool + * + * Description: + * Gets a setting for a boolean value + * + * Input Parameters: + * setting - pointer to the setting type + * f - pointer to return the boolean value + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int get_bool(FAR setting_t *setting, FAR int *i) +{ + assert(setting); + if ((setting->type != SETTING_BOOL) && + (setting->type != SETTING_INT)) + { + return -EACCES; + } + + if ((setting->type == SETTING_INT) || (setting->type == SETTING_BOOL)) + { + *i = !!setting->val.i; + } + else + { + return -EINVAL; + } + + return OK; +} + +/**************************************************************************** + * Name: set_bool + * + * Description: + * Creates a setting for a boolean value + * + * Input Parameters: + * setting - pointer to the setting type + * i - the boolean value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int set_bool(FAR setting_t *setting, int i) +{ + assert(setting); + if ((setting->type != SETTING_BOOL) && (setting->type != SETTING_INT)) + { + return -EACCES; + } + + setting->type = SETTING_BOOL; + setting->val.i = !!i; + + return OK; +} + +/**************************************************************************** + * Name: get_float + * + * Description: + * Gets a setting for a float value + * + * Input Parameters: + * setting - pointer to the setting type + * f - pointer to return the floating point value + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int get_float(FAR setting_t *setting, FAR double *f) +{ + assert(setting); + if ((setting->type != SETTING_FLOAT) && + (setting->type != SETTING_INT)) + { + return -EACCES; + } + + if (setting->type == SETTING_FLOAT) + { + *f = setting->val.f; + } + else if (setting->type == SETTING_INT) + { + *f = (double)setting->val.i; + } + else + { + return -EINVAL; + } + + return OK; +} + +/**************************************************************************** + * Name: set_float + * + * Description: + * Creates a setting for a float value + * + * Input Parameters: + * setting - pointer to the setting type + * f - the floating point value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int set_float(FAR setting_t *setting, double f) +{ + assert(setting); + if ((setting->type != SETTING_FLOAT) && + (setting->type != SETTING_INT)) + { + return -EACCES; + } + + setting->type = SETTING_FLOAT; + setting->val.f = f; + + return OK; +} + +/**************************************************************************** + * Name: get_ip + * + * Description: + * Creates a setting for an IP address + * + * Input Parameters: + * setting - pointer to the setting type + * ip - pointer to return the IP address + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int get_ip(FAR setting_t *setting, FAR struct in_addr *ip) +{ + int ret; + assert(setting); + if ((setting->type != SETTING_IP_ADDR) && + (setting->type != SETTING_STRING)) + { + return -EACCES; + } + + if (setting->type == SETTING_IP_ADDR) + { + memcpy(ip, &setting->val.ip, sizeof(struct in_addr)); + ret = OK; + } + else if (setting->type == SETTING_STRING) + { + ret = inet_pton(AF_INET, setting->val.s, ip); + } + else + { + ret = -EINVAL; + } + + return ret; +} + +/**************************************************************************** + * Name: set_ip + * + * Description: + * Creates a setting for an IP address + * + * Input Parameters: + * setting - pointer to the setting type + * ip - IP address (in network byte order) + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int set_ip(FAR setting_t *setting, FAR struct in_addr *ip) +{ + assert(setting); + if ((setting->type != SETTING_IP_ADDR) && + (setting->type != SETTING_STRING)) + { + return -EACCES; + } + + setting->type = SETTING_IP_ADDR; + memcpy(&setting->val.ip, ip, sizeof(struct in_addr)); + + return OK; +} + +/**************************************************************************** + * Name: load + * + * Description: + * Loads all values + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int load(void) +{ + int i; + int ret; + int loadfailed = 0; + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAX_STORAGES; i++) + { + if ((g_settings.store[i].file[0] != '\0') && + g_settings.store[i].load_fn) + { + ret = g_settings.store[i].load_fn(g_settings.store[i].file); + if (ret < 0) + { + loadfailed++; + } + } + } + + if (loadfailed >= CONFIG_SYSTEM_SETTINGS_MAX_STORAGES) + { + /* ALL storages failed to load. We have a problem. */ + + return -ENODATA; + } + else + { + return OK; + } +} + +/**************************************************************************** + * Name: save + * + * Description: + * Saves cached values, either immediately or on a timer + * + * Input Parameters: + * none + * + * Returned Value: + * None + * + ****************************************************************************/ + +static void save(void) +{ + g_settings.wrpend = true; + +#ifdef CONFIG_SYSTEM_SETTINGS_CACHED_SAVES + ret = timer_settime(g_settings.timerid, 0, &g_settings.trigger, NULL); +#else + union sigval value = + { + .sival_ptr = &g_settings.wrpend, + }; + + dump_cache(value); +#endif +} + +/**************************************************************************** + * Name: signotify + * + * Description: + * Notify anything waiting for a signal + * + * Input Parameters: + * none + * + * Returned Value: + * none + * + ****************************************************************************/ + +static void signotify(void) +{ + int i; + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAX_SIGNALS; i++) + { + if (g_settings.notify[i].pid == 0) + { + break; + } + + kill(g_settings.notify[i].pid, g_settings.notify[i].signo); + } +} + +/**************************************************************************** + * Name: dump_cache + * + * Description: + * Writes out the cached data to the appropriate storage + * + * Input Parameters: + * value - parameter passed if called from a timer signal + * + * Returned Value: + * None + * + ****************************************************************************/ + +static void dump_cache(union sigval ptr) +{ + int ret = OK; + FAR bool *wrpend = (bool *)ptr.sival_ptr; + + int i; + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + assert(0); + } + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAX_STORAGES; i++) + { + if ((g_settings.store[i].file[0] != '\0') && + g_settings.store[i].save_fn) + { + ret = g_settings.store[i].save_fn(g_settings.store[i].file); +#if 0 + if (ret < 0) + { + /* What to do? We can't return anything from a void function. + * + * MIGHT BE A FUTURE REVISIT NEEDED + */ + } +#endif + } + } + + *wrpend = false; + + pthread_mutex_unlock(&g_settings.mtx); +} + +/**************************************************************************** + * Name: sanity_check + * + * Description: + * Checks that the string does not contain "illegal" characters + * + * Input Parameters: + * str - the string to check + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +static int sanity_check(FAR char *str) +{ +#ifdef CONFIG_DEBUG_ASSERTIONS + assert(strchr(str, '=') == NULL); + assert(strchr(str, ';') == NULL); + assert(strchr(str, '\n') == NULL); + assert(strchr(str, '\r') == NULL); +#else + if ((strchr(str, '=') != NULL) || (strchr(str, ';') != NULL) || + (strchr(str, '\n') != NULL) || (strchr(str, '\r') != NULL)) + { + return -EINVAL; + } + +#endif + + return OK; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: settings_init + * + * Description: + * Initializes the settings storage. + * + * Input Parameters: none + * + * Returned Value: none + * + ****************************************************************************/ + +void settings_init(void) +{ + pthread_mutexattr_t attr; + + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT); + pthread_mutex_init(&g_settings.mtx, &attr); + + memset(map, 0, sizeof(map)); + memset(g_settings.store, 0, sizeof(g_settings.store)); + memset(g_settings.notify, 0, sizeof(g_settings.notify)); + +#if defined(CONFIG_SYSTEM_SETTINGS_CACHED_SAVES) + memset(&g_settings.sev, 0, sizeof(struct sigevent)); + g_settings.sev.sigev_notify = SIGEV_THREAD; + g_settings.sev.sigev_signo = TIMER_SIGNAL; + g_settings.sev.sigev_value.sival_ptr = &g_settings.wrpend; + g_settings.sev.sigev_notify_function = dump_cache; + + memset(&g_settings.trigger, 0, sizeof(struct itimerspec)); + g_settings.trigger.it_value.tv_sec = + CONFIG_SYSTEM_SETTINGS_CACHE_TIME_MS / 1000; + g_settings.trigger.it_value.tv_nsec = + (CONFIG_SYSTEM_SETTINGS_CACHE_TIME_MS % 1000) * + 1000 * 1000; + + timer_create(CLOCK_REALTIME, &g_settings.sev, &g_settings.timerid); +#endif + g_settings.initialized = true; + g_settings.hash = 0; + g_settings.wrpend = false; +} + +/**************************************************************************** + * Name: settings_setstorage + * + * Description: + * Sets a file to be used as a settings storage. + * Except from the first file, if loading the file causes any changes + * to the settings, then the new map will be dumped to all files + * (effectively it syncs all storages). + * + * Input Parameters: + * file - the filename of the storage to use + * type - the type of the storage (BINARY or TEXT) + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_setstorage(FAR char *file, enum storage_type_e type) +{ + FAR storage_t *storage = NULL; + int ret = OK; + int idx = 0; + uint32_t h; + + if (!g_settings.initialized) + { + assert(0); + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + while ((idx < CONFIG_SYSTEM_SETTINGS_MAX_STORAGES) && + (g_settings.store[idx].file[0] != '\0')) + { + idx++; + } + + assert(idx < CONFIG_SYSTEM_SETTINGS_MAX_STORAGES); + if (idx >= CONFIG_SYSTEM_SETTINGS_MAX_STORAGES) + { + ret = -ENOSPC; + goto errout; + } + + assert(strlen(file) < CONFIG_SYSTEM_SETTINGS_MAX_FILENAME); + if (strlen(file) >= CONFIG_SYSTEM_SETTINGS_MAX_FILENAME) + { + ret = -EINVAL; + goto errout; + } + + storage = &g_settings.store[idx]; + strncpy(storage->file, file, sizeof(storage->file)); + storage->file[sizeof(storage->file) - 1] = '\0'; + + switch (type) + { + case STORAGE_BINARY: + { + storage->load_fn = load_bin; + storage->save_fn = save_bin; + } + break; + + case STORAGE_TEXT: + { + storage->load_fn = load_text; + storage->save_fn = save_text; + } + break; + + default: + { + assert(0); + } + break; + } + + ret = storage->load_fn(storage->file); + + h = hash_calc(); + + /* Only save if there are more than 1 storages. */ + + if ((storage != &g_settings.store[0]) && ((h != g_settings.hash) || + (access(file, F_OK) != 0))) + { + signotify(); + save(); + } + + g_settings.hash = h; + +errout: + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} + +/**************************************************************************** + * Name: settings_sync + * + * Description: + * Synchronizes the storage. + * + * wait_dump - if cached saves are enabled, this determines whether + * the function will wait until the save is actually + * completed or just schedule a new save + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_sync(bool wait_dump) +{ + int ret = OK; + uint32_t h; + + if (!g_settings.initialized) + { + assert(0); + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + ret = load(); + if (ret < 0) /* All storages failed to load */ + { + goto done; + } + + h = hash_calc(); + if (h != g_settings.hash) + { + g_settings.hash = h; + signotify(); + save(); + } + +done: + pthread_mutex_unlock(&g_settings.mtx); + +#ifdef CONFIG_SYSTEM_SETTINGS_CACHED_SAVES + if ((wait_dump && (ret >= 0))) + { + while (g_settings.wrpend) + { + usleep(10 * 1000); /* Sleep for 10ms */ + } + } +#endif + + return ret; +} + +/**************************************************************************** + * Name: settings_notify + * + * Description: + * Registers a task to be notified on any change of the settings. + * Whenever any value is changed, a signal will be sent to all + * registered threads. Signals are NOT sent when new settings are + * created or when the whole storage is cleared. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_notify(void) +{ + int ret; + int idx = 0; + + if (!g_settings.initialized) + { + assert(0); + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + while ((idx < CONFIG_SYSTEM_SETTINGS_MAX_SIGNALS) && + g_settings.notify[idx].pid) + { + idx++; + } + + assert(idx < CONFIG_SYSTEM_SETTINGS_MAX_SIGNALS); + if (idx >= CONFIG_SYSTEM_SETTINGS_MAX_SIGNALS) + { + ret = -EINVAL; + goto errout; + } + + g_settings.notify[idx].pid = getpid(); + g_settings.notify[idx].signo = CONFIG_SYSTEM_SETTINGS_SIGNO; + +errout: + pthread_mutex_unlock(&g_settings.mtx); + + return OK; +} + +/**************************************************************************** + * Name: settings_hash + * + * Description: + * Gets the hash of the settings storage. + * + * This hash represents the internal state of the settings map. A + * unique number is calculated based on the contents of the whole map. + * + * This hash can be used to check the settings for any alterations, i.e. + * any setting that may had its value changed since last check. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_hash(FAR uint32_t *h) +{ + if (!g_settings.initialized) + { + assert(0); + } + + *h = g_settings.hash; + + return OK; +} + +/**************************************************************************** + * Name: settings_clear + * + * Description: + * Clears all settings. + * Data in all storages are purged. + * + * Note that if the settings are cleared during the application run-time + * (i.e. not during initialization), every access to the settings storage + * will fail. + * + * All settings must be created again. This can be done either by calling + * Settings_create() again, or by restarting the application. + * + * Input Parameters: + * none + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_clear(void) +{ + int ret; + + if (!g_settings.initialized) + { + assert(0); + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + memset(map, 0, sizeof(map)); + g_settings.hash = 0; + + save(); + + pthread_mutex_unlock(&g_settings.mtx); + + while (g_settings.wrpend) + { + usleep(10 * 1000); /* Sleep for 10ms */ + } + + return OK; +} + +/**************************************************************************** + * Name: settings_create + * + * Description: + * Creates a new setting. + * + * If the setting is found to exist in any of the storages, it will + * be loaded. Else, it will be created and the default value will be + * assigned. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting. + * ... - the default value of the setting. + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_create(FAR char *key, enum settings_type_e type, ...) +{ + int ret = OK; + FAR setting_t *setting = NULL; + int j; + + if (!g_settings.initialized) + { + assert(0); + } + + assert(type != SETTING_EMPTY); + + assert(strlen(key)); + if (strlen(key) == 0) + { + return -EINVAL; + } + + assert(strlen(key) < CONFIG_SYSTEM_SETTINGS_KEY_SIZE); + if (strlen(key) >= CONFIG_SYSTEM_SETTINGS_KEY_SIZE) + { + return -EINVAL; + } + + assert(isalpha(key[0]) && (sanity_check(key) == OK)); + if (!isalpha(key[0]) || (sanity_check(key) < 0)) + { + return -EINVAL; + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + for (j = 0; j < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; j++) + { + if (strcmp(key, map[j].key) == 0) + { + setting = &map[j]; + + /* We found a setting with this key name */ + + goto errout; + } + + if (map[j].type == SETTING_EMPTY) + { + setting = &map[j]; + strncpy(setting->key, key, CONFIG_SYSTEM_SETTINGS_KEY_SIZE); + setting->key[CONFIG_SYSTEM_SETTINGS_KEY_SIZE - 1] = '\0'; + + /* This setting is empty/unused - we can use it */ + + break; + } + } + + assert(setting); + if (setting == NULL) + { + goto errout; + } + + if ((setting->type == SETTING_EMPTY) || + (setting->type != type)) + { + bool set_val = false; + + va_list ap; + va_start(ap, type); + + switch (type) + { + case SETTING_STRING: + { + FAR char *str = va_arg(ap, FAR char *); + + if ((setting->type == SETTING_STRING) || + (setting->type == SETTING_IP_ADDR)) + { + break; + } + + set_val = true; + setting->type = SETTING_STRING; + ret = set_string(setting, str); + } + break; + + case SETTING_INT: + { + int i = va_arg(ap, int); + + if ((setting->type == SETTING_INT) || + (setting->type == SETTING_BOOL) || + (setting->type == SETTING_FLOAT)) + { + break; + } + + set_val = true; + setting->type = SETTING_INT; + ret = set_int(setting, i); + } + break; + + case SETTING_BOOL: + { + int i = va_arg(ap, int); + + if ((setting->type == SETTING_BOOL) || + (setting->type == SETTING_INT)) + { + break; + } + + set_val = true; + setting->type = SETTING_BOOL; + ret = set_bool(setting, i); + } + break; + + case SETTING_FLOAT: + { + double f = va_arg(ap, double); + + if ((setting->type == SETTING_FLOAT) || + (setting->type == SETTING_INT)) + { + break; + } + + set_val = true; + setting->type = SETTING_FLOAT; + ret = set_float(setting, f); + } + break; + + case SETTING_IP_ADDR: + { + FAR struct in_addr *ip = va_arg(ap, FAR struct in_addr *); + + if ((setting->type == SETTING_IP_ADDR) || + (setting->type == SETTING_STRING)) + { + break; + } + + set_val = true; + setting->type = SETTING_IP_ADDR; + ret = set_ip(setting, ip); + } + break; + + default: + case SETTING_EMPTY: + { + assert(0); + ret = -EINVAL; + } + break; + } + + va_end(ap); + + if ((ret < 0) || !set_val) + { + memset(setting, 0, sizeof(setting_t)); + setting = NULL; + } + else + { + g_settings.hash = hash_calc(); + save(); + } + } + +errout: + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} + +/**************************************************************************** + * Name: settings_type + * + * Description: + * Gets the type of a setting. + * + * Input Parameters: + * key - the key of the setting. + * type - pointer to int for the returned setting type + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_type(FAR char *key, FAR enum settings_type_e *stype) +{ + int ret; + FAR setting_t *setting; + + if (!g_settings.initialized) + { + assert(0); + } + + assert(stype != NULL); + assert(key != NULL); + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + ret = get_setting(key, &setting); + + if (setting) + { + *stype = setting->type; + } + + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} + +/**************************************************************************** + * Name: settings_get + * + * Description: + * Gets the value of a setting. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting + * ... - pointer to store the setting value plus, if a string + * setting, the length of the string to get + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_get(FAR char *key, enum settings_type_e type, ...) +{ + int ret; + FAR setting_t *setting; + + if (!g_settings.initialized) + { + assert(0); + } + + assert(type != SETTING_EMPTY); + assert(key[0] != '\0'); + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + ret = get_setting(key, &setting); + if (ret < 0) + { + goto errout; + } + + va_list ap; + va_start(ap, type); + + switch (type) + { + case SETTING_STRING: + { + FAR char *buf = va_arg(ap, FAR char *); + size_t len = va_arg(ap, size_t); + ret = (int)get_string(setting, buf, len); + } + break; + + case SETTING_INT: + { + FAR int *i = va_arg(ap, FAR int *); + ret = get_int(setting, i); + } + break; + + case SETTING_BOOL: + { + FAR int *i = va_arg(ap, FAR int *); + ret = get_bool(setting, i); + } + break; + + case SETTING_FLOAT: + { + FAR double *f = va_arg(ap, FAR double *); + ret = get_float(setting, f); + } + break; + + case SETTING_IP_ADDR: + { + FAR struct in_addr *ip = va_arg(ap, FAR struct in_addr *); + ret = get_ip(setting, ip); + } + break; + + default: + { + assert(0); + } + break; + } + + va_end(ap); + +errout: + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} + +/**************************************************************************** + * Name: settings_set + * + * Description: + * Sets the value of a setting. The type can be changed, within limits, + * here too. + * + * Input Parameters: + * key - the key of the setting. + * type - the type of the setting + * ... - the new value of the setting. + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_set(FAR char *key, enum settings_type_e type, ...) +{ + int ret; + FAR setting_t *setting; + uint32_t h; + + if (!g_settings.initialized) + { + assert(0); + } + + assert(type != SETTING_EMPTY); + assert(key[0] != '\0'); + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + ret = get_setting(key, &setting); + if (ret < 0) + { + goto errout; + } + + va_list ap; + va_start(ap, type); + + switch (type) + { + case SETTING_STRING: + { + FAR char *str = va_arg(ap, FAR char *); + ret = set_string(setting, str); + } + break; + + case SETTING_INT: + { + int i = va_arg(ap, int); + ret = set_int(setting, i); + } + break; + + case SETTING_BOOL: + { + int i = va_arg(ap, int); + ret = set_bool(setting, i); + } + break; + + case SETTING_FLOAT: + { + double f = va_arg(ap, double); + ret = set_float(setting, f); + } + break; + + case SETTING_IP_ADDR: + { + FAR struct in_addr *ip = va_arg(ap, FAR struct in_addr *); + ret = set_ip(setting, ip); + } + break; + + default: + { + assert(0); + } + break; + } + + va_end(ap); + + if (ret >= 0) + { + h = hash_calc(); + if (h != g_settings.hash) + { + g_settings.hash = h; + + signotify(); + save(); + } + } + +errout: + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} + +/**************************************************************************** + * Name: settings_iterate + * + * Description: + * Gets a copy of a setting at the specified position. It can be used to + * iterate over the settings map, by using successive values of idx. + * + * Input Parameters: + * idx - the iteration index for the setting. + * setting - pointer to return the setting value + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int settings_iterate(int idx, FAR setting_t *setting) +{ + int ret; + + if (!g_settings.initialized) + { + assert(0); + } + + assert(setting); + + if ((idx < 0) || (idx >= CONFIG_SYSTEM_SETTINGS_MAP_SIZE)) + { + memset(setting, 0, sizeof(setting_t)); + return -EINVAL; + } + + ret = pthread_mutex_lock(&g_settings.mtx); + if (ret < 0) + { + return ret; + } + + memcpy(setting, &map[idx], sizeof(setting_t)); + + if (map[idx].type == SETTING_EMPTY) + { + ret = -ENOENT; + } + + pthread_mutex_unlock(&g_settings.mtx); + + return ret; +} diff --git a/testing/gpu/gpu_screenshot.h b/system/settings/storage.h similarity index 80% rename from testing/gpu/gpu_screenshot.h rename to system/settings/storage.h index 858c60c51..dd6672baa 100644 --- a/testing/gpu/gpu_screenshot.h +++ b/system/settings/storage.h @@ -1,5 +1,5 @@ /**************************************************************************** - * apps/testing/gpu/gpu_screenshot.h + * apps/system/settings/storage.h * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with @@ -18,15 +18,15 @@ * ****************************************************************************/ -#ifndef __APPS_TESTING_GPU_GPU_SCREENSHOT_H -#define __APPS_TESTING_GPU_GPU_SCREENSHOT_H +#ifndef SETTINGS_STORAGE_H_ +#define SETTINGS_STORAGE_H_ /**************************************************************************** * Included Files ****************************************************************************/ #include -#include +#include "system/settings.h" /**************************************************************************** * Pre-processor Definitions @@ -36,29 +36,28 @@ * Public Types ****************************************************************************/ -struct gpu_test_context_s; +/**************************************************************************** + * Public Data + ****************************************************************************/ /**************************************************************************** * Public Function Prototypes ****************************************************************************/ -#ifdef __cplusplus -#define EXTERN extern "C" -extern "C" -{ -#else -#define EXTERN extern -#endif +/* Text storage. */ -/**************************************************************************** - * Name: vglite_log_printf - ****************************************************************************/ +int load_text(FAR char *file); +int save_text(FAR char *file); -int gpu_screenshot(FAR struct gpu_test_context_s *ctx, FAR const char *name); +/* Binary storage. */ -#undef EXTERN -#ifdef __cplusplus -} -#endif +int load_bin(FAR char *file); +int save_bin(FAR char *file); + +/* EEPROM storage. */ + +int load_eeprom(FAR char *file); +int save_eeprom(FAR char *file); + +#endif /* SETTINGS_STORAGE_H_*/ -#endif /* __APPS_TESTING_GPU_GPU_SCREENSHOT_H */ diff --git a/system/settings/storage_bin.c b/system/settings/storage_bin.c new file mode 100644 index 000000000..6c6ed6777 --- /dev/null +++ b/system/settings/storage_bin.c @@ -0,0 +1,285 @@ +/**************************************************************************** + * apps/system/settings/storage_bin.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include "system/settings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define BUFFER_SIZE 256 /* Note alignment for Flash writes! */ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Name: getsetting + * + * Description: + * Gets the setting information from a given key. + * + * Input Parameters: + * key - key of the required setting + * + * Returned Value: + * The setting + * + ****************************************************************************/ + +FAR static setting_t *getsetting(char *key); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +extern setting_t map[CONFIG_SYSTEM_SETTINGS_MAP_SIZE]; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: getsetting + * + * Description: + * Gets the setting information from a given key. + * + * Input Parameters: + * key - key of the required setting + * + * Returned Value: + * The setting + * + ****************************************************************************/ + +FAR setting_t *getsetting(FAR char *key) +{ + int i; + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; i++) + { + FAR setting_t *setting = &map[i]; + + if (strcmp(key, setting->key) == 0) + { + return setting; + } + + if (setting->type == SETTING_EMPTY) + { + return setting; + } + } + + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: load_bin + * + * Description: + * Loads binary data from a storage file. + * + * Input Parameters: + * file - the filename of the storage to use + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int load_bin(FAR char *file) +{ + int fd; + int i; + int ret = OK; + uint16_t valid; + uint16_t count; + uint32_t calc_crc = 0; + uint32_t exp_crc = 0; + setting_t setting; + FAR setting_t *slot; + + fd = open(file, O_RDONLY); + if (fd < 0) + { + return -ENOENT; + } + + valid = 0; + read(fd, &valid, sizeof(uint16_t)); + + if (valid != VALID) + { + ret = -EBADMSG; + goto abort; /* Just exit - the settings aren't valid */ + } + + count = 0; + read(fd, &count, sizeof(uint16_t)); + + for (i = 0; i < count; i++) + { + read(fd, &setting, sizeof(setting_t)); + calc_crc = crc32part((FAR uint8_t *)&setting, sizeof(setting_t), + calc_crc); + } + + read(fd, &exp_crc, sizeof(uint32_t)); + + if (calc_crc != exp_crc) + { + ret = -EBADMSG; + goto abort; + } + + lseek(fd, (sizeof(uint16_t) * 2), SEEK_SET); /* Get after valid & size */ + + for (i = 0; i < count; i++) + { + read(fd, &setting, sizeof(setting_t)); + + slot = getsetting(setting.key); + if (slot == NULL) + { + continue; + } + + memcpy(slot, &setting, sizeof(setting_t)); + } + +abort: + close(fd); + return ret; +} + +/**************************************************************************** + * Name: save_bin + * + * Description: + * Saves binary data to a storage file. + * + * Input Parameters: + * file - the filename of the storage to use + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int save_bin(FAR char *file) +{ + int count; + int fd; + int ret = OK; + off_t offset = sizeof(uint16_t) * 2; /* Valid & count */ + size_t data_size; + size_t rem_data; + uint32_t crc; + size_t rem_crc; + FAR uint8_t *buffer = malloc(BUFFER_SIZE); + + if (buffer == NULL) + { + return -ENOMEM; + } + + count = 0; + int i; + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; i++) + { + if (map[i].type == SETTING_EMPTY) + { + break; + } + + count++; + } + + fd = open(file, (O_RDWR | O_TRUNC), 0666); + if (fd < 0) + { + ret = -ENODEV; + goto abort; + } + + memset(buffer, 0xff, BUFFER_SIZE); + *((FAR uint16_t *)buffer) = VALID; + *(((FAR uint16_t *)buffer) + 1) = count; + + data_size = count *sizeof(setting_t); + rem_data = data_size; + crc = crc32((FAR uint8_t *)map, data_size); + rem_crc = sizeof(crc); + + while ((offset + rem_data + rem_crc) > 0) + { + size_t to_write = ((offset + rem_data) > BUFFER_SIZE) ? + (size_t)(BUFFER_SIZE - offset) : rem_data; + memcpy((buffer + offset), (((FAR uint8_t *)map) + + (data_size - rem_data)), to_write); + + size_t j; + for (j = (to_write + offset); + (j < BUFFER_SIZE) && (rem_crc > 0); j++, rem_crc--) + { + off_t crc_byte = (off_t)(sizeof(crc) - rem_crc); + buffer[j] = (crc >> (8 * crc_byte)) & 0xff; + } + + write(fd, buffer, BUFFER_SIZE); + rem_data -= to_write; + offset = 0; + } + + close(fd); + +abort: + free(buffer); + + return ret; +} + diff --git a/system/settings/storage_text.c b/system/settings/storage_text.c new file mode 100644 index 000000000..d1d4f85fe --- /dev/null +++ b/system/settings/storage_text.c @@ -0,0 +1,425 @@ +/**************************************************************************** + * apps/system/settings/storage_text.c + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. The + * ASF licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the + * License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include "system/settings.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define BUFFER_SIZE 256 /* Note alignment for Flash writes! */ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Name: getsetting + * + * Description: + * Gets the setting information from a given key. + * + * Input Parameters: + * key - key of the required setting + * + * Returned Value: + * The setting + * + ****************************************************************************/ + +FAR static setting_t *getsetting(char *key); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +extern setting_t map[CONFIG_SYSTEM_SETTINGS_MAP_SIZE]; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: getsetting + * + * Description: + * Gets the setting information from a given key. + * + * Input Parameters: + * key - key of the required setting + * + * Returned Value: + * The setting + * + ****************************************************************************/ + +FAR setting_t *getsetting(char *key) +{ + int i; + FAR setting_t *setting; + + if (strlen(key) >= CONFIG_SYSTEM_SETTINGS_KEY_SIZE) + { + return NULL; + } + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; i++) + { + setting = &map[i]; + + if (strcmp(key, setting->key) == 0) + { + return setting; + } + + if (setting->type == SETTING_EMPTY) + { + strncpy(setting->key, key, CONFIG_SYSTEM_SETTINGS_KEY_SIZE); + setting->key[CONFIG_SYSTEM_SETTINGS_KEY_SIZE - 1] = '\0'; + return setting; + } + } + + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: load_text + * + * Description: + * Loads text from a storage file. + * + * Input Parameters: + * file - the filename of the storage to use + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int load_text(FAR char *file) +{ + int ret = OK; + FAR FILE *f; + FAR char *eq; + FAR char *key; + FAR char *val; + FAR char *backup_file; + FAR char *buffer; + FAR setting_t *setting; + + /* Check that the file exists */ + + if (access(file, F_OK) != 0) + { + /* If not, try the backup file */ + + backup_file = malloc(strlen(file) + 2); + if (backup_file == NULL) + { + return -ENODEV; + } + + strcpy(backup_file, file); + strcat(backup_file, "~"); + + if (access(backup_file, F_OK) == 0) + { + /* There is a backup file + * Restore this as the new settings file + */ + + rename(backup_file, file); + } + + free(backup_file); + } + + f = fopen(file, "r"); + if (f == NULL) + { + return -ENOENT; + } + + buffer = malloc(BUFFER_SIZE); + if (buffer == NULL) + { + ret = -ENOMEM; + goto abort; + } + + while (fgets(buffer, BUFFER_SIZE, f)) + { + int i; + + /* Remove any line terminators */ + + for (i = ((int)strlen(buffer) - 1); i > 0; i--) + { + if (buffer[i] == ';' || buffer[i] == '\n' || buffer[i] == '\r') + { + buffer[i] = '\0'; + } + else + { + break; + } + } + + /* Separate the key / value pair */ + + eq = strchr(buffer, '='); + if (eq == NULL) + { + continue; + } + + key = buffer; + val = eq + 1; + *eq = '\0'; + + /* Check if the key is valid */ + + if (!isalpha(key[0])) + { + continue; + } + + /* Get the setting slot */ + + setting = getsetting(key); + if (setting == NULL) + { + continue; + } + + /* Parse the value */ + + if (isalpha(val[0])) + { + if (strcasecmp(val, "true") == 0) + { + /* It's a boolean */ + + setting->type = SETTING_BOOL; + setting->val.i = 1; + } + else if (strcasecmp(val, "false") == 0) + { + /* It's a boolean */ + + setting->type = SETTING_BOOL; + setting->val.i = 0; + } + else + { + /* It's a string */ + + if (strlen(val) >= CONFIG_SYSTEM_SETTINGS_VALUE_SIZE) + { + continue; + } + + setting->type = SETTING_STRING; + strncpy(setting->val.s, val, + CONFIG_SYSTEM_SETTINGS_VALUE_SIZE); + setting->val.s[CONFIG_SYSTEM_SETTINGS_VALUE_SIZE - 1] = '\0'; + } + } + else + { + if (strchr(val, '.') != NULL) + { + FAR char *s = val; + i = 0; + while (s[i]) s[i] == '.' ? i++ : *s++; + if (i == 1) + { + /* It's a float */ + + double d = 0; + if (sscanf(val, "%lf", &d) == 1) + { + setting->type = SETTING_FLOAT; + setting->val.f = d; + } + } + else if (i == 3) + { + /* It's an IP address */ + + setting->type = SETTING_IP_ADDR; + inet_pton(AF_INET, val, &setting->val.ip); + } + } + else + { + /* It's an integer */ + + i = 0; + if (sscanf(val, "%d", &i) == 1) + { + setting->type = SETTING_INT; + setting->val.i = i; + } + } + } + + /* Handle parse errors */ + + if (setting->type == SETTING_EMPTY) + { + memset(setting->key, 0, CONFIG_SYSTEM_SETTINGS_KEY_SIZE); + } + } + + free(buffer); + +abort: + fclose(f); + + return ret; +} + +/**************************************************************************** + * Name: save_text + * + * Description: + * Saves text to a storage file. + * + * Input Parameters: + * file - the filename of the storage to use + * + * Returned Value: + * Success or negated failure code + * + ****************************************************************************/ + +int save_text(FAR char *file) +{ + int ret = OK; + FAR char *backup_file = malloc(strlen(file) + 2); + FAR FILE *f; + int i; + + if (backup_file == NULL) + { + return -ENODEV; + } + + strcpy(backup_file, file); + strcat(backup_file, "~"); + + f = fopen(backup_file, "w"); + if (f == NULL) + { + ret = -ENODEV; + goto abort; + } + + for (i = 0; i < CONFIG_SYSTEM_SETTINGS_MAP_SIZE; i++) + { + if (map[i].type == SETTING_EMPTY) + { + break; + } + + switch (map[i].type) + { + case SETTING_STRING: + { + fprintf(f, "%s=%s\n", map[i].key, + map[i].val.s); + } + break; + + case SETTING_INT: + { + fprintf(f, "%s=%d\n", map[i].key, + map[i].val.i); + } + break; + case SETTING_BOOL: + { + fprintf(f, "%s=%s\n", map[i].key, + map[i].val.i ? + "true" : "false"); + } + break; + + case SETTING_FLOAT: + { + fprintf(f, "%s=%.06f\n", map[i].key, + map[i].val.f); + } + break; + + case SETTING_IP_ADDR: + { + char buffer[20]; + inet_ntop(AF_INET, &map[i].val.ip, buffer, 20); + fprintf(f, "%s=%s\n", map[i].key, buffer); + } + break; + + default: + { + return -EINVAL; + } + break; + } + } + + fclose(f); + + remove(file); + rename(backup_file, file); + +abort: + free(backup_file); + + return ret; +} diff --git a/system/spi/README.md b/system/spi/README.md deleted file mode 100644 index 2e6e3c5af..000000000 --- a/system/spi/README.md +++ /dev/null @@ -1,246 +0,0 @@ -# System / `spi` SPI Tool - -The I2C tool provides a way to debug SPI related problems. This README file will -provide usage information for the SPI tools. - -## Contents - -- System Requirements - - SPI Driver - - Configuration Options -- Help -- Common Line Form -- Common Command Options - - _Sticky_ Options - - Environment variables - - Common Option Summary -- Command summary - - `bus` - - `dev` - - `get` - - `set` - - `verf` -- I2C Build Configuration - - NuttX Configuration Requirements - - I2C Tool Configuration Options - -## System Requirements - -The SPI tool is designed to be implemented as a NuttShell (NSH) add-on. Read the -`apps/nshlib/README.md` file for information about add-ons. - -### Configuration Options - -- `CONFIG_NSH_BUILTIN_APPS` – Build the tools as an NSH built-in command. -- `CONFIG_SPITOOL_MINBUS` – Smallest bus index supported by the hardware - (default `0`). -- `CONFIG_SPITOOL_MAXBUS` – Largest bus index supported by the hardware - (default `3`). -- `CONFIG_SPITOOL_DEFFREQ` – Default frequency (default: `40000000`). -- `CONFIG_SPITOOL_DEFMODE` – Default mode, where - ``` - 0 = CPOL=0, CPHA=0 - 1 = CPOL=0, CPHA=1 - 2 = CPOL=1, CPHA=0 - 3 = CPOL=1, CPHA=1 - ``` -- `CONFIG_SPITOOL_DEFWIDTH` – Default bit width (default `8`). -- `CONFIG_SPITOOL_DEFWORDS` – Default number of words to exchange (default `1`). - -## Help - -The SPI tools supports some help output. That help output can be view by -entering either: - -``` -nsh> spi help -``` - -or - -``` -nsh> spi ? -``` - -Here is an example of the help output. I shows the general form of the command -line, the various SPI commands supported with their unique command line options, -and a more detailed summary of the command SPI command options. - -``` -nsh> Usage: spi [arguments] - -Where is one of: - - Show help : ? - List buses : bus - SPI Exchange : exch [OPTIONS] [] - Show help : help - -Where common _sticky_ OPTIONS include: - [-b bus] is the SPI bus number (decimal). Default: 0 Current: 2 - [-f freq] SPI frequency. Default: 4000000 Current: 4000000 - [-m mode] Mode for transfer. Default: 0 Current: 0 - [-u udelay] Delay after transfer in uS. Default: 0 Current: 0 - [-w width] Width of bus. Default: 8 Current: 8 - [-x count] Words to exchange. Default: 1 Current: 4 -``` - -**Notes**: - -- An environment variable like $PATH may be used for any argument. -- Arguments are _sticky_. For example, once the SPI address is specified, that - address will be re-used until it is changed. - -**Warning**: - -- The SPI commands may have bad side effects on your SPI devices. Use only at - your own risk. - -## Command Line Form - -The SPI is started from NSH by invoking the `spi` command from the NSH command -line. The general form of the `spi` command is: - -```shell -spi [arguments] -``` - -Where `` is a _sub-command_ and identifies one SPI operation supported by -the tool. `[arguments]` represents the list of arguments needed to perform the -SPI operation. Those arguments vary from command to command as described below. -However, there is also a core set of common `OPTIONS` supported by all commands. -So perhaps a better representation of the general SPI command would be: - -```shell -i2c [OPTIONS] [arguments] -``` - -Where `[OPTIONS]` represents the common options and and arguments represent the -operation-specific arguments. - -## Common Command Options - -### _Sticky_ Options - -In order to interact with SPI devices, there are a number of SPI parameters that -must be set correctly. One way to do this would be to provide to set the value -of each separate command for each SPI parameter. The SPI tool takes a different -approach, instead: The SPI configuration can be specified as a (potentially -long) sequence of command line arguments. - -These arguments, however, are _sticky_. They are sticky in the sense that once -you set the SPI parameter, that value will remain until it is reset with a new -value (or until you reset the board). - -### Environment Variables - -**Note** also that if environment variables are not disabled (by -`CONFIG_DISABLE_ENVIRON=y`), then these options may also be environment -variables. Environment variables must be preceded with the special character -`$`. For example, `PWD` is the variable that holds the current working directory -and so `$PWD` could be used as a command line argument. The use of environment -variables on the I2C tools command is really only useful if you wish to write -NSH scripts to execute a longer, more complex series of SPI commands. - -### Common Option Summary - -- `[-b bus]` is the SPI bus number (decimal). Default: `0` - - Which SPI bus to commiuncate on. The bus must have been initialised as a - character device in the config in the form `/dev/spiX` (e.g. `/dev/spi2`). - - The valid range of bus numbers is controlled by the configuration settings - `CONFIG_SPITOOL_MINBUS` and `CONFIG_SPITOOL_MAXBUS`. - - The bus numbers are small, decimal numbers. - -- `[-m mode]` SPI Mode for transfer. - - Which of the available SPI modes is to be used. Options are; - - ``` - 0 = CPOL=0, CPHA=0 - 1 = CPOL=0, CPHA=1 - 2 = CPOL=1, CPHA=0 - 3 = CPOL=1, CPHA=1 - ``` - -- `[-u udelay]` Delay after transfer in uS. Default: `0` - - Any extra delay to be provided after the transfer. Not normally needed from - the command line. - -- `[-x count]` Words to exchange Default: `1` - - The number of words to be transited over the bus. For sanitys sake this is - limited to a relatively small number (`40` by default). Any data on the - command line is sent first, padded by `0xFF`'s while any remaining data are - received. - -- `[-w width]` is the data width (varies according to target). Default: `8` - - Various SPI devices support different data widths. This option is untested. - -- `[-f freq]` I2C frequency. Default: `4000000` Current: `4000000` - - The `[-f freq]` sets the frequency of the SPI device. The default is very - conservative. - -## Command Summary - -### List buses: `bus [OPTIONS]` - -This command will simply list all of the configured SPI buses and indicate which -are supported by the driver and which are not: - -``` -BUS EXISTS? -Bus 1: YES -Bus 2: NO -``` - -The valid range of bus numbers is controlled by the configuration settings -`CONFIG_SPITOOL_MINBUS` and `CONFIG_SPITOOL_MAXBUS`. - -### Exchange data: `exch [OPTIONS] ` - -This command triggers an SPI transfer, returning the data back from the far end. -As an example (with MOSI looped back to MISO); - -```shell -nsh> spi exch -b 2 -x 4 aabbccdd -``` - -``` -Received: AA BB CC DD -``` - -Note that the `TX Data` are always specified in hex, and are always two digits -each, case insensitive. - -## I2C Build Configuration - -### NuttX Configuration Requirements - -The SPI tools requires the following in your NuttX configuration: - -1. Application configuration. - - Using `make menuconfig`, select the SPI tool. The following definition should - appear in your `.config` file: - - ```conf - CONFIG_SYSTEM_SPI=y - ``` - -2. Device-specific SPI driver support must be enabled: - - ```conf - CONFIG_SPI_DRIVER=y - ``` - - The SPI tool will then use the SPI character driver to access the SPI bus. - These devices will reside at `/dev/spiN` where `N` is the I2C bus number. - - **Note**: The SPI driver `ioctl` interface is defined in - `include/nuttx/spi/spi.h`. diff --git a/system/spi/spi_exch.c b/system/spi/spi_exch.c index 31db5d83e..1a898484e 100644 --- a/system/spi/spi_exch.c +++ b/system/spi/spi_exch.c @@ -154,6 +154,13 @@ int spicmd_exch(FAR struct spitool_s *spitool, int argc, FAR char **argv) seq.ntrans = 1; seq.trans = &trans; +#ifdef CONFIG_SPI_DELAY_CONTROL + seq.a = 0; + seq.b = 0; + seq.i = 0; + seq.c = 0; +#endif + trans.deselect = true; #ifdef CONFIG_SPI_CMDDATA trans.cmd = spitool->command; diff --git a/system/system/system.c b/system/system/system.c index 95e4e81cf..5ecc3ae8b 100644 --- a/system/system/system.c +++ b/system/system/system.c @@ -23,7 +23,14 @@ ****************************************************************************/ #include + +#include +#include +#include +#include #include +#include +#include #include "nshlib/nshlib.h" @@ -54,6 +61,12 @@ int system(FAR const char *cmd) { FAR char *argv[4]; + struct sched_param param; + posix_spawnattr_t attr; + pid_t pid; + int errcode; + int rc; + int ret; /* REVISIT: If cmd is NULL, then system() should return a non-zero value to * indicate if the command processor is available or zero if it is not. @@ -61,10 +74,56 @@ int system(FAR const char *cmd) DEBUGASSERT(cmd != NULL); -#ifdef CONFIG_SYSTEM_SYSTEM_SHPATH - argv[0] = CONFIG_SYSTEM_SYSTEM_SHPATH; + /* Initialize attributes for task_spawn() (or posix_spawn()). */ + + errcode = posix_spawnattr_init(&attr); + if (errcode != 0) + { + goto errout; + } + + /* Set the correct stack size and priority */ + + param.sched_priority = CONFIG_SYSTEM_SYSTEM_PRIORITY; + errcode = posix_spawnattr_setschedparam(&attr, ¶m); + if (errcode != 0) + { + goto errout_with_attrs; + } + + errcode = posix_spawnattr_setstacksize(&attr, + CONFIG_SYSTEM_SYSTEM_STACKSIZE); + if (errcode != 0) + { + goto errout_with_attrs; + } + + /* If robin robin scheduling is enabled, then set the scheduling policy + * of the new task to SCHED_RR before it has a chance to run. + */ + +#if CONFIG_RR_INTERVAL > 0 + errcode = posix_spawnattr_setschedpolicy(&attr, SCHED_RR); + if (errcode != 0) + { + goto errout_with_attrs; + } + + errcode = posix_spawnattr_setflags(&attr, + POSIX_SPAWN_SETSCHEDPARAM | + POSIX_SPAWN_SETSCHEDULER); + if (errcode != 0) + { + goto errout_with_attrs; + } + #else - argv[0] = "system"; + errcode = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSCHEDPARAM); + if (errcode != 0) + { + goto errout_with_attrs; + } + #endif /* Spawn nsh_system() which will execute the command under the shell. */ @@ -73,6 +132,42 @@ int system(FAR const char *cmd) argv[2] = (FAR char *)cmd; argv[3] = NULL; - return nsh_spawn(argv[0], nsh_system, argv, CONFIG_SYSTEM_SYSTEM_PRIORITY, - CONFIG_SYSTEM_SYSTEM_STACKSIZE, NULL, 0, true); +#ifdef CONFIG_SYSTEM_SYSTEM_SHPATH + argv[0] = CONFIG_SYSTEM_SYSTEM_SHPATH; + errcode = posix_spawn(&pid, argv[0], NULL, &attr, argv, NULL); +#else + pid = task_spawn("system", nsh_system, NULL, &attr, argv + 1, NULL); + if (pid < 0) + { + errcode = -pid; + } +#endif + + /* Release the attributes and check for an error from the spawn operation */ + + if (errcode != 0) + { + serr("ERROR: Spawn failed: %d\n", errcode); + goto errout_with_attrs; + } + + /* Wait for the shell to return */ + + ret = waitpid(pid, &rc, 0); + if (ret < 0) + { + /* The errno variable has already been set */ + + rc = ERROR; + } + + posix_spawnattr_destroy(&attr); + return rc; + +errout_with_attrs: + posix_spawnattr_destroy(&attr); + +errout: + errno = errcode; + return ERROR; } diff --git a/system/taskset/taskset.c b/system/taskset/taskset.c index 9a973190b..3cffd2e28 100644 --- a/system/taskset/taskset.c +++ b/system/taskset/taskset.c @@ -138,7 +138,8 @@ int main(int argc, FAR char *argv[]) goto errout; } - printf("pid %d's current affinity mask: 0x%" PRIx32 "\n", pid, cpuset); + printf("pid %d's current affinity mask: 0x%" PRIx32 "\n", pid, + (uint32_t)cpuset); } else { diff --git a/system/telnet/telnet_chatd.c b/system/telnet/telnet_chatd.c index 5a7ca4fe5..17c4a7d1a 100644 --- a/system/telnet/telnet_chatd.c +++ b/system/telnet/telnet_chatd.c @@ -118,15 +118,15 @@ static void cleanup_exit(void) close(g_users[i].sock); free(g_users[i].name); telnet_free(g_users[i].telnet); - } + } } exit(1); } static void linebuffer_push(char *buffer, size_t size, int *linepos, - char ch, void (*cb) (const char *line, - int overflow, void *ud), void *ud) + char ch, void (*cb) (const char *line, int overflow, + void *ud), void *ud) { /* CRLF -- line terminator */ @@ -272,8 +272,7 @@ static void _online(const char *line, int overflow, void *ud) _message(user->name, line); } -static void _input(struct user_s *user, const char *buffer, - unsigned int size) +static void _input(struct user_s *user, const char *buffer, unsigned int size) { unsigned int i; @@ -330,7 +329,6 @@ static void _event_handler(struct telnet_s *telnet, break; default: - /* Ignore */ break; @@ -385,8 +383,7 @@ int main(int argc, FAR char *argv[]) /* Reuse address option */ ret = 1; - setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&ret, - sizeof(ret)); + setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&ret, sizeof(ret)); /* Bind to listening addr/port */ @@ -417,7 +414,7 @@ int main(int argc, FAR char *argv[]) /* Loop for ever */ - for (; ; ) + for (;;) { /* Prepare for poll */ @@ -451,8 +448,8 @@ int main(int argc, FAR char *argv[]) /* Accept the sock */ addrlen = sizeof(addr); - if ((ret = accept4(listen_sock, (struct sockaddr *)&addr, - &addrlen, SOCK_CLOEXEC)) == -1) + if ((ret = accept(listen_sock, (struct sockaddr *)&addr, + &addrlen)) == -1) { fprintf(stderr, "accept() failed: %d\n", errno); cleanup_exit(); @@ -480,14 +477,12 @@ int main(int argc, FAR char *argv[]) /* Init, welcome */ g_users[i].sock = ret; - g_users[i].telnet = telnet_init(g_telopts, _event_handler, 0, - &g_users[i]); + g_users[i].telnet = telnet_init(g_telopts, _event_handler, 0, &g_users[i]); telnet_negotiate(g_users[i].telnet, TELNET_WILL, TELNET_TELOPT_COMPRESS2); telnet_printf(g_users[i].telnet, "Enter name: "); - telnet_negotiate(g_users[i].telnet, TELNET_WILL, - TELNET_TELOPT_ECHO); + telnet_negotiate(g_users[i].telnet, TELNET_WILL, TELNET_TELOPT_ECHO); } /* Read from client */ @@ -503,8 +498,7 @@ int main(int argc, FAR char *argv[]) if (pfd[i].revents & (POLLIN | POLLERR | POLLHUP)) { - if ((ret = - recv(g_users[i].sock, buffer, sizeof(buffer), 0)) > 0) + if ((ret = recv(g_users[i].sock, buffer, sizeof(buffer), 0)) > 0) { telnet_recv(g_users[i].telnet, buffer, ret); } diff --git a/system/telnetd/Kconfig b/system/telnetd/Kconfig index 407e1ce5c..bc50ec961 100644 --- a/system/telnetd/Kconfig +++ b/system/telnetd/Kconfig @@ -40,6 +40,6 @@ config SYSTEM_TELNETD_SESSION_PRIORITY config SYSTEM_TELNETD_SESSION_STACKSIZE int "Telnetd session task stack size" - default SYSTEM_NSH_STACKSIZE + default 3072 endif # SYSTEM_TELNETD diff --git a/system/termcurses/README.md b/system/termcurses/README.md deleted file mode 100644 index 9a23cf9b0..000000000 --- a/system/termcurses/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# System / `termcurses` Termcurses - -Terminal emulation library for NuttX - -``` -Author: Ken Pettit - Date: 2018-2019 -``` - -The Termcurses library provides terminal emulation support for performing common -screen actions such as cursor movement, foreground / background color control -and keyboard escape sequence mapping. The initial release supports only `vt100` -/ `ansi` terminal types, but the library architecture has an extensible -interface to allow support for additional emulation types if needed. - -The library can be used standalone or in conjunction with the -`apps/graphics/pdcurses` libraries. The pdcurses libraries have been updated -with a _termcurses_ config option which fully integrates the termcurses library -automatically. - -## Usage - -To use the termcurses library, the routines must be initialized by calling the -`termcurses_initterm()` function. This routine accepts a terminal type string -identifying the type of terminal emulation support requested. If a `NULL` -pointer is passed, then the routine will check for a `TERM` environment variable -and set the terminal type based on that string. If the emulation type still -cannot be determined, the routine will default to `vt100` emulation type. - -Upon successful initialization, the `termcurses_initterm()` function will -allocate an new terminal context which must be passed with all future termcurses -library functions. When this context is no longer needed, the -`termcurses_deinitterm()` routine should be called for proper freeing and -terminal teardown. - -## Use with `telnetd` - -When using termcurses with the telnet daemon, the telnet config option -`CONFIG_TELNET_SUPPORT_NAWS` should be enabled. This option adds code to the -telnet library for terminal size negotiation. Without this option, the telnet -routines have no concept of the terminal size, and therefore the termcurses -routines must default to `80x24` screen mode. - -## Use with `pdcurses` - -When using the pdcurses termcurses support (i.e you have enabled both the -`CONFIG_PDCURSES` and `CONFIG_TERMCURSES` options),, the pdcurses input device -should be selected to be `TERMINPUT` (i.e. set `CONFIG_PDCURSES_TERMINPUT=y`). -This causes the pdcurses keyboard input logic to use `termcurses_getkeycode()` -routine for curses input. diff --git a/system/trace/README.md b/system/trace/README.md deleted file mode 100644 index 3067cd046..000000000 --- a/system/trace/README.md +++ /dev/null @@ -1,4 +0,0 @@ -System / `trace` Task Tracer -============================ - -See https://nuttx.apache.org/docs/latest/guides/tasktraceuser.html diff --git a/system/trace/trace.c b/system/trace/trace.c index e41bf8e8b..141611e91 100644 --- a/system/trace/trace.c +++ b/system/trace/trace.c @@ -48,15 +48,14 @@ * Name: notectl_enable ****************************************************************************/ -static bool notectl_enable(FAR const char *name, int flag, int notectlfd) +static bool notectl_enable(int flag, int notectlfd) { - struct note_filter_named_mode_s mode; + struct note_filter_mode_s mode; int oldflag; - strlcpy(mode.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETMODE, (unsigned long)&mode); - oldflag = (mode.mode.flag & NOTE_FILTER_MODE_FLAG_ENABLE) != 0; + oldflag = (mode.flag & NOTE_FILTER_MODE_FLAG_ENABLE) != 0; if (flag == oldflag) { /* Already set */ @@ -66,11 +65,11 @@ static bool notectl_enable(FAR const char *name, int flag, int notectlfd) if (flag) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_ENABLE; + mode.flag |= NOTE_FILTER_MODE_FLAG_ENABLE; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_ENABLE; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_ENABLE; } ioctl(notectlfd, NOTECTL_SETMODE, (unsigned long)&mode); @@ -82,8 +81,8 @@ static bool notectl_enable(FAR const char *name, int flag, int notectlfd) * Name: trace_cmd_start ****************************************************************************/ -static int trace_cmd_start(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_start(int index, int argc, FAR char **argv, + int notectlfd) { FAR char *endptr; int duration = 0; @@ -122,14 +121,14 @@ static int trace_cmd_start(FAR const char *name, int index, int argc, /* Start tracing */ - notectl_enable(name, true, notectlfd); + notectl_enable(true, notectlfd); if (duration > 0) { /* If is given, stop tracing after specified seconds. */ sleep(duration); - notectl_enable(name, false, notectlfd); + notectl_enable(false, notectlfd); } return index; @@ -140,8 +139,8 @@ static int trace_cmd_start(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_DRIVERS_NOTERAM -static int trace_cmd_dump(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_dump(int index, int argc, FAR char **argv, + int notectlfd) { FAR FILE *out = stdout; bool changed = false; @@ -185,7 +184,7 @@ static int trace_cmd_dump(FAR const char *name, int index, int argc, if (!cont) { - changed = notectl_enable(name, false, notectlfd); + changed = notectl_enable(false, notectlfd); } /* Dump the trace header */ @@ -198,7 +197,7 @@ static int trace_cmd_dump(FAR const char *name, int index, int argc, if (changed) { - notectl_enable(name, true, notectlfd); + notectl_enable(true, notectlfd); } /* If needed, close the file stream for dump. */ @@ -224,8 +223,7 @@ static int trace_cmd_dump(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_SYSTEM_SYSTEM -static int trace_cmd_cmd(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_cmd(int index, int argc, FAR char **argv, int notectlfd) { char command[CONFIG_NSH_LINELEN]; bool changed; @@ -268,13 +266,13 @@ static int trace_cmd_cmd(FAR const char *name, int index, int argc, /* Execute the command with tracing */ - changed = notectl_enable(name, true, notectlfd); + changed = notectl_enable(true, notectlfd); system(command); if (changed) { - notectl_enable(name, false, notectlfd); + notectl_enable(false, notectlfd); } return index; @@ -285,18 +283,18 @@ static int trace_cmd_cmd(FAR const char *name, int index, int argc, * Name: trace_cmd_mode ****************************************************************************/ -static int trace_cmd_mode(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_mode(int index, int argc, FAR char **argv, + int notectlfd) { - struct note_filter_named_mode_s mode; + struct note_filter_mode_s mode; bool owmode; bool enable; bool modified = false; #ifdef CONFIG_SCHED_INSTRUMENTATION_SYSCALL - struct note_filter_named_syscall_s filter_syscall; + struct note_filter_syscall_s filter_syscall; #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_IRQHANDLER - struct note_filter_named_irq_s filter_irq; + struct note_filter_irq_s filter_irq; #endif #if defined(CONFIG_SCHED_INSTRUMENTATION_SYSCALL) ||\ @@ -309,7 +307,6 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, /* Get current trace mode */ - strlcpy(mode.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETMODE, (unsigned long)&mode); owmode = trace_dump_get_overwrite(); @@ -336,11 +333,11 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, case 'w': /* Switch trace */ if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_SWITCH; + mode.flag |= NOTE_FILTER_MODE_FLAG_SWITCH; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_SWITCH; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_SWITCH; } break; #endif @@ -349,22 +346,22 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, case 's': /* Syscall trace */ if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_SYSCALL; + mode.flag |= NOTE_FILTER_MODE_FLAG_SYSCALL; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_SYSCALL; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_SYSCALL; } break; case 'a': /* Record syscall arguments */ if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS; + mode.flag |= NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS; } break; #endif @@ -373,11 +370,11 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, case 'i': /* IRQ trace */ if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_IRQ; + mode.flag |= NOTE_FILTER_MODE_FLAG_IRQ; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_IRQ; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_IRQ; } break; #endif @@ -386,11 +383,11 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, case 'd': /* Dump trace */ if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_DUMP; + mode.flag |= NOTE_FILTER_MODE_FLAG_DUMP; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_DUMP; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_DUMP; } break; #endif @@ -417,9 +414,9 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, /* If no parameter, display current trace mode setting. */ - printf("Task trace mode(%s):\n", mode.name); + printf("Task trace mode:\n"); printf(" Trace : %s\n", - (mode.mode.flag & NOTE_FILTER_MODE_FLAG_ENABLE) ? + (mode.flag & NOTE_FILTER_MODE_FLAG_ENABLE) ? "enabled" : "disabled"); #ifdef CONFIG_DRIVERS_NOTERAM @@ -428,46 +425,43 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_SYSCALL - strlcpy(filter_syscall.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETSYSCALLFILTER, (unsigned long)&filter_syscall); for (count = i = 0; i < SYS_nsyscalls; i++) { - if (NOTE_FILTER_SYSCALLMASK_ISSET(i, &filter_syscall.syscall_mask)) + if (NOTE_FILTER_SYSCALLMASK_ISSET(i, &filter_syscall)) { count++; } } printf(" Syscall trace : %s\n", - mode.mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL ? + mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL ? "on (+s)" : "off (-s)"); - if (mode.mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL) + if (mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL) { printf(" Filtered Syscalls : %d\n", count); } printf(" Syscall trace with args : %s\n", - mode.mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS ? + mode.flag & NOTE_FILTER_MODE_FLAG_SYSCALL_ARGS ? "on (+a)" : "off (-a)"); #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_IRQHANDLER - strlcpy(filter_irq.name, name, NAME_MAX); - ioctl(notectlfd, NOTECTL_GETIRQFILTER, - (unsigned long)&filter_irq.irq_mask); + ioctl(notectlfd, NOTECTL_GETIRQFILTER, (unsigned long)&filter_irq); for (count = i = 0; i < NR_IRQS; i++) { - if (NOTE_FILTER_IRQMASK_ISSET(i, &filter_irq.irq_mask)) + if (NOTE_FILTER_IRQMASK_ISSET(i, &filter_irq)) { count++; } } printf(" IRQ trace : %s\n", - mode.mode.flag & NOTE_FILTER_MODE_FLAG_IRQ ? + mode.flag & NOTE_FILTER_MODE_FLAG_IRQ ? "on (+i)" : "off (-i)"); - if (mode.mode.flag & NOTE_FILTER_MODE_FLAG_IRQ) + if (mode.flag & NOTE_FILTER_MODE_FLAG_IRQ) { printf(" Filtered IRQs : %d\n", count); } @@ -481,17 +475,16 @@ static int trace_cmd_mode(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_SCHED_INSTRUMENTATION_SWITCH -static int trace_cmd_switch(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_switch(int index, int argc, FAR char **argv, + int notectlfd) { bool enable; - struct note_filter_named_mode_s mode; + struct note_filter_mode_s mode; /* Usage: trace switch [+|-] */ /* Get current filter setting */ - strlcpy(mode.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETMODE, (unsigned long)&mode); /* Parse the setting parameters */ @@ -502,7 +495,7 @@ static int trace_cmd_switch(FAR const char *name, int index, int argc, { enable = (argv[index++][0] == '+'); if (enable == - ((mode.mode.flag & NOTE_FILTER_MODE_FLAG_SWITCH) != 0)) + ((mode.flag & NOTE_FILTER_MODE_FLAG_SWITCH) != 0)) { /* Already set */ @@ -511,11 +504,11 @@ static int trace_cmd_switch(FAR const char *name, int index, int argc, if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_SWITCH; + mode.flag |= NOTE_FILTER_MODE_FLAG_SWITCH; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_SWITCH; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_SWITCH; } ioctl(notectlfd, NOTECTL_SETMODE, (unsigned long)&mode); @@ -531,13 +524,13 @@ static int trace_cmd_switch(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_SCHED_INSTRUMENTATION_SYSCALL -static int trace_cmd_syscall(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_syscall(int index, int argc, FAR char **argv, + int notectlfd) { bool enable; bool modified = false; int syscallno; - FAR struct note_filter_named_syscall_s filter_syscall; + FAR struct note_filter_syscall_s filter_syscall; int n; int count; @@ -545,7 +538,6 @@ static int trace_cmd_syscall(FAR const char *name, int index, int argc, /* Get current syscall filter setting */ - strlcpy(filter_syscall.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETSYSCALLFILTER, (unsigned long)&filter_syscall); @@ -573,13 +565,11 @@ static int trace_cmd_syscall(FAR const char *name, int index, int argc, if (enable) { - NOTE_FILTER_SYSCALLMASK_SET(syscallno, - &filter_syscall.syscall_mask); + NOTE_FILTER_SYSCALLMASK_SET(syscallno, &filter_syscall); } else { - NOTE_FILTER_SYSCALLMASK_CLR(syscallno, - &filter_syscall.syscall_mask); + NOTE_FILTER_SYSCALLMASK_CLR(syscallno, &filter_syscall); } } @@ -600,7 +590,7 @@ static int trace_cmd_syscall(FAR const char *name, int index, int argc, for (count = n = 0; n < SYS_nsyscalls; n++) { - if (NOTE_FILTER_SYSCALLMASK_ISSET(n, &filter_syscall.syscall_mask)) + if (NOTE_FILTER_SYSCALLMASK_ISSET(n, &filter_syscall)) { count++; } @@ -610,7 +600,7 @@ static int trace_cmd_syscall(FAR const char *name, int index, int argc, for (n = 0; n < SYS_nsyscalls; n++) { - if (NOTE_FILTER_SYSCALLMASK_ISSET(n, &filter_syscall.syscall_mask)) + if (NOTE_FILTER_SYSCALLMASK_ISSET(n, &filter_syscall)) { printf(" %s\n", g_funcnames[n]); } @@ -626,14 +616,13 @@ static int trace_cmd_syscall(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_SCHED_INSTRUMENTATION_IRQHANDLER -static int trace_cmd_irq(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_irq(int index, int argc, FAR char **argv, int notectlfd) { bool enable; bool modified = false; int irqno; FAR char *endptr; - struct note_filter_named_irq_s filter_irq; + struct note_filter_irq_s filter_irq; int n; int count; @@ -641,7 +630,6 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, /* Get current irq filter setting */ - strlcpy(filter_irq.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETIRQFILTER, (unsigned long)&filter_irq); /* Parse the setting parameters */ @@ -663,12 +651,12 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, { for (n = 0; n < NR_IRQS; n++) { - NOTE_FILTER_IRQMASK_SET(n, &filter_irq.irq_mask); + NOTE_FILTER_IRQMASK_SET(n, &filter_irq); } } else { - NOTE_FILTER_IRQMASK_ZERO(&filter_irq.irq_mask); + NOTE_FILTER_IRQMASK_ZERO(&filter_irq); } } else @@ -688,11 +676,11 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, if (enable) { - NOTE_FILTER_IRQMASK_SET(irqno, &filter_irq.irq_mask); + NOTE_FILTER_IRQMASK_SET(irqno, &filter_irq); } else { - NOTE_FILTER_IRQMASK_CLR(irqno, &filter_irq.irq_mask); + NOTE_FILTER_IRQMASK_CLR(irqno, &filter_irq); } } @@ -712,7 +700,7 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, for (count = n = 0; n < NR_IRQS; n++) { - if (NOTE_FILTER_IRQMASK_ISSET(n, &filter_irq.irq_mask)) + if (NOTE_FILTER_IRQMASK_ISSET(n, &filter_irq)) { count++; } @@ -722,7 +710,7 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, for (n = 0; n < NR_IRQS; n++) { - if (NOTE_FILTER_IRQMASK_ISSET(n, &filter_irq.irq_mask)) + if (NOTE_FILTER_IRQMASK_ISSET(n, &filter_irq)) { printf(" %d\n", n); } @@ -738,17 +726,16 @@ static int trace_cmd_irq(FAR const char *name, int index, int argc, ****************************************************************************/ #ifdef CONFIG_SCHED_INSTRUMENTATION_DUMP -static int trace_cmd_print(FAR const char *name, int index, int argc, - FAR char **argv, int notectlfd) +static int trace_cmd_print(int index, int argc, FAR char **argv, + int notectlfd) { bool enable; - struct note_filter_named_mode_s mode; + struct note_filter_mode_s mode; /* Usage: trace print [+|-] */ /* Get current filter setting */ - strlcpy(mode.name, name, NAME_MAX); ioctl(notectlfd, NOTECTL_GETMODE, (unsigned long)&mode); /* Parse the setting parameters */ @@ -759,7 +746,7 @@ static int trace_cmd_print(FAR const char *name, int index, int argc, { enable = (argv[index++][0] == '+'); if (enable == - ((mode.mode.flag & NOTE_FILTER_MODE_FLAG_DUMP) != 0)) + ((mode.flag & NOTE_FILTER_MODE_FLAG_DUMP) != 0)) { /* Already set */ @@ -768,11 +755,11 @@ static int trace_cmd_print(FAR const char *name, int index, int argc, if (enable) { - mode.mode.flag |= NOTE_FILTER_MODE_FLAG_DUMP; + mode.flag |= NOTE_FILTER_MODE_FLAG_DUMP; } else { - mode.mode.flag &= ~NOTE_FILTER_MODE_FLAG_DUMP; + mode.flag &= ~NOTE_FILTER_MODE_FLAG_DUMP; } ioctl(notectlfd, NOTECTL_SETMODE, (unsigned long)&mode); @@ -790,7 +777,7 @@ static int trace_cmd_print(FAR const char *name, int index, int argc, static void show_usage(void) { fprintf(stderr, - "\nUsage: trace [-n][] ...\n" + "\nUsage: trace ...\n" "Subcommand:\n" " start [-c][] :" " Start task tracing\n" @@ -837,7 +824,6 @@ int main(int argc, FAR char *argv[]) int notectlfd; int exitcode = EXIT_FAILURE; int i; - char name[NAME_MAX]; /* Open note control device */ @@ -849,73 +835,66 @@ int main(int argc, FAR char *argv[]) goto errout; } - name[0] = '\0'; if (argc == 1) { /* No arguments - show current mode */ - trace_cmd_mode(name, 0, 0, NULL, notectlfd); + trace_cmd_mode(0, 0, NULL, notectlfd); goto exit_with_close; } /* Parse command line arguments */ i = 1; - if (strcmp(argv[i], "-n") == 0) - { - strlcpy(name, argv[++i], NAME_MAX); - i++; - } - while (i < argc) { if (strcmp(argv[i], "start") == 0) { - i = trace_cmd_start(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_start(i + 1, argc, argv, notectlfd); } else if (strcmp(argv[i], "stop") == 0) { i++; - notectl_enable(name, false, notectlfd); + notectl_enable(false, notectlfd); } #ifdef CONFIG_DRIVERS_NOTERAM else if (strcmp(argv[i], "dump") == 0) { - i = trace_cmd_dump(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_dump(i + 1, argc, argv, notectlfd); } #endif #ifdef CONFIG_SYSTEM_SYSTEM else if (strcmp(argv[i], "cmd") == 0) { - i = trace_cmd_cmd(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_cmd(i + 1, argc, argv, notectlfd); } #endif else if (strcmp(argv[i], "mode") == 0) { - i = trace_cmd_mode(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_mode(i + 1, argc, argv, notectlfd); } #ifdef CONFIG_SCHED_INSTRUMENTATION_SWITCH else if (strcmp(argv[i], "switch") == 0) { - i = trace_cmd_switch(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_switch(i + 1, argc, argv, notectlfd); } #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_SYSCALL else if (strcmp(argv[i], "syscall") == 0) { - i = trace_cmd_syscall(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_syscall(i + 1, argc, argv, notectlfd); } #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_IRQHANDLER else if (strcmp(argv[i], "irq") == 0) { - i = trace_cmd_irq(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_irq(i + 1, argc, argv, notectlfd); } #endif #ifdef CONFIG_SCHED_INSTRUMENTATION_DUMP else if (strcmp(argv[i], "print") == 0) { - i = trace_cmd_print(name, i + 1, argc, argv, notectlfd); + i = trace_cmd_print(i + 1, argc, argv, notectlfd); } #endif else diff --git a/system/trace/trace_dump.c b/system/trace/trace_dump.c index b78867a84..b819b8cd3 100644 --- a/system/trace/trace_dump.c +++ b/system/trace/trace_dump.c @@ -67,7 +67,7 @@ static void note_ioctl(int cmd, unsigned long arg) int trace_dump(FAR FILE *out) { - uint8_t tracedata[1024]; + uint8_t tracedata[UCHAR_MAX]; int ret; int fd; @@ -85,12 +85,7 @@ int trace_dump(FAR FILE *out) while (1) { ret = read(fd, tracedata, sizeof tracedata); - if (ret < 0 || ret > sizeof(tracedata)) - { - fprintf(stderr, "trace: read error: %d, errno:%d\n", ret, errno); - continue; - } - else if (ret == 0) + if (ret <= 0) { break; } diff --git a/system/uorb/Android.bp b/system/uorb/Android.bp deleted file mode 100644 index 271d91760..000000000 --- a/system/uorb/Android.bp +++ /dev/null @@ -1,59 +0,0 @@ -cc_defaults { - name: "uorb_defaults", - cflags: [ - "-DFAR=", - "-DOK=0", - "-DERROR=-1", - "-DCONFIG_DEBUG_UORB" - ], - shared_libs: [ - "libuorb", - "libcutils" - ], - proprietary: true, -} - -cc_library_headers { - name: "libuorb_headers", - export_include_dirs: ["."], - proprietary: true, -} - -cc_library { - name: "libuorb", - srcs: [ - "uORB/uORB.c", - "sensor/*.c", - ], - cflags: [ - "-DFAR=", - "-DOK=0", - "-DERROR=-1", - "-DCONFIG_DEBUG_UORB" - ], - shared_libs: [ - "libnuttx_libc", - ], - header_libs: [ - "nuttx_libc_headers" - ], - defaults: [ - "nuttx_libc_defaults" - ], - proprietary: true, -} - -cc_binary { - name: "uorb_listener", - srcs: ["listener.c"], - defaults: ["uorb_defaults"] -} - -cc_binary { - name: "uorb_unit_test", - srcs: [ - "test/unit_test.c", - "test/utility.c" - ], - defaults: ["uorb_defaults"] -} diff --git a/system/uorb/CMakeLists.txt b/system/uorb/CMakeLists.txt index b890c0ae8..4c24f94ca 100644 --- a/system/uorb/CMakeLists.txt +++ b/system/uorb/CMakeLists.txt @@ -20,45 +20,22 @@ if(CONFIG_UORB) - set_property( - TARGET nuttx - APPEND - PROPERTY NUTTX_INCLUDE_DIRECTORIES ${NUTTX_APPS_DIR}/system/uorb) - nuttx_add_library(uorb STATIC) file(GLOB_RECURSE CSRCS "sensor/*.c") list(APPEND CSRCS uORB/uORB.c) if(CONFIG_UORB_LISTENER) - nuttx_add_application( - NAME - uorb_listener - PRIORITY - ${CONFIG_UORB_PRIORITY} - STACKSIZE - ${CONFIG_UORB_STACKSIZE} - MODULE - ${CONFIG_UORB} - SRCS - listener.c - DEPENDS - uorb) + nuttx_add_application(NAME uorb_listener SRCS listener.c DEPENDS uorb) endif() if(CONFIG_UORB_TEST) nuttx_add_application( NAME uorb_unit_test - PRIORITY - ${CONFIG_UORB_PRIORITY} - STACKSIZE - ${CONFIG_UORB_STACKSIZE} - MODULE - ${CONFIG_UORB} SRCS - test/unit_test.c test/utility.c + test/unit_test.c DEPENDS uorb) endif() diff --git a/system/uorb/Kconfig b/system/uorb/Kconfig index 41c44d2c4..6345f77b1 100644 --- a/system/uorb/Kconfig +++ b/system/uorb/Kconfig @@ -28,7 +28,7 @@ config UORB_TESTS if UORB_TESTS -config UORB_STORAGE_DIR +config UORB_SRORAGE_DIR string "uorb test result storage dir" default "/data/" diff --git a/system/uorb/listener.c b/system/uorb/listener.c index 9281cdc8e..5d416e627 100644 --- a/system/uorb/listener.c +++ b/system/uorb/listener.c @@ -22,18 +22,17 @@ * Included Files ****************************************************************************/ +#include + #include #include #include -#include #include #include #include #include #include -#include #include -#include #include #include @@ -45,7 +44,6 @@ #define ORB_MAX_PRINT_NAME 32 #define ORB_TOP_WAIT_TIME 1000 -#define ORB_DATA_DIR "/data/uorb/" /**************************************************************************** * Private Types @@ -53,40 +51,32 @@ struct listen_object_s { - SLIST_ENTRY(listen_object_s) node; /* Node of object info list */ - - struct orb_object object; /* Object id */ - orb_abstime timestamp; /* Time of lastest generation */ - unsigned long generation; /* Latest generation */ - FAR FILE *file; + struct list_node node; /* Node of object info list */ + struct orb_object object; /* Object id */ + orb_abstime timestamp; /* Time of lastest generation */ + unsigned long generation; /* Latest generation */ }; -SLIST_HEAD(listen_list_s, listen_object_s); - /**************************************************************************** * Private Function Prototypes ****************************************************************************/ static int listener_get_state(FAR struct orb_object *object, FAR struct orb_state *state); -static int listener_add_object(FAR struct listen_list_s *objlist, +static int listener_add_object(FAR struct list_node *objlist, FAR struct orb_object *object); -static void listener_delete_object_list(FAR struct listen_list_s *objlist); -static int listener_generate_object_list(FAR struct listen_list_s *objlist, +static void listener_delete_object_list(FAR struct list_node *objlist); +static int listener_generate_object_list(FAR struct list_node *objlist, FAR const char *filter); static int listener_print(FAR const struct orb_metadata *meta, int fd); -static void listener_monitor(FAR struct listen_list_s *objlist, - int nb_objects, float topic_rate, - int topic_latency, int nb_msgs, - int timeout, bool record); -static int listener_update(FAR struct listen_list_s *objlist, +static void listener_monitor(FAR struct list_node *objlist, int nb_objects, + float topic_rate, int topic_latency, + int nb_msgs, int timeout); +static int listener_update(FAR struct list_node *objlist, FAR struct orb_object *object); -static void listener_top(FAR struct listen_list_s *objlist, +static void listener_top(FAR struct list_node *objlist, FAR const char *filter, bool only_once); -static int listener_create_dir(FAR char *dir, size_t size); -static int listener_record(FAR const struct orb_metadata *meta, int fd, - FAR FILE *file); /**************************************************************************** * Private Data @@ -124,7 +114,6 @@ listener [arguments...]\n\ Commands:\n\ \t Topic name. Multi name are separated by ','\n\ \t[-h ] Listener commands help\n\ -\t[-f ] Record uorb data to file\n\ \t[-n ] Number of messages, default: 0\n\ \t[-r ] Subscription rate (unlimited if 0), default: 0\n\ \t[-b ] Subscription maximum report latency in us(unlimited if 0),\n\ @@ -135,45 +124,6 @@ listener [arguments...]\n\ "); } -/**************************************************************************** - * Name: creat_record_path - * - * Input Parameters: - * path The path of the storage file. - * - * Description: - * Create the path where files are stored by default. - * - * Returned Value: - * 0 on success, otherwise negative errno. - ****************************************************************************/ - -static int listener_create_dir(FAR char *dir, size_t size) -{ - FAR struct tm *tm_info; - time_t t; - - time(&t); - tm_info = gmtime(&t); - - if (0 == strftime(dir, size, ORB_DATA_DIR "%Y%m%d%H%M%S/", tm_info)) - { - return -EINVAL; - } - - if (access(ORB_DATA_DIR, F_OK) != 0) - { - mkdir(ORB_DATA_DIR, 0777); - } - - if (access(dir, F_OK) != 0) - { - mkdir(dir, 0777); - } - - return OK; -} - /**************************************************************************** * Name: listener_get_state * @@ -219,7 +169,7 @@ static int listener_get_state(FAR struct orb_object *object, * 0 on success, otherwise return negative errno. ****************************************************************************/ -static int listener_add_object(FAR struct listen_list_s *objlist, +static int listener_add_object(FAR struct list_node *objlist, FAR struct orb_object *object) { FAR struct listen_object_s *tmp; @@ -237,8 +187,7 @@ static int listener_add_object(FAR struct listen_list_s *objlist, tmp->object.instance = object->instance; tmp->timestamp = orb_absolute_time(); tmp->generation = ret < 0 ? 0 : state.generation; - tmp->file = NULL; - SLIST_INSERT_HEAD(objlist, tmp, node); + list_add_tail(objlist, &tmp->node); return 0; } @@ -256,7 +205,7 @@ static int listener_add_object(FAR struct listen_list_s *objlist, * 0 on success. ****************************************************************************/ -static int listener_update(FAR struct listen_list_s *objlist, +static int listener_update(FAR struct list_node *objlist, FAR struct orb_object *object) { FAR struct listen_object_s *old = NULL; @@ -265,7 +214,7 @@ static int listener_update(FAR struct listen_list_s *objlist, /* Check wether object already exist in old list */ - SLIST_FOREACH(tmp, objlist, node) + list_for_every_entry(objlist, tmp, struct listen_object_s, node) { if (tmp->object.meta == object->meta && tmp->object.instance == object->instance) @@ -339,18 +288,18 @@ static int listener_update(FAR struct listen_list_s *objlist, * None. ****************************************************************************/ -static void listener_delete_object_list(FAR struct listen_list_s *objlist) +static void listener_delete_object_list(FAR struct list_node *objlist) { FAR struct listen_object_s *tmp; + FAR struct listen_object_s *next; - while (!SLIST_EMPTY(objlist)) + list_for_every_entry_safe(objlist, tmp, next, struct listen_object_s, node) { - tmp = SLIST_FIRST(objlist); - SLIST_REMOVE_HEAD(objlist, node); + list_delete(&tmp->node); free(tmp); } - SLIST_INIT(objlist); + list_initialize(objlist); } /**************************************************************************** @@ -368,7 +317,7 @@ static void listener_delete_object_list(FAR struct listen_list_s *objlist) * Negative errno on failure. ****************************************************************************/ -static int listener_generate_object_list(FAR struct listen_list_s *objlist, +static int listener_generate_object_list(FAR struct list_node *objlist, FAR const char *filter) { FAR struct dirent *entry; @@ -515,49 +464,15 @@ static int listener_print(FAR const struct orb_metadata *meta, int fd) ret = orb_copy(meta, fd, buffer); #ifdef CONFIG_DEBUG_UORB - if (ret == OK && meta->o_format != NULL) + if (ret == OK && meta->o_cb != NULL) { - orb_info(meta->o_format, meta->o_name, buffer); + meta->o_cb(meta, buffer); } #endif return ret; } -/**************************************************************************** - * Name: listener_record - * - * Description: - * record topic data. - * - * Input Parameters: - * meta The uORB metadata. - * fd Subscriber handle. - * file Save file handle. - * - * Returned Value: - * 0 on success copy, otherwise -1 - ****************************************************************************/ - -static int listener_record(FAR const struct orb_metadata *meta, int fd, - FAR FILE *file) -{ - char buffer[meta->o_size]; - int ret; - - ret = orb_copy(meta, fd, buffer); -#ifdef CONFIG_DEBUG_UORB - if (ret == OK && meta->o_format != NULL) - { - ret = orb_fprintf(file, meta->o_format, buffer); - } -#else - (void)file; -#endif - - return ret; -} - /**************************************************************************** * Name: listener_monitor * @@ -576,20 +491,17 @@ static int listener_record(FAR const struct orb_metadata *meta, int fd, * None ****************************************************************************/ -static void listener_monitor(FAR struct listen_list_s *objlist, - int nb_objects, float topic_rate, - int topic_latency, int nb_msgs, - int timeout, bool record) +static void listener_monitor(FAR struct list_node *objlist, int nb_objects, + float topic_rate, int topic_latency, + int nb_msgs, int timeout) { FAR struct pollfd *fds; - char path[PATH_MAX]; FAR int *recv_msgs; float interval = topic_rate ? (1000000 / topic_rate) : 0; int nb_recv_msgs = 0; - FAR char *dir; int i = 0; - FAR struct listen_object_s *tmp; + struct listen_object_s *tmp; fds = malloc(nb_objects * sizeof(struct pollfd)); if (!fds) @@ -606,7 +518,7 @@ static void listener_monitor(FAR struct listen_list_s *objlist, /* Prepare pollfd for all objects */ - SLIST_FOREACH(tmp, objlist, node) + list_for_every_entry(objlist, tmp, struct listen_object_s, node) { int fd; @@ -648,34 +560,6 @@ static void listener_monitor(FAR struct listen_list_s *objlist, return; } - if (record) - { - listener_create_dir(path, sizeof(path)); - dir = path + strlen(path); - - SLIST_FOREACH(tmp, objlist, node) - { - sprintf(dir, "%s%d.csv", tmp->object.meta->o_name, - tmp->object.instance); - tmp->file = fopen(path, "w"); - if (tmp->file != NULL) - { -#ifdef CONFIG_DEBUG_UORB - fprintf(tmp->file, "%s,%d,%d,%s\n", tmp->object.meta->o_format, - tmp->object.meta->o_size, tmp->object.instance, - tmp->object.meta->o_name); -#endif - - uorbinfo_raw("creat file:[%s]", path); - } - else - { - uorbinfo_raw("file creat failed!meta name:%s,instance:%d", - tmp->object.meta->o_name, tmp->object.instance); - } - } - } - /* Loop poll and print recieved messages */ while ((!nb_msgs || nb_recv_msgs < nb_msgs) && !g_should_exit) @@ -683,28 +567,15 @@ static void listener_monitor(FAR struct listen_list_s *objlist, if (poll(&fds[0], nb_objects, timeout * 1000) > 0) { i = 0; - SLIST_FOREACH(tmp, objlist, node) + list_for_every_entry(objlist, tmp, struct listen_object_s, node) { if (fds[i].revents & POLLIN) { nb_recv_msgs++; recv_msgs[i]++; - - if (tmp->file != NULL) + if (listener_print(tmp->object.meta, fds[i].fd) != 0) { - if (listener_record(tmp->object.meta, fds[i].fd, - tmp->file) < 0) - { - uorberr("Listener record %s data failed!", - tmp->object.meta->o_name); - } - } - else - { - if (listener_print(tmp->object.meta, fds[i].fd) != 0) - { - uorberr("Listener callback failed"); - } + uorberr("Listener callback failed"); } if (nb_msgs && nb_recv_msgs >= nb_msgs) @@ -725,7 +596,7 @@ static void listener_monitor(FAR struct listen_list_s *objlist, } i = 0; - SLIST_FOREACH(tmp, objlist, node) + list_for_every_entry(objlist, tmp, struct listen_object_s, node) { if (fds[i].fd < 0) { @@ -745,12 +616,6 @@ static void listener_monitor(FAR struct listen_list_s *objlist, recv_msgs[i]); } - if (tmp->file != NULL) - { - fflush(tmp->file); - fclose(tmp->file); - } - i++; } @@ -776,20 +641,7 @@ static void listener_monitor(FAR struct listen_list_s *objlist, * None. ****************************************************************************/ -static size_t listen_length(FAR struct listen_list_s *objlist) -{ - struct listen_object_s *tmp; - size_t count = 0; - - SLIST_FOREACH(tmp, objlist, node) - { - count++; - } - - return count; -} - -static void listener_top(FAR struct listen_list_s *objlist, +static void listener_top(FAR struct list_node *objlist, FAR const char *filter, bool only_once) { @@ -823,7 +675,7 @@ static void listener_top(FAR struct listen_list_s *objlist, uorbinfo_raw("\033[H"); /* move cursor to top left corner */ } - uorbinfo_raw("\033[K" "current objects: %zu", listen_length(objlist)); + uorbinfo_raw("\033[K" "current objects: %zu", list_length(objlist)); uorbinfo_raw("\033[K" "%-*s INST #SUB RATE #Q SIZE", ORB_MAX_PRINT_NAME - 2, "NAME"); @@ -843,7 +695,6 @@ static void listener_top(FAR struct listen_list_s *objlist, static void exit_handler(int signo) { - (void)signo; g_should_exit = true; } @@ -853,14 +704,13 @@ static void exit_handler(int signo) int main(int argc, FAR char *argv[]) { + struct list_node objlist; FAR struct listen_object_s *tmp; - struct listen_list_s objlist; float topic_rate = 0; int topic_latency = 0; int nb_msgs = 0; int timeout = 5; bool top = false; - bool record = false; bool only_once = false; FAR char *filter = NULL; int ret; @@ -874,7 +724,7 @@ int main(int argc, FAR char *argv[]) /* Pasrse Argument */ - while ((ch = getopt(argc, argv, "r:b:n:t:Tflh")) != EOF) + while ((ch = getopt(argc, argv, "r:b:n:t:Tlh")) != EOF) { switch (ch) { @@ -910,12 +760,6 @@ int main(int argc, FAR char *argv[]) } break; -#ifdef CONFIG_DEBUG_UORB - case 'f': - record = true; - break; -#endif - case 'T': top = true; break; @@ -937,7 +781,7 @@ int main(int argc, FAR char *argv[]) /* Alloc list and exec command */ - SLIST_INIT(&objlist); + list_initialize(&objlist); ret = listener_generate_object_list(&objlist, filter); if (ret <= 0) { @@ -951,7 +795,7 @@ int main(int argc, FAR char *argv[]) else { uorbinfo_raw("\nMointor objects num:%d", ret); - SLIST_FOREACH(tmp, &objlist, node) + list_for_every_entry(&objlist, tmp, struct listen_object_s, node) { uorbinfo_raw("object_name:%s, object_instance:%d", tmp->object.meta->o_name, @@ -959,7 +803,7 @@ int main(int argc, FAR char *argv[]) } listener_monitor(&objlist, ret, topic_rate, topic_latency, - nb_msgs, timeout, record); + nb_msgs, timeout); } listener_delete_object_list(&objlist); diff --git a/system/uorb/sensor/accel.c b/system/uorb/sensor/accel.c index be39b55af..2b15cf5ac 100644 --- a/system/uorb/sensor/accel.c +++ b/system/uorb/sensor/accel.c @@ -29,14 +29,23 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_accel_format[] = - "timestamp:%" PRIu64 ",x:%hf,y:%hf,z:%hf,temperature:%hf"; +static void print_sensor_accel_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_accel *message = buffer; + const orb_abstime now = orb_absolute_time(); + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "temperature: %.2f x: %.2f y: %.2f z: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->temperature, message->x, message->y, message->z); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_accel, struct sensor_accel, sensor_accel_format); -ORB_DEFINE(sensor_accel_uncal, struct sensor_accel, sensor_accel_format); +ORB_DEFINE(sensor_accel, struct sensor_accel, print_sensor_accel_message); +ORB_DEFINE(sensor_accel_uncal, struct sensor_accel, + print_sensor_accel_message); diff --git a/system/uorb/sensor/baro.c b/system/uorb/sensor/baro.c index 5ee66133e..fab5d321f 100644 --- a/system/uorb/sensor/baro.c +++ b/system/uorb/sensor/baro.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_baro_format[] = - "timestamp:%" PRIu64 ",pressure:%hf,temperature:%hf"; +static void print_sensor_baro_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_baro *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "temperature: %.2f pressure: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->temperature, message->pressure); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_baro, struct sensor_baro, sensor_baro_format); +ORB_DEFINE(sensor_baro, struct sensor_baro, print_sensor_baro_message); diff --git a/system/uorb/sensor/cap.c b/system/uorb/sensor/cap.c index b2dd05310..e3a809a4d 100644 --- a/system/uorb/sensor/cap.c +++ b/system/uorb/sensor/cap.c @@ -29,13 +29,23 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_cap_format[] = - "timestamp:%" PRIu64 ",status:%" PRIu32 ",rawdata0:%" PRIu32 "," - "rawdata1:%" PRIu32 ",rawdata2:%" PRIu32 ",rawdata3:%" PRIu32 ""; +static void print_sensor_cap_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_cap *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "status: %" PRIu32 " rawdata0: %" PRIu32 " rawdata1: " + "%" PRIu32 " rawdata2: %" PRIu32 " rawdata3: %" PRIu32 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->status, message->rawdata[0], message->rawdata[1], + message->rawdata[2], message->rawdata[3]); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_cap, struct sensor_cap, sensor_cap_format); +ORB_DEFINE(sensor_cap, struct sensor_cap, print_sensor_cap_message); diff --git a/system/uorb/sensor/co2.c b/system/uorb/sensor/co2.c index 9e23f73b2..8dd09f425 100644 --- a/system/uorb/sensor/co2.c +++ b/system/uorb/sensor/co2.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_co2_format[] = "timestamp:%" PRIu64 ",co2:%hf"; +static void print_sensor_co2_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_co2 *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) co2: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->co2); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_co2, struct sensor_co2, sensor_co2_format); +ORB_DEFINE(sensor_co2, struct sensor_co2, print_sensor_co2_message); diff --git a/system/uorb/sensor/dust.c b/system/uorb/sensor/dust.c index b8f55152d..c205952fa 100644 --- a/system/uorb/sensor/dust.c +++ b/system/uorb/sensor/dust.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_dust_format[] = "timestamp:%" PRIu64 ",dust:%hf"; +static void print_sensor_dust_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_dust *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) dust: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->dust); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_dust, struct sensor_dust, sensor_dust_format); +ORB_DEFINE(sensor_dust, struct sensor_dust, print_sensor_dust_message); diff --git a/system/uorb/sensor/ecg.c b/system/uorb/sensor/ecg.c index 99f51854a..f267c4c76 100644 --- a/system/uorb/sensor/ecg.c +++ b/system/uorb/sensor/ecg.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ecg_format[] = - "timestamp:%" PRIu64 ",ecg:%hf,status:%" PRIx32 ""; +static void print_sensor_ecg_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ecg *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) ecg: %.4f " + "status:0x%" PRIx32 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->ecg, message->status); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ecg, struct sensor_ecg, sensor_ecg_format); +ORB_DEFINE(sensor_ecg, struct sensor_ecg, print_sensor_ecg_message); diff --git a/system/uorb/sensor/force.c b/system/uorb/sensor/force.c index 4761ff82a..f568befa4 100644 --- a/system/uorb/sensor/force.c +++ b/system/uorb/sensor/force.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_force_format[] = - "timestamp:%" PRIu64 ",force:%hf,event:%" PRIi32 ""; +static void print_sensor_force_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_force *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "value: %.2f event: %" PRIi32 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->force, message->event); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_force, struct sensor_force, sensor_force_format); +ORB_DEFINE(sensor_force, struct sensor_force, print_sensor_force_message); diff --git a/system/uorb/sensor/gas.h b/system/uorb/sensor/gas.h deleted file mode 100644 index 625150406..000000000 --- a/system/uorb/sensor/gas.h +++ /dev/null @@ -1,38 +0,0 @@ -/**************************************************************************** - * apps/system/uorb/sensor/gas.h - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. The - * ASF licenses this file to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - ****************************************************************************/ - -#ifndef __APPS_SYSTEM_UORB_SENSOR_GAS_H -#define __APPS_SYSTEM_UORB_SENSOR_GAS_H - -/**************************************************************************** - * Included Files - ****************************************************************************/ - -#include - -/**************************************************************************** - * Public Data - ****************************************************************************/ - -/* register this as object request broker structure */ - -ORB_DECLARE(sensor_gas); - -#endif diff --git a/system/uorb/sensor/gesture.c b/system/uorb/sensor/gesture.c index f19a40a4b..e012adbd7 100644 --- a/system/uorb/sensor/gesture.c +++ b/system/uorb/sensor/gesture.c @@ -29,8 +29,17 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_wake_gesture_format[] = - "timestamp:%" PRIu64 ",event:%" PRIu32 ""; +static void +print_sensor_wake_gesture_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_wake_gesture *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago)" + " event: %" PRIu32 "", meta->o_name, message->timestamp, + now - message->timestamp, message->event); +} #endif /**************************************************************************** @@ -38,6 +47,6 @@ static const char sensor_wake_gesture_format[] = ****************************************************************************/ ORB_DEFINE(sensor_wake_gesture, struct sensor_wake_gesture, - sensor_wake_gesture_format); + print_sensor_wake_gesture_message); ORB_DEFINE(sensor_wake_gesture_uncal, struct sensor_wake_gesture, - sensor_wake_gesture_format); + print_sensor_wake_gesture_message); diff --git a/system/uorb/sensor/gps.c b/system/uorb/sensor/gps.c index 913356d2d..84113972f 100644 --- a/system/uorb/sensor/gps.c +++ b/system/uorb/sensor/gps.c @@ -29,25 +29,54 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_gps_format[] = - "timestamp:%" PRIu64 ",time_utc:%" PRIu64 ",latitude:%hf,longitude:%hf," - "altitude:%hf,altitude_ellipsoid:%hf,eph:%hf,epv:%hf,hdop:%hf,pdop:%hf," - "vdop:%hf,ground_speed:%hf,course:%hf,satellites_used:%" PRIu32 ""; +static void print_sensor_gps_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_gps *message = buffer; + const orb_abstime now = orb_absolute_time(); -static const char sensor_gps_satellite_format[] = - "timestamp:%" PRIu64 ",count:%" PRIu32 ",satellites:%" PRIu32 "," - "svid0:%" PRIu32 ",elevation0:%" PRIu32 ",azimuth0:%" PRIu32 "," - "snr0:%" PRIu32 ",svid1:%" PRIu32 ",elevation1:%" PRIu32 "," - "azimuth1:%" PRIu32 ",snr1:%" PRIu32 ",svid2:%" PRIu32 "," - "elevation2:%" PRIu32 ",azimuth2:%" PRIu32 ",snr2:%" PRIu32 "," - "svid3:%" PRIu32 ",elevation3:%" PRIu32 ",azimuth3:%" PRIu32 "," - "snr3:%" PRIu32 ""; + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "time_utc: %" PRIu64 " latitude: %.4f longitude: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->time_utc, message->latitude, message->longitude); + + uorbinfo_raw("%s:\taltitude: %.4f altitude_ellipsoid: %.4f " + "ground_speed: %.4f course: %.4f", + meta->o_name, message->altitude, message->altitude_ellipsoid, + message->ground_speed, message->course); + + uorbinfo_raw("%s:\teph: %.4f epv: %.4f hdop: %.4f vdop: %.4f", + meta->o_name, message->eph, message->epv, + message->hdop, message->vdop); +} + +static void +print_sensor_gps_satellite_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_gps_satellite *message = buffer; + const orb_abstime now = orb_absolute_time(); + int i; + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago)", + meta->o_name, message->timestamp, now - message->timestamp); + + for (i = 0; i < message->count; i++) + { + uorbinfo_raw("%s:\tnumber:%d svid: %" PRIu32 + " elevation: %" PRIu32 " azimuth: %" PRIu32 + " snr: %" PRIu32 "", + meta->o_name, i, message->info[i].svid, + message->info[i].elevation, message->info[i].azimuth, + message->info[i].snr); + } +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_gps, struct sensor_gps, sensor_gps_format); +ORB_DEFINE(sensor_gps, struct sensor_gps, print_sensor_gps_message); ORB_DEFINE(sensor_gps_satellite, struct sensor_gps_satellite, - sensor_gps_satellite_format); + print_sensor_gps_satellite_message); diff --git a/system/uorb/sensor/gyro.c b/system/uorb/sensor/gyro.c index d28e1ab5b..d0df6a3d4 100644 --- a/system/uorb/sensor/gyro.c +++ b/system/uorb/sensor/gyro.c @@ -29,13 +29,23 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_gyro_format[] = - "timestamp:%" PRIu64 ",x:%hf,y:%hf,z:%hf,temperature:%hf"; +static void print_sensor_gyro_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_gyro *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "temperature: %.2f x: %.2f y: %.2f z: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->temperature, message->x, message->y, message->z); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_gyro, struct sensor_gyro, sensor_gyro_format); -ORB_DEFINE(sensor_gyro_uncal, struct sensor_gyro, sensor_gyro_format); +ORB_DEFINE(sensor_gyro, struct sensor_gyro, print_sensor_gyro_message); +ORB_DEFINE(sensor_gyro_uncal, struct sensor_gyro, + print_sensor_gyro_message); diff --git a/system/uorb/sensor/hall.c b/system/uorb/sensor/hall.c index 54be04414..fa97e4e4d 100644 --- a/system/uorb/sensor/hall.c +++ b/system/uorb/sensor/hall.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_hall_format[] = - "timestamp:%" PRIu64 ",hall:%" PRIi32 ""; +static void print_sensor_hall_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_hall *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "hall: %" PRIi32 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->hall); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_hall, struct sensor_hall, sensor_hall_format); +ORB_DEFINE(sensor_hall, struct sensor_hall, print_sensor_hall_message); diff --git a/system/uorb/sensor/hbeat.c b/system/uorb/sensor/hbeat.c index 45a317b64..ead4d409a 100644 --- a/system/uorb/sensor/hbeat.c +++ b/system/uorb/sensor/hbeat.c @@ -29,12 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_hbeat_format[] = - "timestamp:%" PRIu64 ",heart beat:%hf"; +static void print_sensor_hbeat_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_hbeat *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "heart beat: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->beat); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_hbeat, struct sensor_hbeat, sensor_hbeat_format); +ORB_DEFINE(sensor_hbeat, struct sensor_hbeat, print_sensor_hbeat_message); diff --git a/system/uorb/sensor/hcho.c b/system/uorb/sensor/hcho.c index dea34d3b0..704cbe6c3 100644 --- a/system/uorb/sensor/hcho.c +++ b/system/uorb/sensor/hcho.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_hcho_format[] = "timestamp:%" PRIu64 ",hcho:%hf"; +static void print_sensor_hcho_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_hcho *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) hcho: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->hcho); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_hcho, struct sensor_hcho, sensor_hcho_format); +ORB_DEFINE(sensor_hcho, struct sensor_hcho, print_sensor_hcho_message); diff --git a/system/uorb/sensor/hrate.c b/system/uorb/sensor/hrate.c index 2eb1df8de..04961b305 100644 --- a/system/uorb/sensor/hrate.c +++ b/system/uorb/sensor/hrate.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_hrate_format[] = "timestamp:%" PRIu64 ",bpm:%hf"; +static void print_sensor_hrate_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_hrate *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "heart rate: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->bpm); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_hrate, struct sensor_hrate, sensor_hrate_format); +ORB_DEFINE(sensor_hrate, struct sensor_hrate, print_sensor_hrate_message); diff --git a/system/uorb/sensor/humi.c b/system/uorb/sensor/humi.c index b381dad42..a765d85bd 100644 --- a/system/uorb/sensor/humi.c +++ b/system/uorb/sensor/humi.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_humi_format[] = "timestamp:%" PRIu64 ",humi:%hf"; +static void print_sensor_humi_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_humi *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) humi: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->humidity); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_humi, struct sensor_humi, sensor_humi_format); +ORB_DEFINE(sensor_humi, struct sensor_humi, print_sensor_humi_message); diff --git a/system/uorb/sensor/impd.c b/system/uorb/sensor/impd.c index 680f3c9f7..00ea5f5cc 100644 --- a/system/uorb/sensor/impd.c +++ b/system/uorb/sensor/impd.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_impd_format[] = - "timestamp:%" PRIu64 ",real:%hf,imaginary:%hf"; +static void print_sensor_impd_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_impd *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "real: %.2f imaginary: %.2f", meta->o_name, + message->timestamp, now - message->timestamp, + message->real, message->imag); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_impd, struct sensor_impd, sensor_impd_format); +ORB_DEFINE(sensor_impd, struct sensor_impd, print_sensor_impd_message); diff --git a/system/uorb/sensor/ir.c b/system/uorb/sensor/ir.c index 1f5233bc1..1ee57f8a7 100644 --- a/system/uorb/sensor/ir.c +++ b/system/uorb/sensor/ir.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ir_format[] = "timestamp:%" PRIu64 ",ir:%hf"; +static void print_sensor_ir_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ir *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) ir: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->ir); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ir, struct sensor_ir, sensor_ir_format); +ORB_DEFINE(sensor_ir, struct sensor_ir, print_sensor_ir_message); diff --git a/system/uorb/sensor/light.c b/system/uorb/sensor/light.c index 27365f4c6..89b2fd530 100644 --- a/system/uorb/sensor/light.c +++ b/system/uorb/sensor/light.c @@ -29,13 +29,22 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_light_format[] = - "timestamp:%" PRIu64 ",light:%hf,ir:%hf"; +static void print_sensor_light_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_light *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "light: %.2f ir: %.2f", meta->o_name, message->timestamp, + now - message->timestamp, message->light, message->ir); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_light, struct sensor_light, sensor_light_format); -ORB_DEFINE(sensor_light_uncal, struct sensor_light, sensor_light_format); +ORB_DEFINE(sensor_light, struct sensor_light, print_sensor_light_message); +ORB_DEFINE(sensor_light_uncal, struct sensor_light, + print_sensor_light_message); diff --git a/system/uorb/sensor/mag.c b/system/uorb/sensor/mag.c index dd4e4985c..c68fd71c5 100644 --- a/system/uorb/sensor/mag.c +++ b/system/uorb/sensor/mag.c @@ -29,14 +29,23 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_mag_format[] = - "timestamp:%" PRIu64 ",x:%hf,y:%hf,z:%hf,temperature:%hf," - "status:%" PRId32 ""; +static void print_sensor_mag_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_mag *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "temperature: %.2f x: %.2f y: %.2f z: %.2f", + meta->o_name, message->timestamp, now - message->timestamp, + message->temperature, message->x, message->y, message->z); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_mag, struct sensor_mag, sensor_mag_format); -ORB_DEFINE(sensor_mag_uncal, struct sensor_mag, sensor_mag_format); +ORB_DEFINE(sensor_mag, struct sensor_mag, print_sensor_mag_message); +ORB_DEFINE(sensor_mag_uncal, struct sensor_mag, + print_sensor_mag_message); diff --git a/system/uorb/sensor/noise.c b/system/uorb/sensor/noise.c index a87303bc4..46420e363 100644 --- a/system/uorb/sensor/noise.c +++ b/system/uorb/sensor/noise.c @@ -29,12 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_noise_format[] = - "timestamp:%" PRIu64 ",noise:%hf"; +static void print_sensor_noise_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_noise *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "noise: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->db); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_noise, struct sensor_noise, sensor_noise_format); +ORB_DEFINE(sensor_noise, struct sensor_noise, print_sensor_noise_message); diff --git a/system/uorb/sensor/ots.c b/system/uorb/sensor/ots.c index 913e70366..100054c07 100644 --- a/system/uorb/sensor/ots.c +++ b/system/uorb/sensor/ots.c @@ -29,12 +29,21 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ots_format[] = - "timestamp:%" PRIu64 ",x:%" PRIi32 ",y:%" PRIi32 ""; +static void print_sensor_ots_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ots *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "x: % " PRIi32 " y: % " PRIi32 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->x, message->y); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ots, struct sensor_ots, sensor_ots_format); +ORB_DEFINE(sensor_ots, struct sensor_ots, print_sensor_ots_message); diff --git a/system/uorb/sensor/ph.c b/system/uorb/sensor/ph.c index 35d51e03a..06028869e 100644 --- a/system/uorb/sensor/ph.c +++ b/system/uorb/sensor/ph.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ph_format[] = "timestamp:%" PRIu64 ",ph:%hf"; +static void print_sensor_ph_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ph *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) ph: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->ph); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ph, struct sensor_ph, sensor_ph_format); +ORB_DEFINE(sensor_ph, struct sensor_ph, print_sensor_ph_message); diff --git a/system/uorb/sensor/pm10.c b/system/uorb/sensor/pm10.c index 6ebb6ba47..b2e57f197 100644 --- a/system/uorb/sensor/pm10.c +++ b/system/uorb/sensor/pm10.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_pm10_format[] = "timestamp:%" PRIu64 ",pm10:%hf"; +static void print_sensor_pm10_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_pm10 *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) pm10: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->pm10); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_pm10, struct sensor_pm10, sensor_pm10_format); +ORB_DEFINE(sensor_pm10, struct sensor_pm10, print_sensor_pm10_message); diff --git a/system/uorb/sensor/pm1p0.c b/system/uorb/sensor/pm1p0.c index 4689d660f..31a1db77e 100644 --- a/system/uorb/sensor/pm1p0.c +++ b/system/uorb/sensor/pm1p0.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_pm1p0_format[] = "timestamp:%" PRIu64 ",pm1p0:%hf"; +static void print_sensor_pm1p0_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_pm1p0 *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "pm1p0: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->pm1p0); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_pm1p0, struct sensor_pm1p0, sensor_pm1p0_format); +ORB_DEFINE(sensor_pm1p0, struct sensor_pm1p0, print_sensor_pm1p0_message); diff --git a/system/uorb/sensor/pm25.c b/system/uorb/sensor/pm25.c index c64e56c0d..83dee92cc 100644 --- a/system/uorb/sensor/pm25.c +++ b/system/uorb/sensor/pm25.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_pm25_format[] = "timestamp:%" PRIu64 ",pm25:%hf"; +static void print_sensor_pm25_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_pm25 *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) pm25: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->pm25); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_pm25, struct sensor_pm25, sensor_pm25_format); +ORB_DEFINE(sensor_pm25, struct sensor_pm25, print_sensor_pm25_message); diff --git a/system/uorb/sensor/ppgd.c b/system/uorb/sensor/ppgd.c index abac23e60..9c6bceba1 100644 --- a/system/uorb/sensor/ppgd.c +++ b/system/uorb/sensor/ppgd.c @@ -29,13 +29,23 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ppgd_format[] = - "timestamp:%" PRIu64 ",ppg0:%" PRIu32 ",ppg1:%" PRIu32 "," - "current:%" PRIu32 ",gain0:%" PRIu16 ",gain1:%" PRIu16 ""; +static void print_sensor_ppgd_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ppgd *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "ppg1: %" PRIu32 " ppg2: %" PRIu32 " current: %" PRIu32 " " + "gain1: %" PRIu16 " gain2: %" PRIu16 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->ppg[0], message->ppg[1], message->current, + message->gain[0], message->gain[1]); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ppgd, struct sensor_ppgd, sensor_ppgd_format); +ORB_DEFINE(sensor_ppgd, struct sensor_ppgd, print_sensor_ppgd_message); diff --git a/system/uorb/sensor/ppgq.c b/system/uorb/sensor/ppgq.c index 89e6e592c..92563ceb7 100644 --- a/system/uorb/sensor/ppgq.c +++ b/system/uorb/sensor/ppgq.c @@ -29,14 +29,25 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_ppgq_format[] = - "timestamp:%" PRIu64 ",ppg0:%" PRIu32 ",ppg1:%" PRIu32 ",ppg2:%" PRIu32 "," - "ppg3:%" PRIu32 ",current:%" PRIu32 ",gain0:%" PRIu16 ",gain1:%" PRIu16 "," - "gain2:%" PRIu16 ",gain3:%" PRIu16 ""; +static void print_sensor_ppgq_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_ppgq *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "ppg1: %" PRIu32 " ppg2: %" PRIu32 " ppg3: %" PRIu32 " " + "ppg4: %" PRIu32 "current: %" PRIu32 " gain1: %" PRIu16 " " + "gain2: %" PRIu16 " gain3: %" PRIu16 " gain4: %" PRIu16 "", + meta->o_name, message->timestamp, now - message->timestamp, + message->ppg[0], message->ppg[1], message->ppg[2], + message->ppg[3], message->current, message->gain[0], + message->gain[1], message->gain[2], message->gain[3]); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_ppgq, struct sensor_ppgq, sensor_ppgq_format); +ORB_DEFINE(sensor_ppgq, struct sensor_ppgq, print_sensor_ppgq_message); diff --git a/system/uorb/sensor/prox.c b/system/uorb/sensor/prox.c index 33d12d24d..cc373d936 100644 --- a/system/uorb/sensor/prox.c +++ b/system/uorb/sensor/prox.c @@ -29,12 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_prox_format[] = - "timestamp:%" PRIu64 ",proximity:%hf"; +static void print_sensor_prox_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_prox *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "proximity: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->proximity); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_prox, struct sensor_prox, sensor_prox_format); +ORB_DEFINE(sensor_prox, struct sensor_prox, print_sensor_prox_message); diff --git a/system/uorb/sensor/rgb.c b/system/uorb/sensor/rgb.c index 0f4830570..f5363a3fe 100644 --- a/system/uorb/sensor/rgb.c +++ b/system/uorb/sensor/rgb.c @@ -29,12 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_rgb_format[] = - "timestamp:%" PRIu64 ",r:%hf,g:%hf,b:%hf"; +static void print_sensor_rgb_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_rgb *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) red: %.2f" + " green: %.2f blue: %.2f\n", meta->o_name, message->timestamp, + now - message->timestamp, message->r, message->g, message->b); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_rgb, struct sensor_rgb, sensor_rgb_format); +ORB_DEFINE(sensor_rgb, struct sensor_rgb, print_sensor_rgb_message); diff --git a/system/uorb/sensor/temp.c b/system/uorb/sensor/temp.c index e24089d23..428d51c6d 100644 --- a/system/uorb/sensor/temp.c +++ b/system/uorb/sensor/temp.c @@ -29,12 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_temp_format[] = - "timestamp:%" PRIu64 ",temperature:%hf"; +static void print_sensor_temp_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_temp *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) " + "temperature: %.4f", meta->o_name, message->timestamp, + now - message->timestamp, message->temperature); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_temp, struct sensor_temp, sensor_temp_format); +ORB_DEFINE(sensor_temp, struct sensor_temp, print_sensor_temp_message); diff --git a/system/uorb/sensor/topics.c b/system/uorb/sensor/topics.c index 0228c4042..9d11ff961 100644 --- a/system/uorb/sensor/topics.c +++ b/system/uorb/sensor/topics.c @@ -22,6 +22,8 @@ * Included Files ****************************************************************************/ +#include + #include #include #include @@ -36,7 +38,6 @@ #include #include #include -#include #include #include #include @@ -79,7 +80,6 @@ static FAR const struct orb_metadata *g_sensor_list[] = ORB_ID(sensor_dust), ORB_ID(sensor_ecg), ORB_ID(sensor_force), - ORB_ID(sensor_gas), ORB_ID(sensor_gps), ORB_ID(sensor_gps_satellite), ORB_ID(sensor_gyro), diff --git a/system/uorb/sensor/tvoc.c b/system/uorb/sensor/tvoc.c index 2ffb83141..b3cf21846 100644 --- a/system/uorb/sensor/tvoc.c +++ b/system/uorb/sensor/tvoc.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_tvoc_format[] = "timestamp:%" PRIu64 ",tvoc:%hf"; +static void print_sensor_tvoc_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_tvoc *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) tvoc: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->tvoc); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_tvoc, struct sensor_tvoc, sensor_tvoc_format); +ORB_DEFINE(sensor_tvoc, struct sensor_tvoc, print_sensor_tvoc_message); diff --git a/system/uorb/sensor/uv.c b/system/uorb/sensor/uv.c index 7c4cd205b..0e827c675 100644 --- a/system/uorb/sensor/uv.c +++ b/system/uorb/sensor/uv.c @@ -29,11 +29,20 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char sensor_uv_format[] = "timestamp:%" PRIu64 ",uvi:%hf"; +static void print_sensor_uv_message(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct sensor_uv *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %" PRIu64 " (%" PRIu64 " us ago) uvi: %.4f", + meta->o_name, message->timestamp, now - message->timestamp, + message->uvi); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(sensor_uv, struct sensor_uv, sensor_uv_format); +ORB_DEFINE(sensor_uv, struct sensor_uv, print_sensor_uv_message); diff --git a/system/uorb/test/unit_test.c b/system/uorb/test/unit_test.c index 901d0a794..81f2355a8 100644 --- a/system/uorb/test/unit_test.c +++ b/system/uorb/test/unit_test.c @@ -25,23 +25,15 @@ #include #include #include -#include #include #include #include #include #include -#include -#include +#include #include "utility.h" -/**************************************************************************** - * Pre-processor Definitions - ****************************************************************************/ - -#define nitems(_a) (sizeof(_a) / sizeof(0[(_a)])) - /**************************************************************************** * Private Data ****************************************************************************/ @@ -56,7 +48,7 @@ static int g_pubsubtest_res; * Private Functions ****************************************************************************/ -static FAR void *pubsubtest_thread_entry(FAR void *arg) +static int pubsubtest_thread_entry(int argc, FAR char *argv[]) { /* poll on test topic and output latency */ @@ -76,11 +68,10 @@ static FAR void *pubsubtest_thread_entry(FAR void *arg) unsigned timing_max = 0; unsigned i; - (void)arg; timings = malloc(MAX_RUNS * sizeof(unsigned)); if (timings == NULL) { - return NULL; + return -ENOMEM; } /* clear all ready flags */ @@ -126,7 +117,7 @@ static FAR void *pubsubtest_thread_entry(FAR void *arg) if (pret < 0) { - printf("poll error %d, %d", pret, errno); + snerr("poll error %d, %d", pret, errno); continue; } } @@ -139,14 +130,14 @@ static FAR void *pubsubtest_thread_entry(FAR void *arg) FAR FILE *f; snprintf(fname, sizeof(fname), - UORB_STORAGE_DIR"/uorb_timings%u.txt", timingsgroup); + CONFIG_UORB_SRORAGE_DIR"/uorb_timings%u.txt", timingsgroup); f = fopen(fname, "w"); if (f == NULL) { - printf("Error opening file!"); + snerr("Error opening file!"); free(timings); - return NULL; + return ERROR; } for (i = 0; i < MAX_RUNS; i++) @@ -186,15 +177,14 @@ static FAR void *pubsubtest_thread_entry(FAR void *arg) } free(timings); - return NULL; + return g_pubsubtest_res; } static int latency_test(bool print) { struct orb_test_medium_s sample; - pthread_t pubsub_task; + int pubsub_task; int instance = 0; - int ret = ERROR; int fd; test_note("---------------- LATENCY TEST ------------------"); @@ -212,11 +202,11 @@ static int latency_test(bool print) g_pubsubtest_print = print; g_pubsubtest_passed = false; - if (pthread_create(&pubsub_task, NULL, pubsubtest_thread_entry, NULL) < 0) - { - test_fail("failed launching task"); - goto out; - } + pubsub_task = task_create("uorb_latency", + SCHED_PRIORITY_DEFAULT, + CONFIG_UORB_STACKSIZE, + pubsubtest_thread_entry, + NULL); /* give the test task some data */ @@ -226,8 +216,7 @@ static int latency_test(bool print) sample.timestamp = orb_absolute_time(); if (OK != orb_publish(ORB_ID(orb_test_medium), fd, &sample)) { - test_fail("mult. pub0 timing fail"); - goto out; + return test_fail("mult. pub0 timing fail"); } usleep(1000); /* simulate >800 Hz system operation */ @@ -235,15 +224,11 @@ static int latency_test(bool print) if (pubsub_task < 0) { - test_fail("failed launching task"); - goto out; + return test_fail("failed launching task"); } - ret = OK; - -out: orb_unadvertise(fd); - return ret < 0 ? ret : g_pubsubtest_res; + return g_pubsubtest_res; } static int test_single(void) @@ -254,7 +239,7 @@ static int test_single(void) bool updated; int afd; int sfd; - int ret = ERROR; + int ret; test_note("try single-topic support"); @@ -272,7 +257,6 @@ static int test_single(void) sfd = orb_subscribe(ORB_ID(orb_test)); if (sfd < 0) { - orb_unadvertise(afd); return test_fail("subscribe failed: %d", errno); } @@ -282,27 +266,23 @@ static int test_single(void) if (OK != orb_copy(ORB_ID(orb_test), sfd, &sub_sample)) { - test_fail("copy(1) failed: %d", errno); - goto out; + return test_fail("copy(1) failed: %d", errno); } if (sample.val != sub_sample.val) { - test_fail("copy(1) mismatch: %d expected %d", - sub_sample.val, sample.val); - goto out; + return test_fail("copy(1) mismatch: %d expected %d", + sub_sample.val, sample.val); } if (OK != orb_check(sfd, &updated)) { - test_fail("check(1) failed"); - goto out; + return test_fail("check(1) failed"); } if (updated) { - test_fail("spurious updated flag"); - goto out; + return test_fail("spurious updated flag"); } /* check second publish */ @@ -311,56 +291,45 @@ static int test_single(void) if (OK != orb_publish(ORB_ID(orb_test), afd, &sample)) { - test_fail("publish failed"); - goto out; + return test_fail("publish failed"); } if (OK != orb_check(sfd, &updated)) { - test_fail("check(2) failed"); - goto out; + return test_fail("check(2) failed"); } if (!updated) { - test_fail("missing updated flag"); - goto out; + return test_fail("missing updated flag"); } if (OK != orb_copy(ORB_ID(orb_test), sfd, &sub_sample)) { - test_fail("copy(2) failed: %d", errno); - goto out; + return test_fail("copy(2) failed: %d", errno); } if (sample.val != sub_sample.val) { - test_fail("copy(2) mismatch: %d expected %d", - sub_sample.val, sample.val); - goto out; + return test_fail("copy(2) mismatch: %d expected %d", + sub_sample.val, sample.val); } /* unadvertise and out */ -out: ret = orb_unadvertise(afd); if (ret != OK) { - test_fail("orb_unadvertise failed: %i", ret); + return test_fail("orb_unadvertise failed: %i", ret); } ret = orb_unsubscribe(sfd); if (ret != OK) { - test_fail("orb_unsubscribe failed: %i", ret); + return test_fail("orb_unsubscribe failed: %i", ret); } - if (ret == OK) - { - test_note("PASS single-topic test"); - } - - return ret; + return test_note("PASS single-topic test"); } static int test_multi_inst10(void) @@ -368,7 +337,6 @@ static int test_multi_inst10(void) const int max_inst = 10; int sfd[max_inst]; int afd[max_inst]; - int ret = ERROR; int i; int j; @@ -383,8 +351,7 @@ static int test_multi_inst10(void) { if (OK == orb_exists(ORB_ID(orb_test), i)) { - test_fail("sub %d is advertised", i); - goto out_with_sfd; + return test_fail("sub %d is advertised", i); } } @@ -394,16 +361,9 @@ static int test_multi_inst10(void) { afd[i] = orb_advertise_multi_queue_persist(ORB_ID(orb_test), NULL, &i, 1); - } - - /* verify advertised yet */ - - for (i = 0; i < max_inst; i++) - { if (OK != orb_exists(ORB_ID(orb_test), i)) { - test_fail("sub %d advertise failed", i); - goto out_with_sfd; + return test_fail("sub %d advertise failed", i); } } @@ -433,8 +393,7 @@ static int test_multi_inst10(void) orb_check(sfd[sub_instance], &updated); if (!updated) { - test_fail("sub %d not updated", sub_instance); - goto out; + return test_fail("sub %d not updated", sub_instance); } else { @@ -442,16 +401,14 @@ static int test_multi_inst10(void) if (orb_copy(ORB_ID(orb_test), sfd[sub_instance], &sample)) { - test_fail("sub %d copy failed", sub_instance); - goto out; + return test_fail("sub %d copy failed", sub_instance); } else { if (sample.val != (j * sub_instance + i)) { - test_fail("sub %d invalid value %d", - sub_instance, sample.val); - goto out; + return test_fail("sub %d invalid value %d", + sub_instance, sample.val); } } } @@ -459,26 +416,14 @@ static int test_multi_inst10(void) } } - ret = OK; + /* force unsubscribe all, then repeat */ -out: - for (i = 0; i < max_inst; i++) - { - orb_unadvertise(afd[i]); - } - -out_with_sfd: for (i = 0; i < max_inst; i++) { orb_unsubscribe(sfd[i]); } - if (ret == OK) - { - test_note("PASS orb 10-instances"); - } - - return ret; + return test_note("PASS orb 10-instances"); } static int test_multi(int *afds, int *sfds) @@ -660,7 +605,7 @@ static int test_unadvertise(int *afds) return OK; } -static FAR void *pub_test_multi2_entry(FAR void *arg) +static int pub_test_multi2_entry(int argc, char *argv[]) { struct orb_test_medium_s data_topic; const int num_instances = 3; @@ -670,7 +615,6 @@ static FAR void *pub_test_multi2_entry(FAR void *arg) int num_messages = 50 * num_instances; int i; - (void)arg; memset(&data_topic, '\0', sizeof(data_topic)); for (i = 0; i < num_instances; ++i) { @@ -706,7 +650,7 @@ static FAR void *pub_test_multi2_entry(FAR void *arg) orb_unadvertise(orb_pub[i]); } - return NULL; + return OK; } static int test_multi2(void) @@ -715,10 +659,7 @@ static int test_multi2(void) int orb_data_fd[num_instances]; int orb_data_next = 0; orb_abstime last_time = 0; - struct sched_param param; - pthread_attr_t attr; - pthread_t pubsub_task; - int ret = ERROR; + int pubsub_task; int i; test_note("Testing multi-topic 2 test (queue simulation)"); @@ -734,19 +675,16 @@ static int test_multi2(void) /* launch the publisher thread */ - pthread_attr_init(&attr); - param.sched_priority = sched_get_priority_max(0) - 5; - pthread_attr_setschedparam(&attr, ¶m); - - if (pthread_create(&pubsub_task, &attr, pub_test_multi2_entry, NULL) < 0) + pubsub_task = task_create("uorb_test_multi", + SCHED_PRIORITY_MAX - 5, + CONFIG_UORB_STACKSIZE, + pub_test_multi2_entry, + NULL); + if (pubsub_task < 0) { - pthread_attr_destroy(&attr); - test_fail("failed launching task"); - goto out; + return test_fail("failed launching task"); } - pthread_attr_destroy(&attr); - /* loop check update and copy new data */ while (!g_thread_should_exit) @@ -767,15 +705,13 @@ static int test_multi2(void) if (OK != orb_copy(ORB_ID(orb_test_medium_multi), orb_data_cur_fd, &msg)) { - test_fail("copy failed: %d", errno); - goto out; + return test_fail("copy failed: %d", errno); } if (last_time >= msg.timestamp && last_time != 0) { - test_fail("Timestamp not increasing! (%" PRIu64 - " >= %" PRIu64 ")", last_time, msg.timestamp); - goto out; + return test_fail("Timestamp not increasing! (%" PRIu64 + " >= %" PRIu64 ")", last_time, msg.timestamp); } last_time = msg.timestamp; @@ -783,20 +719,12 @@ static int test_multi2(void) } } - ret = OK; - -out: for (i = 0; i < num_instances; ++i) { orb_unsubscribe(orb_data_fd[i]); } - if (ret == OK) - { - test_note("PASS multi-topic 2 test (queue simulation)"); - } - - return ret; + return test_note("PASS multi-topic 2 test (queue simulation)"); } int test_queue(void) @@ -809,7 +737,6 @@ int test_queue(void) int instance = 0; int ptopic; int sfd; - int ret = ERROR; int i; test_note("Testing orb queuing"); @@ -839,60 +766,52 @@ int test_queue(void) ORB_ID(orb_test_medium_queue), &sample, &instance, queue_size); if (ptopic < 0) { - orb_unsubscribe(sfd); return test_fail("advertise failed: %d", errno); } orb_check(sfd, &updated); if (!updated) { - test_fail("update flag not set"); - goto out; + return test_fail("update flag not set"); } if (OK != orb_copy(ORB_ID(orb_test_medium_queue), sfd, &sub_sample)) { - test_fail("copy(1) failed: %d", errno); - goto out; + return test_fail("copy(1) failed: %d", errno); } if (sub_sample.val != sample.val) { - test_fail("copy(1) mismatch: %d expected %d", - sub_sample.val, sample.val); - goto out; + return test_fail("copy(1) mismatch: %d expected %d", + sub_sample.val, sample.val); } orb_check(sfd, &updated); if (updated) { - test_fail("spurious updated flag"); - goto out; + return test_fail("spurious updated flag"); } #define CHECK_UPDATED(element) \ orb_check(sfd, &updated); \ if (!updated) \ { \ - test_fail("update flag not set, element %i", element); \ - goto out; \ + return test_fail("update flag not set, element %i", element); \ } #define CHECK_NOT_UPDATED(element) \ orb_check(sfd, &updated); \ if (updated) \ { \ - test_fail("update flag set, element %i", element); \ - goto out; \ + return test_fail("update flag set, element %i", element); \ } #define CHECK_COPY(i_got, i_correct) \ orb_copy(ORB_ID(orb_test_medium_queue), sfd, &sub_sample); \ if (i_got != i_correct) \ { \ - test_fail("got wrong element from the queue (got %i," \ - "should be %i)", i_got, i_correct); \ - goto out; \ + return test_fail("got wrong element from the queue (got %i," \ + "should be %i)", i_got, i_correct); \ } /* no messages in the queue anymore */ @@ -948,21 +867,13 @@ int test_queue(void) #undef CHECK_UPDATED #undef CHECK_NOT_UPDATED - ret = OK; - -out: orb_unadvertise(ptopic); orb_unsubscribe(sfd); - if (ret == OK) - { - test_note("PASS orb queuing"); - } - - return ret; + return test_note("PASS orb queuing"); } -static FAR void *pub_test_queue_entry(FAR void *arg) +static int pub_test_queue_entry(int argc, char *argv[]) { const int queue_size = 50; struct orb_test_medium_s t; @@ -971,15 +882,13 @@ static FAR void *pub_test_queue_entry(FAR void *arg) int instance = 0; int ptopic; - (void)arg; memset(&t, '\0', sizeof(t)); ptopic = orb_advertise_multi_queue_persist( ORB_ID(orb_test_medium_queue_poll), &t, &instance, queue_size); if (ptopic < 0) { g_thread_should_exit = true; - test_fail("advertise failed: %d", errno); - return NULL; + return test_fail("advertise failed: %d", errno); } ++t.val; @@ -1006,18 +915,17 @@ static FAR void *pub_test_queue_entry(FAR void *arg) usleep(100 * 1000); g_thread_should_exit = true; orb_unadvertise(ptopic); - return NULL; + + return 0; } static int test_queue_poll_notify(void) { struct pollfd fds[1]; struct orb_test_medium_s t; - struct sched_param param; - pthread_attr_t attr; bool updated; int next_expected_val = 0; - pthread_t pubsub_task; + int pubsub_task; int sfd; test_note("Testing orb queuing (poll & notify)"); @@ -1043,19 +951,17 @@ static int test_queue_poll_notify(void) g_thread_should_exit = false; - pthread_attr_init(&attr); - param.sched_priority = sched_get_priority_min(0) + 5; - pthread_attr_setschedparam(&attr, ¶m); + pubsub_task = task_create("uorb_test_queue", + SCHED_PRIORITY_MIN + 5, + CONFIG_UORB_STACKSIZE, + pub_test_queue_entry, + NULL); - if (pthread_create(&pubsub_task, &attr, pub_test_queue_entry, NULL) < 0) + if (pubsub_task < 0) { - orb_unsubscribe(sfd); - pthread_attr_destroy(&attr); - return test_fail("failed test queue task"); + return test_fail("failed launching task"); } - pthread_attr_destroy(&attr); - fds[0].fd = sfd; fds[0].events = POLLIN; @@ -1071,12 +977,10 @@ static int test_queue_poll_notify(void) break; } - orb_unsubscribe(sfd); return test_fail("poll timeout"); } else if (poll_ret < 0 && errno != EINTR) { - orb_unsubscribe(sfd); return test_fail("poll error (%d, %d)", poll_ret, errno); } @@ -1085,7 +989,6 @@ static int test_queue_poll_notify(void) orb_copy(ORB_ID(orb_test_medium_queue_poll), sfd, &t); if (next_expected_val != t.val) { - orb_unsubscribe(sfd); return test_fail("copy mismatch: %d expected %d", t.val, next_expected_val); } @@ -1096,7 +999,6 @@ static int test_queue_poll_notify(void) if (g_num_messages_sent != next_expected_val) { - orb_unsubscribe(sfd); return test_fail("number of sent and received messages mismatch" " (sent: %i, received: %i)", g_num_messages_sent, next_expected_val); diff --git a/system/uorb/test/utility.c b/system/uorb/test/utility.c index 2b65258de..c56ea39b9 100644 --- a/system/uorb/test/utility.c +++ b/system/uorb/test/utility.c @@ -32,24 +32,58 @@ ****************************************************************************/ #ifdef CONFIG_DEBUG_UORB -static const char orb_test_format[] = - "timestamp:%" PRIu64 ",val:%" PRId32 ""; +static void print_orb_test_msg(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct orb_test_s *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %"PRIu64" (%"PRIu64" us ago) val: %"PRId32"", + meta->o_name, message->timestamp, now - message->timestamp, + message->val); +} + +static void print_orb_test_medium_msg(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct orb_test_medium_s *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %"PRIu64" (%"PRIu64" us ago) val: %"PRId32"", + meta->o_name, message->timestamp, now - message->timestamp, + message->val); +} + +static void print_orb_test_large_msg(FAR const struct orb_metadata *meta, + FAR const void *buffer) +{ + FAR const struct orb_test_large_s *message = buffer; + const orb_abstime now = orb_absolute_time(); + + uorbinfo_raw("%s:\ttimestamp: %"PRIu64" (%"PRIu64" us ago) val: %"PRId32"", + meta->o_name, message->timestamp, now - message->timestamp, + message->val); +} #endif /**************************************************************************** * Public Data ****************************************************************************/ -ORB_DEFINE(orb_test, struct orb_test_s, orb_test_format); -ORB_DEFINE(orb_multitest, struct orb_test_s, orb_test_format); -ORB_DEFINE(orb_test_medium, struct orb_test_medium_s, orb_test_format); -ORB_DEFINE(orb_test_medium_multi, struct orb_test_medium_s, orb_test_format); +ORB_DEFINE(orb_test, struct orb_test_s, print_orb_test_msg); +ORB_DEFINE(orb_multitest, struct orb_test_s, print_orb_test_msg); +ORB_DEFINE(orb_test_medium, struct orb_test_medium_s, + print_orb_test_medium_msg); +ORB_DEFINE(orb_test_medium_multi, struct orb_test_medium_s, + print_orb_test_medium_msg); ORB_DEFINE(orb_test_medium_wrap_around, struct orb_test_medium_s, - orb_test_format); -ORB_DEFINE(orb_test_medium_queue, struct orb_test_medium_s, orb_test_format); + print_orb_test_medium_msg); +ORB_DEFINE(orb_test_medium_queue, struct orb_test_medium_s, + print_orb_test_medium_msg); ORB_DEFINE(orb_test_medium_queue_poll, struct orb_test_medium_s, - orb_test_format); -ORB_DEFINE(orb_test_large, struct orb_test_large_s, orb_test_format); + print_orb_test_medium_msg); +ORB_DEFINE(orb_test_large, struct orb_test_large_s, + print_orb_test_large_msg); /**************************************************************************** * Public Functions diff --git a/system/uorb/uORB/uORB.c b/system/uorb/uORB/uORB.c index 659601744..a84bd1cf7 100644 --- a/system/uorb/uORB/uORB.c +++ b/system/uorb/uORB/uORB.c @@ -25,12 +25,10 @@ #include #include #include +#include #include -#include #include -#include -#include #include /**************************************************************************** @@ -77,7 +75,7 @@ static int orb_advsub_open(FAR const struct orb_metadata *meta, int flags, reginfo.nbuffer = queue_size; reginfo.persist = !!(flags & SENSOR_PERSIST); - fd = open(ORB_USENSOR_PATH, O_WRONLY | O_CLOEXEC); + fd = open(ORB_USENSOR_PATH, O_WRONLY); if (fd < 0) { return fd; @@ -229,16 +227,6 @@ int orb_get_state(int fd, FAR struct orb_state *state) return ret; } -int orb_get_events(int fd, FAR unsigned int *events) -{ - if (!events) - { - return -EINVAL; - } - - return ioctl(fd, SNIOC_GET_EVENTS, (unsigned long)(uintptr_t)events); -} - int orb_check(int fd, FAR bool *updated) { return ioctl(fd, SNIOC_UPDATED, (unsigned long)(uintptr_t)updated); @@ -249,11 +237,6 @@ int orb_ioctl(int fd, int cmd, unsigned long arg) return ioctl(fd, cmd, arg); } -int orb_flush(int fd) -{ - return ioctl(fd, SNIOC_FLUSH, 0); -} - int orb_set_interval(int fd, unsigned interval) { return ioctl(fd, SNIOC_SET_INTERVAL, (unsigned long)interval); @@ -261,29 +244,19 @@ int orb_set_interval(int fd, unsigned interval) int orb_get_interval(int fd, FAR unsigned *interval) { - struct sensor_ustate_s tmp; + struct sensor_state_s tmp; int ret; - ret = ioctl(fd, SNIOC_GET_USTATE, (unsigned long)(uintptr_t)&tmp); + ret = ioctl(fd, SNIOC_GET_STATE, (unsigned long)(uintptr_t)&tmp); if (ret < 0) { return ret; } - *interval = tmp.interval; + *interval = tmp.min_interval; return ret; } -int orb_set_info(int fd, FAR const orb_info_t *info) -{ - return ioctl(fd, SNIOC_SET_INFO, (unsigned long)(uintptr_t)info); -} - -int orb_get_info(int fd, FAR orb_info_t *info) -{ - return ioctl(fd, SNIOC_GET_INFO, (unsigned long)(uintptr_t)info); -} - int orb_set_batch_interval(int fd, unsigned batch_interval) { return ioctl(fd, SNIOC_BATCH, (unsigned long)batch_interval); @@ -291,16 +264,16 @@ int orb_set_batch_interval(int fd, unsigned batch_interval) int orb_get_batch_interval(int fd, FAR unsigned *batch_interval) { - struct sensor_ustate_s tmp; + struct sensor_state_s tmp; int ret; - ret = ioctl(fd, SNIOC_GET_USTATE, (unsigned long)(uintptr_t)&tmp); + ret = ioctl(fd, SNIOC_GET_STATE, (unsigned long)(uintptr_t)&tmp); if (ret < 0) { return ret; } - *batch_interval = tmp.latency; + *batch_interval = tmp.min_latency; return ret; } @@ -349,33 +322,3 @@ int orb_group_count(FAR const struct orb_metadata *meta) return instance; } - -#ifdef CONFIG_DEBUG_UORB -int orb_sscanf(FAR const char *buf, FAR const char *format, FAR void *data) -{ - struct lib_meminstream_s meminstream; - int lastc; - - lib_meminstream(&meminstream, buf, strlen(buf)); - return lib_bscanf(&meminstream.common, &lastc, format, data); -} - -void orb_info(FAR const char *format, FAR const char *name, - FAR const void *data) -{ - struct va_format vaf; - - vaf.fmt = format; - vaf.va = (va_list *)data; - uorbinfo_raw("%s(now:%" PRIu64 "):%pB", name, orb_absolute_time(), &vaf); -} - -int orb_fprintf(FAR FILE *stream, FAR const char *format, - FAR const void *data) -{ - struct lib_stdoutstream_s stdoutstream; - - lib_stdoutstream(&stdoutstream, stream); - return lib_bsprintf(&stdoutstream.common, format, data); -} -#endif diff --git a/system/uorb/uORB/uORB.h b/system/uorb/uORB/uORB.h index d263ab794..d134393c1 100644 --- a/system/uorb/uORB/uORB.h +++ b/system/uorb/uORB/uORB.h @@ -25,31 +25,29 @@ * Included Files ****************************************************************************/ -#ifdef __NuttX__ -#include -#else -#include -#endif +#include +#include #include -#include +#include #include #include #include -#include /**************************************************************************** * Public Types ****************************************************************************/ +struct orb_metadata; +typedef void (*orb_print_message)(FAR const struct orb_metadata *meta, + FAR const void *buffer); + struct orb_metadata { FAR const char *o_name; /* Unique object name */ uint16_t o_size; /* Object size */ #ifdef CONFIG_DEBUG_UORB - FAR const char *o_format; /* Format string used for structure input and - * output. - */ + orb_print_message o_cb; /* Function pointer of output topic message */ #endif }; @@ -73,54 +71,43 @@ struct orb_object }; typedef uint64_t orb_abstime; -typedef struct sensor_device_info_s orb_info_t; /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ -#define ORB_EVENT_FLUSH_COMPLETE SENSOR_EVENT_FLUSH_COMPLETE - #define ORB_SENSOR_PATH "/dev/uorb/" #define ORB_USENSOR_PATH "/dev/usensor" #define ORB_PATH_MAX (NAME_MAX + 16) -#ifdef CONFIG_UORB_STORAGE_DIR -#define UORB_STORAGE_DIR CONFIG_UORB_STORAGE_DIR -#else -#define UORB_STORAGE_DIR "/data" -#endif - -#define uorbnone(fmt, ...) do { if (0) syslog(LOG_INFO, fmt, ##__VA_ARGS__); } while (0) - #ifdef CONFIG_UORB_ALERT -# define uorbpanic(fmt, ...) syslog(LOG_EMERGY, fmt "\n", ##__VA_ARGS__) +# define uorbpanic(fmt, ...) _alert(fmt "\n", ##__VA_ARGS__) #else -# define uorbpanic uorbnone +# define uorbpanic _none #endif #ifdef CONFIG_UORB_ERROR -# define uorberr(fmt, ...) syslog(LOG_ERR, fmt "\n", ##__VA_ARGS__) +# define uorberr(fmt, ...) _err(fmt "\n", ##__VA_ARGS__) #else -# define uorberr uorbnone +# define uorberr _none #endif #ifdef CONFIG_UORB_WARN -# define uorbwarn(fmt, ...) syslog(LOG_WARN, fmt "\n", ##__VA_ARGS__) +# define uorbwarn(fmt, ...) _warn(fmt "\n", ##__VA_ARGS__) #else -# define uorbwarn uorbnone +# define uorbwarn _none #endif #ifdef CONFIG_UORB_INFO -# define uorbinfo(fmt, ...) syslog(LOG_INFO, fmt "\n", ##__VA_ARGS__) +# define uorbinfo(fmt, ...) _info(fmt "\n", ##__VA_ARGS__) #else -# define uorbinfo uorbnone +# define uorbinfo _none #endif #ifdef CONFIG_DEBUG_UORB # define uorbdebug(fmt, ...) syslog(LOG_INFO, fmt "\n", ##__VA_ARGS__) #else -# define uorbdebug uorbnone +# define uorbdebug _none #endif #define uorbinfo_raw(fmt, ...) syslog(LOG_INFO, fmt "\n", ##__VA_ARGS__) @@ -160,15 +147,15 @@ typedef struct sensor_device_info_s orb_info_t; * cb The function pointer of output topic message. */ #ifdef CONFIG_DEBUG_UORB -#define ORB_DEFINE(name, structure, format) \ +#define ORB_DEFINE(name, structure, cb) \ const struct orb_metadata g_orb_##name = \ { \ #name, \ sizeof(structure), \ - format, \ + cb, \ }; #else -#define ORB_DEFINE(name, structure, format) \ +#define ORB_DEFINE(name, structure, cb) \ const struct orb_metadata g_orb_##name = \ { \ #name, \ @@ -488,23 +475,6 @@ static inline int orb_copy(FAR const struct orb_metadata *meta, int orb_get_state(int fd, FAR struct orb_state *state); -/**************************************************************************** - * Name: orb_get_events - * - * Description: - * Get the events about the specify subscriber of topic. - * - * Input Parameters: - * fd The fd returned from orb_advertise / orb_subscribe. - * events Pointer to events, type is unsigned int pointer. - * eg: ORB_EVENT_FLUSH_COMPLETE - * - * Returned Value: - * -1 on error. - ****************************************************************************/ - -int orb_get_events(int fd, FAR unsigned int *events); - /**************************************************************************** * Name: orb_check * @@ -547,27 +517,6 @@ int orb_check(int fd, FAR bool *updated); int orb_ioctl(int fd, int cmd, unsigned long arg); -/**************************************************************************** - * Name: orb_flush - * - * Description: - * When topic data accumulates in the hardware buffer but does not reach - * the watermark, you can mmediately read the fifo data through the flush - * operation. You can call the flush operation at any time. - * - * After you call flush, you can determine whether the flush is completed - * by listening to the POLLPRI event of fd and getting the event in - * orb_get_events - * - * Input Parameters: - * fd A fd returned from orb_advertise / orb_subscribe. - * - * Returned Value: - * 0 on success. - ****************************************************************************/ - -int orb_flush(int fd); - /**************************************************************************** * Name: orb_set_batch_interval * @@ -643,38 +592,6 @@ int orb_set_interval(int fd, unsigned interval); int orb_get_interval(int fd, FAR unsigned *interval); -/**************************************************************************** - * Name: orb_set_info - * - * Description: - * Set topic information. - * - * Input Parameters: - * fd A fd returned from orb_subscribe. - * info Data to be transmitted. - * - * Returned Value: - * 0 on success, -1 otherwise with ERRNO set accordingly. - ****************************************************************************/ - -int orb_set_info(int fd, FAR const orb_info_t *info); - -/**************************************************************************** - * Name: orb_get_info - * - * Description: - * Get topic information. - * - * Input Parameters: - * fd A fd returned from orb_subscribe. - * info The returned topic info. - * - * Returned Value: - * 0 on success, -1 otherwise with ERRNO set accordingly. - ****************************************************************************/ - -int orb_get_info(int fd, FAR orb_info_t *info); - /**************************************************************************** * Name: * orb_set_frequency @@ -804,61 +721,6 @@ int orb_group_count(FAR const struct orb_metadata *meta); FAR const struct orb_metadata *orb_get_meta(FAR const char *name); -#ifdef CONFIG_DEBUG_UORB -/**************************************************************************** - * Name: orb_scanf - * - * Description: - * Convert string value to structure buffer. - * - * Input Parameters: - * buf Input string value. - * format The uORB metadata.o_format. - * data Structure buffer pointer. - * - * Returned Value: - * Zero (OK) or positive on success; a negated errno value on failure. - ****************************************************************************/ - -int orb_sscanf(FAR const char *buf, FAR const char *format, FAR void *data); - -/**************************************************************************** - * Name: orb_info - * - * Description: - * Print sensor data. - * - * Input Parameters: - * format The uORB metadata.o_format. - * name The uORB metadata.o_name. - * data Topic data that needs to be print. - * - * Returned Value: - * Format string length on success, otherwise returns negative value. - ****************************************************************************/ - -void orb_info(FAR const char *format, FAR const char *name, - FAR const void *data); - -/**************************************************************************** - * Name: orb_fprintf - * - * Description: - * Print sensor data to file. - * - * Input Parameters: - * stream file handle. - * format The uORB metadata.o_format. - * data Topic data that needs to be print. - * - * Returned Value: - * String length on success, otherwise returns negative value. - ****************************************************************************/ - -int orb_fprintf(FAR FILE *stream, FAR const char *format, - FAR const void *data); -#endif - #ifdef __cplusplus } #endif diff --git a/system/usbmsc/README.md b/system/usbmsc/README.md deleted file mode 100644 index da85f8bbc..000000000 --- a/system/usbmsc/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# System / `usbmsc` USB storage driver - -This add-on registers a block device driver, then exports the block the device -using the USB storage class driver. In order to use this add-on, your -board-specific logic must provide the function: - -```c -void board_usbmsc_initialize(void); -``` - -This function will be called by the `system/usbmsc` indirectly via the `boardctl` -`BOARDIOC_USBDEV_CONTROL` command in order to do the actual registration of the -block device drivers. For examples of the implementation of -`board_usbmsc_initialize()` see -`boards/arm/lpc214x/mcu123-lpc214x/src/up_usbmsc.c` or -`boards/arm/stm32/stm3210e-eval/src/usbmsc.c`. - -Configuration options: - -- `CONFIG_NSH_BUILTIN_APPS` – This add-on can be built as two NSH _built-in_ - commands if this option is selected: `msconn` will connect the USB mass - storage device; `msdis` will disconnect the USB storage device. - -- `CONFIG_BOARDCTL` – Enables the `boardctl()` interfaces. - -- `CONFIG_BOARDCTL_USBDEVCTRL` – Enables the `BOARDIOC_USBDEV_CONTROL` - `boardctl()` command. - -- `CONFIG_SYSTEM_USBMSC_NLUNS` – Defines the number of logical units (LUNs) - exported by the USB storage driver. Each LUN corresponds to one exported block - driver (or partition of a block driver). May be `1`, `2`, or `3`. Default is - `1`. - -- `CONFIG_SYSTEM_USBMSC_DEVMINOR1` – The minor device number of the block driver - for the first LUN. For example, `N` in `/dev/mmcsdN`. Used for registering the - block driver. Default is zero. - -- `CONFIG_SYSTEM_USBMSC_DEVPATH1` – The full path to the registered block - driver. Default is `/dev/mmcsd0` - -- `CONFIG_SYSTEM_USBMSC_DEVMINOR2` and `CONFIG_SYSTEM_USBMSC_DEVPATH2` - Similar parameters that would have to be provided if - `CONFIG_SYSTEM_USBMSC_NLUNS` is `2` or `3`. No defaults. - -- `CONFIG_SYSTEM_USBMSC_DEVMINOR3` and `CONFIG_SYSTEM_USBMSC_DEVPATH3` - Similar parameters that would have to be provided if - `CONFIG_SYSTEM_USBMSC_NLUNS` is `3`. No defaults. - -- `CONFIG_SYSTEM_USBMSC_DEBUGMM` – Enables some debug tests to check for memory - usage and memory leaks. - -If `CONFIG_USBDEV_TRACE` is enabled (or `CONFIG_DEBUG_FEATURES` and -`CONFIG_DEBUG_USB`), then the code will also manage the USB trace output. The -amount of trace output can be controlled using: - -- `CONFIG_SYSTEM_USBMSC_TRACEINIT` – Show initialization events. -- `CONFIG_SYSTEM_USBMSC_TRACECLASS` – Show class driver events. -- `CONFIG_SYSTEM_USBMSC_TRACETRANSFERS` – Show data transfer events. -- `CONFIG_SYSTEM_USBMSC_TRACECONTROLLER` – Show controller events. -- `CONFIG_SYSTEM_USBMSC_TRACEINTERRUPTS` – Show interrupt-related events. - -Error results are always shown in the trace output - -**Note 1**: When built as an NSH add-on command (`CONFIG_NSH_BUILTIN_APPS=y`), -Caution should be used to assure that the SD drive (or other storage device) is -not in use when the USB storage device is configured. Specifically, the SD -driver should be unmounted like: - -```shell -nsh> mount -t vfat /dev/mmcsd0 /mnt/sdcard # Card is mounted in NSH -... -nsh> umount /mnd/sdcard # Unmount before connecting USB!!! -nsh> msconn # Connect the USB storage device -... -nsh> msdis # Disconnect USB storate device -nsh> mount -t vfat /dev/mmcsd0 /mnt/sdcard # Restore the mount -``` - -Failure to do this could result in corruption of the SD card format. - -**Note 2**: This add-on used internal USB device driver interfaces. As such, it -relies on internal OS interfaces that are not normally available to a user-space -program. As a result, this add-on cannot be used if a NuttX is built as a -protected, supervisor kernel (`CONFIG_BUILD_PROTECTED` or -`CONFIG_BUILD_KERNEL`). diff --git a/system/ymodem/README.md b/system/ymodem/README.md deleted file mode 100644 index f7bf687de..000000000 --- a/system/ymodem/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Introduce - -This is [ymodem protocal](http://pauillac.inria.fr/~doligez/zmodem/ymodem.txt). -According to it, the sb rb application is realized, which is used to send files and receive files respectively - -# Usage - -## Common Usage - -In the ubuntu system, lszrz needs to be installed, can use `sudo apt install lszrz`. -Use minicom to communicate with the board. - - -## Advanced Usage - -In order to achieve a faster transmission speed, -I added a specific HEADER `STC` to the YMODEM protocol to represent the custom length. -Using the `sb` and `rb` commands on the board, you can use the `-k` option to set the length -of the custom packet, and the unit is KB. Therefore, you need to use `sbrb.py` for file transfer, -and you need `sbrb.py` -k to set the same length as the board. According to my test, -when using -k 32, it can reach 93% of the baud rate, -and is fully compatible with the original ymodem protocol. -First, you need to add a soft link to sbrb.py, for example `sudo ln -s /home//...//apps/system/ymodem/sbrb.py /usr/bin` -and then sbrb.py can be configured into minicom.` z o` then chose `File transfer protocols` and -crate two option cmd is 'sbrb.py -k 32'. like this - -| Name | Program | Name | U/D | FullScr | IO-Red. | Multi | -| ---- | ------- | ---- | --- | ------- | ------- | ----- | -| ymodem-k | sbrb.py -k 32 | Y | U | N | Y | Y | -| ymodem-k | sbrb.py -k 32 | N | D | N | Y | Y | - -usb `sb -k 32` or `rb -k 32` for file transfer on board. - -## Sendfile to pc - -use sb command like this `nsh> sb /tmp/test.c ...`, this command support send multiple files together -then use ` , r` chose `ymodem` to receive board file. - -## Sendfile to board - -use rb cmd like this `nsh> rb`, this command support receive multiple files together -then use ` , s` chose `ymodem`, then chose what file need to send. - -## help - -can use `sb -h` or `rb -h` get help. - -# Debug - -Because the serial port is used for communication, the log is printed to the debug file -you can use `CONFIG_SYSTEM_YMODEM_DEBUGFILE_PATH` set debug file path. diff --git a/system/ymodem/rb_main.c b/system/ymodem/rb_main.c index 28fa4ee92..1beb8c2a2 100644 --- a/system/ymodem/rb_main.c +++ b/system/ymodem/rb_main.c @@ -27,7 +27,7 @@ #include #include -#include +#include #include "ymodem.h" @@ -330,12 +330,6 @@ static void show_usage(FAR const char *progname) fprintf(stderr, "\t-t|--threshold : Threshold for writing asynchronously." "Threshold must be less than or equal buffersize, Default: 0kB\n"); - fprintf(stderr, - "\t-i|--interval