Compare commits
43
Commits
2cdb65309f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e86c7e3df4 | ||
|
|
2dc2adce3c | ||
|
|
b69717b964 | ||
|
|
c347c988f2 | ||
|
|
e885c1b7ea | ||
|
|
e834928457 | ||
|
|
2e76d7b4db | ||
|
|
d8558bd8d4 | ||
|
|
3bbb500a61 | ||
|
|
524a274275 | ||
|
|
ccac60a1e9 | ||
|
|
a87625df90 | ||
|
|
8e779dce30 | ||
|
|
f8420cd3b5 | ||
|
|
ade2008f6c | ||
|
|
5275511b20 | ||
|
|
30cbf31276 | ||
|
|
9230e7985d | ||
|
|
2fa3bbf647 | ||
|
|
c4c95b2a3b | ||
|
|
b8dbaa619d | ||
|
|
e3d08f7f26 | ||
|
|
46c9c0ab73 | ||
|
|
49605367e9 | ||
|
|
cde0bd8243 | ||
|
|
58b98a1a3f | ||
|
|
d53ab96f53 | ||
|
|
15f5230095 | ||
|
|
c1121aecd6 | ||
|
|
fbe2e121db | ||
|
|
38169f38ce | ||
|
|
63d3d63ad0 | ||
|
|
0ef14a0ecb | ||
|
|
3b0a03d4b2 | ||
|
|
15a56a96c3 | ||
|
|
644b04926d | ||
|
|
f940356c75 | ||
|
|
31191a4156 | ||
|
|
82d672a2d3 | ||
|
|
621ab220ef | ||
|
|
d58b9c0282 | ||
|
|
e6e07e2f55 | ||
|
|
ea4368bf15 |
@@ -0,0 +1,161 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
|
||||||
|
<storageModule moduleId="org.eclipse.cdt.core.settings">
|
||||||
|
<cconfiguration id="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074">
|
||||||
|
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074" moduleId="org.eclipse.cdt.core.settings" name="obj">
|
||||||
|
<externalSettings/>
|
||||||
|
<extensions>
|
||||||
|
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
|
||||||
|
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
|
||||||
|
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
|
||||||
|
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
|
||||||
|
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
|
||||||
|
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
|
||||||
|
</extensions>
|
||||||
|
</storageModule>
|
||||||
|
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
|
||||||
|
<configuration artifactName="${ProjName}" buildArtefactType="org.eclipse.cdt.build.core.buildArtefactType.exe" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.eclipse.cdt.build.core.buildArtefactType.exe,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" cleanCommand="${cross_rm} -rf" description="" id="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074" name="obj" parent="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release">
|
||||||
|
<folderInfo id="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074." name="/" resourcePath="">
|
||||||
|
<toolChain id="ilg.gnumcueclipse.managedbuild.cross.riscv.toolchain.elf.release.231146001" name="RISC-V Cross GCC" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.toolchain.elf.release">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.createflash.1311852988" name="Create flash image" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.createflash" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.createlisting.1983282875" name="Create extended listing" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.createlisting" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.printsize.1000761142" name="Print size" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.addtools.printsize" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.level.514997414" name="Optimization Level" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.level" useByScannerDiscovery="true" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.level.size" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.messagelength.1008570639" name="Message length (-fmessage-length=0)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.messagelength" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.signedchar.467272439" name="'char' is signed (-fsigned-char)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.signedchar" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.functionsections.2047756949" name="Function sections (-ffunction-sections)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.functionsections" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.datasections.207613650" name="Data sections (-fdata-sections)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.datasections" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.debugging.level.1204865254" name="Debug level" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.debugging.level" useByScannerDiscovery="true" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.debugging.level.default" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.debugging.format.867779652" name="Debug format" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.debugging.format" useByScannerDiscovery="true"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.base.1900297968" name="Architecture" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.base" useByScannerDiscovery="false" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.arch.rv32i" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.abi.integer.387605487" name="Integer ABI" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.abi.integer" useByScannerDiscovery="false" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.abi.integer.ilp32" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.multiply.1509705449" name="Multiply extension (RVM)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.multiply" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.compressed.1038505275" name="Compressed extension (RVC)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.compressed" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.toolchain.name.1218760634" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.toolchain.name" useByScannerDiscovery="false" value="GNU MCU RISC-V GCC" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.prefix.103341323" name="Prefix" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.prefix" useByScannerDiscovery="false" value="riscv-none-embed-" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.c.487601824" name="C compiler" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.c" useByScannerDiscovery="false" value="gcc" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.cpp.1062130429" name="C++ compiler" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.cpp" useByScannerDiscovery="false" value="g++" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.ar.1194282993" name="Archiver" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.ar" useByScannerDiscovery="false" value="ar" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.objcopy.1529355265" name="Hex/Bin converter" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.objcopy" useByScannerDiscovery="false" value="objcopy" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.objdump.1053750745" name="Listing generator" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.objdump" useByScannerDiscovery="false" value="objdump" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.size.1441326233" name="Size command" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.size" useByScannerDiscovery="false" value="size" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.make.550105535" name="Build command" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.make" useByScannerDiscovery="false" value="make" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.rm.719280496" name="Remove command" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.command.rm" useByScannerDiscovery="false" value="rm" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.toolchain.id.226017994" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.toolchain.id" useByScannerDiscovery="false" value="512258282" valueType="string"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.atomic.1590833110" name="Atomic extension (RVA)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.atomic" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.unused.1961191588" name="Warn on various unused elements (-Wunused)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.unused" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.uninitialized.929829166" name="Warn on uninitialized variables (-Wuninitialized)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.uninitialized" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.allwarn.939046180" name="Enable all common warnings (-Wall)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.allwarn" useByScannerDiscovery="true" value="false" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.extrawarn.514839450" name="Enable extra warnings (-Wextra)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.warnings.extrawarn" useByScannerDiscovery="true" value="false" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.fp.724881041" name="Floating point" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.fp" useByScannerDiscovery="false" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.isa.fp.none" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.abi.fp.2007116846" name="Floating point ABI" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.abi.fp" useByScannerDiscovery="false" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.abi.fp.none" valueType="enumerated"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.xw.807347098" name="Extra Compressed extension (RVXW)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.isa.xw" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.saverestore.1764921922" name="Small prologue/epilogue (-msave-restore)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.target.saverestore" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.nocommon.1353073444" name="No common unitialized (-fno-common)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.optimization.nocommon" useByScannerDiscovery="true" value="true" valueType="boolean"/>
|
||||||
|
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="ilg.gnumcueclipse.managedbuild.cross.riscv.targetPlatform.1944008784" isAbstract="false" osList="all" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.targetPlatform"/>
|
||||||
|
<builder buildPath="${workspace_loc:/${ProjName}}/obj" id="ilg.gnumcueclipse.managedbuild.cross.riscv.builder.1421508906" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="GNU Make 构建器" parallelBuildOn="true" parallelizationNumber="optimal" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.builder"/>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.assembler.1244756189" name="GNU RISC-V Cross Assembler" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.assembler">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.assembler.usepreprocessor.1692176068" name="Use preprocessor" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.assembler.usepreprocessor" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.assembler.include.paths.1034038285" name="Include paths (-I)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.assembler.include.paths" useByScannerDiscovery="true" valueType="includePath">
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Startup}""/>
|
||||||
|
</option>
|
||||||
|
<inputType id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.assembler.input.126366858" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.assembler.input"/>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.1731377187" name="GNU RISC-V Cross C Compiler" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler">
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.include.paths.1567947810" name="Include paths (-I)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.include.paths" useByScannerDiscovery="true" valueType="includePath">
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/NetLib}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Core}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Debug}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Peripheral/inc}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/User}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Middle/QDXnetworkStack}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/FreeRTOS/include}""/>
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/FreeRTOS/portable/GCC/RISC-V}""/>
|
||||||
|
</option>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.std.2020844713" name="Language standard" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.std" useByScannerDiscovery="true" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.std.gnu99" valueType="enumerated"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="true" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.defs.177116515" name="Defined symbols (-D)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.compiler.defs" useByScannerDiscovery="true" valueType="definedSymbols"/>
|
||||||
|
<inputType id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.input.2036806839" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.input"/>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.cpp.compiler.1610882921" name="GNU RISC-V Cross C++ Compiler" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.cpp.compiler"/>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.linker.1620074387" name="GNU RISC-V Cross C Linker" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.linker">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.gcsections.194760422" name="Remove unused sections (-Xlinker --gc-sections)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.gcsections" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.paths.2057340378" name="Library search path (-L)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.paths" useByScannerDiscovery="false" valueType="libPaths">
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/NetLib}""/>
|
||||||
|
</option>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.scriptfile.1390103472" name="Script files (-T)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.scriptfile" useByScannerDiscovery="false" valueType="stringList">
|
||||||
|
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/Ld/Link.ld}""/>
|
||||||
|
</option>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.nostart.913830613" name="Do not use standard start files (-nostartfiles)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.nostart" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.usenewlibnano.239404511" name="Use newlib-nano (--specs=nano.specs)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.usenewlibnano" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.usenewlibnosys.351964161" name="Do not use syscalls (--specs=nosys.specs)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.usenewlibnosys" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="true" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.otherobjs.16994550" name="Other objects" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.otherobjs" useByScannerDiscovery="false" valueType="userObjs"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="true" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.flags.1125808200" name="Linker flags (-Xlinker [option])" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.flags" useByScannerDiscovery="false" valueType="stringList"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.libs.760735347" name="Libraries (-l)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.libs" useByScannerDiscovery="false" valueType="libs">
|
||||||
|
<listOptionValue builtIn="false" value="m"/>
|
||||||
|
<listOptionValue builtIn="false" value="wchnet"/>
|
||||||
|
</option>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.printf.1692020198" name="Use wchprintf(-lprintf)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.c.linker.printf" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<inputType id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.linker.input.1859223768" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.linker.input">
|
||||||
|
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
|
||||||
|
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
|
||||||
|
</inputType>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.cpp.linker.1947503520" name="GNU RISC-V Cross C++ Linker" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.cpp.linker">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.gcsections.1689063433" name="Remove unused sections (-Xlinker --gc-sections)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.gcsections" value="true" valueType="boolean"/>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.paths.1029177148" name="Library search path (-L)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.paths" valueType="libPaths">
|
||||||
|
<listOptionValue builtIn="false" value=""../LD""/>
|
||||||
|
</option>
|
||||||
|
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.scriptfile.1751226764" name="Script files (-T)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.scriptfile" valueType="stringList">
|
||||||
|
<listOptionValue builtIn="false" value="Link.ld"/>
|
||||||
|
</option>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.nostart.642896175" name="Do not use standard start files (-nostartfiles)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.nostart" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.usenewlibnano.1540675679" name="Use newlib-nano (--specs=nano.specs)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.cpp.linker.usenewlibnano" value="true" valueType="boolean"/>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.archiver.1292785366" name="GNU RISC-V Cross Archiver" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.archiver"/>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.createflash.1801165667" name="GNU RISC-V Cross Create Flash Image" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.createflash">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createflash.choice.1490695600" name="Output file format (-O)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createflash.choice" useByScannerDiscovery="false" value="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createflash.choice.ihex" valueType="enumerated"/>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.createlisting.1356766765" name="GNU RISC-V Cross Create Listing" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.createlisting">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.source.2052761852" name="Display source (--source|-S)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.source" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.allheaders.439659821" name="Display all headers (--all-headers|-x)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.allheaders" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.demangle.67111865" name="Demangle names (--demangle|-C)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.demangle" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.linenumbers.1549373929" name="Display line numbers (--line-numbers|-l)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.linenumbers" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.wide.1298918921" name="Wide lines (--wide|-w)" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.createlisting.wide" useByScannerDiscovery="false" value="true" valueType="boolean"/>
|
||||||
|
</tool>
|
||||||
|
<tool id="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.printsize.712424314" name="GNU RISC-V Cross Print Size" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.tool.printsize">
|
||||||
|
<option id="ilg.gnumcueclipse.managedbuild.cross.riscv.option.printsize.format.1404031980" name="Size format" superClass="ilg.gnumcueclipse.managedbuild.cross.riscv.option.printsize.format" useByScannerDiscovery="false"/>
|
||||||
|
</tool>
|
||||||
|
</toolChain>
|
||||||
|
</folderInfo>
|
||||||
|
<sourceEntries>
|
||||||
|
<entry excluding="Middle/QDXnetworkStack/qdx_port_template.c|NetLib|ETH_driver|Startup|Peripheral|Ld|Debug|Core" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name=""/>
|
||||||
|
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Core"/>
|
||||||
|
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Debug"/>
|
||||||
|
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Ld"/>
|
||||||
|
<entry excluding="eth_driver_10M.c|eth_driver_RMII.c|eth_driver_CH32V317.c|eth_driver_MII.c|libwchnet_float.a" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="NetLib"/>
|
||||||
|
<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Peripheral"/>
|
||||||
|
<entry excluding="startup_ch32v30x.S|startup_ch32v30x_D8.S" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Startup"/>
|
||||||
|
</sourceEntries>
|
||||||
|
</configuration>
|
||||||
|
</storageModule>
|
||||||
|
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
|
||||||
|
<storageModule moduleId="ilg.gnumcueclipse.managedbuild.packs"/>
|
||||||
|
</cconfiguration>
|
||||||
|
</storageModule>
|
||||||
|
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
|
||||||
|
<project id="999.ilg.gnumcueclipse.managedbuild.cross.riscv.target.elf.275846018" name="Executable file" projectType="ilg.gnumcueclipse.managedbuild.cross.riscv.target.elf"/>
|
||||||
|
</storageModule>
|
||||||
|
<storageModule moduleId="scannerConfiguration">
|
||||||
|
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
|
||||||
|
<scannerConfigBuildInfo instanceId="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.debug.767917625;ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.debug.767917625.;ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.1375371130;ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.input.1473381709">
|
||||||
|
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
|
||||||
|
</scannerConfigBuildInfo>
|
||||||
|
<scannerConfigBuildInfo instanceId="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074;ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074.;ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.1731377187;ilg.gnumcueclipse.managedbuild.cross.riscv.tool.c.compiler.input.2036806839">
|
||||||
|
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
|
||||||
|
</scannerConfigBuildInfo>
|
||||||
|
</storageModule>
|
||||||
|
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
|
||||||
|
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets"/>
|
||||||
|
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
|
||||||
|
|
||||||
|
</cproject>
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
---
|
||||||
|
description: Implement tasks from an OpenSpec change (Experimental)
|
||||||
|
---
|
||||||
|
|
||||||
|
Implement tasks from an OpenSpec change.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||||
|
|
||||||
|
2. **Check status to understand the schema**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||||
|
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||||
|
|
||||||
|
3. **Get apply instructions**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec instructions apply --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns:
|
||||||
|
- Context file paths (varies by schema)
|
||||||
|
- Progress (total, complete, remaining)
|
||||||
|
- Task list with status
|
||||||
|
- Dynamic instruction based on current state
|
||||||
|
|
||||||
|
**Handle states:**
|
||||||
|
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
|
||||||
|
- If `state: "all_done"`: congratulate, suggest archive
|
||||||
|
- Otherwise: proceed to implementation
|
||||||
|
|
||||||
|
4. **Read context files**
|
||||||
|
|
||||||
|
Read the files listed in `contextFiles` from the apply instructions output.
|
||||||
|
The files depend on the schema being used:
|
||||||
|
- **spec-driven**: proposal, specs, design, tasks
|
||||||
|
- Other schemas: follow the contextFiles from CLI output
|
||||||
|
|
||||||
|
5. **Show current progress**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Schema being used
|
||||||
|
- Progress: "N/M tasks complete"
|
||||||
|
- Remaining tasks overview
|
||||||
|
- Dynamic instruction from CLI
|
||||||
|
|
||||||
|
6. **Implement tasks (loop until done or blocked)**
|
||||||
|
|
||||||
|
For each pending task:
|
||||||
|
- Show which task is being worked on
|
||||||
|
- Make the code changes required
|
||||||
|
- Keep changes minimal and focused
|
||||||
|
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||||
|
- Continue to next task
|
||||||
|
|
||||||
|
**Pause if:**
|
||||||
|
- Task is unclear → ask for clarification
|
||||||
|
- Implementation reveals a design issue → suggest updating artifacts
|
||||||
|
- Error or blocker encountered → report and wait for guidance
|
||||||
|
- User interrupts
|
||||||
|
|
||||||
|
7. **On completion or pause, show status**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Tasks completed this session
|
||||||
|
- Overall progress: "N/M tasks complete"
|
||||||
|
- If all done: suggest archive
|
||||||
|
- If paused: explain why and wait for guidance
|
||||||
|
|
||||||
|
**Output During Implementation**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementing: <change-name> (schema: <schema-name>)
|
||||||
|
|
||||||
|
Working on task 3/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
|
||||||
|
Working on task 4/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Completion**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 7/7 tasks complete ✓
|
||||||
|
|
||||||
|
### Completed This Session
|
||||||
|
- [x] Task 1
|
||||||
|
- [x] Task 2
|
||||||
|
...
|
||||||
|
|
||||||
|
All tasks complete! You can archive this change with `/opsx:archive`.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Pause (Issue Encountered)**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Paused
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 4/7 tasks complete
|
||||||
|
|
||||||
|
### Issue Encountered
|
||||||
|
<description of the issue>
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. <option 1>
|
||||||
|
2. <option 2>
|
||||||
|
3. Other approach
|
||||||
|
|
||||||
|
What would you like to do?
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Keep going through tasks until done or blocked
|
||||||
|
- Always read context files before starting (from the apply instructions output)
|
||||||
|
- If task is ambiguous, pause and ask before implementing
|
||||||
|
- If implementation reveals issues, pause and suggest artifact updates
|
||||||
|
- Keep code changes minimal and scoped to each task
|
||||||
|
- Update task checkbox immediately after completing each task
|
||||||
|
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||||
|
- Use contextFiles from CLI output, don't assume specific file names
|
||||||
|
|
||||||
|
**Fluid Workflow Integration**
|
||||||
|
|
||||||
|
This skill supports the "actions on a change" model:
|
||||||
|
|
||||||
|
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||||
|
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
---
|
||||||
|
description: Archive a completed change in the experimental workflow
|
||||||
|
---
|
||||||
|
|
||||||
|
Archive a completed change in the experimental workflow.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show only active changes (not already archived).
|
||||||
|
Include the schema used for each change if available.
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check artifact completion status**
|
||||||
|
|
||||||
|
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||||
|
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used
|
||||||
|
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||||
|
|
||||||
|
**If any artifacts are not `done`:**
|
||||||
|
- Display warning listing incomplete artifacts
|
||||||
|
- Prompt user for confirmation to continue
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
3. **Check task completion status**
|
||||||
|
|
||||||
|
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||||
|
|
||||||
|
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||||
|
|
||||||
|
**If incomplete tasks found:**
|
||||||
|
- Display warning showing count of incomplete tasks
|
||||||
|
- Prompt user for confirmation to continue
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
**If no tasks file exists:** Proceed without task-related warning.
|
||||||
|
|
||||||
|
4. **Assess delta spec sync state**
|
||||||
|
|
||||||
|
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||||
|
|
||||||
|
**If delta specs exist:**
|
||||||
|
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||||
|
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||||
|
- Show a combined summary before prompting
|
||||||
|
|
||||||
|
**Prompt options:**
|
||||||
|
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||||
|
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||||
|
|
||||||
|
If user chooses sync, execute `/opsx:sync` logic. Proceed to archive regardless of choice.
|
||||||
|
|
||||||
|
5. **Perform the archive**
|
||||||
|
|
||||||
|
Create the archive directory if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||||
|
|
||||||
|
**Check if target already exists:**
|
||||||
|
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||||
|
- If no: Move the change directory to archive
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Display summary**
|
||||||
|
|
||||||
|
Show archive completion summary including:
|
||||||
|
- Change name
|
||||||
|
- Schema that was used
|
||||||
|
- Archive location
|
||||||
|
- Spec sync status (synced / sync skipped / no delta specs)
|
||||||
|
- Note about any warnings (incomplete artifacts/tasks)
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Archive Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||||
|
**Specs:** ✓ Synced to main specs
|
||||||
|
|
||||||
|
All artifacts complete. All tasks complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Success (No Delta Specs)**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Archive Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||||
|
**Specs:** No delta specs
|
||||||
|
|
||||||
|
All artifacts complete. All tasks complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Success With Warnings**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Archive Complete (with warnings)
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||||
|
**Specs:** Sync skipped (user chose to skip)
|
||||||
|
|
||||||
|
**Warnings:**
|
||||||
|
- Archived with 2 incomplete artifacts
|
||||||
|
- Archived with 3 incomplete tasks
|
||||||
|
- Delta spec sync was skipped (user chose to skip)
|
||||||
|
|
||||||
|
Review the archive if this was not intentional.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Error (Archive Exists)**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Archive Failed
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||||
|
|
||||||
|
Target archive directory already exists.
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. Rename the existing archive
|
||||||
|
2. Delete the existing archive if it's a duplicate
|
||||||
|
3. Wait until a different date to archive
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Always prompt for change selection if not provided
|
||||||
|
- Use artifact graph (openspec status --json) for completion checking
|
||||||
|
- Don't block archive on warnings - just inform and confirm
|
||||||
|
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||||
|
- Show clear summary of what happened
|
||||||
|
- If sync is requested, use /opsx:sync approach (agent-driven)
|
||||||
|
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
---
|
||||||
|
description: Archive multiple completed changes at once
|
||||||
|
---
|
||||||
|
|
||||||
|
Archive multiple completed changes in a single operation.
|
||||||
|
|
||||||
|
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
|
||||||
|
|
||||||
|
**Input**: None required (prompts for selection)
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Get active changes**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get all active changes.
|
||||||
|
|
||||||
|
If no active changes exist, inform user and stop.
|
||||||
|
|
||||||
|
2. **Prompt for change selection**
|
||||||
|
|
||||||
|
Use **AskUserQuestion tool** with multi-select to let user choose changes:
|
||||||
|
- Show each change with its schema
|
||||||
|
- Include an option for "All changes"
|
||||||
|
- Allow any number of selections (1+ works, 2+ is the typical use case)
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
|
||||||
|
|
||||||
|
3. **Batch validation - gather status for all selected changes**
|
||||||
|
|
||||||
|
For each selected change, collect:
|
||||||
|
|
||||||
|
a. **Artifact status** - Run `openspec status --change "<name>" --json`
|
||||||
|
- Parse `schemaName` and `artifacts` list
|
||||||
|
- Note which artifacts are `done` vs other states
|
||||||
|
|
||||||
|
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
|
||||||
|
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||||
|
- If no tasks file exists, note as "No tasks"
|
||||||
|
|
||||||
|
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
|
||||||
|
- List which capability specs exist
|
||||||
|
- For each, extract requirement names (lines matching `### Requirement: <name>`)
|
||||||
|
|
||||||
|
4. **Detect spec conflicts**
|
||||||
|
|
||||||
|
Build a map of `capability -> [changes that touch it]`:
|
||||||
|
|
||||||
|
```
|
||||||
|
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
|
||||||
|
api -> [change-c] <- OK (only 1 change)
|
||||||
|
```
|
||||||
|
|
||||||
|
A conflict exists when 2+ selected changes have delta specs for the same capability.
|
||||||
|
|
||||||
|
5. **Resolve conflicts agentically**
|
||||||
|
|
||||||
|
**For each conflict**, investigate the codebase:
|
||||||
|
|
||||||
|
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
|
||||||
|
|
||||||
|
b. **Search the codebase** for implementation evidence:
|
||||||
|
- Look for code implementing requirements from each delta spec
|
||||||
|
- Check for related files, functions, or tests
|
||||||
|
|
||||||
|
c. **Determine resolution**:
|
||||||
|
- If only one change is actually implemented -> sync that one's specs
|
||||||
|
- If both implemented -> apply in chronological order (older first, newer overwrites)
|
||||||
|
- If neither implemented -> skip spec sync, warn user
|
||||||
|
|
||||||
|
d. **Record resolution** for each conflict:
|
||||||
|
- Which change's specs to apply
|
||||||
|
- In what order (if both)
|
||||||
|
- Rationale (what was found in codebase)
|
||||||
|
|
||||||
|
6. **Show consolidated status table**
|
||||||
|
|
||||||
|
Display a table summarizing all changes:
|
||||||
|
|
||||||
|
```
|
||||||
|
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|
||||||
|
|---------------------|-----------|-------|---------|-----------|--------|
|
||||||
|
| schema-management | Done | 5/5 | 2 delta | None | Ready |
|
||||||
|
| project-config | Done | 3/3 | 1 delta | None | Ready |
|
||||||
|
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
|
||||||
|
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
|
||||||
|
```
|
||||||
|
|
||||||
|
For conflicts, show the resolution:
|
||||||
|
```
|
||||||
|
* Conflict resolution:
|
||||||
|
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
|
||||||
|
```
|
||||||
|
|
||||||
|
For incomplete changes, show warnings:
|
||||||
|
```
|
||||||
|
Warnings:
|
||||||
|
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
|
||||||
|
```
|
||||||
|
|
||||||
|
7. **Confirm batch operation**
|
||||||
|
|
||||||
|
Use **AskUserQuestion tool** with a single confirmation:
|
||||||
|
|
||||||
|
- "Archive N changes?" with options based on status
|
||||||
|
- Options might include:
|
||||||
|
- "Archive all N changes"
|
||||||
|
- "Archive only N ready changes (skip incomplete)"
|
||||||
|
- "Cancel"
|
||||||
|
|
||||||
|
If there are incomplete changes, make clear they'll be archived with warnings.
|
||||||
|
|
||||||
|
8. **Execute archive for each confirmed change**
|
||||||
|
|
||||||
|
Process changes in the determined order (respecting conflict resolution):
|
||||||
|
|
||||||
|
a. **Sync specs** if delta specs exist:
|
||||||
|
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
|
||||||
|
- For conflicts, apply in resolved order
|
||||||
|
- Track if sync was done
|
||||||
|
|
||||||
|
b. **Perform the archive**:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/archive
|
||||||
|
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||||
|
```
|
||||||
|
|
||||||
|
c. **Track outcome** for each change:
|
||||||
|
- Success: archived successfully
|
||||||
|
- Failed: error during archive (record error)
|
||||||
|
- Skipped: user chose not to archive (if applicable)
|
||||||
|
|
||||||
|
9. **Display summary**
|
||||||
|
|
||||||
|
Show final results:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete
|
||||||
|
|
||||||
|
Archived 3 changes:
|
||||||
|
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
|
||||||
|
- project-config -> archive/2026-01-19-project-config/
|
||||||
|
- add-oauth -> archive/2026-01-19-add-oauth/
|
||||||
|
|
||||||
|
Skipped 1 change:
|
||||||
|
- add-verify-skill (user chose not to archive incomplete)
|
||||||
|
|
||||||
|
Spec sync summary:
|
||||||
|
- 4 delta specs synced to main specs
|
||||||
|
- 1 conflict resolved (auth: applied both in chronological order)
|
||||||
|
```
|
||||||
|
|
||||||
|
If any failures:
|
||||||
|
```
|
||||||
|
Failed 1 change:
|
||||||
|
- some-change: Archive directory already exists
|
||||||
|
```
|
||||||
|
|
||||||
|
**Conflict Resolution Examples**
|
||||||
|
|
||||||
|
Example 1: Only one implemented
|
||||||
|
```
|
||||||
|
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
|
||||||
|
|
||||||
|
Checking add-oauth:
|
||||||
|
- Delta adds "OAuth Provider Integration" requirement
|
||||||
|
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
|
||||||
|
|
||||||
|
Checking add-jwt:
|
||||||
|
- Delta adds "JWT Token Handling" requirement
|
||||||
|
- Searching codebase... no JWT implementation found
|
||||||
|
|
||||||
|
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
|
||||||
|
```
|
||||||
|
|
||||||
|
Example 2: Both implemented
|
||||||
|
```
|
||||||
|
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
|
||||||
|
|
||||||
|
Checking add-rest-api (created 2026-01-10):
|
||||||
|
- Delta adds "REST Endpoints" requirement
|
||||||
|
- Searching codebase... found src/api/rest.ts
|
||||||
|
|
||||||
|
Checking add-graphql (created 2026-01-15):
|
||||||
|
- Delta adds "GraphQL Schema" requirement
|
||||||
|
- Searching codebase... found src/api/graphql.ts
|
||||||
|
|
||||||
|
Resolution: Both implemented. Will apply add-rest-api specs first,
|
||||||
|
then add-graphql specs (chronological order, newer takes precedence).
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete
|
||||||
|
|
||||||
|
Archived N changes:
|
||||||
|
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||||
|
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
|
||||||
|
|
||||||
|
Spec sync summary:
|
||||||
|
- N delta specs synced to main specs
|
||||||
|
- No conflicts (or: M conflicts resolved)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Partial Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete (partial)
|
||||||
|
|
||||||
|
Archived N changes:
|
||||||
|
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||||
|
|
||||||
|
Skipped M changes:
|
||||||
|
- <change-2> (user chose not to archive incomplete)
|
||||||
|
|
||||||
|
Failed K changes:
|
||||||
|
- <change-3>: Archive directory already exists
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output When No Changes**
|
||||||
|
|
||||||
|
```
|
||||||
|
## No Changes to Archive
|
||||||
|
|
||||||
|
No active changes found. Use `/opsx:new` to create a new change.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
|
||||||
|
- Always prompt for selection, never auto-select
|
||||||
|
- Detect spec conflicts early and resolve by checking codebase
|
||||||
|
- When both changes are implemented, apply specs in chronological order
|
||||||
|
- Skip spec sync only when implementation is missing (warn user)
|
||||||
|
- Show clear per-change status before confirming
|
||||||
|
- Use single confirmation for entire batch
|
||||||
|
- Track and report all outcomes (success/skip/fail)
|
||||||
|
- Preserve .openspec.yaml when moving to archive
|
||||||
|
- Archive directory target uses current date: YYYY-MM-DD-<name>
|
||||||
|
- If archive target exists, fail that change but continue with others
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
---
|
||||||
|
description: Continue working on a change - create the next artifact (Experimental)
|
||||||
|
---
|
||||||
|
|
||||||
|
Continue working on a change by creating the next artifact.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name after `/opsx:continue` (e.g., `/opsx:continue add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
|
||||||
|
|
||||||
|
Present the top 3-4 most recently modified changes as options, showing:
|
||||||
|
- Change name
|
||||||
|
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||||
|
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||||
|
- How recently it was modified (from `lastModified` field)
|
||||||
|
|
||||||
|
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check current status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand current state. The response includes:
|
||||||
|
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||||
|
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
|
||||||
|
- `isComplete`: Boolean indicating if all artifacts are complete
|
||||||
|
|
||||||
|
3. **Act based on status**:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If all artifacts are complete (`isComplete: true`)**:
|
||||||
|
- Congratulate the user
|
||||||
|
- Show final status including the schema used
|
||||||
|
- Suggest: "All artifacts created! You can now implement this change with `/opsx:apply` or archive it with `/opsx:archive`."
|
||||||
|
- STOP
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
|
||||||
|
- Pick the FIRST artifact with `status: "ready"` from the status output
|
||||||
|
- Get its instructions:
|
||||||
|
```bash
|
||||||
|
openspec instructions <artifact-id> --change "<name>" --json
|
||||||
|
```
|
||||||
|
- Parse the JSON. The key fields are:
|
||||||
|
- `context`: Project background (constraints for you - do NOT include in output)
|
||||||
|
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||||
|
- `template`: The structure to use for your output file
|
||||||
|
- `instruction`: Schema-specific guidance
|
||||||
|
- `outputPath`: Where to write the artifact
|
||||||
|
- `dependencies`: Completed artifacts to read for context
|
||||||
|
- **Create the artifact file**:
|
||||||
|
- Read any completed dependency files for context
|
||||||
|
- Use `template` as the structure - fill in its sections
|
||||||
|
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
|
||||||
|
- Write to the output path specified in instructions
|
||||||
|
- Show what was created and what's now unlocked
|
||||||
|
- STOP after creating ONE artifact
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If no artifacts are ready (all blocked)**:
|
||||||
|
- This shouldn't happen with a valid schema
|
||||||
|
- Show status and suggest checking for issues
|
||||||
|
|
||||||
|
4. **After creating an artifact, show progress**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After each invocation, show:
|
||||||
|
- Which artifact was created
|
||||||
|
- Schema workflow being used
|
||||||
|
- Current progress (N/M complete)
|
||||||
|
- What artifacts are now unlocked
|
||||||
|
- Prompt: "Run `/opsx:continue` to create the next artifact"
|
||||||
|
|
||||||
|
**Artifact Creation Guidelines**
|
||||||
|
|
||||||
|
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
|
||||||
|
|
||||||
|
Common artifact patterns:
|
||||||
|
|
||||||
|
**spec-driven schema** (proposal → specs → design → tasks):
|
||||||
|
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
|
||||||
|
- The Capabilities section is critical - each capability listed will need a spec file.
|
||||||
|
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
|
||||||
|
- **design.md**: Document technical decisions, architecture, and implementation approach.
|
||||||
|
- **tasks.md**: Break down implementation into checkboxed tasks.
|
||||||
|
|
||||||
|
For other schemas, follow the `instruction` field from the CLI output.
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Create ONE artifact per invocation
|
||||||
|
- Always read dependency artifacts before creating a new one
|
||||||
|
- Never skip artifacts or create out of order
|
||||||
|
- If context is unclear, ask the user before creating
|
||||||
|
- Verify the artifact file exists after writing before marking progress
|
||||||
|
- Use the schema's artifact sequence, don't assume specific artifact names
|
||||||
|
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||||
|
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||||
|
- These guide what you write, but should never appear in the output
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
---
|
||||||
|
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
|
||||||
|
---
|
||||||
|
|
||||||
|
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||||
|
|
||||||
|
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first (e.g., start a change with `/opsx:new` or `/opsx:ff`). You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||||
|
|
||||||
|
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||||
|
|
||||||
|
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||||
|
- A vague idea: "real-time collaboration"
|
||||||
|
- A specific problem: "the auth system is getting unwieldy"
|
||||||
|
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||||
|
- A comparison: "postgres vs sqlite for this"
|
||||||
|
- Nothing (just enter explore mode)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The Stance
|
||||||
|
|
||||||
|
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||||
|
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||||
|
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||||
|
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||||
|
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||||
|
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Might Do
|
||||||
|
|
||||||
|
Depending on what the user brings, you might:
|
||||||
|
|
||||||
|
**Explore the problem space**
|
||||||
|
- Ask clarifying questions that emerge from what they said
|
||||||
|
- Challenge assumptions
|
||||||
|
- Reframe the problem
|
||||||
|
- Find analogies
|
||||||
|
|
||||||
|
**Investigate the codebase**
|
||||||
|
- Map existing architecture relevant to the discussion
|
||||||
|
- Find integration points
|
||||||
|
- Identify patterns already in use
|
||||||
|
- Surface hidden complexity
|
||||||
|
|
||||||
|
**Compare options**
|
||||||
|
- Brainstorm multiple approaches
|
||||||
|
- Build comparison tables
|
||||||
|
- Sketch tradeoffs
|
||||||
|
- Recommend a path (if asked)
|
||||||
|
|
||||||
|
**Visualize**
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ Use ASCII diagrams liberally │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ ┌────────┐ ┌────────┐ │
|
||||||
|
│ │ State │────────▶│ State │ │
|
||||||
|
│ │ A │ │ B │ │
|
||||||
|
│ └────────┘ └────────┘ │
|
||||||
|
│ │
|
||||||
|
│ System diagrams, state machines, │
|
||||||
|
│ data flows, architecture sketches, │
|
||||||
|
│ dependency graphs, comparison tables │
|
||||||
|
│ │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Surface risks and unknowns**
|
||||||
|
- Identify what could go wrong
|
||||||
|
- Find gaps in understanding
|
||||||
|
- Suggest spikes or investigations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OpenSpec Awareness
|
||||||
|
|
||||||
|
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||||
|
|
||||||
|
### Check for context
|
||||||
|
|
||||||
|
At the start, quickly check what exists:
|
||||||
|
```bash
|
||||||
|
openspec list --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This tells you:
|
||||||
|
- If there are active changes
|
||||||
|
- Their names, schemas, and status
|
||||||
|
- What the user might be working on
|
||||||
|
|
||||||
|
If the user mentioned a specific change name, read its artifacts for context.
|
||||||
|
|
||||||
|
### When no change exists
|
||||||
|
|
||||||
|
Think freely. When insights crystallize, you might offer:
|
||||||
|
|
||||||
|
- "This feels solid enough to start a change. Want me to create one?"
|
||||||
|
→ Can transition to `/opsx:new` or `/opsx:ff`
|
||||||
|
- Or keep exploring - no pressure to formalize
|
||||||
|
|
||||||
|
### When a change exists
|
||||||
|
|
||||||
|
If the user mentions a change or you detect one is relevant:
|
||||||
|
|
||||||
|
1. **Read existing artifacts for context**
|
||||||
|
- `openspec/changes/<name>/proposal.md`
|
||||||
|
- `openspec/changes/<name>/design.md`
|
||||||
|
- `openspec/changes/<name>/tasks.md`
|
||||||
|
- etc.
|
||||||
|
|
||||||
|
2. **Reference them naturally in conversation**
|
||||||
|
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||||
|
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||||
|
|
||||||
|
3. **Offer to capture when decisions are made**
|
||||||
|
|
||||||
|
| Insight Type | Where to Capture |
|
||||||
|
|--------------|------------------|
|
||||||
|
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||||
|
| Requirement changed | `specs/<capability>/spec.md` |
|
||||||
|
| Design decision made | `design.md` |
|
||||||
|
| Scope changed | `proposal.md` |
|
||||||
|
| New work identified | `tasks.md` |
|
||||||
|
| Assumption invalidated | Relevant artifact |
|
||||||
|
|
||||||
|
Example offers:
|
||||||
|
- "That's a design decision. Capture it in design.md?"
|
||||||
|
- "This is a new requirement. Add it to specs?"
|
||||||
|
- "This changes scope. Update the proposal?"
|
||||||
|
|
||||||
|
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Don't Have To Do
|
||||||
|
|
||||||
|
- Follow a script
|
||||||
|
- Ask the same questions every time
|
||||||
|
- Produce a specific artifact
|
||||||
|
- Reach a conclusion
|
||||||
|
- Stay on topic if a tangent is valuable
|
||||||
|
- Be brief (this is thinking time)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ending Discovery
|
||||||
|
|
||||||
|
There's no required ending. Discovery might:
|
||||||
|
|
||||||
|
- **Flow into action**: "Ready to start? `/opsx:new` or `/opsx:ff`"
|
||||||
|
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||||
|
- **Just provide clarity**: User has what they need, moves on
|
||||||
|
- **Continue later**: "We can pick this up anytime"
|
||||||
|
|
||||||
|
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||||
|
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||||
|
- **Don't rush** - Discovery is thinking time, not task time
|
||||||
|
- **Don't force structure** - Let patterns emerge naturally
|
||||||
|
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||||
|
- **Do visualize** - A good diagram is worth many paragraphs
|
||||||
|
- **Do explore the codebase** - Ground discussions in reality
|
||||||
|
- **Do question assumptions** - Including the user's and your own
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
---
|
||||||
|
description: Create a change and generate all artifacts needed for implementation in one go
|
||||||
|
---
|
||||||
|
|
||||||
|
Fast-forward through artifact creation - generate everything needed to start implementation.
|
||||||
|
|
||||||
|
**Input**: The argument after `/opsx:ff` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no input provided, ask what they want to build**
|
||||||
|
|
||||||
|
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||||
|
> "What change do you want to work on? Describe what you want to build or fix."
|
||||||
|
|
||||||
|
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||||
|
|
||||||
|
2. **Create the change directory**
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>"
|
||||||
|
```
|
||||||
|
This creates a scaffolded change at `openspec/changes/<name>/`.
|
||||||
|
|
||||||
|
3. **Get the artifact build order**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to get:
|
||||||
|
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||||
|
- `artifacts`: list of all artifacts with their status and dependencies
|
||||||
|
|
||||||
|
4. **Create artifacts in sequence until apply-ready**
|
||||||
|
|
||||||
|
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||||
|
|
||||||
|
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||||
|
|
||||||
|
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||||
|
- Get instructions:
|
||||||
|
```bash
|
||||||
|
openspec instructions <artifact-id> --change "<name>" --json
|
||||||
|
```
|
||||||
|
- The instructions JSON includes:
|
||||||
|
- `context`: Project background (constraints for you - do NOT include in output)
|
||||||
|
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||||
|
- `template`: The structure to use for your output file
|
||||||
|
- `instruction`: Schema-specific guidance for this artifact type
|
||||||
|
- `outputPath`: Where to write the artifact
|
||||||
|
- `dependencies`: Completed artifacts to read for context
|
||||||
|
- Read any completed dependency files for context
|
||||||
|
- Create the artifact file using `template` as the structure
|
||||||
|
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||||
|
- Show brief progress: "✓ Created <artifact-id>"
|
||||||
|
|
||||||
|
b. **Continue until all `applyRequires` artifacts are complete**
|
||||||
|
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||||
|
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||||
|
- Stop when all `applyRequires` artifacts are done
|
||||||
|
|
||||||
|
c. **If an artifact requires user input** (unclear context):
|
||||||
|
- Use **AskUserQuestion tool** to clarify
|
||||||
|
- Then continue with creation
|
||||||
|
|
||||||
|
5. **Show final status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After completing all artifacts, summarize:
|
||||||
|
- Change name and location
|
||||||
|
- List of artifacts created with brief descriptions
|
||||||
|
- What's ready: "All artifacts created! Ready for implementation."
|
||||||
|
- Prompt: "Run `/opsx:apply` to start implementing."
|
||||||
|
|
||||||
|
**Artifact Creation Guidelines**
|
||||||
|
|
||||||
|
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||||
|
- The schema defines what each artifact should contain - follow it
|
||||||
|
- Read dependency artifacts for context before creating new ones
|
||||||
|
- Use the `template` as a starting point, filling in based on context
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||||
|
- Always read dependency artifacts before creating a new one
|
||||||
|
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||||
|
- If a change with that name already exists, ask if user wants to continue it or create a new one
|
||||||
|
- Verify each artifact file exists after writing before proceeding to next
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
---
|
||||||
|
description: Start a new change using the experimental artifact workflow (OPSX)
|
||||||
|
---
|
||||||
|
|
||||||
|
Start a new change using the experimental artifact-driven approach.
|
||||||
|
|
||||||
|
**Input**: The argument after `/opsx:new` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no input provided, ask what they want to build**
|
||||||
|
|
||||||
|
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||||
|
> "What change do you want to work on? Describe what you want to build or fix."
|
||||||
|
|
||||||
|
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||||
|
|
||||||
|
2. **Determine the workflow schema**
|
||||||
|
|
||||||
|
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
|
||||||
|
|
||||||
|
**Use a different schema only if the user mentions:**
|
||||||
|
- A specific schema name → use `--schema <name>`
|
||||||
|
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
|
||||||
|
|
||||||
|
**Otherwise**: Omit `--schema` to use the default.
|
||||||
|
|
||||||
|
3. **Create the change directory**
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>"
|
||||||
|
```
|
||||||
|
Add `--schema <name>` only if the user requested a specific workflow.
|
||||||
|
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
|
||||||
|
|
||||||
|
4. **Show the artifact status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
This shows which artifacts need to be created and which are ready (dependencies satisfied).
|
||||||
|
|
||||||
|
5. **Get instructions for the first artifact**
|
||||||
|
The first artifact depends on the schema. Check the status output to find the first artifact with status "ready".
|
||||||
|
```bash
|
||||||
|
openspec instructions <first-artifact-id> --change "<name>"
|
||||||
|
```
|
||||||
|
This outputs the template and context for creating the first artifact.
|
||||||
|
|
||||||
|
6. **STOP and wait for user direction**
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After completing the steps, summarize:
|
||||||
|
- Change name and location
|
||||||
|
- Schema/workflow being used and its artifact sequence
|
||||||
|
- Current status (0/N artifacts complete)
|
||||||
|
- The template for the first artifact
|
||||||
|
- Prompt: "Ready to create the first artifact? Run `/opsx:continue` or just describe what this change is about and I'll draft it."
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Do NOT create any artifacts yet - just show the instructions
|
||||||
|
- Do NOT advance beyond showing the first artifact template
|
||||||
|
- If the name is invalid (not kebab-case), ask for a valid name
|
||||||
|
- If a change with that name already exists, suggest using `/opsx:continue` instead
|
||||||
|
- Pass --schema if using a non-default workflow
|
||||||
@@ -0,0 +1,522 @@
|
|||||||
|
---
|
||||||
|
description: Guided onboarding - walk through a complete OpenSpec workflow cycle with narration
|
||||||
|
---
|
||||||
|
|
||||||
|
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preflight
|
||||||
|
|
||||||
|
Before starting, check if OpenSpec is initialized:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec status --json 2>&1 || echo "NOT_INITIALIZED"
|
||||||
|
```
|
||||||
|
|
||||||
|
**If not initialized:**
|
||||||
|
> OpenSpec isn't set up in this project yet. Run `openspec init` first, then come back to `/opsx:onboard`.
|
||||||
|
|
||||||
|
Stop here if not initialized.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1: Welcome
|
||||||
|
|
||||||
|
Display:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Welcome to OpenSpec!
|
||||||
|
|
||||||
|
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
|
||||||
|
|
||||||
|
**What we'll do:**
|
||||||
|
1. Pick a small, real task in your codebase
|
||||||
|
2. Explore the problem briefly
|
||||||
|
3. Create a change (the container for our work)
|
||||||
|
4. Build the artifacts: proposal → specs → design → tasks
|
||||||
|
5. Implement the tasks
|
||||||
|
6. Archive the completed change
|
||||||
|
|
||||||
|
**Time:** ~15-20 minutes
|
||||||
|
|
||||||
|
Let's start by finding something to work on.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2: Task Selection
|
||||||
|
|
||||||
|
### Codebase Analysis
|
||||||
|
|
||||||
|
Scan the codebase for small improvement opportunities. Look for:
|
||||||
|
|
||||||
|
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
|
||||||
|
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
|
||||||
|
3. **Functions without tests** - Cross-reference `src/` with test directories
|
||||||
|
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
|
||||||
|
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
|
||||||
|
6. **Missing validation** - User input handlers without validation
|
||||||
|
|
||||||
|
Also check recent git activity:
|
||||||
|
```bash
|
||||||
|
git log --oneline -10 2>/dev/null || echo "No git history"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Present Suggestions
|
||||||
|
|
||||||
|
From your analysis, present 3-4 specific suggestions:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Task Suggestions
|
||||||
|
|
||||||
|
Based on scanning your codebase, here are some good starter tasks:
|
||||||
|
|
||||||
|
**1. [Most promising task]**
|
||||||
|
Location: `src/path/to/file.ts:42`
|
||||||
|
Scope: ~1-2 files, ~20-30 lines
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**2. [Second task]**
|
||||||
|
Location: `src/another/file.ts`
|
||||||
|
Scope: ~1 file, ~15 lines
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**3. [Third task]**
|
||||||
|
Location: [location]
|
||||||
|
Scope: [estimate]
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**4. Something else?**
|
||||||
|
Tell me what you'd like to work on.
|
||||||
|
|
||||||
|
Which task interests you? (Pick a number or describe your own)
|
||||||
|
```
|
||||||
|
|
||||||
|
**If nothing found:** Fall back to asking what the user wants to build:
|
||||||
|
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
|
||||||
|
|
||||||
|
### Scope Guardrail
|
||||||
|
|
||||||
|
If the user picks or describes something too large (major feature, multi-day work):
|
||||||
|
|
||||||
|
```
|
||||||
|
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
|
||||||
|
|
||||||
|
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
|
||||||
|
2. **Pick something else** - One of the other suggestions, or a different small task?
|
||||||
|
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
|
||||||
|
|
||||||
|
What would you prefer?
|
||||||
|
```
|
||||||
|
|
||||||
|
Let the user override if they insist—this is a soft guardrail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3: Explore Demo
|
||||||
|
|
||||||
|
Once a task is selected, briefly demonstrate explore mode:
|
||||||
|
|
||||||
|
```
|
||||||
|
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
|
||||||
|
```
|
||||||
|
|
||||||
|
Spend 1-2 minutes investigating the relevant code:
|
||||||
|
- Read the file(s) involved
|
||||||
|
- Draw a quick ASCII diagram if it helps
|
||||||
|
- Note any considerations
|
||||||
|
|
||||||
|
```
|
||||||
|
## Quick Exploration
|
||||||
|
|
||||||
|
[Your brief analysis—what you found, any considerations]
|
||||||
|
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ [Optional: ASCII diagram if helpful] │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
|
||||||
|
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
|
||||||
|
|
||||||
|
Now let's create a change to hold our work.
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user acknowledgment before proceeding.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 4: Create the Change
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Creating a Change
|
||||||
|
|
||||||
|
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
|
||||||
|
|
||||||
|
Let me create one for our task.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Create the change with a derived kebab-case name:
|
||||||
|
```bash
|
||||||
|
openspec new change "<derived-name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**SHOW:**
|
||||||
|
```
|
||||||
|
Created: `openspec/changes/<name>/`
|
||||||
|
|
||||||
|
The folder structure:
|
||||||
|
```
|
||||||
|
openspec/changes/<name>/
|
||||||
|
├── proposal.md ← Why we're doing this (empty, we'll fill it)
|
||||||
|
├── design.md ← How we'll build it (empty)
|
||||||
|
├── specs/ ← Detailed requirements (empty)
|
||||||
|
└── tasks.md ← Implementation checklist (empty)
|
||||||
|
```
|
||||||
|
|
||||||
|
Now let's fill in the first artifact—the proposal.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 5: Proposal
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## The Proposal
|
||||||
|
|
||||||
|
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
|
||||||
|
|
||||||
|
I'll draft one based on our task.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Draft the proposal content (don't save yet):
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's a draft proposal:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
[1-2 sentences explaining the problem/opportunity]
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
[Bullet points of what will be different]
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `<capability-name>`: [brief description]
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
<!-- If modifying existing behavior -->
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- `src/path/to/file.ts`: [what changes]
|
||||||
|
- [other files if applicable]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Does this capture the intent? I can adjust before we save it.
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user approval/feedback.
|
||||||
|
|
||||||
|
After approval, save the proposal:
|
||||||
|
```bash
|
||||||
|
openspec instructions proposal --change "<name>" --json
|
||||||
|
```
|
||||||
|
Then write the content to `openspec/changes/<name>/proposal.md`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
|
||||||
|
|
||||||
|
Next up: specs.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 6: Specs
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Specs
|
||||||
|
|
||||||
|
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
|
||||||
|
|
||||||
|
For a small task like this, we might only need one spec file.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Create the spec file:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/<name>/specs/<capability-name>
|
||||||
|
```
|
||||||
|
|
||||||
|
Draft the spec content:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's the spec:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: <Name>
|
||||||
|
|
||||||
|
<Description of what the system should do>
|
||||||
|
|
||||||
|
#### Scenario: <Scenario name>
|
||||||
|
|
||||||
|
- **WHEN** <trigger condition>
|
||||||
|
- **THEN** <expected outcome>
|
||||||
|
- **AND** <additional outcome if needed>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
|
||||||
|
```
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 7: Design
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Design
|
||||||
|
|
||||||
|
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
|
||||||
|
|
||||||
|
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Draft design.md:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's the design:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
[Brief context about the current state]
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- [What we're trying to achieve]
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- [What's explicitly out of scope]
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### Decision 1: [Key decision]
|
||||||
|
|
||||||
|
[Explanation of approach and rationale]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For a small task, this captures the key decisions without over-engineering.
|
||||||
|
```
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/design.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 8: Tasks
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
|
||||||
|
|
||||||
|
These should be small, clear, and in logical order.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Generate tasks based on specs and design:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here are the implementation tasks:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. [Category or file]
|
||||||
|
|
||||||
|
- [ ] 1.1 [Specific task]
|
||||||
|
- [ ] 1.2 [Specific task]
|
||||||
|
|
||||||
|
## 2. Verify
|
||||||
|
|
||||||
|
- [ ] 2.1 [Verification step]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user to confirm they're ready to implement.
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/tasks.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 9: Apply (Implementation)
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** For each task:
|
||||||
|
|
||||||
|
1. Announce: "Working on task N: [description]"
|
||||||
|
2. Implement the change in the codebase
|
||||||
|
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
|
||||||
|
4. Mark complete in tasks.md: `- [ ]` → `- [x]`
|
||||||
|
5. Brief status: "✓ Task N complete"
|
||||||
|
|
||||||
|
Keep narration light—don't over-explain every line of code.
|
||||||
|
|
||||||
|
After all tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Complete
|
||||||
|
|
||||||
|
All tasks done:
|
||||||
|
- [x] Task 1
|
||||||
|
- [x] Task 2
|
||||||
|
- [x] ...
|
||||||
|
|
||||||
|
The change is implemented! One more step—let's archive it.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 10: Archive
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Archiving
|
||||||
|
|
||||||
|
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
|
||||||
|
|
||||||
|
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:**
|
||||||
|
```bash
|
||||||
|
openspec archive "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**SHOW:**
|
||||||
|
```
|
||||||
|
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
|
||||||
|
|
||||||
|
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 11: Recap & Next Steps
|
||||||
|
|
||||||
|
```
|
||||||
|
## Congratulations!
|
||||||
|
|
||||||
|
You just completed a full OpenSpec cycle:
|
||||||
|
|
||||||
|
1. **Explore** - Thought through the problem
|
||||||
|
2. **New** - Created a change container
|
||||||
|
3. **Proposal** - Captured WHY
|
||||||
|
4. **Specs** - Defined WHAT in detail
|
||||||
|
5. **Design** - Decided HOW
|
||||||
|
6. **Tasks** - Broke it into steps
|
||||||
|
7. **Apply** - Implemented the work
|
||||||
|
8. **Archive** - Preserved the record
|
||||||
|
|
||||||
|
This same rhythm works for any size change—a small fix or a major feature.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Command Reference
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
|---------|--------------|
|
||||||
|
| `/opsx:explore` | Think through problems before/during work |
|
||||||
|
| `/opsx:new` | Start a new change, step through artifacts |
|
||||||
|
| `/opsx:ff` | Fast-forward: create all artifacts at once |
|
||||||
|
| `/opsx:continue` | Continue working on an existing change |
|
||||||
|
| `/opsx:apply` | Implement tasks from a change |
|
||||||
|
| `/opsx:verify` | Verify implementation matches artifacts |
|
||||||
|
| `/opsx:archive` | Archive a completed change |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What's Next?
|
||||||
|
|
||||||
|
Try `/opsx:new` or `/opsx:ff` on something you actually want to build. You've got the rhythm now!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Graceful Exit Handling
|
||||||
|
|
||||||
|
### User wants to stop mid-way
|
||||||
|
|
||||||
|
If the user says they need to stop, want to pause, or seem disengaged:
|
||||||
|
|
||||||
|
```
|
||||||
|
No problem! Your change is saved at `openspec/changes/<name>/`.
|
||||||
|
|
||||||
|
To pick up where we left off later:
|
||||||
|
- `/opsx:continue <name>` - Resume artifact creation
|
||||||
|
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
|
||||||
|
|
||||||
|
The work won't be lost. Come back whenever you're ready.
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit gracefully without pressure.
|
||||||
|
|
||||||
|
### User just wants command reference
|
||||||
|
|
||||||
|
If the user says they just want to see the commands or skip the tutorial:
|
||||||
|
|
||||||
|
```
|
||||||
|
## OpenSpec Quick Reference
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
|---------|--------------|
|
||||||
|
| `/opsx:explore` | Think through problems (no code changes) |
|
||||||
|
| `/opsx:new <name>` | Start a new change, step by step |
|
||||||
|
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
|
||||||
|
| `/opsx:continue <name>` | Continue an existing change |
|
||||||
|
| `/opsx:apply <name>` | Implement tasks |
|
||||||
|
| `/opsx:verify <name>` | Verify implementation |
|
||||||
|
| `/opsx:archive <name>` | Archive when done |
|
||||||
|
|
||||||
|
Try `/opsx:new` to start your first change, or `/opsx:ff` if you want to move fast.
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit gracefully.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
|
||||||
|
- **Keep narration light** during implementation—teach without lecturing
|
||||||
|
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
|
||||||
|
- **Pause for acknowledgment** at marked points, but don't over-pause
|
||||||
|
- **Handle exits gracefully**—never pressure the user to continue
|
||||||
|
- **Use real codebase tasks**—don't simulate or use fake examples
|
||||||
|
- **Adjust scope gently**—guide toward smaller tasks but respect user choice
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
---
|
||||||
|
description: Sync delta specs from a change to main specs
|
||||||
|
---
|
||||||
|
|
||||||
|
Sync delta specs from a change to main specs.
|
||||||
|
|
||||||
|
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show changes that have delta specs (under `specs/` directory).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Find delta specs**
|
||||||
|
|
||||||
|
Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.
|
||||||
|
|
||||||
|
Each delta spec file contains sections like:
|
||||||
|
- `## ADDED Requirements` - New requirements to add
|
||||||
|
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||||
|
- `## REMOVED Requirements` - Requirements to remove
|
||||||
|
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||||
|
|
||||||
|
If no delta specs found, inform user and stop.
|
||||||
|
|
||||||
|
3. **For each delta spec, apply changes to main specs**
|
||||||
|
|
||||||
|
For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:
|
||||||
|
|
||||||
|
a. **Read the delta spec** to understand the intended changes
|
||||||
|
|
||||||
|
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
|
||||||
|
|
||||||
|
c. **Apply changes intelligently**:
|
||||||
|
|
||||||
|
**ADDED Requirements:**
|
||||||
|
- If requirement doesn't exist in main spec → add it
|
||||||
|
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||||
|
|
||||||
|
**MODIFIED Requirements:**
|
||||||
|
- Find the requirement in main spec
|
||||||
|
- Apply the changes - this can be:
|
||||||
|
- Adding new scenarios (don't need to copy existing ones)
|
||||||
|
- Modifying existing scenarios
|
||||||
|
- Changing the requirement description
|
||||||
|
- Preserve scenarios/content not mentioned in the delta
|
||||||
|
|
||||||
|
**REMOVED Requirements:**
|
||||||
|
- Remove the entire requirement block from main spec
|
||||||
|
|
||||||
|
**RENAMED Requirements:**
|
||||||
|
- Find the FROM requirement, rename to TO
|
||||||
|
|
||||||
|
d. **Create new main spec** if capability doesn't exist yet:
|
||||||
|
- Create `openspec/specs/<capability>/spec.md`
|
||||||
|
- Add Purpose section (can be brief, mark as TBD)
|
||||||
|
- Add Requirements section with the ADDED requirements
|
||||||
|
|
||||||
|
4. **Show summary**
|
||||||
|
|
||||||
|
After applying all changes, summarize:
|
||||||
|
- Which capabilities were updated
|
||||||
|
- What changes were made (requirements added/modified/removed/renamed)
|
||||||
|
|
||||||
|
**Delta Spec Format Reference**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: New Feature
|
||||||
|
The system SHALL do something new.
|
||||||
|
|
||||||
|
#### Scenario: Basic case
|
||||||
|
- **WHEN** user does X
|
||||||
|
- **THEN** system does Y
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Existing Feature
|
||||||
|
#### Scenario: New scenario to add
|
||||||
|
- **WHEN** user does A
|
||||||
|
- **THEN** system does B
|
||||||
|
|
||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: Deprecated Feature
|
||||||
|
|
||||||
|
## RENAMED Requirements
|
||||||
|
|
||||||
|
- FROM: `### Requirement: Old Name`
|
||||||
|
- TO: `### Requirement: New Name`
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Principle: Intelligent Merging**
|
||||||
|
|
||||||
|
Unlike programmatic merging, you can apply **partial updates**:
|
||||||
|
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
|
||||||
|
- The delta represents *intent*, not a wholesale replacement
|
||||||
|
- Use your judgment to merge changes sensibly
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Specs Synced: <change-name>
|
||||||
|
|
||||||
|
Updated main specs:
|
||||||
|
|
||||||
|
**<capability-1>**:
|
||||||
|
- Added requirement: "New Feature"
|
||||||
|
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||||
|
|
||||||
|
**<capability-2>**:
|
||||||
|
- Created new spec file
|
||||||
|
- Added requirement: "Another Feature"
|
||||||
|
|
||||||
|
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Read both delta and main specs before making changes
|
||||||
|
- Preserve existing content not mentioned in delta
|
||||||
|
- If something is unclear, ask for clarification
|
||||||
|
- Show what you're changing as you go
|
||||||
|
- The operation should be idempotent - running twice should give same result
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
---
|
||||||
|
description: Verify implementation matches change artifacts before archiving
|
||||||
|
---
|
||||||
|
|
||||||
|
Verify that an implementation matches the change artifacts (specs, tasks, design).
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name after `/opsx:verify` (e.g., `/opsx:verify add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show changes that have implementation tasks (tasks artifact exists).
|
||||||
|
Include the schema used for each change if available.
|
||||||
|
Mark changes with incomplete tasks as "(In Progress)".
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check status to understand the schema**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||||
|
- Which artifacts exist for this change
|
||||||
|
|
||||||
|
3. **Get the change directory and load artifacts**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec instructions apply --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns the change directory and context files. Read all available artifacts from `contextFiles`.
|
||||||
|
|
||||||
|
4. **Initialize verification report structure**
|
||||||
|
|
||||||
|
Create a report structure with three dimensions:
|
||||||
|
- **Completeness**: Track tasks and spec coverage
|
||||||
|
- **Correctness**: Track requirement implementation and scenario coverage
|
||||||
|
- **Coherence**: Track design adherence and pattern consistency
|
||||||
|
|
||||||
|
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
|
||||||
|
|
||||||
|
5. **Verify Completeness**
|
||||||
|
|
||||||
|
**Task Completion**:
|
||||||
|
- If tasks.md exists in contextFiles, read it
|
||||||
|
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||||
|
- Count complete vs total tasks
|
||||||
|
- If incomplete tasks exist:
|
||||||
|
- Add CRITICAL issue for each incomplete task
|
||||||
|
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
|
||||||
|
|
||||||
|
**Spec Coverage**:
|
||||||
|
- If delta specs exist in `openspec/changes/<name>/specs/`:
|
||||||
|
- Extract all requirements (marked with "### Requirement:")
|
||||||
|
- For each requirement:
|
||||||
|
- Search codebase for keywords related to the requirement
|
||||||
|
- Assess if implementation likely exists
|
||||||
|
- If requirements appear unimplemented:
|
||||||
|
- Add CRITICAL issue: "Requirement not found: <requirement name>"
|
||||||
|
- Recommendation: "Implement requirement X: <description>"
|
||||||
|
|
||||||
|
6. **Verify Correctness**
|
||||||
|
|
||||||
|
**Requirement Implementation Mapping**:
|
||||||
|
- For each requirement from delta specs:
|
||||||
|
- Search codebase for implementation evidence
|
||||||
|
- If found, note file paths and line ranges
|
||||||
|
- Assess if implementation matches requirement intent
|
||||||
|
- If divergence detected:
|
||||||
|
- Add WARNING: "Implementation may diverge from spec: <details>"
|
||||||
|
- Recommendation: "Review <file>:<lines> against requirement X"
|
||||||
|
|
||||||
|
**Scenario Coverage**:
|
||||||
|
- For each scenario in delta specs (marked with "#### Scenario:"):
|
||||||
|
- Check if conditions are handled in code
|
||||||
|
- Check if tests exist covering the scenario
|
||||||
|
- If scenario appears uncovered:
|
||||||
|
- Add WARNING: "Scenario not covered: <scenario name>"
|
||||||
|
- Recommendation: "Add test or implementation for scenario: <description>"
|
||||||
|
|
||||||
|
7. **Verify Coherence**
|
||||||
|
|
||||||
|
**Design Adherence**:
|
||||||
|
- If design.md exists in contextFiles:
|
||||||
|
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
|
||||||
|
- Verify implementation follows those decisions
|
||||||
|
- If contradiction detected:
|
||||||
|
- Add WARNING: "Design decision not followed: <decision>"
|
||||||
|
- Recommendation: "Update implementation or revise design.md to match reality"
|
||||||
|
- If no design.md: Skip design adherence check, note "No design.md to verify against"
|
||||||
|
|
||||||
|
**Code Pattern Consistency**:
|
||||||
|
- Review new code for consistency with project patterns
|
||||||
|
- Check file naming, directory structure, coding style
|
||||||
|
- If significant deviations found:
|
||||||
|
- Add SUGGESTION: "Code pattern deviation: <details>"
|
||||||
|
- Recommendation: "Consider following project pattern: <example>"
|
||||||
|
|
||||||
|
8. **Generate Verification Report**
|
||||||
|
|
||||||
|
**Summary Scorecard**:
|
||||||
|
```
|
||||||
|
## Verification Report: <change-name>
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
| Dimension | Status |
|
||||||
|
|--------------|------------------|
|
||||||
|
| Completeness | X/Y tasks, N reqs|
|
||||||
|
| Correctness | M/N reqs covered |
|
||||||
|
| Coherence | Followed/Issues |
|
||||||
|
```
|
||||||
|
|
||||||
|
**Issues by Priority**:
|
||||||
|
|
||||||
|
1. **CRITICAL** (Must fix before archive):
|
||||||
|
- Incomplete tasks
|
||||||
|
- Missing requirement implementations
|
||||||
|
- Each with specific, actionable recommendation
|
||||||
|
|
||||||
|
2. **WARNING** (Should fix):
|
||||||
|
- Spec/design divergences
|
||||||
|
- Missing scenario coverage
|
||||||
|
- Each with specific recommendation
|
||||||
|
|
||||||
|
3. **SUGGESTION** (Nice to fix):
|
||||||
|
- Pattern inconsistencies
|
||||||
|
- Minor improvements
|
||||||
|
- Each with specific recommendation
|
||||||
|
|
||||||
|
**Final Assessment**:
|
||||||
|
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
|
||||||
|
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
|
||||||
|
- If all clear: "All checks passed. Ready for archive."
|
||||||
|
|
||||||
|
**Verification Heuristics**
|
||||||
|
|
||||||
|
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
|
||||||
|
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
|
||||||
|
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
|
||||||
|
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
|
||||||
|
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
|
||||||
|
|
||||||
|
**Graceful Degradation**
|
||||||
|
|
||||||
|
- If only tasks.md exists: verify task completion only, skip spec/design checks
|
||||||
|
- If tasks + specs exist: verify completeness and correctness, skip design
|
||||||
|
- If full artifacts: verify all three dimensions
|
||||||
|
- Always note which checks were skipped and why
|
||||||
|
|
||||||
|
**Output Format**
|
||||||
|
|
||||||
|
Use clear markdown with:
|
||||||
|
- Table for summary scorecard
|
||||||
|
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
|
||||||
|
- Code references in format: `file.ts:123`
|
||||||
|
- Specific, actionable recommendations
|
||||||
|
- No vague suggestions like "consider reviewing"
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
name: openspec-apply-change
|
||||||
|
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Implement tasks from an OpenSpec change.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Select the change**
|
||||||
|
|
||||||
|
If a name is provided, use it. Otherwise:
|
||||||
|
- Infer from conversation context if the user mentioned a change
|
||||||
|
- Auto-select if only one active change exists
|
||||||
|
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
|
||||||
|
|
||||||
|
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
|
||||||
|
|
||||||
|
2. **Check status to understand the schema**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||||
|
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
|
||||||
|
|
||||||
|
3. **Get apply instructions**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec instructions apply --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns:
|
||||||
|
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
|
||||||
|
- Progress (total, complete, remaining)
|
||||||
|
- Task list with status
|
||||||
|
- Dynamic instruction based on current state
|
||||||
|
|
||||||
|
**Handle states:**
|
||||||
|
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||||
|
- If `state: "all_done"`: congratulate, suggest archive
|
||||||
|
- Otherwise: proceed to implementation
|
||||||
|
|
||||||
|
4. **Read context files**
|
||||||
|
|
||||||
|
Read the files listed in `contextFiles` from the apply instructions output.
|
||||||
|
The files depend on the schema being used:
|
||||||
|
- **spec-driven**: proposal, specs, design, tasks
|
||||||
|
- Other schemas: follow the contextFiles from CLI output
|
||||||
|
|
||||||
|
5. **Show current progress**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Schema being used
|
||||||
|
- Progress: "N/M tasks complete"
|
||||||
|
- Remaining tasks overview
|
||||||
|
- Dynamic instruction from CLI
|
||||||
|
|
||||||
|
6. **Implement tasks (loop until done or blocked)**
|
||||||
|
|
||||||
|
For each pending task:
|
||||||
|
- Show which task is being worked on
|
||||||
|
- Make the code changes required
|
||||||
|
- Keep changes minimal and focused
|
||||||
|
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
|
||||||
|
- Continue to next task
|
||||||
|
|
||||||
|
**Pause if:**
|
||||||
|
- Task is unclear → ask for clarification
|
||||||
|
- Implementation reveals a design issue → suggest updating artifacts
|
||||||
|
- Error or blocker encountered → report and wait for guidance
|
||||||
|
- User interrupts
|
||||||
|
|
||||||
|
7. **On completion or pause, show status**
|
||||||
|
|
||||||
|
Display:
|
||||||
|
- Tasks completed this session
|
||||||
|
- Overall progress: "N/M tasks complete"
|
||||||
|
- If all done: suggest archive
|
||||||
|
- If paused: explain why and wait for guidance
|
||||||
|
|
||||||
|
**Output During Implementation**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementing: <change-name> (schema: <schema-name>)
|
||||||
|
|
||||||
|
Working on task 3/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
|
||||||
|
Working on task 4/7: <task description>
|
||||||
|
[...implementation happening...]
|
||||||
|
✓ Task complete
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Completion**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 7/7 tasks complete ✓
|
||||||
|
|
||||||
|
### Completed This Session
|
||||||
|
- [x] Task 1
|
||||||
|
- [x] Task 2
|
||||||
|
...
|
||||||
|
|
||||||
|
All tasks complete! Ready to archive this change.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Pause (Issue Encountered)**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Paused
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Progress:** 4/7 tasks complete
|
||||||
|
|
||||||
|
### Issue Encountered
|
||||||
|
<description of the issue>
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. <option 1>
|
||||||
|
2. <option 2>
|
||||||
|
3. Other approach
|
||||||
|
|
||||||
|
What would you like to do?
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Keep going through tasks until done or blocked
|
||||||
|
- Always read context files before starting (from the apply instructions output)
|
||||||
|
- If task is ambiguous, pause and ask before implementing
|
||||||
|
- If implementation reveals issues, pause and suggest artifact updates
|
||||||
|
- Keep code changes minimal and scoped to each task
|
||||||
|
- Update task checkbox immediately after completing each task
|
||||||
|
- Pause on errors, blockers, or unclear requirements - don't guess
|
||||||
|
- Use contextFiles from CLI output, don't assume specific file names
|
||||||
|
|
||||||
|
**Fluid Workflow Integration**
|
||||||
|
|
||||||
|
This skill supports the "actions on a change" model:
|
||||||
|
|
||||||
|
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
|
||||||
|
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
---
|
||||||
|
name: openspec-archive-change
|
||||||
|
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Archive a completed change in the experimental workflow.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show only active changes (not already archived).
|
||||||
|
Include the schema used for each change if available.
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check artifact completion status**
|
||||||
|
|
||||||
|
Run `openspec status --change "<name>" --json` to check artifact completion.
|
||||||
|
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used
|
||||||
|
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||||
|
|
||||||
|
**If any artifacts are not `done`:**
|
||||||
|
- Display warning listing incomplete artifacts
|
||||||
|
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
3. **Check task completion status**
|
||||||
|
|
||||||
|
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
|
||||||
|
|
||||||
|
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
|
||||||
|
|
||||||
|
**If incomplete tasks found:**
|
||||||
|
- Display warning showing count of incomplete tasks
|
||||||
|
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||||
|
- Proceed if user confirms
|
||||||
|
|
||||||
|
**If no tasks file exists:** Proceed without task-related warning.
|
||||||
|
|
||||||
|
4. **Assess delta spec sync state**
|
||||||
|
|
||||||
|
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||||
|
|
||||||
|
**If delta specs exist:**
|
||||||
|
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||||
|
- Determine what changes would be applied (adds, modifications, removals, renames)
|
||||||
|
- Show a combined summary before prompting
|
||||||
|
|
||||||
|
**Prompt options:**
|
||||||
|
- If changes needed: "Sync now (recommended)", "Archive without syncing"
|
||||||
|
- If already synced: "Archive now", "Sync anyway", "Cancel"
|
||||||
|
|
||||||
|
If user chooses sync, execute /opsx:sync logic (use the openspec-sync-specs skill). Proceed to archive regardless of choice.
|
||||||
|
|
||||||
|
5. **Perform the archive**
|
||||||
|
|
||||||
|
Create the archive directory if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/archive
|
||||||
|
```
|
||||||
|
|
||||||
|
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||||
|
|
||||||
|
**Check if target already exists:**
|
||||||
|
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||||
|
- If no: Move the change directory to archive
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Display summary**
|
||||||
|
|
||||||
|
Show archive completion summary including:
|
||||||
|
- Change name
|
||||||
|
- Schema that was used
|
||||||
|
- Archive location
|
||||||
|
- Whether specs were synced (if applicable)
|
||||||
|
- Note about any warnings (incomplete artifacts/tasks)
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Archive Complete
|
||||||
|
|
||||||
|
**Change:** <change-name>
|
||||||
|
**Schema:** <schema-name>
|
||||||
|
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||||
|
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||||
|
|
||||||
|
All artifacts complete. All tasks complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Always prompt for change selection if not provided
|
||||||
|
- Use artifact graph (openspec status --json) for completion checking
|
||||||
|
- Don't block archive on warnings - just inform and confirm
|
||||||
|
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
|
||||||
|
- Show clear summary of what happened
|
||||||
|
- If sync is requested, use openspec-sync-specs approach (agent-driven)
|
||||||
|
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
---
|
||||||
|
name: openspec-bulk-archive-change
|
||||||
|
description: Archive multiple completed changes at once. Use when archiving several parallel changes.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Archive multiple completed changes in a single operation.
|
||||||
|
|
||||||
|
This skill allows you to batch-archive changes, handling spec conflicts intelligently by checking the codebase to determine what's actually implemented.
|
||||||
|
|
||||||
|
**Input**: None required (prompts for selection)
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **Get active changes**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get all active changes.
|
||||||
|
|
||||||
|
If no active changes exist, inform user and stop.
|
||||||
|
|
||||||
|
2. **Prompt for change selection**
|
||||||
|
|
||||||
|
Use **AskUserQuestion tool** with multi-select to let user choose changes:
|
||||||
|
- Show each change with its schema
|
||||||
|
- Include an option for "All changes"
|
||||||
|
- Allow any number of selections (1+ works, 2+ is the typical use case)
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT auto-select. Always let the user choose.
|
||||||
|
|
||||||
|
3. **Batch validation - gather status for all selected changes**
|
||||||
|
|
||||||
|
For each selected change, collect:
|
||||||
|
|
||||||
|
a. **Artifact status** - Run `openspec status --change "<name>" --json`
|
||||||
|
- Parse `schemaName` and `artifacts` list
|
||||||
|
- Note which artifacts are `done` vs other states
|
||||||
|
|
||||||
|
b. **Task completion** - Read `openspec/changes/<name>/tasks.md`
|
||||||
|
- Count `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||||
|
- If no tasks file exists, note as "No tasks"
|
||||||
|
|
||||||
|
c. **Delta specs** - Check `openspec/changes/<name>/specs/` directory
|
||||||
|
- List which capability specs exist
|
||||||
|
- For each, extract requirement names (lines matching `### Requirement: <name>`)
|
||||||
|
|
||||||
|
4. **Detect spec conflicts**
|
||||||
|
|
||||||
|
Build a map of `capability -> [changes that touch it]`:
|
||||||
|
|
||||||
|
```
|
||||||
|
auth -> [change-a, change-b] <- CONFLICT (2+ changes)
|
||||||
|
api -> [change-c] <- OK (only 1 change)
|
||||||
|
```
|
||||||
|
|
||||||
|
A conflict exists when 2+ selected changes have delta specs for the same capability.
|
||||||
|
|
||||||
|
5. **Resolve conflicts agentically**
|
||||||
|
|
||||||
|
**For each conflict**, investigate the codebase:
|
||||||
|
|
||||||
|
a. **Read the delta specs** from each conflicting change to understand what each claims to add/modify
|
||||||
|
|
||||||
|
b. **Search the codebase** for implementation evidence:
|
||||||
|
- Look for code implementing requirements from each delta spec
|
||||||
|
- Check for related files, functions, or tests
|
||||||
|
|
||||||
|
c. **Determine resolution**:
|
||||||
|
- If only one change is actually implemented -> sync that one's specs
|
||||||
|
- If both implemented -> apply in chronological order (older first, newer overwrites)
|
||||||
|
- If neither implemented -> skip spec sync, warn user
|
||||||
|
|
||||||
|
d. **Record resolution** for each conflict:
|
||||||
|
- Which change's specs to apply
|
||||||
|
- In what order (if both)
|
||||||
|
- Rationale (what was found in codebase)
|
||||||
|
|
||||||
|
6. **Show consolidated status table**
|
||||||
|
|
||||||
|
Display a table summarizing all changes:
|
||||||
|
|
||||||
|
```
|
||||||
|
| Change | Artifacts | Tasks | Specs | Conflicts | Status |
|
||||||
|
|---------------------|-----------|-------|---------|-----------|--------|
|
||||||
|
| schema-management | Done | 5/5 | 2 delta | None | Ready |
|
||||||
|
| project-config | Done | 3/3 | 1 delta | None | Ready |
|
||||||
|
| add-oauth | Done | 4/4 | 1 delta | auth (!) | Ready* |
|
||||||
|
| add-verify-skill | 1 left | 2/5 | None | None | Warn |
|
||||||
|
```
|
||||||
|
|
||||||
|
For conflicts, show the resolution:
|
||||||
|
```
|
||||||
|
* Conflict resolution:
|
||||||
|
- auth spec: Will apply add-oauth then add-jwt (both implemented, chronological order)
|
||||||
|
```
|
||||||
|
|
||||||
|
For incomplete changes, show warnings:
|
||||||
|
```
|
||||||
|
Warnings:
|
||||||
|
- add-verify-skill: 1 incomplete artifact, 3 incomplete tasks
|
||||||
|
```
|
||||||
|
|
||||||
|
7. **Confirm batch operation**
|
||||||
|
|
||||||
|
Use **AskUserQuestion tool** with a single confirmation:
|
||||||
|
|
||||||
|
- "Archive N changes?" with options based on status
|
||||||
|
- Options might include:
|
||||||
|
- "Archive all N changes"
|
||||||
|
- "Archive only N ready changes (skip incomplete)"
|
||||||
|
- "Cancel"
|
||||||
|
|
||||||
|
If there are incomplete changes, make clear they'll be archived with warnings.
|
||||||
|
|
||||||
|
8. **Execute archive for each confirmed change**
|
||||||
|
|
||||||
|
Process changes in the determined order (respecting conflict resolution):
|
||||||
|
|
||||||
|
a. **Sync specs** if delta specs exist:
|
||||||
|
- Use the openspec-sync-specs approach (agent-driven intelligent merge)
|
||||||
|
- For conflicts, apply in resolved order
|
||||||
|
- Track if sync was done
|
||||||
|
|
||||||
|
b. **Perform the archive**:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/archive
|
||||||
|
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||||
|
```
|
||||||
|
|
||||||
|
c. **Track outcome** for each change:
|
||||||
|
- Success: archived successfully
|
||||||
|
- Failed: error during archive (record error)
|
||||||
|
- Skipped: user chose not to archive (if applicable)
|
||||||
|
|
||||||
|
9. **Display summary**
|
||||||
|
|
||||||
|
Show final results:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete
|
||||||
|
|
||||||
|
Archived 3 changes:
|
||||||
|
- schema-management-cli -> archive/2026-01-19-schema-management-cli/
|
||||||
|
- project-config -> archive/2026-01-19-project-config/
|
||||||
|
- add-oauth -> archive/2026-01-19-add-oauth/
|
||||||
|
|
||||||
|
Skipped 1 change:
|
||||||
|
- add-verify-skill (user chose not to archive incomplete)
|
||||||
|
|
||||||
|
Spec sync summary:
|
||||||
|
- 4 delta specs synced to main specs
|
||||||
|
- 1 conflict resolved (auth: applied both in chronological order)
|
||||||
|
```
|
||||||
|
|
||||||
|
If any failures:
|
||||||
|
```
|
||||||
|
Failed 1 change:
|
||||||
|
- some-change: Archive directory already exists
|
||||||
|
```
|
||||||
|
|
||||||
|
**Conflict Resolution Examples**
|
||||||
|
|
||||||
|
Example 1: Only one implemented
|
||||||
|
```
|
||||||
|
Conflict: specs/auth/spec.md touched by [add-oauth, add-jwt]
|
||||||
|
|
||||||
|
Checking add-oauth:
|
||||||
|
- Delta adds "OAuth Provider Integration" requirement
|
||||||
|
- Searching codebase... found src/auth/oauth.ts implementing OAuth flow
|
||||||
|
|
||||||
|
Checking add-jwt:
|
||||||
|
- Delta adds "JWT Token Handling" requirement
|
||||||
|
- Searching codebase... no JWT implementation found
|
||||||
|
|
||||||
|
Resolution: Only add-oauth is implemented. Will sync add-oauth specs only.
|
||||||
|
```
|
||||||
|
|
||||||
|
Example 2: Both implemented
|
||||||
|
```
|
||||||
|
Conflict: specs/api/spec.md touched by [add-rest-api, add-graphql]
|
||||||
|
|
||||||
|
Checking add-rest-api (created 2026-01-10):
|
||||||
|
- Delta adds "REST Endpoints" requirement
|
||||||
|
- Searching codebase... found src/api/rest.ts
|
||||||
|
|
||||||
|
Checking add-graphql (created 2026-01-15):
|
||||||
|
- Delta adds "GraphQL Schema" requirement
|
||||||
|
- Searching codebase... found src/api/graphql.ts
|
||||||
|
|
||||||
|
Resolution: Both implemented. Will apply add-rest-api specs first,
|
||||||
|
then add-graphql specs (chronological order, newer takes precedence).
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete
|
||||||
|
|
||||||
|
Archived N changes:
|
||||||
|
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||||
|
- <change-2> -> archive/YYYY-MM-DD-<change-2>/
|
||||||
|
|
||||||
|
Spec sync summary:
|
||||||
|
- N delta specs synced to main specs
|
||||||
|
- No conflicts (or: M conflicts resolved)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output On Partial Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Bulk Archive Complete (partial)
|
||||||
|
|
||||||
|
Archived N changes:
|
||||||
|
- <change-1> -> archive/YYYY-MM-DD-<change-1>/
|
||||||
|
|
||||||
|
Skipped M changes:
|
||||||
|
- <change-2> (user chose not to archive incomplete)
|
||||||
|
|
||||||
|
Failed K changes:
|
||||||
|
- <change-3>: Archive directory already exists
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output When No Changes**
|
||||||
|
|
||||||
|
```
|
||||||
|
## No Changes to Archive
|
||||||
|
|
||||||
|
No active changes found. Use `/opsx:new` to create a new change.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Allow any number of changes (1+ is fine, 2+ is the typical use case)
|
||||||
|
- Always prompt for selection, never auto-select
|
||||||
|
- Detect spec conflicts early and resolve by checking codebase
|
||||||
|
- When both changes are implemented, apply specs in chronological order
|
||||||
|
- Skip spec sync only when implementation is missing (warn user)
|
||||||
|
- Show clear per-change status before confirming
|
||||||
|
- Use single confirmation for entire batch
|
||||||
|
- Track and report all outcomes (success/skip/fail)
|
||||||
|
- Preserve .openspec.yaml when moving to archive
|
||||||
|
- Archive directory target uses current date: YYYY-MM-DD-<name>
|
||||||
|
- If archive target exists, fail that change but continue with others
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
---
|
||||||
|
name: openspec-continue-change
|
||||||
|
description: Continue working on an OpenSpec change by creating the next artifact. Use when the user wants to progress their change, create the next artifact, or continue their workflow.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Continue working on a change by creating the next artifact.
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes sorted by most recently modified. Then use the **AskUserQuestion tool** to let the user select which change to work on.
|
||||||
|
|
||||||
|
Present the top 3-4 most recently modified changes as options, showing:
|
||||||
|
- Change name
|
||||||
|
- Schema (from `schema` field if present, otherwise "spec-driven")
|
||||||
|
- Status (e.g., "0/5 tasks", "complete", "no tasks")
|
||||||
|
- How recently it was modified (from `lastModified` field)
|
||||||
|
|
||||||
|
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to continue.
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check current status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand current state. The response includes:
|
||||||
|
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
|
||||||
|
- `artifacts`: Array of artifacts with their status ("done", "ready", "blocked")
|
||||||
|
- `isComplete`: Boolean indicating if all artifacts are complete
|
||||||
|
|
||||||
|
3. **Act based on status**:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If all artifacts are complete (`isComplete: true`)**:
|
||||||
|
- Congratulate the user
|
||||||
|
- Show final status including the schema used
|
||||||
|
- Suggest: "All artifacts created! You can now implement this change or archive it."
|
||||||
|
- STOP
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If artifacts are ready to create** (status shows artifacts with `status: "ready"`):
|
||||||
|
- Pick the FIRST artifact with `status: "ready"` from the status output
|
||||||
|
- Get its instructions:
|
||||||
|
```bash
|
||||||
|
openspec instructions <artifact-id> --change "<name>" --json
|
||||||
|
```
|
||||||
|
- Parse the JSON. The key fields are:
|
||||||
|
- `context`: Project background (constraints for you - do NOT include in output)
|
||||||
|
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||||
|
- `template`: The structure to use for your output file
|
||||||
|
- `instruction`: Schema-specific guidance
|
||||||
|
- `outputPath`: Where to write the artifact
|
||||||
|
- `dependencies`: Completed artifacts to read for context
|
||||||
|
- **Create the artifact file**:
|
||||||
|
- Read any completed dependency files for context
|
||||||
|
- Use `template` as the structure - fill in its sections
|
||||||
|
- Apply `context` and `rules` as constraints when writing - but do NOT copy them into the file
|
||||||
|
- Write to the output path specified in instructions
|
||||||
|
- Show what was created and what's now unlocked
|
||||||
|
- STOP after creating ONE artifact
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**If no artifacts are ready (all blocked)**:
|
||||||
|
- This shouldn't happen with a valid schema
|
||||||
|
- Show status and suggest checking for issues
|
||||||
|
|
||||||
|
4. **After creating an artifact, show progress**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After each invocation, show:
|
||||||
|
- Which artifact was created
|
||||||
|
- Schema workflow being used
|
||||||
|
- Current progress (N/M complete)
|
||||||
|
- What artifacts are now unlocked
|
||||||
|
- Prompt: "Want to continue? Just ask me to continue or tell me what to do next."
|
||||||
|
|
||||||
|
**Artifact Creation Guidelines**
|
||||||
|
|
||||||
|
The artifact types and their purpose depend on the schema. Use the `instruction` field from the instructions output to understand what to create.
|
||||||
|
|
||||||
|
Common artifact patterns:
|
||||||
|
|
||||||
|
**spec-driven schema** (proposal → specs → design → tasks):
|
||||||
|
- **proposal.md**: Ask user about the change if not clear. Fill in Why, What Changes, Capabilities, Impact.
|
||||||
|
- The Capabilities section is critical - each capability listed will need a spec file.
|
||||||
|
- **specs/<capability>/spec.md**: Create one spec per capability listed in the proposal's Capabilities section (use the capability name, not the change name).
|
||||||
|
- **design.md**: Document technical decisions, architecture, and implementation approach.
|
||||||
|
- **tasks.md**: Break down implementation into checkboxed tasks.
|
||||||
|
|
||||||
|
For other schemas, follow the `instruction` field from the CLI output.
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Create ONE artifact per invocation
|
||||||
|
- Always read dependency artifacts before creating a new one
|
||||||
|
- Never skip artifacts or create out of order
|
||||||
|
- If context is unclear, ask the user before creating
|
||||||
|
- Verify the artifact file exists after writing before marking progress
|
||||||
|
- Use the schema's artifact sequence, don't assume specific artifact names
|
||||||
|
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||||
|
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||||
|
- These guide what you write, but should never appear in the output
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
---
|
||||||
|
name: openspec-explore
|
||||||
|
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
|
||||||
|
|
||||||
|
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first (e.g., start a change with `/opsx:new` or `/opsx:ff`). You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
|
||||||
|
|
||||||
|
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The Stance
|
||||||
|
|
||||||
|
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
|
||||||
|
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
|
||||||
|
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
|
||||||
|
- **Adaptive** - Follow interesting threads, pivot when new information emerges
|
||||||
|
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
|
||||||
|
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Might Do
|
||||||
|
|
||||||
|
Depending on what the user brings, you might:
|
||||||
|
|
||||||
|
**Explore the problem space**
|
||||||
|
- Ask clarifying questions that emerge from what they said
|
||||||
|
- Challenge assumptions
|
||||||
|
- Reframe the problem
|
||||||
|
- Find analogies
|
||||||
|
|
||||||
|
**Investigate the codebase**
|
||||||
|
- Map existing architecture relevant to the discussion
|
||||||
|
- Find integration points
|
||||||
|
- Identify patterns already in use
|
||||||
|
- Surface hidden complexity
|
||||||
|
|
||||||
|
**Compare options**
|
||||||
|
- Brainstorm multiple approaches
|
||||||
|
- Build comparison tables
|
||||||
|
- Sketch tradeoffs
|
||||||
|
- Recommend a path (if asked)
|
||||||
|
|
||||||
|
**Visualize**
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ Use ASCII diagrams liberally │
|
||||||
|
├─────────────────────────────────────────┤
|
||||||
|
│ │
|
||||||
|
│ ┌────────┐ ┌────────┐ │
|
||||||
|
│ │ State │────────▶│ State │ │
|
||||||
|
│ │ A │ │ B │ │
|
||||||
|
│ └────────┘ └────────┘ │
|
||||||
|
│ │
|
||||||
|
│ System diagrams, state machines, │
|
||||||
|
│ data flows, architecture sketches, │
|
||||||
|
│ dependency graphs, comparison tables │
|
||||||
|
│ │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Surface risks and unknowns**
|
||||||
|
- Identify what could go wrong
|
||||||
|
- Find gaps in understanding
|
||||||
|
- Suggest spikes or investigations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OpenSpec Awareness
|
||||||
|
|
||||||
|
You have full context of the OpenSpec system. Use it naturally, don't force it.
|
||||||
|
|
||||||
|
### Check for context
|
||||||
|
|
||||||
|
At the start, quickly check what exists:
|
||||||
|
```bash
|
||||||
|
openspec list --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This tells you:
|
||||||
|
- If there are active changes
|
||||||
|
- Their names, schemas, and status
|
||||||
|
- What the user might be working on
|
||||||
|
|
||||||
|
### When no change exists
|
||||||
|
|
||||||
|
Think freely. When insights crystallize, you might offer:
|
||||||
|
|
||||||
|
- "This feels solid enough to start a change. Want me to create one?"
|
||||||
|
→ Can transition to `/opsx:new` or `/opsx:ff`
|
||||||
|
- Or keep exploring - no pressure to formalize
|
||||||
|
|
||||||
|
### When a change exists
|
||||||
|
|
||||||
|
If the user mentions a change or you detect one is relevant:
|
||||||
|
|
||||||
|
1. **Read existing artifacts for context**
|
||||||
|
- `openspec/changes/<name>/proposal.md`
|
||||||
|
- `openspec/changes/<name>/design.md`
|
||||||
|
- `openspec/changes/<name>/tasks.md`
|
||||||
|
- etc.
|
||||||
|
|
||||||
|
2. **Reference them naturally in conversation**
|
||||||
|
- "Your design mentions using Redis, but we just realized SQLite fits better..."
|
||||||
|
- "The proposal scopes this to premium users, but we're now thinking everyone..."
|
||||||
|
|
||||||
|
3. **Offer to capture when decisions are made**
|
||||||
|
|
||||||
|
| Insight Type | Where to Capture |
|
||||||
|
|--------------|------------------|
|
||||||
|
| New requirement discovered | `specs/<capability>/spec.md` |
|
||||||
|
| Requirement changed | `specs/<capability>/spec.md` |
|
||||||
|
| Design decision made | `design.md` |
|
||||||
|
| Scope changed | `proposal.md` |
|
||||||
|
| New work identified | `tasks.md` |
|
||||||
|
| Assumption invalidated | Relevant artifact |
|
||||||
|
|
||||||
|
Example offers:
|
||||||
|
- "That's a design decision. Capture it in design.md?"
|
||||||
|
- "This is a new requirement. Add it to specs?"
|
||||||
|
- "This changes scope. Update the proposal?"
|
||||||
|
|
||||||
|
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What You Don't Have To Do
|
||||||
|
|
||||||
|
- Follow a script
|
||||||
|
- Ask the same questions every time
|
||||||
|
- Produce a specific artifact
|
||||||
|
- Reach a conclusion
|
||||||
|
- Stay on topic if a tangent is valuable
|
||||||
|
- Be brief (this is thinking time)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Handling Different Entry Points
|
||||||
|
|
||||||
|
**User brings a vague idea:**
|
||||||
|
```
|
||||||
|
User: I'm thinking about adding real-time collaboration
|
||||||
|
|
||||||
|
You: Real-time collab is a big space. Let me think about this...
|
||||||
|
|
||||||
|
COLLABORATION SPECTRUM
|
||||||
|
════════════════════════════════════════════
|
||||||
|
|
||||||
|
Awareness Coordination Sync
|
||||||
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌────────┐ ┌────────┐ ┌────────┐
|
||||||
|
│Presence│ │Cursors │ │ CRDT │
|
||||||
|
│ "3 │ │ Multi │ │Conflict│
|
||||||
|
│online" │ │ select │ │ free │
|
||||||
|
└────────┘ └────────┘ └────────┘
|
||||||
|
│ │ │
|
||||||
|
trivial moderate complex
|
||||||
|
|
||||||
|
Where's your head at?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User brings a specific problem:**
|
||||||
|
```
|
||||||
|
User: The auth system is a mess
|
||||||
|
|
||||||
|
You: [reads codebase]
|
||||||
|
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ CURRENT AUTH FLOW │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌─────────────┼─────────────┐
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌─────────┐ ┌─────────┐ ┌─────────┐
|
||||||
|
│ Google │ │ GitHub │ │ Email │
|
||||||
|
│ OAuth │ │ OAuth │ │ Magic │
|
||||||
|
└────┬────┘ └────┬────┘ └────┬────┘
|
||||||
|
│ │ │
|
||||||
|
└─────────────┼─────────────┘
|
||||||
|
▼
|
||||||
|
┌───────────┐
|
||||||
|
│ Session │
|
||||||
|
└─────┬─────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌───────────┐
|
||||||
|
│ Perms │
|
||||||
|
└───────────┘
|
||||||
|
|
||||||
|
I see three tangles. Which one's burning?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User is stuck mid-implementation:**
|
||||||
|
```
|
||||||
|
User: /opsx:explore add-auth-system
|
||||||
|
The OAuth integration is more complex than expected
|
||||||
|
|
||||||
|
You: [reads change artifacts]
|
||||||
|
|
||||||
|
You're on task 4: "Implement OAuth flow"
|
||||||
|
|
||||||
|
Let me trace what's involved...
|
||||||
|
|
||||||
|
[draws diagram, explores options, suggests paths]
|
||||||
|
|
||||||
|
Want to update the design to reflect this?
|
||||||
|
Or add a spike task to investigate?
|
||||||
|
```
|
||||||
|
|
||||||
|
**User wants to compare options:**
|
||||||
|
```
|
||||||
|
User: Should we use Postgres or SQLite?
|
||||||
|
|
||||||
|
You: Generic answer is boring. What's the context?
|
||||||
|
|
||||||
|
User: A CLI tool that tracks local dev environments
|
||||||
|
|
||||||
|
You: That changes everything.
|
||||||
|
|
||||||
|
┌─────────────────────────────────────────────────┐
|
||||||
|
│ CLI TOOL DATA STORAGE │
|
||||||
|
└─────────────────────────────────────────────────┘
|
||||||
|
|
||||||
|
Key constraints:
|
||||||
|
• No daemon running
|
||||||
|
• Must work offline
|
||||||
|
• Single user
|
||||||
|
|
||||||
|
SQLite Postgres
|
||||||
|
Deployment embedded ✓ needs server ✗
|
||||||
|
Offline yes ✓ no ✗
|
||||||
|
Single file yes ✓ no ✗
|
||||||
|
|
||||||
|
SQLite. Not even close.
|
||||||
|
|
||||||
|
Unless... is there a sync component?
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ending Discovery
|
||||||
|
|
||||||
|
There's no required ending. Discovery might:
|
||||||
|
|
||||||
|
- **Flow into action**: "Ready to start? /opsx:new or /opsx:ff"
|
||||||
|
- **Result in artifact updates**: "Updated design.md with these decisions"
|
||||||
|
- **Just provide clarity**: User has what they need, moves on
|
||||||
|
- **Continue later**: "We can pick this up anytime"
|
||||||
|
|
||||||
|
When it feels like things are crystallizing, you might summarize:
|
||||||
|
|
||||||
|
```
|
||||||
|
## What We Figured Out
|
||||||
|
|
||||||
|
**The problem**: [crystallized understanding]
|
||||||
|
|
||||||
|
**The approach**: [if one emerged]
|
||||||
|
|
||||||
|
**Open questions**: [if any remain]
|
||||||
|
|
||||||
|
**Next steps** (if ready):
|
||||||
|
- Create a change: /opsx:new <name>
|
||||||
|
- Fast-forward to tasks: /opsx:ff <name>
|
||||||
|
- Keep exploring: just keep talking
|
||||||
|
```
|
||||||
|
|
||||||
|
But this summary is optional. Sometimes the thinking IS the value.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
|
||||||
|
- **Don't fake understanding** - If something is unclear, dig deeper
|
||||||
|
- **Don't rush** - Discovery is thinking time, not task time
|
||||||
|
- **Don't force structure** - Let patterns emerge naturally
|
||||||
|
- **Don't auto-capture** - Offer to save insights, don't just do it
|
||||||
|
- **Do visualize** - A good diagram is worth many paragraphs
|
||||||
|
- **Do explore the codebase** - Ground discussions in reality
|
||||||
|
- **Do question assumptions** - Including the user's and your own
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
---
|
||||||
|
name: openspec-ff-change
|
||||||
|
description: Fast-forward through OpenSpec artifact creation. Use when the user wants to quickly create all artifacts needed for implementation without stepping through each one individually.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Fast-forward through artifact creation - generate everything needed to start implementation in one go.
|
||||||
|
|
||||||
|
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no clear input provided, ask what they want to build**
|
||||||
|
|
||||||
|
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||||
|
> "What change do you want to work on? Describe what you want to build or fix."
|
||||||
|
|
||||||
|
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||||
|
|
||||||
|
2. **Create the change directory**
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>"
|
||||||
|
```
|
||||||
|
This creates a scaffolded change at `openspec/changes/<name>/`.
|
||||||
|
|
||||||
|
3. **Get the artifact build order**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to get:
|
||||||
|
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
|
||||||
|
- `artifacts`: list of all artifacts with their status and dependencies
|
||||||
|
|
||||||
|
4. **Create artifacts in sequence until apply-ready**
|
||||||
|
|
||||||
|
Use the **TodoWrite tool** to track progress through the artifacts.
|
||||||
|
|
||||||
|
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
|
||||||
|
|
||||||
|
a. **For each artifact that is `ready` (dependencies satisfied)**:
|
||||||
|
- Get instructions:
|
||||||
|
```bash
|
||||||
|
openspec instructions <artifact-id> --change "<name>" --json
|
||||||
|
```
|
||||||
|
- The instructions JSON includes:
|
||||||
|
- `context`: Project background (constraints for you - do NOT include in output)
|
||||||
|
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
|
||||||
|
- `template`: The structure to use for your output file
|
||||||
|
- `instruction`: Schema-specific guidance for this artifact type
|
||||||
|
- `outputPath`: Where to write the artifact
|
||||||
|
- `dependencies`: Completed artifacts to read for context
|
||||||
|
- Read any completed dependency files for context
|
||||||
|
- Create the artifact file using `template` as the structure
|
||||||
|
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||||
|
- Show brief progress: "✓ Created <artifact-id>"
|
||||||
|
|
||||||
|
b. **Continue until all `applyRequires` artifacts are complete**
|
||||||
|
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||||
|
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||||
|
- Stop when all `applyRequires` artifacts are done
|
||||||
|
|
||||||
|
c. **If an artifact requires user input** (unclear context):
|
||||||
|
- Use **AskUserQuestion tool** to clarify
|
||||||
|
- Then continue with creation
|
||||||
|
|
||||||
|
5. **Show final status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After completing all artifacts, summarize:
|
||||||
|
- Change name and location
|
||||||
|
- List of artifacts created with brief descriptions
|
||||||
|
- What's ready: "All artifacts created! Ready for implementation."
|
||||||
|
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
|
||||||
|
|
||||||
|
**Artifact Creation Guidelines**
|
||||||
|
|
||||||
|
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||||
|
- The schema defines what each artifact should contain - follow it
|
||||||
|
- Read dependency artifacts for context before creating new ones
|
||||||
|
- Use `template` as the structure for your output file - fill in its sections
|
||||||
|
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
|
||||||
|
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
|
||||||
|
- These guide what you write, but should never appear in the output
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||||
|
- Always read dependency artifacts before creating a new one
|
||||||
|
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
|
||||||
|
- If a change with that name already exists, suggest continuing that change instead
|
||||||
|
- Verify each artifact file exists after writing before proceeding to next
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
---
|
||||||
|
name: openspec-new-change
|
||||||
|
description: Start a new OpenSpec change using the experimental artifact workflow. Use when the user wants to create a new feature, fix, or modification with a structured step-by-step approach.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Start a new change using the experimental artifact-driven approach.
|
||||||
|
|
||||||
|
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no clear input provided, ask what they want to build**
|
||||||
|
|
||||||
|
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||||
|
> "What change do you want to work on? Describe what you want to build or fix."
|
||||||
|
|
||||||
|
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
|
||||||
|
|
||||||
|
2. **Determine the workflow schema**
|
||||||
|
|
||||||
|
Use the default schema (omit `--schema`) unless the user explicitly requests a different workflow.
|
||||||
|
|
||||||
|
**Use a different schema only if the user mentions:**
|
||||||
|
- A specific schema name → use `--schema <name>`
|
||||||
|
- "show workflows" or "what workflows" → run `openspec schemas --json` and let them choose
|
||||||
|
|
||||||
|
**Otherwise**: Omit `--schema` to use the default.
|
||||||
|
|
||||||
|
3. **Create the change directory**
|
||||||
|
```bash
|
||||||
|
openspec new change "<name>"
|
||||||
|
```
|
||||||
|
Add `--schema <name>` only if the user requested a specific workflow.
|
||||||
|
This creates a scaffolded change at `openspec/changes/<name>/` with the selected schema.
|
||||||
|
|
||||||
|
4. **Show the artifact status**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>"
|
||||||
|
```
|
||||||
|
This shows which artifacts need to be created and which are ready (dependencies satisfied).
|
||||||
|
|
||||||
|
5. **Get instructions for the first artifact**
|
||||||
|
The first artifact depends on the schema (e.g., `proposal` for spec-driven).
|
||||||
|
Check the status output to find the first artifact with status "ready".
|
||||||
|
```bash
|
||||||
|
openspec instructions <first-artifact-id> --change "<name>"
|
||||||
|
```
|
||||||
|
This outputs the template and context for creating the first artifact.
|
||||||
|
|
||||||
|
6. **STOP and wait for user direction**
|
||||||
|
|
||||||
|
**Output**
|
||||||
|
|
||||||
|
After completing the steps, summarize:
|
||||||
|
- Change name and location
|
||||||
|
- Schema/workflow being used and its artifact sequence
|
||||||
|
- Current status (0/N artifacts complete)
|
||||||
|
- The template for the first artifact
|
||||||
|
- Prompt: "Ready to create the first artifact? Just describe what this change is about and I'll draft it, or ask me to continue."
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Do NOT create any artifacts yet - just show the instructions
|
||||||
|
- Do NOT advance beyond showing the first artifact template
|
||||||
|
- If the name is invalid (not kebab-case), ask for a valid name
|
||||||
|
- If a change with that name already exists, suggest continuing that change instead
|
||||||
|
- Pass --schema if using a non-default workflow
|
||||||
@@ -0,0 +1,529 @@
|
|||||||
|
---
|
||||||
|
name: openspec-onboard
|
||||||
|
description: Guided onboarding for OpenSpec - walk through a complete workflow cycle with narration and real codebase work.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Guide the user through their first complete OpenSpec workflow cycle. This is a teaching experience—you'll do real work in their codebase while explaining each step.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Preflight
|
||||||
|
|
||||||
|
Before starting, check if OpenSpec is initialized:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec status --json 2>&1 || echo "NOT_INITIALIZED"
|
||||||
|
```
|
||||||
|
|
||||||
|
**If not initialized:**
|
||||||
|
> OpenSpec isn't set up in this project yet. Run `openspec init` first, then come back to `/opsx:onboard`.
|
||||||
|
|
||||||
|
Stop here if not initialized.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 1: Welcome
|
||||||
|
|
||||||
|
Display:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Welcome to OpenSpec!
|
||||||
|
|
||||||
|
I'll walk you through a complete change cycle—from idea to implementation—using a real task in your codebase. Along the way, you'll learn the workflow by doing it.
|
||||||
|
|
||||||
|
**What we'll do:**
|
||||||
|
1. Pick a small, real task in your codebase
|
||||||
|
2. Explore the problem briefly
|
||||||
|
3. Create a change (the container for our work)
|
||||||
|
4. Build the artifacts: proposal → specs → design → tasks
|
||||||
|
5. Implement the tasks
|
||||||
|
6. Archive the completed change
|
||||||
|
|
||||||
|
**Time:** ~15-20 minutes
|
||||||
|
|
||||||
|
Let's start by finding something to work on.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 2: Task Selection
|
||||||
|
|
||||||
|
### Codebase Analysis
|
||||||
|
|
||||||
|
Scan the codebase for small improvement opportunities. Look for:
|
||||||
|
|
||||||
|
1. **TODO/FIXME comments** - Search for `TODO`, `FIXME`, `HACK`, `XXX` in code files
|
||||||
|
2. **Missing error handling** - `catch` blocks that swallow errors, risky operations without try-catch
|
||||||
|
3. **Functions without tests** - Cross-reference `src/` with test directories
|
||||||
|
4. **Type issues** - `any` types in TypeScript files (`: any`, `as any`)
|
||||||
|
5. **Debug artifacts** - `console.log`, `console.debug`, `debugger` statements in non-debug code
|
||||||
|
6. **Missing validation** - User input handlers without validation
|
||||||
|
|
||||||
|
Also check recent git activity:
|
||||||
|
```bash
|
||||||
|
git log --oneline -10 2>/dev/null || echo "No git history"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Present Suggestions
|
||||||
|
|
||||||
|
From your analysis, present 3-4 specific suggestions:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Task Suggestions
|
||||||
|
|
||||||
|
Based on scanning your codebase, here are some good starter tasks:
|
||||||
|
|
||||||
|
**1. [Most promising task]**
|
||||||
|
Location: `src/path/to/file.ts:42`
|
||||||
|
Scope: ~1-2 files, ~20-30 lines
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**2. [Second task]**
|
||||||
|
Location: `src/another/file.ts`
|
||||||
|
Scope: ~1 file, ~15 lines
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**3. [Third task]**
|
||||||
|
Location: [location]
|
||||||
|
Scope: [estimate]
|
||||||
|
Why it's good: [brief reason]
|
||||||
|
|
||||||
|
**4. Something else?**
|
||||||
|
Tell me what you'd like to work on.
|
||||||
|
|
||||||
|
Which task interests you? (Pick a number or describe your own)
|
||||||
|
```
|
||||||
|
|
||||||
|
**If nothing found:** Fall back to asking what the user wants to build:
|
||||||
|
> I didn't find obvious quick wins in your codebase. What's something small you've been meaning to add or fix?
|
||||||
|
|
||||||
|
### Scope Guardrail
|
||||||
|
|
||||||
|
If the user picks or describes something too large (major feature, multi-day work):
|
||||||
|
|
||||||
|
```
|
||||||
|
That's a valuable task, but it's probably larger than ideal for your first OpenSpec run-through.
|
||||||
|
|
||||||
|
For learning the workflow, smaller is better—it lets you see the full cycle without getting stuck in implementation details.
|
||||||
|
|
||||||
|
**Options:**
|
||||||
|
1. **Slice it smaller** - What's the smallest useful piece of [their task]? Maybe just [specific slice]?
|
||||||
|
2. **Pick something else** - One of the other suggestions, or a different small task?
|
||||||
|
3. **Do it anyway** - If you really want to tackle this, we can. Just know it'll take longer.
|
||||||
|
|
||||||
|
What would you prefer?
|
||||||
|
```
|
||||||
|
|
||||||
|
Let the user override if they insist—this is a soft guardrail.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3: Explore Demo
|
||||||
|
|
||||||
|
Once a task is selected, briefly demonstrate explore mode:
|
||||||
|
|
||||||
|
```
|
||||||
|
Before we create a change, let me quickly show you **explore mode**—it's how you think through problems before committing to a direction.
|
||||||
|
```
|
||||||
|
|
||||||
|
Spend 1-2 minutes investigating the relevant code:
|
||||||
|
- Read the file(s) involved
|
||||||
|
- Draw a quick ASCII diagram if it helps
|
||||||
|
- Note any considerations
|
||||||
|
|
||||||
|
```
|
||||||
|
## Quick Exploration
|
||||||
|
|
||||||
|
[Your brief analysis—what you found, any considerations]
|
||||||
|
|
||||||
|
┌─────────────────────────────────────────┐
|
||||||
|
│ [Optional: ASCII diagram if helpful] │
|
||||||
|
└─────────────────────────────────────────┘
|
||||||
|
|
||||||
|
Explore mode (`/opsx:explore`) is for this kind of thinking—investigating before implementing. You can use it anytime you need to think through a problem.
|
||||||
|
|
||||||
|
Now let's create a change to hold our work.
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user acknowledgment before proceeding.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 4: Create the Change
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Creating a Change
|
||||||
|
|
||||||
|
A "change" in OpenSpec is a container for all the thinking and planning around a piece of work. It lives in `openspec/changes/<name>/` and holds your artifacts—proposal, specs, design, tasks.
|
||||||
|
|
||||||
|
Let me create one for our task.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Create the change with a derived kebab-case name:
|
||||||
|
```bash
|
||||||
|
openspec new change "<derived-name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**SHOW:**
|
||||||
|
```
|
||||||
|
Created: `openspec/changes/<name>/`
|
||||||
|
|
||||||
|
The folder structure:
|
||||||
|
```
|
||||||
|
openspec/changes/<name>/
|
||||||
|
├── proposal.md ← Why we're doing this (empty, we'll fill it)
|
||||||
|
├── design.md ← How we'll build it (empty)
|
||||||
|
├── specs/ ← Detailed requirements (empty)
|
||||||
|
└── tasks.md ← Implementation checklist (empty)
|
||||||
|
```
|
||||||
|
|
||||||
|
Now let's fill in the first artifact—the proposal.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 5: Proposal
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## The Proposal
|
||||||
|
|
||||||
|
The proposal captures **why** we're making this change and **what** it involves at a high level. It's the "elevator pitch" for the work.
|
||||||
|
|
||||||
|
I'll draft one based on our task.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Draft the proposal content (don't save yet):
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's a draft proposal:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
[1-2 sentences explaining the problem/opportunity]
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
[Bullet points of what will be different]
|
||||||
|
|
||||||
|
## Capabilities
|
||||||
|
|
||||||
|
### New Capabilities
|
||||||
|
- `<capability-name>`: [brief description]
|
||||||
|
|
||||||
|
### Modified Capabilities
|
||||||
|
<!-- If modifying existing behavior -->
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
|
||||||
|
- `src/path/to/file.ts`: [what changes]
|
||||||
|
- [other files if applicable]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Does this capture the intent? I can adjust before we save it.
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user approval/feedback.
|
||||||
|
|
||||||
|
After approval, save the proposal:
|
||||||
|
```bash
|
||||||
|
openspec instructions proposal --change "<name>" --json
|
||||||
|
```
|
||||||
|
Then write the content to `openspec/changes/<name>/proposal.md`.
|
||||||
|
|
||||||
|
```
|
||||||
|
Proposal saved. This is your "why" document—you can always come back and refine it as understanding evolves.
|
||||||
|
|
||||||
|
Next up: specs.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 6: Specs
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Specs
|
||||||
|
|
||||||
|
Specs define **what** we're building in precise, testable terms. They use a requirement/scenario format that makes expected behavior crystal clear.
|
||||||
|
|
||||||
|
For a small task like this, we might only need one spec file.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Create the spec file:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/<name>/specs/<capability-name>
|
||||||
|
```
|
||||||
|
|
||||||
|
Draft the spec content:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's the spec:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: <Name>
|
||||||
|
|
||||||
|
<Description of what the system should do>
|
||||||
|
|
||||||
|
#### Scenario: <Scenario name>
|
||||||
|
|
||||||
|
- **WHEN** <trigger condition>
|
||||||
|
- **THEN** <expected outcome>
|
||||||
|
- **AND** <additional outcome if needed>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
This format—WHEN/THEN/AND—makes requirements testable. You can literally read them as test cases.
|
||||||
|
```
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/specs/<capability>/spec.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 7: Design
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Design
|
||||||
|
|
||||||
|
The design captures **how** we'll build it—technical decisions, tradeoffs, approach.
|
||||||
|
|
||||||
|
For small changes, this might be brief. That's fine—not every change needs deep design discussion.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Draft design.md:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here's the design:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
[Brief context about the current state]
|
||||||
|
|
||||||
|
## Goals / Non-Goals
|
||||||
|
|
||||||
|
**Goals:**
|
||||||
|
- [What we're trying to achieve]
|
||||||
|
|
||||||
|
**Non-Goals:**
|
||||||
|
- [What's explicitly out of scope]
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
### Decision 1: [Key decision]
|
||||||
|
|
||||||
|
[Explanation of approach and rationale]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For a small task, this captures the key decisions without over-engineering.
|
||||||
|
```
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/design.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 8: Tasks
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
Finally, we break the work into implementation tasks—checkboxes that drive the apply phase.
|
||||||
|
|
||||||
|
These should be small, clear, and in logical order.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** Generate tasks based on specs and design:
|
||||||
|
|
||||||
|
```
|
||||||
|
Here are the implementation tasks:
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. [Category or file]
|
||||||
|
|
||||||
|
- [ ] 1.1 [Specific task]
|
||||||
|
- [ ] 1.2 [Specific task]
|
||||||
|
|
||||||
|
## 2. Verify
|
||||||
|
|
||||||
|
- [ ] 2.1 [Verification step]
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Each checkbox becomes a unit of work in the apply phase. Ready to implement?
|
||||||
|
```
|
||||||
|
|
||||||
|
**PAUSE** - Wait for user to confirm they're ready to implement.
|
||||||
|
|
||||||
|
Save to `openspec/changes/<name>/tasks.md`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 9: Apply (Implementation)
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Implementation
|
||||||
|
|
||||||
|
Now we implement each task, checking them off as we go. I'll announce each one and occasionally note how the specs/design informed the approach.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:** For each task:
|
||||||
|
|
||||||
|
1. Announce: "Working on task N: [description]"
|
||||||
|
2. Implement the change in the codebase
|
||||||
|
3. Reference specs/design naturally: "The spec says X, so I'm doing Y"
|
||||||
|
4. Mark complete in tasks.md: `- [ ]` → `- [x]`
|
||||||
|
5. Brief status: "✓ Task N complete"
|
||||||
|
|
||||||
|
Keep narration light—don't over-explain every line of code.
|
||||||
|
|
||||||
|
After all tasks:
|
||||||
|
|
||||||
|
```
|
||||||
|
## Implementation Complete
|
||||||
|
|
||||||
|
All tasks done:
|
||||||
|
- [x] Task 1
|
||||||
|
- [x] Task 2
|
||||||
|
- [x] ...
|
||||||
|
|
||||||
|
The change is implemented! One more step—let's archive it.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 10: Archive
|
||||||
|
|
||||||
|
**EXPLAIN:**
|
||||||
|
```
|
||||||
|
## Archiving
|
||||||
|
|
||||||
|
When a change is complete, we archive it. This moves it from `openspec/changes/` to `openspec/changes/archive/YYYY-MM-DD-<name>/`.
|
||||||
|
|
||||||
|
Archived changes become your project's decision history—you can always find them later to understand why something was built a certain way.
|
||||||
|
```
|
||||||
|
|
||||||
|
**DO:**
|
||||||
|
```bash
|
||||||
|
openspec archive "<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**SHOW:**
|
||||||
|
```
|
||||||
|
Archived to: `openspec/changes/archive/YYYY-MM-DD-<name>/`
|
||||||
|
|
||||||
|
The change is now part of your project's history. The code is in your codebase, the decision record is preserved.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 11: Recap & Next Steps
|
||||||
|
|
||||||
|
```
|
||||||
|
## Congratulations!
|
||||||
|
|
||||||
|
You just completed a full OpenSpec cycle:
|
||||||
|
|
||||||
|
1. **Explore** - Thought through the problem
|
||||||
|
2. **New** - Created a change container
|
||||||
|
3. **Proposal** - Captured WHY
|
||||||
|
4. **Specs** - Defined WHAT in detail
|
||||||
|
5. **Design** - Decided HOW
|
||||||
|
6. **Tasks** - Broke it into steps
|
||||||
|
7. **Apply** - Implemented the work
|
||||||
|
8. **Archive** - Preserved the record
|
||||||
|
|
||||||
|
This same rhythm works for any size change—a small fix or a major feature.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Command Reference
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
|---------|--------------|
|
||||||
|
| `/opsx:explore` | Think through problems before/during work |
|
||||||
|
| `/opsx:new` | Start a new change, step through artifacts |
|
||||||
|
| `/opsx:ff` | Fast-forward: create all artifacts at once |
|
||||||
|
| `/opsx:continue` | Continue working on an existing change |
|
||||||
|
| `/opsx:apply` | Implement tasks from a change |
|
||||||
|
| `/opsx:verify` | Verify implementation matches artifacts |
|
||||||
|
| `/opsx:archive` | Archive a completed change |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What's Next?
|
||||||
|
|
||||||
|
Try `/opsx:new` or `/opsx:ff` on something you actually want to build. You've got the rhythm now!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Graceful Exit Handling
|
||||||
|
|
||||||
|
### User wants to stop mid-way
|
||||||
|
|
||||||
|
If the user says they need to stop, want to pause, or seem disengaged:
|
||||||
|
|
||||||
|
```
|
||||||
|
No problem! Your change is saved at `openspec/changes/<name>/`.
|
||||||
|
|
||||||
|
To pick up where we left off later:
|
||||||
|
- `/opsx:continue <name>` - Resume artifact creation
|
||||||
|
- `/opsx:apply <name>` - Jump to implementation (if tasks exist)
|
||||||
|
|
||||||
|
The work won't be lost. Come back whenever you're ready.
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit gracefully without pressure.
|
||||||
|
|
||||||
|
### User just wants command reference
|
||||||
|
|
||||||
|
If the user says they just want to see the commands or skip the tutorial:
|
||||||
|
|
||||||
|
```
|
||||||
|
## OpenSpec Quick Reference
|
||||||
|
|
||||||
|
| Command | What it does |
|
||||||
|
|---------|--------------|
|
||||||
|
| `/opsx:explore` | Think through problems (no code changes) |
|
||||||
|
| `/opsx:new <name>` | Start a new change, step by step |
|
||||||
|
| `/opsx:ff <name>` | Fast-forward: all artifacts at once |
|
||||||
|
| `/opsx:continue <name>` | Continue an existing change |
|
||||||
|
| `/opsx:apply <name>` | Implement tasks |
|
||||||
|
| `/opsx:verify <name>` | Verify implementation |
|
||||||
|
| `/opsx:archive <name>` | Archive when done |
|
||||||
|
|
||||||
|
Try `/opsx:new` to start your first change, or `/opsx:ff` if you want to move fast.
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit gracefully.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Guardrails
|
||||||
|
|
||||||
|
- **Follow the EXPLAIN → DO → SHOW → PAUSE pattern** at key transitions (after explore, after proposal draft, after tasks, after archive)
|
||||||
|
- **Keep narration light** during implementation—teach without lecturing
|
||||||
|
- **Don't skip phases** even if the change is small—the goal is teaching the workflow
|
||||||
|
- **Pause for acknowledgment** at marked points, but don't over-pause
|
||||||
|
- **Handle exits gracefully**—never pressure the user to continue
|
||||||
|
- **Use real codebase tasks**—don't simulate or use fake examples
|
||||||
|
- **Adjust scope gently**—guide toward smaller tasks but respect user choice
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
---
|
||||||
|
name: openspec-sync-specs
|
||||||
|
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Sync delta specs from a change to main specs.
|
||||||
|
|
||||||
|
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show changes that have delta specs (under `specs/` directory).
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Find delta specs**
|
||||||
|
|
||||||
|
Look for delta spec files in `openspec/changes/<name>/specs/*/spec.md`.
|
||||||
|
|
||||||
|
Each delta spec file contains sections like:
|
||||||
|
- `## ADDED Requirements` - New requirements to add
|
||||||
|
- `## MODIFIED Requirements` - Changes to existing requirements
|
||||||
|
- `## REMOVED Requirements` - Requirements to remove
|
||||||
|
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
|
||||||
|
|
||||||
|
If no delta specs found, inform user and stop.
|
||||||
|
|
||||||
|
3. **For each delta spec, apply changes to main specs**
|
||||||
|
|
||||||
|
For each capability with a delta spec at `openspec/changes/<name>/specs/<capability>/spec.md`:
|
||||||
|
|
||||||
|
a. **Read the delta spec** to understand the intended changes
|
||||||
|
|
||||||
|
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
|
||||||
|
|
||||||
|
c. **Apply changes intelligently**:
|
||||||
|
|
||||||
|
**ADDED Requirements:**
|
||||||
|
- If requirement doesn't exist in main spec → add it
|
||||||
|
- If requirement already exists → update it to match (treat as implicit MODIFIED)
|
||||||
|
|
||||||
|
**MODIFIED Requirements:**
|
||||||
|
- Find the requirement in main spec
|
||||||
|
- Apply the changes - this can be:
|
||||||
|
- Adding new scenarios (don't need to copy existing ones)
|
||||||
|
- Modifying existing scenarios
|
||||||
|
- Changing the requirement description
|
||||||
|
- Preserve scenarios/content not mentioned in the delta
|
||||||
|
|
||||||
|
**REMOVED Requirements:**
|
||||||
|
- Remove the entire requirement block from main spec
|
||||||
|
|
||||||
|
**RENAMED Requirements:**
|
||||||
|
- Find the FROM requirement, rename to TO
|
||||||
|
|
||||||
|
d. **Create new main spec** if capability doesn't exist yet:
|
||||||
|
- Create `openspec/specs/<capability>/spec.md`
|
||||||
|
- Add Purpose section (can be brief, mark as TBD)
|
||||||
|
- Add Requirements section with the ADDED requirements
|
||||||
|
|
||||||
|
4. **Show summary**
|
||||||
|
|
||||||
|
After applying all changes, summarize:
|
||||||
|
- Which capabilities were updated
|
||||||
|
- What changes were made (requirements added/modified/removed/renamed)
|
||||||
|
|
||||||
|
**Delta Spec Format Reference**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: New Feature
|
||||||
|
The system SHALL do something new.
|
||||||
|
|
||||||
|
#### Scenario: Basic case
|
||||||
|
- **WHEN** user does X
|
||||||
|
- **THEN** system does Y
|
||||||
|
|
||||||
|
## MODIFIED Requirements
|
||||||
|
|
||||||
|
### Requirement: Existing Feature
|
||||||
|
#### Scenario: New scenario to add
|
||||||
|
- **WHEN** user does A
|
||||||
|
- **THEN** system does B
|
||||||
|
|
||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: Deprecated Feature
|
||||||
|
|
||||||
|
## RENAMED Requirements
|
||||||
|
|
||||||
|
- FROM: `### Requirement: Old Name`
|
||||||
|
- TO: `### Requirement: New Name`
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Principle: Intelligent Merging**
|
||||||
|
|
||||||
|
Unlike programmatic merging, you can apply **partial updates**:
|
||||||
|
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
|
||||||
|
- The delta represents *intent*, not a wholesale replacement
|
||||||
|
- Use your judgment to merge changes sensibly
|
||||||
|
|
||||||
|
**Output On Success**
|
||||||
|
|
||||||
|
```
|
||||||
|
## Specs Synced: <change-name>
|
||||||
|
|
||||||
|
Updated main specs:
|
||||||
|
|
||||||
|
**<capability-1>**:
|
||||||
|
- Added requirement: "New Feature"
|
||||||
|
- Modified requirement: "Existing Feature" (added 1 scenario)
|
||||||
|
|
||||||
|
**<capability-2>**:
|
||||||
|
- Created new spec file
|
||||||
|
- Added requirement: "Another Feature"
|
||||||
|
|
||||||
|
Main specs are now updated. The change remains active - archive when implementation is complete.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Guardrails**
|
||||||
|
- Read both delta and main specs before making changes
|
||||||
|
- Preserve existing content not mentioned in delta
|
||||||
|
- If something is unclear, ask for clarification
|
||||||
|
- Show what you're changing as you go
|
||||||
|
- The operation should be idempotent - running twice should give same result
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
---
|
||||||
|
name: openspec-verify-change
|
||||||
|
description: Verify implementation matches change artifacts. Use when the user wants to validate that implementation is complete, correct, and coherent before archiving.
|
||||||
|
license: MIT
|
||||||
|
compatibility: Requires openspec CLI.
|
||||||
|
metadata:
|
||||||
|
author: openspec
|
||||||
|
version: "1.0"
|
||||||
|
generatedBy: "1.1.1"
|
||||||
|
---
|
||||||
|
|
||||||
|
Verify that an implementation matches the change artifacts (specs, tasks, design).
|
||||||
|
|
||||||
|
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||||
|
|
||||||
|
**Steps**
|
||||||
|
|
||||||
|
1. **If no change name provided, prompt for selection**
|
||||||
|
|
||||||
|
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||||
|
|
||||||
|
Show changes that have implementation tasks (tasks artifact exists).
|
||||||
|
Include the schema used for each change if available.
|
||||||
|
Mark changes with incomplete tasks as "(In Progress)".
|
||||||
|
|
||||||
|
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||||
|
|
||||||
|
2. **Check status to understand the schema**
|
||||||
|
```bash
|
||||||
|
openspec status --change "<name>" --json
|
||||||
|
```
|
||||||
|
Parse the JSON to understand:
|
||||||
|
- `schemaName`: The workflow being used (e.g., "spec-driven")
|
||||||
|
- Which artifacts exist for this change
|
||||||
|
|
||||||
|
3. **Get the change directory and load artifacts**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openspec instructions apply --change "<name>" --json
|
||||||
|
```
|
||||||
|
|
||||||
|
This returns the change directory and context files. Read all available artifacts from `contextFiles`.
|
||||||
|
|
||||||
|
4. **Initialize verification report structure**
|
||||||
|
|
||||||
|
Create a report structure with three dimensions:
|
||||||
|
- **Completeness**: Track tasks and spec coverage
|
||||||
|
- **Correctness**: Track requirement implementation and scenario coverage
|
||||||
|
- **Coherence**: Track design adherence and pattern consistency
|
||||||
|
|
||||||
|
Each dimension can have CRITICAL, WARNING, or SUGGESTION issues.
|
||||||
|
|
||||||
|
5. **Verify Completeness**
|
||||||
|
|
||||||
|
**Task Completion**:
|
||||||
|
- If tasks.md exists in contextFiles, read it
|
||||||
|
- Parse checkboxes: `- [ ]` (incomplete) vs `- [x]` (complete)
|
||||||
|
- Count complete vs total tasks
|
||||||
|
- If incomplete tasks exist:
|
||||||
|
- Add CRITICAL issue for each incomplete task
|
||||||
|
- Recommendation: "Complete task: <description>" or "Mark as done if already implemented"
|
||||||
|
|
||||||
|
**Spec Coverage**:
|
||||||
|
- If delta specs exist in `openspec/changes/<name>/specs/`:
|
||||||
|
- Extract all requirements (marked with "### Requirement:")
|
||||||
|
- For each requirement:
|
||||||
|
- Search codebase for keywords related to the requirement
|
||||||
|
- Assess if implementation likely exists
|
||||||
|
- If requirements appear unimplemented:
|
||||||
|
- Add CRITICAL issue: "Requirement not found: <requirement name>"
|
||||||
|
- Recommendation: "Implement requirement X: <description>"
|
||||||
|
|
||||||
|
6. **Verify Correctness**
|
||||||
|
|
||||||
|
**Requirement Implementation Mapping**:
|
||||||
|
- For each requirement from delta specs:
|
||||||
|
- Search codebase for implementation evidence
|
||||||
|
- If found, note file paths and line ranges
|
||||||
|
- Assess if implementation matches requirement intent
|
||||||
|
- If divergence detected:
|
||||||
|
- Add WARNING: "Implementation may diverge from spec: <details>"
|
||||||
|
- Recommendation: "Review <file>:<lines> against requirement X"
|
||||||
|
|
||||||
|
**Scenario Coverage**:
|
||||||
|
- For each scenario in delta specs (marked with "#### Scenario:"):
|
||||||
|
- Check if conditions are handled in code
|
||||||
|
- Check if tests exist covering the scenario
|
||||||
|
- If scenario appears uncovered:
|
||||||
|
- Add WARNING: "Scenario not covered: <scenario name>"
|
||||||
|
- Recommendation: "Add test or implementation for scenario: <description>"
|
||||||
|
|
||||||
|
7. **Verify Coherence**
|
||||||
|
|
||||||
|
**Design Adherence**:
|
||||||
|
- If design.md exists in contextFiles:
|
||||||
|
- Extract key decisions (look for sections like "Decision:", "Approach:", "Architecture:")
|
||||||
|
- Verify implementation follows those decisions
|
||||||
|
- If contradiction detected:
|
||||||
|
- Add WARNING: "Design decision not followed: <decision>"
|
||||||
|
- Recommendation: "Update implementation or revise design.md to match reality"
|
||||||
|
- If no design.md: Skip design adherence check, note "No design.md to verify against"
|
||||||
|
|
||||||
|
**Code Pattern Consistency**:
|
||||||
|
- Review new code for consistency with project patterns
|
||||||
|
- Check file naming, directory structure, coding style
|
||||||
|
- If significant deviations found:
|
||||||
|
- Add SUGGESTION: "Code pattern deviation: <details>"
|
||||||
|
- Recommendation: "Consider following project pattern: <example>"
|
||||||
|
|
||||||
|
8. **Generate Verification Report**
|
||||||
|
|
||||||
|
**Summary Scorecard**:
|
||||||
|
```
|
||||||
|
## Verification Report: <change-name>
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
| Dimension | Status |
|
||||||
|
|--------------|------------------|
|
||||||
|
| Completeness | X/Y tasks, N reqs|
|
||||||
|
| Correctness | M/N reqs covered |
|
||||||
|
| Coherence | Followed/Issues |
|
||||||
|
```
|
||||||
|
|
||||||
|
**Issues by Priority**:
|
||||||
|
|
||||||
|
1. **CRITICAL** (Must fix before archive):
|
||||||
|
- Incomplete tasks
|
||||||
|
- Missing requirement implementations
|
||||||
|
- Each with specific, actionable recommendation
|
||||||
|
|
||||||
|
2. **WARNING** (Should fix):
|
||||||
|
- Spec/design divergences
|
||||||
|
- Missing scenario coverage
|
||||||
|
- Each with specific recommendation
|
||||||
|
|
||||||
|
3. **SUGGESTION** (Nice to fix):
|
||||||
|
- Pattern inconsistencies
|
||||||
|
- Minor improvements
|
||||||
|
- Each with specific recommendation
|
||||||
|
|
||||||
|
**Final Assessment**:
|
||||||
|
- If CRITICAL issues: "X critical issue(s) found. Fix before archiving."
|
||||||
|
- If only warnings: "No critical issues. Y warning(s) to consider. Ready for archive (with noted improvements)."
|
||||||
|
- If all clear: "All checks passed. Ready for archive."
|
||||||
|
|
||||||
|
**Verification Heuristics**
|
||||||
|
|
||||||
|
- **Completeness**: Focus on objective checklist items (checkboxes, requirements list)
|
||||||
|
- **Correctness**: Use keyword search, file path analysis, reasonable inference - don't require perfect certainty
|
||||||
|
- **Coherence**: Look for glaring inconsistencies, don't nitpick style
|
||||||
|
- **False Positives**: When uncertain, prefer SUGGESTION over WARNING, WARNING over CRITICAL
|
||||||
|
- **Actionability**: Every issue must have a specific recommendation with file/line references where applicable
|
||||||
|
|
||||||
|
**Graceful Degradation**
|
||||||
|
|
||||||
|
- If only tasks.md exists: verify task completion only, skip spec/design checks
|
||||||
|
- If tasks + specs exist: verify completeness and correctness, skip design
|
||||||
|
- If full artifacts: verify all three dimensions
|
||||||
|
- Always note which checks were skipped and why
|
||||||
|
|
||||||
|
**Output Format**
|
||||||
|
|
||||||
|
Use clear markdown with:
|
||||||
|
- Table for summary scorecard
|
||||||
|
- Grouped lists for issues (CRITICAL/WARNING/SUGGESTION)
|
||||||
|
- Code references in format: `file.ts:123`
|
||||||
|
- Specific, actionable recommendations
|
||||||
|
- No vague suggestions like "consider reviewing"
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
*.o
|
||||||
|
*.d
|
||||||
|
obj/
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<projectDescription>
|
||||||
|
<name>SealCheck</name>
|
||||||
|
<comment></comment>
|
||||||
|
<projects>
|
||||||
|
</projects>
|
||||||
|
<buildSpec>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
|
||||||
|
<triggers>clean,full,incremental,</triggers>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
|
<buildCommand>
|
||||||
|
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
|
||||||
|
<triggers>full,incremental,</triggers>
|
||||||
|
<arguments>
|
||||||
|
</arguments>
|
||||||
|
</buildCommand>
|
||||||
|
</buildSpec>
|
||||||
|
<natures>
|
||||||
|
<nature>org.eclipse.cdt.core.cnature</nature>
|
||||||
|
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
|
||||||
|
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
|
||||||
|
</natures>
|
||||||
|
</projectDescription>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<project>
|
||||||
|
<configuration id="ilg.gnumcueclipse.managedbuild.cross.riscv.config.elf.release.1008047074" name="obj">
|
||||||
|
<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
|
||||||
|
<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
|
||||||
|
<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
|
||||||
|
<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
|
||||||
|
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="false" env-hash="1474445554347202125" id="ilg.gnumcueclipse.managedbuild.cross.riscv.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT RISC-V Cross GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} ${cross_toolchain_flags} -E -P -v -dD "${INPUTS}"" prefer-non-shared="true">
|
||||||
|
<language-scope id="org.eclipse.cdt.core.gcc"/>
|
||||||
|
<language-scope id="org.eclipse.cdt.core.g++"/>
|
||||||
|
</provider>
|
||||||
|
</extension>
|
||||||
|
</configuration>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
eclipse.preferences.version=1
|
||||||
|
org.eclipse.cdt.codan.checkers.errnoreturn=Warning
|
||||||
|
org.eclipse.cdt.codan.checkers.errnoreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return\\")",implicit\=>false}
|
||||||
|
org.eclipse.cdt.codan.checkers.errreturnvalue=Error
|
||||||
|
org.eclipse.cdt.codan.checkers.errreturnvalue.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused return value\\")"}
|
||||||
|
org.eclipse.cdt.codan.checkers.nocommentinside=-Error
|
||||||
|
org.eclipse.cdt.codan.checkers.nocommentinside.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Nesting comments\\")"}
|
||||||
|
org.eclipse.cdt.codan.checkers.nolinecomment=-Error
|
||||||
|
org.eclipse.cdt.codan.checkers.nolinecomment.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Line comments\\")"}
|
||||||
|
org.eclipse.cdt.codan.checkers.noreturn=Error
|
||||||
|
org.eclipse.cdt.codan.checkers.noreturn.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No return value\\")",implicit\=>false}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AbstractClassCreation.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Abstract class cannot be instantiated\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AmbiguousProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Ambiguous problem\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AssignmentInConditionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment in condition\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.AssignmentToItselfProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Assignment to itself\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CaseBreakProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"No break at end of case\\")",no_break_comment\=>"no break",last_case_param\=>false,empty_case_param\=>false,enable_fallthrough_quickfix_param\=>false}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CatchByReference=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CatchByReference.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Catching by reference is recommended\\")",unknown\=>false,exceptions\=>()}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.CircularReferenceProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Circular inheritance\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ClassMembersInitialization.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class members should be properly initialized\\")",skip\=>true}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.DecltypeAutoProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid 'decltype(auto)' specifier\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.FieldResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"\u5B57\u6BB5\u65E0\u6CD5\u88AB\u89E3\u6790\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.FunctionResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"\u51FD\u6570\u65E0\u6CD5\u88AB\u89E3\u6790\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.InvalidArguments=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.InvalidArguments.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"\u65E0\u6548\u53C2\u6570\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.InvalidTemplateArgumentsProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid template argument\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.LabelStatementNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Label statement not found\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.MemberDeclarationNotFoundProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Member declaration not found\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.MethodResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"\u65B9\u6CD5\u65E0\u6CD5\u88AB\u89E3\u6790\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker=-Info
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.NamingConventionFunctionChecker.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Name convention for function\\")",pattern\=>"^[a-z]",macro\=>true,exceptions\=>()}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.NonVirtualDestructorProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Class has a virtual method and non-virtual destructor\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.OverloadProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.OverloadProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid overload\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.RedeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redeclaration\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.RedefinitionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Invalid redefinition\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem=-Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ReturnStyleProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Return with parenthesis\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem=-Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.ScanfFormatStringSecurityProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Format String Vulnerability\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.StatementHasNoEffectProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Statement has no effect\\")",macro\=>true,exceptions\=>()}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.SuggestedParenthesisProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suggested parenthesis around expression\\")",paramNot\=>false}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.SuspiciousSemicolonProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Suspicious semicolon\\")",else\=>false,afterelse\=>false}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.TypeResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Type cannot be resolved\\")"}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedFunctionDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused function declaration\\")",macro\=>true}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedStaticFunctionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"\u672A\u4F7F\u7528\u7684\u9759\u6001\u51FD\u6570\\")",macro\=>true}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused variable declaration in file scope\\")",macro\=>true,exceptions\=>("@(\#)","$Id")}
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Error
|
||||||
|
org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Symbol is not resolved\\")"}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
eclipse.preferences.version=1
|
||||||
|
encoding//Debug/mini212g2.h=UTF-8
|
||||||
|
encoding//User/ch32v30x_it.c=UTF-8
|
||||||
|
encoding//User/main.c=UTF-8
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
eclipse.preferences.version=1
|
||||||
|
org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
Toolchain=RISC-V
|
||||||
|
Series=CH32V307
|
||||||
|
RTOS=NoneOS
|
||||||
|
PeripheralVersion=======1.4
|
||||||
|
Description=======ROM(byte): 256K, SRAM(byte): 64K, CHIP PINS: 64, GPIO PORTS: 51.\nWCH CH32V3 series of mainstream MCUs covers the needs of a large variety of applications in the industrial,medical and consumer markets. High performance with first-class peripherals and low-power,low-voltage operation is paired with a high level of integration at accessible prices with a simple architecture and easy-to-use tools.
|
||||||
|
Address=0x08000000
|
||||||
|
CLKSpeed=1
|
||||||
|
DebugInterfaceMode=-1
|
||||||
|
Erase All=true
|
||||||
|
Program=true
|
||||||
|
Verify=true
|
||||||
|
Reset=true
|
||||||
|
SDIPrintf=false
|
||||||
|
|
||||||
|
Vendor=WCH
|
||||||
|
MCU=CH32V307RCT6
|
||||||
|
Mcu Type=CH32V30x
|
||||||
|
Link=WCH-Link
|
||||||
|
Target Path=obj/SealCheck.hex
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : core_riscv.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.1
|
||||||
|
* Date : 2023/11/11
|
||||||
|
* Description : RISC-V V4 Core Peripheral Access Layer Source File for CH32V30x
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
/* define compiler specific symbols */
|
||||||
|
#if defined ( __CC_ARM )
|
||||||
|
#define __ASM __asm /*!< asm keyword for ARM Compiler */
|
||||||
|
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
|
||||||
|
|
||||||
|
#elif defined ( __ICCARM__ )
|
||||||
|
#define __ASM __asm /*!< asm keyword for IAR Compiler */
|
||||||
|
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */
|
||||||
|
|
||||||
|
#elif defined ( __GNUC__ )
|
||||||
|
#define __ASM __asm /*!< asm keyword for GNU Compiler */
|
||||||
|
#define __INLINE inline /*!< inline keyword for GNU Compiler */
|
||||||
|
|
||||||
|
#elif defined ( __TASKING__ )
|
||||||
|
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
|
||||||
|
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_FFLAGS
|
||||||
|
*
|
||||||
|
* @brief Return the Floating-Point Accrued Exceptions
|
||||||
|
*
|
||||||
|
* @return fflags value
|
||||||
|
*/
|
||||||
|
uint32_t __get_FFLAGS(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "fflags" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_FFLAGS
|
||||||
|
*
|
||||||
|
* @brief Set the Floating-Point Accrued Exceptions
|
||||||
|
*
|
||||||
|
* @param value - set FFLAGS value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_FFLAGS(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw fflags, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_FRM
|
||||||
|
*
|
||||||
|
* @brief Return the Floating-Point Dynamic Rounding Mode
|
||||||
|
*
|
||||||
|
* @return frm value
|
||||||
|
*/
|
||||||
|
uint32_t __get_FRM(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "frm" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_FRM
|
||||||
|
*
|
||||||
|
* @brief Set the Floating-Point Dynamic Rounding Mode
|
||||||
|
*
|
||||||
|
* @param value - set frm value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_FRM(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw frm, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_FCSR
|
||||||
|
*
|
||||||
|
* @brief Return the Floating-Point Control and Status Register
|
||||||
|
*
|
||||||
|
* @return fcsr value
|
||||||
|
*/
|
||||||
|
uint32_t __get_FCSR(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "fcsr" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_FCSR
|
||||||
|
*
|
||||||
|
* @brief Set the Floating-Point Dynamic Rounding Mode
|
||||||
|
*
|
||||||
|
* @param value - set fcsr value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_FCSR(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw fcsr, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MSTATUS
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Status Register
|
||||||
|
*
|
||||||
|
* @return mstatus value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MSTATUS(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mstatus" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MSTATUS
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Status Register
|
||||||
|
*
|
||||||
|
* @param value - set mstatus value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_MSTATUS(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mstatus, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MISA
|
||||||
|
*
|
||||||
|
* @brief Return the Machine ISA Register
|
||||||
|
*
|
||||||
|
* @return misa value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MISA(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "misa" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MISA
|
||||||
|
*
|
||||||
|
* @brief Set the Machine ISA Register
|
||||||
|
*
|
||||||
|
* @param value - set misa value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_MISA(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw misa, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MTVEC
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Trap-Vector Base-Address Register
|
||||||
|
*
|
||||||
|
* @return mtvec value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MTVEC(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mtvec" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MTVEC
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Trap-Vector Base-Address Register
|
||||||
|
*
|
||||||
|
* @param value - set mtvec value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_MTVEC(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mtvec, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MSCRATCH
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Seratch Register
|
||||||
|
*
|
||||||
|
* @return mscratch value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MSCRATCH(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mscratch" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MSCRATCH
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Seratch Register
|
||||||
|
*
|
||||||
|
* @param value - set mscratch value
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void __set_MSCRATCH(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mscratch, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MEPC
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Exception Program Register
|
||||||
|
*
|
||||||
|
* @return mepc value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MEPC(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mepc" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MEPC
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Exception Program Register
|
||||||
|
*
|
||||||
|
* @return mepc value
|
||||||
|
*/
|
||||||
|
void __set_MEPC(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mepc, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MCAUSE
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Cause Register
|
||||||
|
*
|
||||||
|
* @return mcause value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MCAUSE(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mcause" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MEPC
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Cause Register
|
||||||
|
*
|
||||||
|
* @return mcause value
|
||||||
|
*/
|
||||||
|
void __set_MCAUSE(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mcause, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MTVAL
|
||||||
|
*
|
||||||
|
* @brief Return the Machine Trap Value Register
|
||||||
|
*
|
||||||
|
* @return mtval value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MTVAL(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mtval" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __set_MTVAL
|
||||||
|
*
|
||||||
|
* @brief Set the Machine Trap Value Register
|
||||||
|
*
|
||||||
|
* @return mtval value
|
||||||
|
*/
|
||||||
|
void __set_MTVAL(uint32_t value)
|
||||||
|
{
|
||||||
|
__ASM volatile ("csrw mtval, %0" : : "r" (value) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MVENDORID
|
||||||
|
*
|
||||||
|
* @brief Return Vendor ID Register
|
||||||
|
*
|
||||||
|
* @return mvendorid value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MVENDORID(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mvendorid" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MARCHID
|
||||||
|
*
|
||||||
|
* @brief Return Machine Architecture ID Register
|
||||||
|
*
|
||||||
|
* @return marchid value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MARCHID(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "marchid" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MIMPID
|
||||||
|
*
|
||||||
|
* @brief Return Machine Implementation ID Register
|
||||||
|
*
|
||||||
|
* @return mimpid value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MIMPID(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mimpid" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_MHARTID
|
||||||
|
*
|
||||||
|
* @brief Return Hart ID Register
|
||||||
|
*
|
||||||
|
* @return mhartid value
|
||||||
|
*/
|
||||||
|
uint32_t __get_MHARTID(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "csrr %0," "mhartid" : "=r" (result) );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __get_SP
|
||||||
|
*
|
||||||
|
* @brief Return SP Register
|
||||||
|
*
|
||||||
|
* @return SP value
|
||||||
|
*/
|
||||||
|
uint32_t __get_SP(void)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__ASM volatile ( "mv %0," "sp" : "=r"(result) : );
|
||||||
|
return (result);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,599 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : core_riscv.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.2
|
||||||
|
* Date : 2025/03/06
|
||||||
|
* Description : RISC-V V4 Core Peripheral Access Layer Header File for CH32V30x
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CORE_RISCV_H__
|
||||||
|
#define __CORE_RISCV_H__
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* IO definitions */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
#define __I volatile /* defines 'read only' permissions */
|
||||||
|
#else
|
||||||
|
#define __I volatile const /* defines 'read only' permissions */
|
||||||
|
#endif
|
||||||
|
#define __O volatile /* defines 'write only' permissions */
|
||||||
|
#define __IO volatile /* defines 'read / write' permissions */
|
||||||
|
|
||||||
|
/* Standard Peripheral Library old types (maintained for legacy purpose) */
|
||||||
|
typedef __I uint64_t vuc64; /* Read Only */
|
||||||
|
typedef __I uint32_t vuc32; /* Read Only */
|
||||||
|
typedef __I uint16_t vuc16; /* Read Only */
|
||||||
|
typedef __I uint8_t vuc8; /* Read Only */
|
||||||
|
|
||||||
|
typedef const uint64_t uc64; /* Read Only */
|
||||||
|
typedef const uint32_t uc32; /* Read Only */
|
||||||
|
typedef const uint16_t uc16; /* Read Only */
|
||||||
|
typedef const uint8_t uc8; /* Read Only */
|
||||||
|
|
||||||
|
typedef __I int64_t vsc64; /* Read Only */
|
||||||
|
typedef __I int32_t vsc32; /* Read Only */
|
||||||
|
typedef __I int16_t vsc16; /* Read Only */
|
||||||
|
typedef __I int8_t vsc8; /* Read Only */
|
||||||
|
|
||||||
|
typedef const int64_t sc64; /* Read Only */
|
||||||
|
typedef const int32_t sc32; /* Read Only */
|
||||||
|
typedef const int16_t sc16; /* Read Only */
|
||||||
|
typedef const int8_t sc8; /* Read Only */
|
||||||
|
|
||||||
|
typedef __IO uint64_t vu64;
|
||||||
|
typedef __IO uint32_t vu32;
|
||||||
|
typedef __IO uint16_t vu16;
|
||||||
|
typedef __IO uint8_t vu8;
|
||||||
|
|
||||||
|
typedef uint64_t u64;
|
||||||
|
typedef uint32_t u32;
|
||||||
|
typedef uint16_t u16;
|
||||||
|
typedef uint8_t u8;
|
||||||
|
|
||||||
|
typedef __IO int64_t vs64;
|
||||||
|
typedef __IO int32_t vs32;
|
||||||
|
typedef __IO int16_t vs16;
|
||||||
|
typedef __IO int8_t vs8;
|
||||||
|
|
||||||
|
typedef int64_t s64;
|
||||||
|
typedef int32_t s32;
|
||||||
|
typedef int16_t s16;
|
||||||
|
typedef int8_t s8;
|
||||||
|
|
||||||
|
typedef enum {NoREADY = 0, READY = !NoREADY} ErrorStatus;
|
||||||
|
|
||||||
|
typedef enum {DISABLE = 0, ENABLE = !DISABLE} FunctionalState;
|
||||||
|
|
||||||
|
typedef enum {RESET = 0, SET = !RESET} FlagStatus, ITStatus;
|
||||||
|
|
||||||
|
#define RV_STATIC_INLINE static inline
|
||||||
|
|
||||||
|
/* memory mapped structure for Program Fast Interrupt Controller (PFIC) */
|
||||||
|
typedef struct{
|
||||||
|
__I uint32_t ISR[8];
|
||||||
|
__I uint32_t IPR[8];
|
||||||
|
__IO uint32_t ITHRESDR;
|
||||||
|
__IO uint32_t RESERVED;
|
||||||
|
__IO uint32_t CFGR;
|
||||||
|
__I uint32_t GISR;
|
||||||
|
__IO uint8_t VTFIDR[4];
|
||||||
|
uint8_t RESERVED0[12];
|
||||||
|
__IO uint32_t VTFADDR[4];
|
||||||
|
uint8_t RESERVED1[0x90];
|
||||||
|
__O uint32_t IENR[8];
|
||||||
|
uint8_t RESERVED2[0x60];
|
||||||
|
__O uint32_t IRER[8];
|
||||||
|
uint8_t RESERVED3[0x60];
|
||||||
|
__O uint32_t IPSR[8];
|
||||||
|
uint8_t RESERVED4[0x60];
|
||||||
|
__O uint32_t IPRR[8];
|
||||||
|
uint8_t RESERVED5[0x60];
|
||||||
|
__IO uint32_t IACTR[8];
|
||||||
|
uint8_t RESERVED6[0xE0];
|
||||||
|
__IO uint8_t IPRIOR[256];
|
||||||
|
uint8_t RESERVED7[0x810];
|
||||||
|
__IO uint32_t SCTLR;
|
||||||
|
}PFIC_Type;
|
||||||
|
|
||||||
|
/* memory mapped structure for SysTick */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
__IO uint32_t CTLR;
|
||||||
|
__IO uint32_t SR;
|
||||||
|
__IO uint64_t CNT;
|
||||||
|
__IO uint64_t CMP;
|
||||||
|
}SysTick_Type;
|
||||||
|
|
||||||
|
|
||||||
|
#define PFIC ((PFIC_Type *) 0xE000E000 )
|
||||||
|
#define NVIC PFIC
|
||||||
|
#define NVIC_KEY1 ((uint32_t)0xFA050000)
|
||||||
|
#define NVIC_KEY2 ((uint32_t)0xBCAF0000)
|
||||||
|
#define NVIC_KEY3 ((uint32_t)0xBEEF0000)
|
||||||
|
|
||||||
|
#define SysTick ((SysTick_Type *) 0xE000F000)
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __enable_irq
|
||||||
|
*
|
||||||
|
* @brief Enable Global Interrupt
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void __enable_irq()
|
||||||
|
{
|
||||||
|
__asm volatile ("csrs 0x800, %0" : : "r" (0x88) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __disable_irq
|
||||||
|
*
|
||||||
|
* @brief Disable Global Interrupt
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void __disable_irq()
|
||||||
|
{
|
||||||
|
__asm volatile ("csrc 0x800, %0" : : "r" (0x88) );
|
||||||
|
__asm volatile ("fence.i");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __NOP
|
||||||
|
*
|
||||||
|
* @brief nop
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void __NOP()
|
||||||
|
{
|
||||||
|
__asm volatile ("nop");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_EnableIRQ
|
||||||
|
*
|
||||||
|
* @brief Enable Interrupt
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
NVIC->IENR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_DisableIRQ
|
||||||
|
*
|
||||||
|
* @brief Disable Interrupt
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
NVIC->IRER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F));
|
||||||
|
__asm volatile ("fence.i");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_GetStatusIRQ
|
||||||
|
*
|
||||||
|
* @brief Get Interrupt Enable State
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return 1 - Interrupt Enable
|
||||||
|
* 0 - Interrupt Disable
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t NVIC_GetStatusIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
return((uint32_t) ((NVIC->ISR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_GetPendingIRQ
|
||||||
|
*
|
||||||
|
* @brief Get Interrupt Pending State
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return 1 - Interrupt Pending Enable
|
||||||
|
* 0 - Interrupt Pending Disable
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
return((uint32_t) ((NVIC->IPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_SetPendingIRQ
|
||||||
|
*
|
||||||
|
* @brief Set Interrupt Pending
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
NVIC->IPSR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_ClearPendingIRQ
|
||||||
|
*
|
||||||
|
* @brief Clear Interrupt Pending
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
NVIC->IPRR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_GetActive
|
||||||
|
*
|
||||||
|
* @brief Get Interrupt Active State
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
*
|
||||||
|
* @return 1 - Interrupt Active
|
||||||
|
* 0 - Interrupt No Active
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)
|
||||||
|
{
|
||||||
|
return((uint32_t)((NVIC->IACTR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_SetPriority
|
||||||
|
*
|
||||||
|
* @brief Set Interrupt Priority
|
||||||
|
*
|
||||||
|
* @param IRQn - Interrupt Numbers
|
||||||
|
* interrupt nesting enable-8 Level(CSR-0x804 bit1 = 1 bit[3:2] = 3)
|
||||||
|
* priority - bit[7:5] - Preemption Priority
|
||||||
|
* bit[4:0] - Reserve
|
||||||
|
* interrupt nesting enable-4 Level(CSR-0x804 bit1 = 1 bit[3:2] = 2)
|
||||||
|
* priority - bit[7:6] - Preemption Priority
|
||||||
|
* bit[5] - Sub priority
|
||||||
|
* bit[4:0] - Reserve
|
||||||
|
* interrupt nesting enable-2 Level(CSR-0x804 bit1 = 1 bit[3:2] = 1)
|
||||||
|
* priority - bit[7] - Preemption Priority
|
||||||
|
* bit[6:5] - Sub priority
|
||||||
|
* bit[4:0] - Reserve
|
||||||
|
* interrupt nesting disable(CSR-0x804 bit1 = 0)
|
||||||
|
* priority - bit[7:5] - Sub priority
|
||||||
|
* bit[4:0] - Reserve
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint8_t priority)
|
||||||
|
{
|
||||||
|
NVIC->IPRIOR[(uint32_t)(IRQn)] = priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __WFI
|
||||||
|
*
|
||||||
|
* @brief Wait for Interrupt
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void __WFI(void)
|
||||||
|
{
|
||||||
|
NVIC->SCTLR &= ~(1<<3); // wfi
|
||||||
|
asm volatile ("wfi");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn _SEV
|
||||||
|
*
|
||||||
|
* @brief Set Event
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void _SEV(void)
|
||||||
|
{
|
||||||
|
uint32_t t;
|
||||||
|
|
||||||
|
t = NVIC->SCTLR;
|
||||||
|
NVIC->SCTLR |= (1<<3)|(1<<5);
|
||||||
|
NVIC->SCTLR = (NVIC->SCTLR & ~(1<<5)) | ( t & (1<<5));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn _WFE
|
||||||
|
*
|
||||||
|
* @brief Wait for Events
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void _WFE(void)
|
||||||
|
{
|
||||||
|
NVIC->SCTLR |= (1<<3);
|
||||||
|
asm volatile ("wfi");
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __WFE
|
||||||
|
*
|
||||||
|
* @brief Wait for Events
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void __WFE(void)
|
||||||
|
{
|
||||||
|
_SEV();
|
||||||
|
_WFE();
|
||||||
|
_WFE();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn SetVTFIRQ
|
||||||
|
*
|
||||||
|
* @brief Set VTF Interrupt
|
||||||
|
*
|
||||||
|
* @param add - VTF interrupt service function base address.
|
||||||
|
* IRQn -Interrupt Numbers
|
||||||
|
* num - VTF Interrupt Numbers
|
||||||
|
* NewState - DISABLE or ENABLE
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void SetVTFIRQ(uint32_t addr, IRQn_Type IRQn, uint8_t num, FunctionalState NewState)
|
||||||
|
{
|
||||||
|
if(num > 3) return ;
|
||||||
|
|
||||||
|
if (NewState != DISABLE)
|
||||||
|
{
|
||||||
|
NVIC->VTFIDR[num] = IRQn;
|
||||||
|
NVIC->VTFADDR[num] = ((addr&0xFFFFFFFE)|0x1);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
NVIC->VTFIDR[num] = IRQn;
|
||||||
|
NVIC->VTFADDR[num] = ((addr&0xFFFFFFFE)&(~0x1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn NVIC_SystemReset
|
||||||
|
*
|
||||||
|
* @brief Initiate a system reset request
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE void NVIC_SystemReset(void)
|
||||||
|
{
|
||||||
|
NVIC->CFGR = NVIC_KEY3|(1<<7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOADD_W
|
||||||
|
*
|
||||||
|
* @brief Atomic Add with 32bit value
|
||||||
|
* Atomically ADD 32bit value with value in memory using amoadd.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be ADDed
|
||||||
|
*
|
||||||
|
* @return return memory value + add value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOADD_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amoadd.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOAND_W
|
||||||
|
*
|
||||||
|
* @brief Atomic And with 32bit value
|
||||||
|
* Atomically AND 32bit value with value in memory using amoand.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be ANDed
|
||||||
|
*
|
||||||
|
* @return return memory value & and value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOAND_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amoand.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOMAX_W
|
||||||
|
*
|
||||||
|
* @brief Atomic signed MAX with 32bit value
|
||||||
|
* Atomically signed max compare 32bit value with value in memory using amomax.d.
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be compared
|
||||||
|
*
|
||||||
|
* @return return the bigger value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOMAX_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amomax.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOMAXU_W
|
||||||
|
*
|
||||||
|
* @brief Atomic unsigned MAX with 32bit value
|
||||||
|
* Atomically unsigned max compare 32bit value with value in memory using amomaxu.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be compared
|
||||||
|
*
|
||||||
|
* @return return the bigger value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t __AMOMAXU_W(volatile uint32_t *addr, uint32_t value)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amomaxu.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOMIN_W
|
||||||
|
*
|
||||||
|
* @brief Atomic signed MIN with 32bit value
|
||||||
|
* Atomically signed min compare 32bit value with value in memory using amomin.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be compared
|
||||||
|
*
|
||||||
|
* @return return the smaller value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOMIN_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amomin.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOMINU_W
|
||||||
|
*
|
||||||
|
* @brief Atomic unsigned MIN with 32bit value
|
||||||
|
* Atomically unsigned min compare 32bit value with value in memory using amominu.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be compared
|
||||||
|
*
|
||||||
|
* @return return the smaller value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t __AMOMINU_W(volatile uint32_t *addr, uint32_t value)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amominu.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOOR_W
|
||||||
|
*
|
||||||
|
* @brief Atomic OR with 32bit value
|
||||||
|
* Atomically OR 32bit value with value in memory using amoor.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be ORed
|
||||||
|
*
|
||||||
|
* @return return memory value | and value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOOR_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amoor.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOSWAP_W
|
||||||
|
*
|
||||||
|
* @brief Atomically swap new 32bit value into memory using amoswap.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* newval - New value to be stored into the address
|
||||||
|
*
|
||||||
|
* @return return the original value in memory
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE uint32_t __AMOSWAP_W(volatile uint32_t *addr, uint32_t newval)
|
||||||
|
{
|
||||||
|
uint32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amoswap.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(newval) : "memory");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn __AMOXOR_W
|
||||||
|
*
|
||||||
|
* @brief Atomic XOR with 32bit value
|
||||||
|
* Atomically XOR 32bit value with value in memory using amoxor.d.
|
||||||
|
*
|
||||||
|
* @param addr - Address pointer to data, address need to be 4byte aligned
|
||||||
|
* value - value to be XORed
|
||||||
|
*
|
||||||
|
* @return return memory value ^ and value
|
||||||
|
*/
|
||||||
|
__attribute__( ( always_inline ) ) RV_STATIC_INLINE int32_t __AMOXOR_W(volatile int32_t *addr, int32_t value)
|
||||||
|
{
|
||||||
|
int32_t result;
|
||||||
|
|
||||||
|
__asm volatile ("amoxor.w %0, %2, %1" : \
|
||||||
|
"=r"(result), "+A"(*addr) : "r"(value) : "memory");
|
||||||
|
return *addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Core_Exported_Functions */
|
||||||
|
extern uint32_t __get_FFLAGS(void);
|
||||||
|
extern void __set_FFLAGS(uint32_t value);
|
||||||
|
extern uint32_t __get_FRM(void);
|
||||||
|
extern void __set_FRM(uint32_t value);
|
||||||
|
extern uint32_t __get_FCSR(void);
|
||||||
|
extern void __set_FCSR(uint32_t value);
|
||||||
|
extern uint32_t __get_MSTATUS(void);
|
||||||
|
extern void __set_MSTATUS(uint32_t value);
|
||||||
|
extern uint32_t __get_MISA(void);
|
||||||
|
extern void __set_MISA(uint32_t value);
|
||||||
|
extern uint32_t __get_MTVEC(void);
|
||||||
|
extern void __set_MTVEC(uint32_t value);
|
||||||
|
extern uint32_t __get_MSCRATCH(void);
|
||||||
|
extern void __set_MSCRATCH(uint32_t value);
|
||||||
|
extern uint32_t __get_MEPC(void);
|
||||||
|
extern void __set_MEPC(uint32_t value);
|
||||||
|
extern uint32_t __get_MCAUSE(void);
|
||||||
|
extern void __set_MCAUSE(uint32_t value);
|
||||||
|
extern uint32_t __get_MTVAL(void);
|
||||||
|
extern void __set_MTVAL(uint32_t value);
|
||||||
|
extern uint32_t __get_MVENDORID(void);
|
||||||
|
extern uint32_t __get_MARCHID(void);
|
||||||
|
extern uint32_t __get_MIMPID(void);
|
||||||
|
extern uint32_t __get_MHARTID(void);
|
||||||
|
extern uint32_t __get_SP(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+339
@@ -0,0 +1,339 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : debug.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for UART
|
||||||
|
* Printf , Delay functions.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#include "debug.h"
|
||||||
|
|
||||||
|
static uint8_t p_us = 0;
|
||||||
|
static uint16_t p_ms = 0;
|
||||||
|
|
||||||
|
#define DEBUG_DATA0_ADDRESS ((volatile uint32_t*)0xE0000380)
|
||||||
|
#define DEBUG_DATA1_ADDRESS ((volatile uint32_t*)0xE0000384)
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn Delay_Init
|
||||||
|
*
|
||||||
|
* @brief Initializes Delay Funcation.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void Delay_Init(void)
|
||||||
|
{
|
||||||
|
p_us = SystemCoreClock / 8000000;
|
||||||
|
p_ms = (uint16_t)p_us * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn Delay_Us
|
||||||
|
*
|
||||||
|
* @brief Microsecond Delay Time.
|
||||||
|
*
|
||||||
|
* @param n - Microsecond number.
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void Delay_Us(uint32_t n)
|
||||||
|
{
|
||||||
|
uint32_t i;
|
||||||
|
|
||||||
|
SysTick->SR &= ~(1 << 0);
|
||||||
|
i = (uint32_t)n * p_us;
|
||||||
|
|
||||||
|
SysTick->CMP = i;
|
||||||
|
SysTick->CTLR |= (1 << 4);
|
||||||
|
SysTick->CTLR |= (1 << 5) | (1 << 0);
|
||||||
|
|
||||||
|
while((SysTick->SR & (1 << 0)) != (1 << 0))
|
||||||
|
;
|
||||||
|
SysTick->CTLR &= ~(1 << 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn Delay_Ms
|
||||||
|
*
|
||||||
|
* @brief Millisecond Delay Time.
|
||||||
|
*
|
||||||
|
* @param n - Millisecond number.
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void Delay_Ms(uint32_t n)
|
||||||
|
{
|
||||||
|
uint32_t i;
|
||||||
|
|
||||||
|
SysTick->SR &= ~(1 << 0);
|
||||||
|
i = (uint32_t)n * p_ms;
|
||||||
|
|
||||||
|
SysTick->CMP = i;
|
||||||
|
SysTick->CTLR |= (1 << 4);
|
||||||
|
SysTick->CTLR |= (1 << 5) | (1 << 0);
|
||||||
|
|
||||||
|
while((SysTick->SR & (1 << 0)) != (1 << 0))
|
||||||
|
;
|
||||||
|
SysTick->CTLR &= ~(1 << 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn USART_Printf_Init
|
||||||
|
*
|
||||||
|
* @brief Initializes the USARTx peripheral.
|
||||||
|
*
|
||||||
|
* @param baudrate - USART communication baud rate.
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void USART_Printf_Init(uint32_t baudrate)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure;
|
||||||
|
USART_InitTypeDef USART_InitStructure;
|
||||||
|
|
||||||
|
/* When sensor occupies USART3, skip debug UART init entirely */
|
||||||
|
#include "mini212g2.h"
|
||||||
|
#if SENSOR_USE_USART3 && (DEBUG == DEBUG_UART3)
|
||||||
|
(void)GPIO_InitStructure;
|
||||||
|
(void)USART_InitStructure;
|
||||||
|
(void)baudrate;
|
||||||
|
return; /* USART3 reserved for sensor, printf disabled */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if(DEBUG == DEBUG_UART1)
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
|
||||||
|
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
|
||||||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
|
||||||
|
GPIO_Init(GPIOA, &GPIO_InitStructure);
|
||||||
|
|
||||||
|
#elif(DEBUG == DEBUG_UART2)
|
||||||
|
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
|
||||||
|
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
|
||||||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
|
||||||
|
GPIO_Init(GPIOA, &GPIO_InitStructure);
|
||||||
|
|
||||||
|
#elif(DEBUG == DEBUG_UART3)
|
||||||
|
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
|
||||||
|
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
|
||||||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
|
||||||
|
GPIO_Init(GPIOB, &GPIO_InitStructure);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
USART_InitStructure.USART_BaudRate = baudrate;
|
||||||
|
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
|
||||||
|
USART_InitStructure.USART_StopBits = USART_StopBits_1;
|
||||||
|
USART_InitStructure.USART_Parity = USART_Parity_No;
|
||||||
|
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
|
||||||
|
USART_InitStructure.USART_Mode = USART_Mode_Tx;
|
||||||
|
|
||||||
|
#if(DEBUG == DEBUG_UART1)
|
||||||
|
USART_Init(USART1, &USART_InitStructure);
|
||||||
|
USART_Cmd(USART1, ENABLE);
|
||||||
|
|
||||||
|
#elif(DEBUG == DEBUG_UART2)
|
||||||
|
USART_Init(USART2, &USART_InitStructure);
|
||||||
|
USART_Cmd(USART2, ENABLE);
|
||||||
|
|
||||||
|
#elif(DEBUG == DEBUG_UART3)
|
||||||
|
USART_Init(USART3, &USART_InitStructure);
|
||||||
|
USART_Cmd(USART3, ENABLE);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn SDI_Printf_Enable
|
||||||
|
*
|
||||||
|
* @brief Initializes the SDI printf Function.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void SDI_Printf_Enable(void)
|
||||||
|
{
|
||||||
|
*(DEBUG_DATA0_ADDRESS) = 0;
|
||||||
|
Delay_Init();
|
||||||
|
Delay_Ms(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn _write
|
||||||
|
*
|
||||||
|
* @brief Support Printf Function
|
||||||
|
*
|
||||||
|
* @param *buf - UART send Data.
|
||||||
|
* size - Data length
|
||||||
|
*
|
||||||
|
* @return size: Data length
|
||||||
|
*/
|
||||||
|
__attribute__((used)) int _write(int fd, char *buf, int size)
|
||||||
|
{
|
||||||
|
int i = 0;
|
||||||
|
|
||||||
|
#if (SDI_PRINT == SDI_PR_OPEN)
|
||||||
|
int writeSize = size;
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
|
||||||
|
/**
|
||||||
|
* data0 data1 8 bytes
|
||||||
|
* data0 The lowest byte storage length, the maximum is 7
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
while( (*(DEBUG_DATA0_ADDRESS) != 0u))
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if(writeSize>7)
|
||||||
|
{
|
||||||
|
*(DEBUG_DATA1_ADDRESS) = (*(buf+i+3)) | (*(buf+i+4)<<8) | (*(buf+i+5)<<16) | (*(buf+i+6)<<24);
|
||||||
|
*(DEBUG_DATA0_ADDRESS) = (7u) | (*(buf+i)<<8) | (*(buf+i+1)<<16) | (*(buf+i+2)<<24);
|
||||||
|
|
||||||
|
i += 7;
|
||||||
|
writeSize -= 7;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
*(DEBUG_DATA1_ADDRESS) = (*(buf+i+3)) | (*(buf+i+4)<<8) | (*(buf+i+5)<<16) | (*(buf+i+6)<<24);
|
||||||
|
*(DEBUG_DATA0_ADDRESS) = (writeSize) | (*(buf+i)<<8) | (*(buf+i+1)<<16) | (*(buf+i+2)<<24);
|
||||||
|
|
||||||
|
writeSize = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
} while (writeSize);
|
||||||
|
|
||||||
|
|
||||||
|
#else
|
||||||
|
for(i = 0; i < size; i++)
|
||||||
|
{
|
||||||
|
#if(DEBUG == DEBUG_UART1)
|
||||||
|
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
|
||||||
|
USART_SendData(USART1, *buf++);
|
||||||
|
#elif(DEBUG == DEBUG_UART2)
|
||||||
|
while(USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET);
|
||||||
|
USART_SendData(USART2, *buf++);
|
||||||
|
#elif(DEBUG == DEBUG_UART3)
|
||||||
|
#include "mini212g2.h"
|
||||||
|
#if !SENSOR_USE_USART3
|
||||||
|
while(USART_GetFlagStatus(USART3, USART_FLAG_TC) == RESET);
|
||||||
|
USART_SendData(USART3, *buf++);
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn _sbrk
|
||||||
|
*
|
||||||
|
* @brief Change the spatial position of data segment.
|
||||||
|
*
|
||||||
|
* @return size: Data length
|
||||||
|
*/
|
||||||
|
__attribute__((used)) void *_sbrk(ptrdiff_t incr)
|
||||||
|
{
|
||||||
|
extern char _end[];
|
||||||
|
extern char _heap_end[];
|
||||||
|
static char *curbrk = _end;
|
||||||
|
|
||||||
|
if ((curbrk + incr < _end) || (curbrk + incr > _heap_end))
|
||||||
|
return NULL - 1;
|
||||||
|
|
||||||
|
curbrk += incr;
|
||||||
|
return curbrk - incr;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief 初始化LED相关IO口, 并使能时钟
|
||||||
|
* @param 无
|
||||||
|
* @retval 无
|
||||||
|
*/
|
||||||
|
void led_init(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef gpio_init_struct;
|
||||||
|
LED0_GPIO_CLK_ENABLE(); /* LED0时钟使能 */
|
||||||
|
LED1_GPIO_CLK_ENABLE(); /* LED1时钟使能 */
|
||||||
|
LED2_GPIO_CLK_ENABLE(); /* LED2时钟使能 */
|
||||||
|
INPUT_GPIO_CLK_ENABLE(); /* 输入引脚时钟使能 */
|
||||||
|
OUTPUT1_GPIO_CLK_ENABLE(); /* 输出1引脚时钟使能 */
|
||||||
|
OUTPUT2_GPIO_CLK_ENABLE(); /* 输出2引脚时钟使能 */
|
||||||
|
|
||||||
|
gpio_init_struct.GPIO_Pin = LED0_GPIO_PIN; /* LED0引脚 */
|
||||||
|
gpio_init_struct.GPIO_Mode = GPIO_Mode_Out_PP; /* 推挽输出 */
|
||||||
|
gpio_init_struct.GPIO_Speed = GPIO_Speed_50MHz; /* 高速 */
|
||||||
|
GPIO_Init(LED0_GPIO_PORT, &gpio_init_struct); /* 初始化LED0引脚 */
|
||||||
|
|
||||||
|
gpio_init_struct.GPIO_Pin = LED1_GPIO_PIN; /* LED1引脚 */
|
||||||
|
GPIO_Init(LED1_GPIO_PORT, &gpio_init_struct); /* 初始化LED1引脚 */
|
||||||
|
|
||||||
|
gpio_init_struct.GPIO_Pin = LED2_GPIO_PIN; /* LED2引脚 */
|
||||||
|
GPIO_Init(LED2_GPIO_PORT, &gpio_init_struct); /* 初始化LED2引脚 */
|
||||||
|
|
||||||
|
gpio_init_struct.GPIO_Pin = INPUT_GPIO_PIN; /* INPUT引脚 */
|
||||||
|
gpio_init_struct.GPIO_Mode = GPIO_Mode_IPU; /* 上拉输入 */
|
||||||
|
GPIO_Init(INPUT_GPIO_PORT, &gpio_init_struct); /* 初始化INPUT引脚 */
|
||||||
|
|
||||||
|
gpio_init_struct.GPIO_Pin = OUTPUT1_GPIO_PIN | OUTPUT2_GPIO_PIN; /* OUTPUT引脚 */
|
||||||
|
gpio_init_struct.GPIO_Mode = GPIO_Mode_Out_PP; /* 推挽输出 */
|
||||||
|
GPIO_Init(OUTPUT1_GPIO_PORT, &gpio_init_struct); /* 初始化OUTPUT引脚 */
|
||||||
|
|
||||||
|
|
||||||
|
LED0(1); /* 关闭 LED0 */
|
||||||
|
LED1(1); /* 关闭 LED1 */
|
||||||
|
LED2(1); /* 关闭 LED2 */
|
||||||
|
OUTPUT1(0); /* 拉低DO1 */
|
||||||
|
OUTPUT2(0); /* 拉低DO2 */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void check_input(void)
|
||||||
|
{
|
||||||
|
if (GPIO_ReadInputDataBit(INPUT_GPIO_PORT, INPUT_GPIO_PIN) == Bit_RESET) {
|
||||||
|
LED0(0);
|
||||||
|
} else {
|
||||||
|
LED0(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void set_outpot(uint8_t pd8_state, uint8_t pd9_state)
|
||||||
|
{
|
||||||
|
if(pd8_state)
|
||||||
|
GPIO_SetBits(OUTPUT1_GPIO_PORT, OUTPUT1_GPIO_PIN); /* PD8拉高 */
|
||||||
|
else
|
||||||
|
GPIO_ResetBits(OUTPUT1_GPIO_PORT, OUTPUT1_GPIO_PIN); /* PD8拉低 */
|
||||||
|
|
||||||
|
if(pd9_state)
|
||||||
|
GPIO_SetBits(OUTPUT2_GPIO_PORT, OUTPUT2_GPIO_PIN); /* PD9拉高 */
|
||||||
|
else
|
||||||
|
GPIO_ResetBits(OUTPUT2_GPIO_PORT, OUTPUT2_GPIO_PIN); /* PD9拉低 */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : debug.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for UART
|
||||||
|
* Printf , Delay functions.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __DEBUG_H
|
||||||
|
#define __DEBUG_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "stdio.h"
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* UART Printf Definition */
|
||||||
|
#define DEBUG_UART1 1
|
||||||
|
#define DEBUG_UART2 2
|
||||||
|
#define DEBUG_UART3 3
|
||||||
|
|
||||||
|
/* DEBUG UATR Definition */
|
||||||
|
#ifndef DEBUG
|
||||||
|
#define DEBUG DEBUG_UART3
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* SDI Printf Definition */
|
||||||
|
#define SDI_PR_CLOSE 0
|
||||||
|
#define SDI_PR_OPEN 1
|
||||||
|
|
||||||
|
#ifndef SDI_PRINT
|
||||||
|
#define SDI_PRINT SDI_PR_CLOSE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* 引脚 定义 */
|
||||||
|
#define LED0_GPIO_PORT GPIOB
|
||||||
|
#define LED0_GPIO_PIN GPIO_Pin_5
|
||||||
|
#define LED0_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); }while(0) /* PB口时钟使能 */
|
||||||
|
|
||||||
|
#define LED1_GPIO_PORT GPIOB
|
||||||
|
#define LED1_GPIO_PIN GPIO_Pin_6
|
||||||
|
#define LED1_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); }while(0) /* PB口时钟使能 */
|
||||||
|
|
||||||
|
#define LED2_GPIO_PORT GPIOB
|
||||||
|
#define LED2_GPIO_PIN GPIO_Pin_7
|
||||||
|
#define LED2_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); }while(0) /* PC口时钟使能 */
|
||||||
|
|
||||||
|
#define INPUT_GPIO_PORT GPIOB
|
||||||
|
#define INPUT_GPIO_PIN GPIO_Pin_14
|
||||||
|
#define INPUT_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); }while(0) /* PA口时钟使能 */
|
||||||
|
|
||||||
|
#define OUTPUT1_GPIO_PORT GPIOD
|
||||||
|
#define OUTPUT1_GPIO_PIN GPIO_Pin_8
|
||||||
|
#define OUTPUT1_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); }while(0) /* PD口时钟使能 */
|
||||||
|
|
||||||
|
#define OUTPUT2_GPIO_PORT GPIOD
|
||||||
|
#define OUTPUT2_GPIO_PIN GPIO_Pin_9
|
||||||
|
#define OUTPUT2_GPIO_CLK_ENABLE() do{ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); }while(0) /* PD口时钟使能 */
|
||||||
|
|
||||||
|
/******************************************************************************************/
|
||||||
|
|
||||||
|
/* LED端口定义 */
|
||||||
|
#define LED0(x) do{ x ? \
|
||||||
|
GPIO_SetBits(LED0_GPIO_PORT,LED0_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(LED0_GPIO_PORT,LED0_GPIO_PIN); \
|
||||||
|
}while(0) /* LED0 = BLUE */
|
||||||
|
|
||||||
|
#define LED1(x) do{ x ? \
|
||||||
|
GPIO_SetBits(LED1_GPIO_PORT,LED1_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(LED1_GPIO_PORT,LED1_GPIO_PIN); \
|
||||||
|
}while(0) /* LED1 = YELLOW */
|
||||||
|
|
||||||
|
#define LED2(x) do{ x ? \
|
||||||
|
GPIO_SetBits(LED2_GPIO_PORT,LED2_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(LED2_GPIO_PORT,LED2_GPIO_PIN); \
|
||||||
|
}while(0) /* LED2 = GREEN */
|
||||||
|
|
||||||
|
#define INPUT(x) do{ x ? \
|
||||||
|
GPIO_SetBits(INPUT_GPIO_PORT,INPUT_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(INPUT_GPIO_PORT,INPUT_GPIO_PIN); \
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define OUTPUT1(x) do{ x ? \
|
||||||
|
GPIO_SetBits(OUTPUT1_GPIO_PORT,OUTPUT1_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(OUTPUT1_GPIO_PORT,OUTPUT1_GPIO_PIN); \
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define OUTPUT2(x) do{ x ? \
|
||||||
|
GPIO_SetBits(OUTPUT2_GPIO_PORT,OUTPUT2_GPIO_PIN): \
|
||||||
|
GPIO_ResetBits(OUTPUT2_GPIO_PORT,OUTPUT2_GPIO_PIN); \
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
/* LED取反定义 */
|
||||||
|
#define LED0_TOGGLE() do{ gpio_toggle_pin(LED0_GPIO_PORT, LED0_GPIO_PIN); }while(0) /* 翻转LED0 */
|
||||||
|
#define LED1_TOGGLE() do{ gpio_toggle_pin(LED1_GPIO_PORT, LED1_GPIO_PIN); }while(0) /* 翻转LED1 */
|
||||||
|
#define LED2_TOGGLE() do{ gpio_toggle_pin(LED2_GPIO_PORT, LED2_GPIO_PIN); }while(0) /* 翻转LED2 */
|
||||||
|
|
||||||
|
/******************************************************************************************/
|
||||||
|
|
||||||
|
void led_init(void); /* 初始化LED */
|
||||||
|
|
||||||
|
void check_input(void); /*检查PA8口的输入电平*/
|
||||||
|
|
||||||
|
void set_outpot(uint8_t pd8_state, uint8_t pd9_state); /*设置PD8\PD9输出电平*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
void Delay_Init(void);
|
||||||
|
void Delay_Us (uint32_t n);
|
||||||
|
void Delay_Ms (uint32_t n);
|
||||||
|
void USART_Printf_Init(uint32_t baudrate);
|
||||||
|
void SDI_Printf_Enable(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
#include "dvp.h"
|
||||||
|
#include "ch32v30x_dvp.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
#include "string.h"
|
||||||
|
#include "qdx_port.h"
|
||||||
|
|
||||||
|
__attribute__((aligned(4))) uint8_t DMA_LineBuf0[BYTES_PER_LINE];
|
||||||
|
__attribute__((aligned(4))) uint8_t DMA_LineBuf1[BYTES_PER_LINE];
|
||||||
|
|
||||||
|
volatile uint8_t Line_Ready_Flag = 0;
|
||||||
|
volatile uint8_t *Ready_Line_Ptr = NULL;
|
||||||
|
volatile uint32_t current_line_idx = 0;
|
||||||
|
volatile uint32_t dvp_frame_count = 0;
|
||||||
|
volatile uint32_t dvp_row_irq_cnt = 0;
|
||||||
|
|
||||||
|
extern u8 socket[];
|
||||||
|
extern volatile uint32_t sys_tick_ms;
|
||||||
|
|
||||||
|
void DVP_Init(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure = {0};
|
||||||
|
NVIC_InitTypeDef NVIC_InitStructure = {0};
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC, ENABLE);
|
||||||
|
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DVP, ENABLE);
|
||||||
|
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_9 | GPIO_Pin_10;
|
||||||
|
GPIO_Init(GPIOA, &GPIO_InitStructure);
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9 | GPIO_Pin_11;
|
||||||
|
GPIO_Init(GPIOC, &GPIO_InitStructure);
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_8 | GPIO_Pin_9;
|
||||||
|
GPIO_Init(GPIOB, &GPIO_InitStructure);
|
||||||
|
|
||||||
|
/* Step 1: Reset DVP logic */
|
||||||
|
DVP->CR1 = RB_DVP_ALL_CLR | RB_DVP_RCV_CLR;
|
||||||
|
DVP->CR1 = 0x00; /* release reset */
|
||||||
|
|
||||||
|
/* Step 2: Configure mode - 8-bit data, Video/RGB, continuous capture */
|
||||||
|
DVP->CR0 = 0; /* clear everything first */
|
||||||
|
DVP_Mode(RB_DVP_D8_MOD, Video_Mode);
|
||||||
|
/* Mini212G2 polarity: PCLK normal(rising), VSYNC high-active, HSYNC high-active */
|
||||||
|
DVP->CR0 &= ~(RB_DVP_P_POLAR | RB_DVP_V_POLAR | RB_DVP_H_POLAR);
|
||||||
|
DVP->CR0 |= RB_DVP_V_POLAR; /* VSYNC active-high (FIELD_VALID=HIGH) */
|
||||||
|
|
||||||
|
/* Step 3: Configure DMA buffers */
|
||||||
|
DVP->DMA_BUF0 = (uint32_t)DMA_LineBuf0;
|
||||||
|
DVP->DMA_BUF1 = (uint32_t)DMA_LineBuf1;
|
||||||
|
|
||||||
|
/* Step 4: Configure image dimensions */
|
||||||
|
DVP->ROW_NUM = 1;
|
||||||
|
DVP->COL_NUM = BYTES_PER_LINE;
|
||||||
|
|
||||||
|
/* Step 5: Enable interrupts */
|
||||||
|
DVP_INTCfg(ENABLE, RB_DVP_IE_STR_FRM | RB_DVP_IE_ROW_DONE);
|
||||||
|
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannel = DVP_IRQn;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
|
||||||
|
NVIC_Init(&NVIC_InitStructure);
|
||||||
|
|
||||||
|
/* Step 6: Enable DMA, then enable DVP */
|
||||||
|
DVP->CR1 = RB_DVP_DMA_EN; /* DMA on, CM=0 continuous, no reset bits */
|
||||||
|
DVP->CR0 |= RB_DVP_ENABLE;
|
||||||
|
|
||||||
|
DBG_INIT("DVP CR0=0x%02x CR1=0x%02x ROW=%d COL=%d\r\n",
|
||||||
|
(int)(DVP->CR0 & 0xFF), (int)(DVP->CR1 & 0xFF),
|
||||||
|
(int)DVP->ROW_NUM, (int)DVP->COL_NUM);
|
||||||
|
DBG_INIT("DVP DMA_BUF0=0x%08x DMA_BUF1=0x%08x\r\n",
|
||||||
|
(int)DVP->DMA_BUF0, (int)DVP->DMA_BUF1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#define PROTOCOL_HEADER_RESERVE 64
|
||||||
|
|
||||||
|
__attribute__((aligned(4))) uint8_t FrameBuffer[SENSOR_HEIGHT][BYTES_PER_LINE];
|
||||||
|
volatile uint8_t Frame_Ready_Flag = 0;
|
||||||
|
volatile uint32_t Ready_Frame_Count = 0;
|
||||||
|
|
||||||
|
void DVP_Task(void)
|
||||||
|
{
|
||||||
|
/* Line copying is done directly in DVP_IRQHandler to prevent
|
||||||
|
* line drops when the task runs slower than the DVP pixel clock.
|
||||||
|
* This function is intentionally empty. */
|
||||||
|
}
|
||||||
|
|
||||||
|
void DVP_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
|
||||||
|
void DVP_IRQHandler(void)
|
||||||
|
{
|
||||||
|
if (DVP->IFR & RB_DVP_IF_STR_FRM)
|
||||||
|
{
|
||||||
|
DVP->IFR = RB_DVP_IF_STR_FRM;
|
||||||
|
current_line_idx = 0;
|
||||||
|
dvp_frame_count++;
|
||||||
|
}
|
||||||
|
if (DVP->IFR & RB_DVP_IF_ROW_DONE)
|
||||||
|
{
|
||||||
|
DVP->IFR = RB_DVP_IF_ROW_DONE;
|
||||||
|
/* Capture src and idx before incrementing to fix off-by-one:
|
||||||
|
* STR_FRM sets idx=0, so first ROW_DONE copies to FrameBuffer[0]. */
|
||||||
|
uint8_t *src = (DVP->CR1 & RB_DVP_BUF_TOG) ? DMA_LineBuf0 : DMA_LineBuf1;
|
||||||
|
uint32_t idx = current_line_idx;
|
||||||
|
current_line_idx++;
|
||||||
|
dvp_row_irq_cnt++;
|
||||||
|
if (idx < SENSOR_HEIGHT)
|
||||||
|
{
|
||||||
|
memcpy(FrameBuffer[idx], src, BYTES_PER_LINE);
|
||||||
|
if (idx == SENSOR_HEIGHT - 1)
|
||||||
|
{
|
||||||
|
Frame_Ready_Flag = 1;
|
||||||
|
Ready_Frame_Count = dvp_frame_count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
#ifndef DVP_H_
|
||||||
|
#define DVP_H_
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
#define SENSOR_WIDTH 256
|
||||||
|
#define SENSOR_HEIGHT 192
|
||||||
|
#define SENSOR_TOTAL_LINES (SENSOR_HEIGHT) // TMP 模式无参数行,共 192 行
|
||||||
|
#define BYTES_PER_LINE (SENSOR_WIDTH * 2) // 每行512字节
|
||||||
|
|
||||||
|
#define ALARM_TEMP_RAW 800 // 80.0℃ (raw/10)
|
||||||
|
|
||||||
|
extern volatile uint8_t Line_Ready_Flag;
|
||||||
|
extern volatile uint8_t *Ready_Line_Ptr;
|
||||||
|
extern volatile uint32_t current_line_idx;
|
||||||
|
extern volatile uint32_t dvp_frame_count;
|
||||||
|
extern volatile uint32_t dvp_row_irq_cnt;
|
||||||
|
|
||||||
|
void DVP_Init(void);
|
||||||
|
void DVP_Task(void);
|
||||||
|
|
||||||
|
extern __attribute__((aligned(4))) uint8_t FrameBuffer[SENSOR_HEIGHT][BYTES_PER_LINE];
|
||||||
|
extern volatile uint8_t Frame_Ready_Flag;
|
||||||
|
extern volatile uint32_t Ready_Frame_Count;
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
#include "mini212g2.h"
|
||||||
|
#include "debug.h"
|
||||||
|
#include "string.h"
|
||||||
|
#include "qdx_port.h"
|
||||||
|
|
||||||
|
#if SENSOR_UART_ENABLE
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Protocol constants
|
||||||
|
* ============================================================ */
|
||||||
|
#define FRAME_HEAD1 0x55
|
||||||
|
#define FRAME_HEAD2 0xAA
|
||||||
|
#define FRAME_TAIL 0xF0
|
||||||
|
|
||||||
|
/* ACK response: 55 AA 01 00 01 F0 */
|
||||||
|
#define ACK_LEN 6
|
||||||
|
static const uint8_t ACK_PATTERN[ACK_LEN] = {0x55, 0xAA, 0x01, 0x00, 0x01, 0xF0};
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* DVP output configuration commands
|
||||||
|
* (from Mini212G2 serial protocol document)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* Digital port type → CMOS */
|
||||||
|
static const uint8_t CMD_DIGITAL_CMOS[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x04, 0xF0};
|
||||||
|
|
||||||
|
/* CMOS interface → CMOS8(MSB) */
|
||||||
|
static const uint8_t CMD_CMOS8_MSB[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0xF0};
|
||||||
|
|
||||||
|
/* CMOS content → Y16 */
|
||||||
|
static const uint8_t CMD_CONTENT_Y16[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0x05, 0xF0};
|
||||||
|
|
||||||
|
/* Frame rate → 30Hz */
|
||||||
|
static const uint8_t CMD_FPS_30HZ[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x05, 0x00, 0x00, 0x00, 0x00, 0x01, 0xF0};
|
||||||
|
|
||||||
|
/* Save settings */
|
||||||
|
static const uint8_t CMD_SAVE[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x03, 0xF0};
|
||||||
|
|
||||||
|
/* Shutter compensation (NUC) */
|
||||||
|
static const uint8_t CMD_SHUTTER[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x08, 0x00, 0x00, 0x00, 0x01, 0x0D, 0xF0};
|
||||||
|
|
||||||
|
/* Query: digital video page */
|
||||||
|
static const uint8_t CMD_QUERY_DIGITAL[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x02, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x84, 0xF0};
|
||||||
|
|
||||||
|
/* Query: status page (simplest query, always works) */
|
||||||
|
static const uint8_t CMD_QUERY_STATUS[] =
|
||||||
|
{0x55, 0xAA, 0x07, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x87, 0xF0};
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Low-level UART helpers
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
static void Sensor_UART_Init(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef gpio = {0};
|
||||||
|
USART_InitTypeDef usart = {0};
|
||||||
|
|
||||||
|
#if SENSOR_USE_USART3
|
||||||
|
/* USART3: PB10=TX PB11=RX
|
||||||
|
* NOTE: This reuses the debug printf port. printf is disabled. */
|
||||||
|
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
|
||||||
|
|
||||||
|
gpio.GPIO_Pin = GPIO_Pin_10;
|
||||||
|
gpio.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
gpio.GPIO_Mode = GPIO_Mode_AF_PP;
|
||||||
|
GPIO_Init(GPIOB, &gpio);
|
||||||
|
|
||||||
|
gpio.GPIO_Pin = GPIO_Pin_11;
|
||||||
|
gpio.GPIO_Mode = GPIO_Mode_IN_FLOATING;
|
||||||
|
GPIO_Init(GPIOB, &gpio);
|
||||||
|
#else
|
||||||
|
/* USART2: PA2=TX PA3=RX */
|
||||||
|
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
|
||||||
|
|
||||||
|
gpio.GPIO_Pin = GPIO_Pin_2;
|
||||||
|
gpio.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
gpio.GPIO_Mode = GPIO_Mode_AF_PP;
|
||||||
|
GPIO_Init(GPIOA, &gpio);
|
||||||
|
|
||||||
|
gpio.GPIO_Pin = GPIO_Pin_3;
|
||||||
|
gpio.GPIO_Mode = GPIO_Mode_IN_FLOATING;
|
||||||
|
GPIO_Init(GPIOA, &gpio);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
usart.USART_BaudRate = SENSOR_UART_BAUD;
|
||||||
|
usart.USART_WordLength = USART_WordLength_8b;
|
||||||
|
usart.USART_StopBits = USART_StopBits_1;
|
||||||
|
usart.USART_Parity = USART_Parity_No;
|
||||||
|
usart.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
|
||||||
|
usart.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
|
||||||
|
|
||||||
|
USART_Init(SENSOR_UART, &usart);
|
||||||
|
USART_Cmd(SENSOR_UART, ENABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void Sensor_SendBytes(const uint8_t *data, uint8_t len)
|
||||||
|
{
|
||||||
|
for (uint8_t i = 0; i < len; i++) {
|
||||||
|
while (!USART_GetFlagStatus(SENSOR_UART, USART_FLAG_TXE));
|
||||||
|
USART_SendData(SENSOR_UART, data[i]);
|
||||||
|
}
|
||||||
|
while (!USART_GetFlagStatus(SENSOR_UART, USART_FLAG_TC));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read response bytes until FRAME_TAIL seen or timeout.
|
||||||
|
* timeout_ms ≈ approximate milliseconds (uses Delay_Us polling).
|
||||||
|
* Returns number of bytes actually read.
|
||||||
|
*/
|
||||||
|
static int Sensor_ReadResp(uint8_t *buf, uint8_t max_len, uint16_t timeout_ms)
|
||||||
|
{
|
||||||
|
uint8_t idx = 0;
|
||||||
|
/* Poll with ~0.1 ms granularity */
|
||||||
|
for (uint32_t i = 0; i < (uint32_t)timeout_ms * 10; i++) {
|
||||||
|
if (USART_GetFlagStatus(SENSOR_UART, USART_FLAG_RXNE)) {
|
||||||
|
buf[idx++] = (uint8_t)USART_ReceiveData(SENSOR_UART);
|
||||||
|
if (idx >= max_len) return idx;
|
||||||
|
if (idx >= 2 && buf[idx - 1] == FRAME_TAIL) return idx;
|
||||||
|
} else {
|
||||||
|
Delay_Us(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void Sensor_FlushRx(void)
|
||||||
|
{
|
||||||
|
while (USART_GetFlagStatus(SENSOR_UART, USART_FLAG_RXNE))
|
||||||
|
(void)USART_ReceiveData(SENSOR_UART);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Public API
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Debug inspection variables (watch in JTAG debugger)
|
||||||
|
* ============================================================ */
|
||||||
|
volatile uint8_t sensor_init_ok = 0;
|
||||||
|
volatile uint8_t sensor_init_fail = 0;
|
||||||
|
volatile uint8_t sensor_last_resp[32] = {0};
|
||||||
|
volatile uint8_t sensor_last_resp_len = 0;
|
||||||
|
volatile uint8_t sensor_comm_test = 0;
|
||||||
|
|
||||||
|
int Mini212G2_SendCmd(const uint8_t *cmd, uint8_t len)
|
||||||
|
{
|
||||||
|
uint8_t resp[8];
|
||||||
|
Sensor_FlushRx();
|
||||||
|
Sensor_SendBytes(cmd, len);
|
||||||
|
|
||||||
|
int n = Sensor_ReadResp(resp, sizeof(resp), 200);
|
||||||
|
/* Save last response for debugger inspection */
|
||||||
|
sensor_last_resp_len = (uint8_t)n;
|
||||||
|
for (int j = 0; j < n && j < 32; j++)
|
||||||
|
sensor_last_resp[j] = resp[j];
|
||||||
|
|
||||||
|
if (n == ACK_LEN && memcmp(resp, ACK_PATTERN, ACK_LEN) == 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
DBG_INIT("Sensor resp(%d):", n);
|
||||||
|
for (int j = 0; j < n; j++) printf(" %02x", resp[j]);
|
||||||
|
printf("\r\n");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* SENSOR_UART_ENABLE (UART helpers + SendCmd) */
|
||||||
|
|
||||||
|
int Mini212G2_Init(void)
|
||||||
|
{
|
||||||
|
#if !SENSOR_UART_ENABLE
|
||||||
|
DBG_INIT("Sensor: UART disabled, pre-configured via USB\r\n");
|
||||||
|
DBG_INIT("Sensor: CMOS output, CMOS8(MSB), Y16, 30Hz\r\n");
|
||||||
|
return 0;
|
||||||
|
#else
|
||||||
|
int ok = 0, fail = 0;
|
||||||
|
|
||||||
|
Sensor_UART_Init();
|
||||||
|
DBG_INIT("Sensor: UART%d baud=%d\r\n",
|
||||||
|
(int)(SENSOR_UART == USART3 ? 3 : 2), (int)SENSOR_UART_BAUD);
|
||||||
|
|
||||||
|
/* Sensor needs several seconds to boot after power-on */
|
||||||
|
DBG_INIT("Sensor: Waiting 3s for boot...\r\n");
|
||||||
|
Delay_Ms(3000);
|
||||||
|
|
||||||
|
/* === Communication test: send status query === */
|
||||||
|
{
|
||||||
|
uint8_t test_resp[32];
|
||||||
|
Sensor_FlushRx();
|
||||||
|
Sensor_SendBytes(CMD_QUERY_STATUS, sizeof(CMD_QUERY_STATUS));
|
||||||
|
int tn = Sensor_ReadResp(test_resp, sizeof(test_resp), 500);
|
||||||
|
sensor_last_resp_len = (uint8_t)tn;
|
||||||
|
for (int j = 0; j < tn && j < 32; j++)
|
||||||
|
sensor_last_resp[j] = test_resp[j];
|
||||||
|
sensor_comm_test = (tn > 0) ? 1 : 0xFF;
|
||||||
|
/* Breakpoint here to check sensor_comm_test and sensor_last_resp */
|
||||||
|
}
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
DBG_INIT("Sensor: Configuring CMOS/DVP output...\r\n");
|
||||||
|
|
||||||
|
/* 1. Shutter compensation */
|
||||||
|
if (Mini212G2_SendCmd(CMD_SHUTTER, sizeof(CMD_SHUTTER)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: Shutter OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: Shutter FAIL\r\n"); }
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
/* 2. Digital port → CMOS */
|
||||||
|
if (Mini212G2_SendCmd(CMD_DIGITAL_CMOS, sizeof(CMD_DIGITAL_CMOS)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: Digital->CMOS OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: Digital->CMOS FAIL\r\n"); }
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
/* 3. CMOS interface → 8-bit MSB */
|
||||||
|
if (Mini212G2_SendCmd(CMD_CMOS8_MSB, sizeof(CMD_CMOS8_MSB)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: CMOS8(MSB) OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: CMOS8(MSB) FAIL\r\n"); }
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
/* 4. CMOS content → Y16 (raw 16-bit thermal) */
|
||||||
|
if (Mini212G2_SendCmd(CMD_CONTENT_Y16, sizeof(CMD_CONTENT_Y16)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: Y16 OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: Y16 FAIL\r\n"); }
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
/* 5. Frame rate → 30Hz */
|
||||||
|
if (Mini212G2_SendCmd(CMD_FPS_30HZ, sizeof(CMD_FPS_30HZ)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: 30Hz OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: 30Hz FAIL\r\n"); }
|
||||||
|
Delay_Ms(200);
|
||||||
|
|
||||||
|
/* 6. Save settings to flash */
|
||||||
|
if (Mini212G2_SendCmd(CMD_SAVE, sizeof(CMD_SAVE)) == 0)
|
||||||
|
{ ok++; DBG_INIT("Sensor: Save OK\r\n"); }
|
||||||
|
else
|
||||||
|
{ fail++; DBG_ERR("Sensor: Save FAIL\r\n"); }
|
||||||
|
Delay_Ms(500);
|
||||||
|
|
||||||
|
DBG_INIT("Sensor: %d ok, %d fail\r\n", ok, fail);
|
||||||
|
sensor_init_ok = (uint8_t)ok;
|
||||||
|
sensor_init_fail = (uint8_t)fail;
|
||||||
|
|
||||||
|
/* Print current digital video status for verification */
|
||||||
|
Mini212G2_PrintDigitalVideoStatus();
|
||||||
|
|
||||||
|
return (fail == 0) ? 0 : -1;
|
||||||
|
#endif /* SENSOR_UART_ENABLE */
|
||||||
|
}
|
||||||
|
|
||||||
|
#if SENSOR_UART_ENABLE
|
||||||
|
void Mini212G2_PrintDigitalVideoStatus(void)
|
||||||
|
{
|
||||||
|
uint8_t resp[32];
|
||||||
|
Sensor_FlushRx();
|
||||||
|
Sensor_SendBytes(CMD_QUERY_DIGITAL, sizeof(CMD_QUERY_DIGITAL));
|
||||||
|
|
||||||
|
int n = Sensor_ReadResp(resp, sizeof(resp), 500);
|
||||||
|
if (n < 24) {
|
||||||
|
DBG_ERR("Sensor: Query failed (got %d bytes)\r\n", n);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Parse per protocol spec (Page 11-12):
|
||||||
|
* Byte5 = ext-sync, Byte6 = digital port type, Byte7 = CMOS content,
|
||||||
|
* Byte8 = CMOS interface, Byte9 = frame rate, Byte11 = clock phase */
|
||||||
|
static const char *port_names[] = {
|
||||||
|
"OFF", "USB2.0", "CMOS", "BT1120", "BT656",
|
||||||
|
"USB+UART", "LCD", "LVDS", "LCD+DVP", "UVC+CDC"
|
||||||
|
};
|
||||||
|
static const char *content_names[] = {
|
||||||
|
"YUV422", "YUV422+Param", "Y16", "Y16+Param",
|
||||||
|
"Y16+YUV422", "Y16+Param+YUV422"
|
||||||
|
};
|
||||||
|
static const char *iface_names[] = {"CMOS16", "CMOS8(MSB)", "CMOS8(LSB)"};
|
||||||
|
static const char *fps_names[] = {"30Hz", "25Hz", "9Hz", "50Hz"};
|
||||||
|
|
||||||
|
uint8_t port_type = resp[6];
|
||||||
|
uint8_t content = resp[7];
|
||||||
|
uint8_t iface = resp[8];
|
||||||
|
uint8_t fps = resp[9];
|
||||||
|
uint8_t clk_phase = resp[11];
|
||||||
|
|
||||||
|
DBG_INIT("Sensor Digital Video Status:\r\n");
|
||||||
|
DBG_INIT(" Port: %s (%d)\r\n",
|
||||||
|
(port_type < 10) ? port_names[port_type] : "?", (int)port_type);
|
||||||
|
DBG_INIT(" Content: %s (%d)\r\n",
|
||||||
|
(content < 6) ? content_names[content] : "?", (int)content);
|
||||||
|
DBG_INIT(" Interface: %s (%d)\r\n",
|
||||||
|
(iface < 3) ? iface_names[iface] : "?", (int)iface);
|
||||||
|
DBG_INIT(" FPS: %s (%d)\r\n",
|
||||||
|
(fps < 4) ? fps_names[fps] : "?", (int)fps);
|
||||||
|
DBG_INIT(" ClkPhase: %s (%d)\r\n",
|
||||||
|
(clk_phase == 0) ? "Rising" : "Falling", (int)clk_phase);
|
||||||
|
}
|
||||||
|
|
||||||
|
int Mini212G2_ShutterCompensation(void)
|
||||||
|
{
|
||||||
|
return Mini212G2_SendCmd(CMD_SHUTTER, sizeof(CMD_SHUTTER));
|
||||||
|
}
|
||||||
|
#endif /* SENSOR_UART_ENABLE */
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#ifndef MINI212G2_H_
|
||||||
|
#define MINI212G2_H_
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* ---- Sensor UART configuration ----
|
||||||
|
* 模组已通过 USB 预配置,不需要 MCU UART 配置。
|
||||||
|
* 注意:USART2 (PA2/PA3) 引脚已被占用,不可使用。
|
||||||
|
* 如需重新启用 MCU UART 配置传感器,将下面的 #if 0 改为 #if 1。
|
||||||
|
* 启用后仅可使用 USART3 (PB10/PB11),但会占用 printf 调试口。 */
|
||||||
|
#if 0 /* MCU UART 配置已禁用 */
|
||||||
|
#define SENSOR_USE_USART3 1 /* 必须用 USART3,USART2 引脚已占用 */
|
||||||
|
#define SENSOR_UART_ENABLE 1
|
||||||
|
#define SENSOR_UART USART3
|
||||||
|
#define SENSOR_UART_BAUD 115200
|
||||||
|
#else
|
||||||
|
#define SENSOR_USE_USART3 0
|
||||||
|
#define SENSOR_UART_ENABLE 0
|
||||||
|
#define SENSOR_UART_BAUD 115200
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize sensor. When SENSOR_UART_ENABLE=1, configures via UART.
|
||||||
|
* When SENSOR_UART_ENABLE=0, assumes sensor is pre-configured via USB.
|
||||||
|
* Call BEFORE DVP_Init(). Returns 0 on success.
|
||||||
|
*/
|
||||||
|
int Mini212G2_Init(void);
|
||||||
|
|
||||||
|
/* Debug variables — inspect via JTAG debugger when printf is unavailable.
|
||||||
|
* sensor_init_ok: number of commands that succeeded
|
||||||
|
* sensor_init_fail: number of commands that failed
|
||||||
|
* sensor_last_resp[]: raw bytes of last failed response
|
||||||
|
* sensor_last_resp_len: length of last response */
|
||||||
|
extern volatile uint8_t sensor_init_ok;
|
||||||
|
extern volatile uint8_t sensor_init_fail;
|
||||||
|
extern volatile uint8_t sensor_last_resp[32];
|
||||||
|
extern volatile uint8_t sensor_last_resp_len;
|
||||||
|
/* sensor_comm_test: 0=not run, 1=got response, 0xFF=no response (timeout) */
|
||||||
|
extern volatile uint8_t sensor_comm_test;
|
||||||
|
|
||||||
|
#if SENSOR_UART_ENABLE
|
||||||
|
/**
|
||||||
|
* Send a raw protocol command and wait for ACK.
|
||||||
|
* Returns 0 on ACK received, -1 on timeout/bad response.
|
||||||
|
*/
|
||||||
|
int Mini212G2_SendCmd(const uint8_t *cmd, uint8_t len);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query current digital video settings. Prints result to debug console.
|
||||||
|
*/
|
||||||
|
void Mini212G2_PrintDigitalVideoStatus(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger shutter compensation (NUC).
|
||||||
|
*/
|
||||||
|
int Mini212G2_ShutterCompensation(void);
|
||||||
|
#endif /* SENSOR_UART_ENABLE */
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,777 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Standard includes. */
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
|
||||||
|
* all the API functions to use the MPU wrappers. That should only be done when
|
||||||
|
* task.h is included from an application file. */
|
||||||
|
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
|
||||||
|
|
||||||
|
/* FreeRTOS includes. */
|
||||||
|
#include "FreeRTOS.h"
|
||||||
|
#include "task.h"
|
||||||
|
#include "timers.h"
|
||||||
|
#include "event_groups.h"
|
||||||
|
|
||||||
|
/* Lint e961, e750 and e9021 are suppressed as a MISRA exception justified
|
||||||
|
* because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
|
||||||
|
* for the header files above, but not in this file, in order to generate the
|
||||||
|
* correct privileged Vs unprivileged linkage and placement. */
|
||||||
|
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021 See comment above. */
|
||||||
|
|
||||||
|
/* The following bit fields convey control information in a task's event list
|
||||||
|
* item value. It is important they don't clash with the
|
||||||
|
* taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */
|
||||||
|
#if configUSE_16_BIT_TICKS == 1
|
||||||
|
#define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U
|
||||||
|
#define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U
|
||||||
|
#define eventWAIT_FOR_ALL_BITS 0x0400U
|
||||||
|
#define eventEVENT_BITS_CONTROL_BYTES 0xff00U
|
||||||
|
#else
|
||||||
|
#define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL
|
||||||
|
#define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL
|
||||||
|
#define eventWAIT_FOR_ALL_BITS 0x04000000UL
|
||||||
|
#define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef struct EventGroupDef_t
|
||||||
|
{
|
||||||
|
EventBits_t uxEventBits;
|
||||||
|
List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */
|
||||||
|
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
UBaseType_t uxEventGroupNumber;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
|
||||||
|
uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */
|
||||||
|
#endif
|
||||||
|
} EventGroup_t;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Test the bits set in uxCurrentEventBits to see if the wait condition is met.
|
||||||
|
* The wait condition is defined by xWaitForAllBits. If xWaitForAllBits is
|
||||||
|
* pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor
|
||||||
|
* are also set in uxCurrentEventBits. If xWaitForAllBits is pdFALSE then the
|
||||||
|
* wait condition is met if any of the bits set in uxBitsToWait for are also set
|
||||||
|
* in uxCurrentEventBits.
|
||||||
|
*/
|
||||||
|
static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
|
||||||
|
|
||||||
|
EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer )
|
||||||
|
{
|
||||||
|
EventGroup_t * pxEventBits;
|
||||||
|
|
||||||
|
/* A StaticEventGroup_t object must be provided. */
|
||||||
|
configASSERT( pxEventGroupBuffer );
|
||||||
|
|
||||||
|
#if ( configASSERT_DEFINED == 1 )
|
||||||
|
{
|
||||||
|
/* Sanity check that the size of the structure used to declare a
|
||||||
|
* variable of type StaticEventGroup_t equals the size of the real
|
||||||
|
* event group structure. */
|
||||||
|
volatile size_t xSize = sizeof( StaticEventGroup_t );
|
||||||
|
configASSERT( xSize == sizeof( EventGroup_t ) );
|
||||||
|
} /*lint !e529 xSize is referenced if configASSERT() is defined. */
|
||||||
|
#endif /* configASSERT_DEFINED */
|
||||||
|
|
||||||
|
/* The user has provided a statically allocated event group - use it. */
|
||||||
|
pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */
|
||||||
|
|
||||||
|
if( pxEventBits != NULL )
|
||||||
|
{
|
||||||
|
pxEventBits->uxEventBits = 0;
|
||||||
|
vListInitialise( &( pxEventBits->xTasksWaitingForBits ) );
|
||||||
|
|
||||||
|
#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
|
||||||
|
{
|
||||||
|
/* Both static and dynamic allocation can be used, so note that
|
||||||
|
* this event group was created statically in case the event group
|
||||||
|
* is later deleted. */
|
||||||
|
pxEventBits->ucStaticallyAllocated = pdTRUE;
|
||||||
|
}
|
||||||
|
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
|
||||||
|
|
||||||
|
traceEVENT_GROUP_CREATE( pxEventBits );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* xEventGroupCreateStatic should only ever be called with
|
||||||
|
* pxEventGroupBuffer pointing to a pre-allocated (compile time
|
||||||
|
* allocated) StaticEventGroup_t variable. */
|
||||||
|
traceEVENT_GROUP_CREATE_FAILED();
|
||||||
|
}
|
||||||
|
|
||||||
|
return pxEventBits;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configSUPPORT_STATIC_ALLOCATION */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
|
||||||
|
|
||||||
|
EventGroupHandle_t xEventGroupCreate( void )
|
||||||
|
{
|
||||||
|
EventGroup_t * pxEventBits;
|
||||||
|
|
||||||
|
/* Allocate the event group. Justification for MISRA deviation as
|
||||||
|
* follows: pvPortMalloc() always ensures returned memory blocks are
|
||||||
|
* aligned per the requirements of the MCU stack. In this case
|
||||||
|
* pvPortMalloc() must return a pointer that is guaranteed to meet the
|
||||||
|
* alignment requirements of the EventGroup_t structure - which (if you
|
||||||
|
* follow it through) is the alignment requirements of the TickType_t type
|
||||||
|
* (EventBits_t being of TickType_t itself). Therefore, whenever the
|
||||||
|
* stack alignment requirements are greater than or equal to the
|
||||||
|
* TickType_t alignment requirements the cast is safe. In other cases,
|
||||||
|
* where the natural word size of the architecture is less than
|
||||||
|
* sizeof( TickType_t ), the TickType_t variables will be accessed in two
|
||||||
|
* or more reads operations, and the alignment requirements is only that
|
||||||
|
* of each individual read. */
|
||||||
|
pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */
|
||||||
|
|
||||||
|
if( pxEventBits != NULL )
|
||||||
|
{
|
||||||
|
pxEventBits->uxEventBits = 0;
|
||||||
|
vListInitialise( &( pxEventBits->xTasksWaitingForBits ) );
|
||||||
|
|
||||||
|
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
|
||||||
|
{
|
||||||
|
/* Both static and dynamic allocation can be used, so note this
|
||||||
|
* event group was allocated statically in case the event group is
|
||||||
|
* later deleted. */
|
||||||
|
pxEventBits->ucStaticallyAllocated = pdFALSE;
|
||||||
|
}
|
||||||
|
#endif /* configSUPPORT_STATIC_ALLOCATION */
|
||||||
|
|
||||||
|
traceEVENT_GROUP_CREATE( pxEventBits );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */
|
||||||
|
}
|
||||||
|
|
||||||
|
return pxEventBits;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
TickType_t xTicksToWait )
|
||||||
|
{
|
||||||
|
EventBits_t uxOriginalBitValue, uxReturn;
|
||||||
|
EventGroup_t * pxEventBits = xEventGroup;
|
||||||
|
BaseType_t xAlreadyYielded;
|
||||||
|
BaseType_t xTimeoutOccurred = pdFALSE;
|
||||||
|
|
||||||
|
configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
|
||||||
|
configASSERT( uxBitsToWaitFor != 0 );
|
||||||
|
#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
|
||||||
|
{
|
||||||
|
configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
uxOriginalBitValue = pxEventBits->uxEventBits;
|
||||||
|
|
||||||
|
( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet );
|
||||||
|
|
||||||
|
if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor )
|
||||||
|
{
|
||||||
|
/* All the rendezvous bits are now set - no need to block. */
|
||||||
|
uxReturn = ( uxOriginalBitValue | uxBitsToSet );
|
||||||
|
|
||||||
|
/* Rendezvous always clear the bits. They will have been cleared
|
||||||
|
* already unless this is the only task in the rendezvous. */
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
|
||||||
|
|
||||||
|
xTicksToWait = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if( xTicksToWait != ( TickType_t ) 0 )
|
||||||
|
{
|
||||||
|
traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor );
|
||||||
|
|
||||||
|
/* Store the bits that the calling task is waiting for in the
|
||||||
|
* task's event list item so the kernel knows when a match is
|
||||||
|
* found. Then enter the blocked state. */
|
||||||
|
vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait );
|
||||||
|
|
||||||
|
/* This assignment is obsolete as uxReturn will get set after
|
||||||
|
* the task unblocks, but some compilers mistakenly generate a
|
||||||
|
* warning about uxReturn being returned without being set if the
|
||||||
|
* assignment is omitted. */
|
||||||
|
uxReturn = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* The rendezvous bits were not set, but no block time was
|
||||||
|
* specified - just return the current event bit value. */
|
||||||
|
uxReturn = pxEventBits->uxEventBits;
|
||||||
|
xTimeoutOccurred = pdTRUE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xAlreadyYielded = xTaskResumeAll();
|
||||||
|
|
||||||
|
if( xTicksToWait != ( TickType_t ) 0 )
|
||||||
|
{
|
||||||
|
if( xAlreadyYielded == pdFALSE )
|
||||||
|
{
|
||||||
|
portYIELD_WITHIN_API();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The task blocked to wait for its required bits to be set - at this
|
||||||
|
* point either the required bits were set or the block time expired. If
|
||||||
|
* the required bits were set they will have been stored in the task's
|
||||||
|
* event list item, and they should now be retrieved then cleared. */
|
||||||
|
uxReturn = uxTaskResetEventItemValue();
|
||||||
|
|
||||||
|
if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
/* The task timed out, just return the current event bit value. */
|
||||||
|
taskENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
uxReturn = pxEventBits->uxEventBits;
|
||||||
|
|
||||||
|
/* Although the task got here because it timed out before the
|
||||||
|
* bits it was waiting for were set, it is possible that since it
|
||||||
|
* unblocked another task has set the bits. If this is the case
|
||||||
|
* then it needs to clear the bits before exiting. */
|
||||||
|
if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor )
|
||||||
|
{
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
taskEXIT_CRITICAL();
|
||||||
|
|
||||||
|
xTimeoutOccurred = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* The task unblocked because the bits were set. */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Control bits might be set as the task had blocked should not be
|
||||||
|
* returned. */
|
||||||
|
uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
|
||||||
|
}
|
||||||
|
|
||||||
|
traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred );
|
||||||
|
|
||||||
|
/* Prevent compiler warnings when trace macros are not used. */
|
||||||
|
( void ) xTimeoutOccurred;
|
||||||
|
|
||||||
|
return uxReturn;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
const BaseType_t xClearOnExit,
|
||||||
|
const BaseType_t xWaitForAllBits,
|
||||||
|
TickType_t xTicksToWait )
|
||||||
|
{
|
||||||
|
EventGroup_t * pxEventBits = xEventGroup;
|
||||||
|
EventBits_t uxReturn, uxControlBits = 0;
|
||||||
|
BaseType_t xWaitConditionMet, xAlreadyYielded;
|
||||||
|
BaseType_t xTimeoutOccurred = pdFALSE;
|
||||||
|
|
||||||
|
/* Check the user is not attempting to wait on the bits used by the kernel
|
||||||
|
* itself, and that at least one bit is being requested. */
|
||||||
|
configASSERT( xEventGroup );
|
||||||
|
configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
|
||||||
|
configASSERT( uxBitsToWaitFor != 0 );
|
||||||
|
#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
|
||||||
|
{
|
||||||
|
configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;
|
||||||
|
|
||||||
|
/* Check to see if the wait condition is already met or not. */
|
||||||
|
xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits );
|
||||||
|
|
||||||
|
if( xWaitConditionMet != pdFALSE )
|
||||||
|
{
|
||||||
|
/* The wait condition has already been met so there is no need to
|
||||||
|
* block. */
|
||||||
|
uxReturn = uxCurrentEventBits;
|
||||||
|
xTicksToWait = ( TickType_t ) 0;
|
||||||
|
|
||||||
|
/* Clear the wait bits if requested to do so. */
|
||||||
|
if( xClearOnExit != pdFALSE )
|
||||||
|
{
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if( xTicksToWait == ( TickType_t ) 0 )
|
||||||
|
{
|
||||||
|
/* The wait condition has not been met, but no block time was
|
||||||
|
* specified, so just return the current value. */
|
||||||
|
uxReturn = uxCurrentEventBits;
|
||||||
|
xTimeoutOccurred = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* The task is going to block to wait for its required bits to be
|
||||||
|
* set. uxControlBits are used to remember the specified behaviour of
|
||||||
|
* this call to xEventGroupWaitBits() - for use when the event bits
|
||||||
|
* unblock the task. */
|
||||||
|
if( xClearOnExit != pdFALSE )
|
||||||
|
{
|
||||||
|
uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
if( xWaitForAllBits != pdFALSE )
|
||||||
|
{
|
||||||
|
uxControlBits |= eventWAIT_FOR_ALL_BITS;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Store the bits that the calling task is waiting for in the
|
||||||
|
* task's event list item so the kernel knows when a match is
|
||||||
|
* found. Then enter the blocked state. */
|
||||||
|
vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait );
|
||||||
|
|
||||||
|
/* This is obsolete as it will get set after the task unblocks, but
|
||||||
|
* some compilers mistakenly generate a warning about the variable
|
||||||
|
* being returned without being set if it is not done. */
|
||||||
|
uxReturn = 0;
|
||||||
|
|
||||||
|
traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xAlreadyYielded = xTaskResumeAll();
|
||||||
|
|
||||||
|
if( xTicksToWait != ( TickType_t ) 0 )
|
||||||
|
{
|
||||||
|
if( xAlreadyYielded == pdFALSE )
|
||||||
|
{
|
||||||
|
portYIELD_WITHIN_API();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The task blocked to wait for its required bits to be set - at this
|
||||||
|
* point either the required bits were set or the block time expired. If
|
||||||
|
* the required bits were set they will have been stored in the task's
|
||||||
|
* event list item, and they should now be retrieved then cleared. */
|
||||||
|
uxReturn = uxTaskResetEventItemValue();
|
||||||
|
|
||||||
|
if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
taskENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
/* The task timed out, just return the current event bit value. */
|
||||||
|
uxReturn = pxEventBits->uxEventBits;
|
||||||
|
|
||||||
|
/* It is possible that the event bits were updated between this
|
||||||
|
* task leaving the Blocked state and running again. */
|
||||||
|
if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE )
|
||||||
|
{
|
||||||
|
if( xClearOnExit != pdFALSE )
|
||||||
|
{
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
xTimeoutOccurred = pdTRUE;
|
||||||
|
}
|
||||||
|
taskEXIT_CRITICAL();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* The task unblocked because the bits were set. */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The task blocked so control bits may have been set. */
|
||||||
|
uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
|
||||||
|
}
|
||||||
|
|
||||||
|
traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred );
|
||||||
|
|
||||||
|
/* Prevent compiler warnings when trace macros are not used. */
|
||||||
|
( void ) xTimeoutOccurred;
|
||||||
|
|
||||||
|
return uxReturn;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToClear )
|
||||||
|
{
|
||||||
|
EventGroup_t * pxEventBits = xEventGroup;
|
||||||
|
EventBits_t uxReturn;
|
||||||
|
|
||||||
|
/* Check the user is not attempting to clear the bits used by the kernel
|
||||||
|
* itself. */
|
||||||
|
configASSERT( xEventGroup );
|
||||||
|
configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
|
||||||
|
|
||||||
|
taskENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear );
|
||||||
|
|
||||||
|
/* The value returned is the event group value prior to the bits being
|
||||||
|
* cleared. */
|
||||||
|
uxReturn = pxEventBits->uxEventBits;
|
||||||
|
|
||||||
|
/* Clear the bits. */
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToClear;
|
||||||
|
}
|
||||||
|
taskEXIT_CRITICAL();
|
||||||
|
|
||||||
|
return uxReturn;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
|
||||||
|
|
||||||
|
BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToClear )
|
||||||
|
{
|
||||||
|
BaseType_t xReturn;
|
||||||
|
|
||||||
|
traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear );
|
||||||
|
xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
|
||||||
|
|
||||||
|
return xReturn;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup )
|
||||||
|
{
|
||||||
|
UBaseType_t uxSavedInterruptStatus;
|
||||||
|
EventGroup_t const * const pxEventBits = xEventGroup;
|
||||||
|
EventBits_t uxReturn;
|
||||||
|
|
||||||
|
uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
|
||||||
|
{
|
||||||
|
uxReturn = pxEventBits->uxEventBits;
|
||||||
|
}
|
||||||
|
portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
|
||||||
|
|
||||||
|
return uxReturn;
|
||||||
|
} /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet )
|
||||||
|
{
|
||||||
|
ListItem_t * pxListItem, * pxNext;
|
||||||
|
ListItem_t const * pxListEnd;
|
||||||
|
List_t const * pxList;
|
||||||
|
EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits;
|
||||||
|
EventGroup_t * pxEventBits = xEventGroup;
|
||||||
|
BaseType_t xMatchFound = pdFALSE;
|
||||||
|
|
||||||
|
/* Check the user is not attempting to set the bits used by the kernel
|
||||||
|
* itself. */
|
||||||
|
configASSERT( xEventGroup );
|
||||||
|
configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
|
||||||
|
|
||||||
|
pxList = &( pxEventBits->xTasksWaitingForBits );
|
||||||
|
pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet );
|
||||||
|
|
||||||
|
pxListItem = listGET_HEAD_ENTRY( pxList );
|
||||||
|
|
||||||
|
/* Set the bits. */
|
||||||
|
pxEventBits->uxEventBits |= uxBitsToSet;
|
||||||
|
|
||||||
|
/* See if the new bit value should unblock any tasks. */
|
||||||
|
while( pxListItem != pxListEnd )
|
||||||
|
{
|
||||||
|
pxNext = listGET_NEXT( pxListItem );
|
||||||
|
uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem );
|
||||||
|
xMatchFound = pdFALSE;
|
||||||
|
|
||||||
|
/* Split the bits waited for from the control bits. */
|
||||||
|
uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
|
||||||
|
uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;
|
||||||
|
|
||||||
|
if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
/* Just looking for single bit being set. */
|
||||||
|
if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
xMatchFound = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor )
|
||||||
|
{
|
||||||
|
/* All bits are set. */
|
||||||
|
xMatchFound = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Need all bits to be set, but not all the bits were set. */
|
||||||
|
}
|
||||||
|
|
||||||
|
if( xMatchFound != pdFALSE )
|
||||||
|
{
|
||||||
|
/* The bits match. Should the bits be cleared on exit? */
|
||||||
|
if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
uxBitsToClear |= uxBitsWaitedFor;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Store the actual event flag value in the task's event list
|
||||||
|
* item before removing the task from the event list. The
|
||||||
|
* eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows
|
||||||
|
* that is was unblocked due to its required bits matching, rather
|
||||||
|
* than because it timed out. */
|
||||||
|
vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET );
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Move onto the next list item. Note pxListItem->pxNext is not
|
||||||
|
* used here as the list item may have been removed from the event list
|
||||||
|
* and inserted into the ready/pending reading list. */
|
||||||
|
pxListItem = pxNext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT
|
||||||
|
* bit was set in the control word. */
|
||||||
|
pxEventBits->uxEventBits &= ~uxBitsToClear;
|
||||||
|
}
|
||||||
|
( void ) xTaskResumeAll();
|
||||||
|
|
||||||
|
return pxEventBits->uxEventBits;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vEventGroupDelete( EventGroupHandle_t xEventGroup )
|
||||||
|
{
|
||||||
|
EventGroup_t * pxEventBits = xEventGroup;
|
||||||
|
const List_t * pxTasksWaitingForBits;
|
||||||
|
|
||||||
|
configASSERT( pxEventBits );
|
||||||
|
|
||||||
|
pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits );
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
traceEVENT_GROUP_DELETE( xEventGroup );
|
||||||
|
|
||||||
|
while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 )
|
||||||
|
{
|
||||||
|
/* Unblock the task, returning 0 as the event list is being deleted
|
||||||
|
* and cannot therefore have any bits set. */
|
||||||
|
configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) );
|
||||||
|
vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET );
|
||||||
|
}
|
||||||
|
|
||||||
|
#if ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) )
|
||||||
|
{
|
||||||
|
/* The event group can only have been allocated dynamically - free
|
||||||
|
* it again. */
|
||||||
|
vPortFree( pxEventBits );
|
||||||
|
}
|
||||||
|
#elif ( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
|
||||||
|
{
|
||||||
|
/* The event group could have been allocated statically or
|
||||||
|
* dynamically, so check before attempting to free the memory. */
|
||||||
|
if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE )
|
||||||
|
{
|
||||||
|
vPortFree( pxEventBits );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
|
||||||
|
}
|
||||||
|
( void ) xTaskResumeAll();
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* For internal use only - execute a 'set bits' command that was pended from
|
||||||
|
* an interrupt. */
|
||||||
|
void vEventGroupSetBitsCallback( void * pvEventGroup,
|
||||||
|
const uint32_t ulBitsToSet )
|
||||||
|
{
|
||||||
|
( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* For internal use only - execute a 'clear bits' command that was pended from
|
||||||
|
* an interrupt. */
|
||||||
|
void vEventGroupClearBitsCallback( void * pvEventGroup,
|
||||||
|
const uint32_t ulBitsToClear )
|
||||||
|
{
|
||||||
|
( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
const BaseType_t xWaitForAllBits )
|
||||||
|
{
|
||||||
|
BaseType_t xWaitConditionMet = pdFALSE;
|
||||||
|
|
||||||
|
if( xWaitForAllBits == pdFALSE )
|
||||||
|
{
|
||||||
|
/* Task only has to wait for one bit within uxBitsToWaitFor to be
|
||||||
|
* set. Is one already set? */
|
||||||
|
if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 )
|
||||||
|
{
|
||||||
|
xWaitConditionMet = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* Task has to wait for all the bits in uxBitsToWaitFor to be set.
|
||||||
|
* Are they set already? */
|
||||||
|
if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor )
|
||||||
|
{
|
||||||
|
xWaitConditionMet = pdTRUE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return xWaitConditionMet;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
|
||||||
|
|
||||||
|
BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet,
|
||||||
|
BaseType_t * pxHigherPriorityTaskWoken )
|
||||||
|
{
|
||||||
|
BaseType_t xReturn;
|
||||||
|
|
||||||
|
traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet );
|
||||||
|
xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
|
||||||
|
|
||||||
|
return xReturn;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) ) */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
|
||||||
|
UBaseType_t uxEventGroupGetNumber( void * xEventGroup )
|
||||||
|
{
|
||||||
|
UBaseType_t xReturn;
|
||||||
|
EventGroup_t const * pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
|
||||||
|
|
||||||
|
if( xEventGroup == NULL )
|
||||||
|
{
|
||||||
|
xReturn = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
xReturn = pxEventBits->uxEventGroupNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
return xReturn;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configUSE_TRACE_FACILITY */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
|
||||||
|
void vEventGroupSetNumber( void * xEventGroup,
|
||||||
|
UBaseType_t uxEventGroupNumber )
|
||||||
|
{
|
||||||
|
( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configUSE_TRACE_FACILITY */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef _MSC_VER /* Visual Studio doesn't support #warning. */
|
||||||
|
#warning The name of this file has changed to stack_macros.h. Please update your code accordingly. This source file (which has the original name) will be removed in future released.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "stack_macros.h"
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @file atomic.h
|
||||||
|
* @brief FreeRTOS atomic operation support.
|
||||||
|
*
|
||||||
|
* This file implements atomic functions by disabling interrupts globally.
|
||||||
|
* Implementations with architecture specific atomic instructions can be
|
||||||
|
* provided under each compiler directory.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef ATOMIC_H
|
||||||
|
#define ATOMIC_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "include FreeRTOS.h must appear in source files before include atomic.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Standard includes. */
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Port specific definitions -- entering/exiting critical section.
|
||||||
|
* Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h
|
||||||
|
*
|
||||||
|
* Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with
|
||||||
|
* ATOMIC_ENTER_CRITICAL().
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#if defined( portSET_INTERRUPT_MASK_FROM_ISR )
|
||||||
|
|
||||||
|
/* Nested interrupt scheme is supported in this port. */
|
||||||
|
#define ATOMIC_ENTER_CRITICAL() \
|
||||||
|
UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR()
|
||||||
|
|
||||||
|
#define ATOMIC_EXIT_CRITICAL() \
|
||||||
|
portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType )
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
/* Nested interrupt scheme is NOT supported in this port. */
|
||||||
|
#define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL()
|
||||||
|
#define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL()
|
||||||
|
|
||||||
|
#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Port specific definition -- "always inline".
|
||||||
|
* Inline is compiler specific, and may not always get inlined depending on your
|
||||||
|
* optimization level. Also, inline is considered as performance optimization
|
||||||
|
* for atomic. Thus, if portFORCE_INLINE is not provided by portmacro.h,
|
||||||
|
* instead of resulting error, simply define it away.
|
||||||
|
*/
|
||||||
|
#ifndef portFORCE_INLINE
|
||||||
|
#define portFORCE_INLINE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */
|
||||||
|
#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */
|
||||||
|
|
||||||
|
/*----------------------------- Swap && CAS ------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic compare-and-swap
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic compare-and-swap operation on the specified values.
|
||||||
|
*
|
||||||
|
* @param[in, out] pulDestination Pointer to memory location from where value is
|
||||||
|
* to be loaded and checked.
|
||||||
|
* @param[in] ulExchange If condition meets, write this value to memory.
|
||||||
|
* @param[in] ulComparand Swap condition.
|
||||||
|
*
|
||||||
|
* @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped.
|
||||||
|
*
|
||||||
|
* @note This function only swaps *pulDestination with ulExchange, if previous
|
||||||
|
* *pulDestination value equals ulComparand.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( uint32_t volatile * pulDestination,
|
||||||
|
uint32_t ulExchange,
|
||||||
|
uint32_t ulComparand )
|
||||||
|
{
|
||||||
|
uint32_t ulReturnValue;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
if( *pulDestination == ulComparand )
|
||||||
|
{
|
||||||
|
*pulDestination = ulExchange;
|
||||||
|
ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulReturnValue;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic swap (pointers)
|
||||||
|
*
|
||||||
|
* @brief Atomically sets the address pointed to by *ppvDestination to the value
|
||||||
|
* of *pvExchange.
|
||||||
|
*
|
||||||
|
* @param[in, out] ppvDestination Pointer to memory location from where a pointer
|
||||||
|
* value is to be loaded and written back to.
|
||||||
|
* @param[in] pvExchange Pointer value to be written to *ppvDestination.
|
||||||
|
*
|
||||||
|
* @return The initial value of *ppvDestination.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE void * Atomic_SwapPointers_p32( void * volatile * ppvDestination,
|
||||||
|
void * pvExchange )
|
||||||
|
{
|
||||||
|
void * pReturnValue;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
pReturnValue = *ppvDestination;
|
||||||
|
*ppvDestination = pvExchange;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return pReturnValue;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic compare-and-swap (pointers)
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic compare-and-swap operation on the specified pointer
|
||||||
|
* values.
|
||||||
|
*
|
||||||
|
* @param[in, out] ppvDestination Pointer to memory location from where a pointer
|
||||||
|
* value is to be loaded and checked.
|
||||||
|
* @param[in] pvExchange If condition meets, write this value to memory.
|
||||||
|
* @param[in] pvComparand Swap condition.
|
||||||
|
*
|
||||||
|
* @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped.
|
||||||
|
*
|
||||||
|
* @note This function only swaps *ppvDestination with pvExchange, if previous
|
||||||
|
* *ppvDestination value equals pvComparand.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( void * volatile * ppvDestination,
|
||||||
|
void * pvExchange,
|
||||||
|
void * pvComparand )
|
||||||
|
{
|
||||||
|
uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
if( *ppvDestination == pvComparand )
|
||||||
|
{
|
||||||
|
*ppvDestination = pvExchange;
|
||||||
|
ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulReturnValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*----------------------------- Arithmetic ------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic add
|
||||||
|
*
|
||||||
|
* @brief Atomically adds count to the value of the specified pointer points to.
|
||||||
|
*
|
||||||
|
* @param[in,out] pulAddend Pointer to memory location from where value is to be
|
||||||
|
* loaded and written back to.
|
||||||
|
* @param[in] ulCount Value to be added to *pulAddend.
|
||||||
|
*
|
||||||
|
* @return previous *pulAddend value.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_Add_u32( uint32_t volatile * pulAddend,
|
||||||
|
uint32_t ulCount )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulAddend;
|
||||||
|
*pulAddend += ulCount;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic subtract
|
||||||
|
*
|
||||||
|
* @brief Atomically subtracts count from the value of the specified pointer
|
||||||
|
* pointers to.
|
||||||
|
*
|
||||||
|
* @param[in,out] pulAddend Pointer to memory location from where value is to be
|
||||||
|
* loaded and written back to.
|
||||||
|
* @param[in] ulCount Value to be subtract from *pulAddend.
|
||||||
|
*
|
||||||
|
* @return previous *pulAddend value.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_Subtract_u32( uint32_t volatile * pulAddend,
|
||||||
|
uint32_t ulCount )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulAddend;
|
||||||
|
*pulAddend -= ulCount;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic increment
|
||||||
|
*
|
||||||
|
* @brief Atomically increments the value of the specified pointer points to.
|
||||||
|
*
|
||||||
|
* @param[in,out] pulAddend Pointer to memory location from where value is to be
|
||||||
|
* loaded and written back to.
|
||||||
|
*
|
||||||
|
* @return *pulAddend value before increment.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pulAddend )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulAddend;
|
||||||
|
*pulAddend += 1;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic decrement
|
||||||
|
*
|
||||||
|
* @brief Atomically decrements the value of the specified pointer points to
|
||||||
|
*
|
||||||
|
* @param[in,out] pulAddend Pointer to memory location from where value is to be
|
||||||
|
* loaded and written back to.
|
||||||
|
*
|
||||||
|
* @return *pulAddend value before decrement.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pulAddend )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulAddend;
|
||||||
|
*pulAddend -= 1;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*----------------------------- Bitwise Logical ------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic OR
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic OR operation on the specified values.
|
||||||
|
*
|
||||||
|
* @param [in, out] pulDestination Pointer to memory location from where value is
|
||||||
|
* to be loaded and written back to.
|
||||||
|
* @param [in] ulValue Value to be ORed with *pulDestination.
|
||||||
|
*
|
||||||
|
* @return The original value of *pulDestination.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_OR_u32( uint32_t volatile * pulDestination,
|
||||||
|
uint32_t ulValue )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulDestination;
|
||||||
|
*pulDestination |= ulValue;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic AND
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic AND operation on the specified values.
|
||||||
|
*
|
||||||
|
* @param [in, out] pulDestination Pointer to memory location from where value is
|
||||||
|
* to be loaded and written back to.
|
||||||
|
* @param [in] ulValue Value to be ANDed with *pulDestination.
|
||||||
|
*
|
||||||
|
* @return The original value of *pulDestination.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_AND_u32( uint32_t volatile * pulDestination,
|
||||||
|
uint32_t ulValue )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulDestination;
|
||||||
|
*pulDestination &= ulValue;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic NAND
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic NAND operation on the specified values.
|
||||||
|
*
|
||||||
|
* @param [in, out] pulDestination Pointer to memory location from where value is
|
||||||
|
* to be loaded and written back to.
|
||||||
|
* @param [in] ulValue Value to be NANDed with *pulDestination.
|
||||||
|
*
|
||||||
|
* @return The original value of *pulDestination.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_NAND_u32( uint32_t volatile * pulDestination,
|
||||||
|
uint32_t ulValue )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulDestination;
|
||||||
|
*pulDestination = ~( ulCurrent & ulValue );
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Atomic XOR
|
||||||
|
*
|
||||||
|
* @brief Performs an atomic XOR operation on the specified values.
|
||||||
|
*
|
||||||
|
* @param [in, out] pulDestination Pointer to memory location from where value is
|
||||||
|
* to be loaded and written back to.
|
||||||
|
* @param [in] ulValue Value to be XORed with *pulDestination.
|
||||||
|
*
|
||||||
|
* @return The original value of *pulDestination.
|
||||||
|
*/
|
||||||
|
static portFORCE_INLINE uint32_t Atomic_XOR_u32( uint32_t volatile * pulDestination,
|
||||||
|
uint32_t ulValue )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrent;
|
||||||
|
|
||||||
|
ATOMIC_ENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
ulCurrent = *pulDestination;
|
||||||
|
*pulDestination ^= ulValue;
|
||||||
|
}
|
||||||
|
ATOMIC_EXIT_CRITICAL();
|
||||||
|
|
||||||
|
return ulCurrent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* ATOMIC_H */
|
||||||
@@ -0,0 +1,753 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef CO_ROUTINE_H
|
||||||
|
#define CO_ROUTINE_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "include FreeRTOS.h must appear in source files before include croutine.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "list.h"
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/* Used to hide the implementation of the co-routine control block. The
|
||||||
|
* control block structure however has to be included in the header due to
|
||||||
|
* the macro implementation of the co-routine functionality. */
|
||||||
|
typedef void * CoRoutineHandle_t;
|
||||||
|
|
||||||
|
/* Defines the prototype to which co-routine functions must conform. */
|
||||||
|
typedef void (* crCOROUTINE_CODE)( CoRoutineHandle_t,
|
||||||
|
UBaseType_t );
|
||||||
|
|
||||||
|
typedef struct corCoRoutineControlBlock
|
||||||
|
{
|
||||||
|
crCOROUTINE_CODE pxCoRoutineFunction;
|
||||||
|
ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */
|
||||||
|
ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */
|
||||||
|
UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */
|
||||||
|
UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */
|
||||||
|
uint16_t uxState; /*< Used internally by the co-routine implementation. */
|
||||||
|
} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xCoRoutineCreate(
|
||||||
|
* crCOROUTINE_CODE pxCoRoutineCode,
|
||||||
|
* UBaseType_t uxPriority,
|
||||||
|
* UBaseType_t uxIndex
|
||||||
|
* );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Create a new co-routine and add it to the list of co-routines that are
|
||||||
|
* ready to run.
|
||||||
|
*
|
||||||
|
* @param pxCoRoutineCode Pointer to the co-routine function. Co-routine
|
||||||
|
* functions require special syntax - see the co-routine section of the WEB
|
||||||
|
* documentation for more information.
|
||||||
|
*
|
||||||
|
* @param uxPriority The priority with respect to other co-routines at which
|
||||||
|
* the co-routine will run.
|
||||||
|
*
|
||||||
|
* @param uxIndex Used to distinguish between different co-routines that
|
||||||
|
* execute the same function. See the example below and the co-routine section
|
||||||
|
* of the WEB documentation for further information.
|
||||||
|
*
|
||||||
|
* @return pdPASS if the co-routine was successfully created and added to a ready
|
||||||
|
* list, otherwise an error code defined with ProjDefs.h.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Co-routine to be created.
|
||||||
|
* void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* // This may not be necessary for const variables.
|
||||||
|
* static const char cLedToFlash[ 2 ] = { 5, 6 };
|
||||||
|
* static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
|
||||||
|
*
|
||||||
|
* // Must start every co-routine with a call to crSTART();
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // This co-routine just delays for a fixed period, then toggles
|
||||||
|
* // an LED. Two co-routines are created using this function, so
|
||||||
|
* // the uxIndex parameter is used to tell the co-routine which
|
||||||
|
* // LED to flash and how int32_t to delay. This assumes xQueue has
|
||||||
|
* // already been created.
|
||||||
|
* vParTestToggleLED( cLedToFlash[ uxIndex ] );
|
||||||
|
* crDELAY( xHandle, uxFlashRates[ uxIndex ] );
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Must end every co-routine with a call to crEND();
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Function that creates two co-routines.
|
||||||
|
* void vOtherFunction( void )
|
||||||
|
* {
|
||||||
|
* uint8_t ucParameterToPass;
|
||||||
|
* TaskHandle_t xHandle;
|
||||||
|
*
|
||||||
|
* // Create two co-routines at priority 0. The first is given index 0
|
||||||
|
* // so (from the code above) toggles LED 5 every 200 ticks. The second
|
||||||
|
* // is given index 1 so toggles LED 6 every 400 ticks.
|
||||||
|
* for( uxIndex = 0; uxIndex < 2; uxIndex++ )
|
||||||
|
* {
|
||||||
|
* xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xCoRoutineCreate xCoRoutineCreate
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode,
|
||||||
|
UBaseType_t uxPriority,
|
||||||
|
UBaseType_t uxIndex );
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* void vCoRoutineSchedule( void );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Run a co-routine.
|
||||||
|
*
|
||||||
|
* vCoRoutineSchedule() executes the highest priority co-routine that is able
|
||||||
|
* to run. The co-routine will execute until it either blocks, yields or is
|
||||||
|
* preempted by a task. Co-routines execute cooperatively so one
|
||||||
|
* co-routine cannot be preempted by another, but can be preempted by a task.
|
||||||
|
*
|
||||||
|
* If an application comprises of both tasks and co-routines then
|
||||||
|
* vCoRoutineSchedule should be called from the idle task (in an idle task
|
||||||
|
* hook).
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // This idle task hook will schedule a co-routine each time it is called.
|
||||||
|
* // The rest of the idle task will execute between co-routine calls.
|
||||||
|
* void vApplicationIdleHook( void )
|
||||||
|
* {
|
||||||
|
* vCoRoutineSchedule();
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Alternatively, if you do not require any other part of the idle task to
|
||||||
|
* // execute, the idle task hook can call vCoRoutineSchedule() within an
|
||||||
|
* // infinite loop.
|
||||||
|
* void vApplicationIdleHook( void )
|
||||||
|
* {
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* vCoRoutineSchedule();
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup vCoRoutineSchedule vCoRoutineSchedule
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
void vCoRoutineSchedule( void );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crSTART( CoRoutineHandle_t xHandle );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* This macro MUST always be called at the start of a co-routine function.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Co-routine to be created.
|
||||||
|
* void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* static int32_t ulAVariable;
|
||||||
|
*
|
||||||
|
* // Must start every co-routine with a call to crSTART();
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Co-routine functionality goes here.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Must end every co-routine with a call to crEND();
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crSTART crSTART
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crSTART( pxCRCB ) \
|
||||||
|
switch( ( ( CRCB_t * ) ( pxCRCB ) )->uxState ) { \
|
||||||
|
case 0:
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crEND();
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* This macro MUST always be called at the end of a co-routine function.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Co-routine to be created.
|
||||||
|
* void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* static int32_t ulAVariable;
|
||||||
|
*
|
||||||
|
* // Must start every co-routine with a call to crSTART();
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Co-routine functionality goes here.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Must end every co-routine with a call to crEND();
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crSTART crSTART
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crEND() }
|
||||||
|
|
||||||
|
/*
|
||||||
|
* These macros are intended for internal use by the co-routine implementation
|
||||||
|
* only. The macros should not be used directly by application writers.
|
||||||
|
*/
|
||||||
|
#define crSET_STATE0( xHandle ) \
|
||||||
|
( ( CRCB_t * ) ( xHandle ) )->uxState = ( __LINE__ * 2 ); return; \
|
||||||
|
case ( __LINE__ * 2 ):
|
||||||
|
#define crSET_STATE1( xHandle ) \
|
||||||
|
( ( CRCB_t * ) ( xHandle ) )->uxState = ( ( __LINE__ * 2 ) + 1 ); return; \
|
||||||
|
case ( ( __LINE__ * 2 ) + 1 ):
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Delay a co-routine for a fixed period of time.
|
||||||
|
*
|
||||||
|
* crDELAY can only be called from the co-routine function itself - not
|
||||||
|
* from within a function called by the co-routine function. This is because
|
||||||
|
* co-routines do not maintain their own stack.
|
||||||
|
*
|
||||||
|
* @param xHandle The handle of the co-routine to delay. This is the xHandle
|
||||||
|
* parameter of the co-routine function.
|
||||||
|
*
|
||||||
|
* @param xTickToDelay The number of ticks that the co-routine should delay
|
||||||
|
* for. The actual amount of time this equates to is defined by
|
||||||
|
* configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS
|
||||||
|
* can be used to convert ticks to milliseconds.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Co-routine to be created.
|
||||||
|
* void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* // This may not be necessary for const variables.
|
||||||
|
* // We are to delay for 200ms.
|
||||||
|
* static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
|
||||||
|
*
|
||||||
|
* // Must start every co-routine with a call to crSTART();
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Delay for 200ms.
|
||||||
|
* crDELAY( xHandle, xDelayTime );
|
||||||
|
*
|
||||||
|
* // Do something here.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Must end every co-routine with a call to crEND();
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crDELAY crDELAY
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crDELAY( xHandle, xTicksToDelay ) \
|
||||||
|
if( ( xTicksToDelay ) > 0 ) \
|
||||||
|
{ \
|
||||||
|
vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \
|
||||||
|
} \
|
||||||
|
crSET_STATE0( ( xHandle ) );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @code{c}
|
||||||
|
* crQUEUE_SEND(
|
||||||
|
* CoRoutineHandle_t xHandle,
|
||||||
|
* QueueHandle_t pxQueue,
|
||||||
|
* void *pvItemToQueue,
|
||||||
|
* TickType_t xTicksToWait,
|
||||||
|
* BaseType_t *pxResult
|
||||||
|
* )
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
|
||||||
|
* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
|
||||||
|
* xQueueSend() and xQueueReceive() can only be used from tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND can only be called from the co-routine function itself - not
|
||||||
|
* from within a function called by the co-routine function. This is because
|
||||||
|
* co-routines do not maintain their own stack.
|
||||||
|
*
|
||||||
|
* See the co-routine section of the WEB documentation for information on
|
||||||
|
* passing data between tasks and co-routines and between ISR's and
|
||||||
|
* co-routines.
|
||||||
|
*
|
||||||
|
* @param xHandle The handle of the calling co-routine. This is the xHandle
|
||||||
|
* parameter of the co-routine function.
|
||||||
|
*
|
||||||
|
* @param pxQueue The handle of the queue on which the data will be posted.
|
||||||
|
* The handle is obtained as the return value when the queue is created using
|
||||||
|
* the xQueueCreate() API function.
|
||||||
|
*
|
||||||
|
* @param pvItemToQueue A pointer to the data being posted onto the queue.
|
||||||
|
* The number of bytes of each queued item is specified when the queue is
|
||||||
|
* created. This number of bytes is copied from pvItemToQueue into the queue
|
||||||
|
* itself.
|
||||||
|
*
|
||||||
|
* @param xTickToDelay The number of ticks that the co-routine should block
|
||||||
|
* to wait for space to become available on the queue, should space not be
|
||||||
|
* available immediately. The actual amount of time this equates to is defined
|
||||||
|
* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant
|
||||||
|
* portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example
|
||||||
|
* below).
|
||||||
|
*
|
||||||
|
* @param pxResult The variable pointed to by pxResult will be set to pdPASS if
|
||||||
|
* data was successfully posted onto the queue, otherwise it will be set to an
|
||||||
|
* error defined within ProjDefs.h.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Co-routine function that blocks for a fixed period then posts a number onto
|
||||||
|
* // a queue.
|
||||||
|
* static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* static BaseType_t xNumberToPost = 0;
|
||||||
|
* static BaseType_t xResult;
|
||||||
|
*
|
||||||
|
* // Co-routines must begin with a call to crSTART().
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // This assumes the queue has already been created.
|
||||||
|
* crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
|
||||||
|
*
|
||||||
|
* if( xResult != pdPASS )
|
||||||
|
* {
|
||||||
|
* // The message was not posted!
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Increment the number to be posted onto the queue.
|
||||||
|
* xNumberToPost++;
|
||||||
|
*
|
||||||
|
* // Delay for 100 ticks.
|
||||||
|
* crDELAY( xHandle, 100 );
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Co-routines must end with a call to crEND().
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crQUEUE_SEND crQUEUE_SEND
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \
|
||||||
|
{ \
|
||||||
|
*( pxResult ) = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), ( xTicksToWait ) ); \
|
||||||
|
if( *( pxResult ) == errQUEUE_BLOCKED ) \
|
||||||
|
{ \
|
||||||
|
crSET_STATE0( ( xHandle ) ); \
|
||||||
|
*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \
|
||||||
|
} \
|
||||||
|
if( *pxResult == errQUEUE_YIELD ) \
|
||||||
|
{ \
|
||||||
|
crSET_STATE1( ( xHandle ) ); \
|
||||||
|
*pxResult = pdPASS; \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crQUEUE_RECEIVE(
|
||||||
|
* CoRoutineHandle_t xHandle,
|
||||||
|
* QueueHandle_t pxQueue,
|
||||||
|
* void *pvBuffer,
|
||||||
|
* TickType_t xTicksToWait,
|
||||||
|
* BaseType_t *pxResult
|
||||||
|
* )
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
|
||||||
|
* equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
|
||||||
|
* xQueueSend() and xQueueReceive() can only be used from tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_RECEIVE can only be called from the co-routine function itself - not
|
||||||
|
* from within a function called by the co-routine function. This is because
|
||||||
|
* co-routines do not maintain their own stack.
|
||||||
|
*
|
||||||
|
* See the co-routine section of the WEB documentation for information on
|
||||||
|
* passing data between tasks and co-routines and between ISR's and
|
||||||
|
* co-routines.
|
||||||
|
*
|
||||||
|
* @param xHandle The handle of the calling co-routine. This is the xHandle
|
||||||
|
* parameter of the co-routine function.
|
||||||
|
*
|
||||||
|
* @param pxQueue The handle of the queue from which the data will be received.
|
||||||
|
* The handle is obtained as the return value when the queue is created using
|
||||||
|
* the xQueueCreate() API function.
|
||||||
|
*
|
||||||
|
* @param pvBuffer The buffer into which the received item is to be copied.
|
||||||
|
* The number of bytes of each queued item is specified when the queue is
|
||||||
|
* created. This number of bytes is copied into pvBuffer.
|
||||||
|
*
|
||||||
|
* @param xTickToDelay The number of ticks that the co-routine should block
|
||||||
|
* to wait for data to become available from the queue, should data not be
|
||||||
|
* available immediately. The actual amount of time this equates to is defined
|
||||||
|
* by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant
|
||||||
|
* portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the
|
||||||
|
* crQUEUE_SEND example).
|
||||||
|
*
|
||||||
|
* @param pxResult The variable pointed to by pxResult will be set to pdPASS if
|
||||||
|
* data was successfully retrieved from the queue, otherwise it will be set to
|
||||||
|
* an error code as defined within ProjDefs.h.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // A co-routine receives the number of an LED to flash from a queue. It
|
||||||
|
* // blocks on the queue until the number is received.
|
||||||
|
* static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // Variables in co-routines must be declared static if they must maintain value across a blocking call.
|
||||||
|
* static BaseType_t xResult;
|
||||||
|
* static UBaseType_t uxLEDToFlash;
|
||||||
|
*
|
||||||
|
* // All co-routines must start with a call to crSTART().
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Wait for data to become available on the queue.
|
||||||
|
* crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
|
||||||
|
*
|
||||||
|
* if( xResult == pdPASS )
|
||||||
|
* {
|
||||||
|
* // We received the LED to flash - flash it!
|
||||||
|
* vParTestToggleLED( uxLEDToFlash );
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \
|
||||||
|
{ \
|
||||||
|
*( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), ( xTicksToWait ) ); \
|
||||||
|
if( *( pxResult ) == errQUEUE_BLOCKED ) \
|
||||||
|
{ \
|
||||||
|
crSET_STATE0( ( xHandle ) ); \
|
||||||
|
*( pxResult ) = xQueueCRReceive( ( pxQueue ), ( pvBuffer ), 0 ); \
|
||||||
|
} \
|
||||||
|
if( *( pxResult ) == errQUEUE_YIELD ) \
|
||||||
|
{ \
|
||||||
|
crSET_STATE1( ( xHandle ) ); \
|
||||||
|
*( pxResult ) = pdPASS; \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crQUEUE_SEND_FROM_ISR(
|
||||||
|
* QueueHandle_t pxQueue,
|
||||||
|
* void *pvItemToQueue,
|
||||||
|
* BaseType_t xCoRoutinePreviouslyWoken
|
||||||
|
* )
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
|
||||||
|
* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
|
||||||
|
* functions used by tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
|
||||||
|
* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
|
||||||
|
* xQueueReceiveFromISR() can only be used to pass data between a task and and
|
||||||
|
* ISR.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue
|
||||||
|
* that is being used from within a co-routine.
|
||||||
|
*
|
||||||
|
* See the co-routine section of the WEB documentation for information on
|
||||||
|
* passing data between tasks and co-routines and between ISR's and
|
||||||
|
* co-routines.
|
||||||
|
*
|
||||||
|
* @param xQueue The handle to the queue on which the item is to be posted.
|
||||||
|
*
|
||||||
|
* @param pvItemToQueue A pointer to the item that is to be placed on the
|
||||||
|
* queue. The size of the items the queue will hold was defined when the
|
||||||
|
* queue was created, so this many bytes will be copied from pvItemToQueue
|
||||||
|
* into the queue storage area.
|
||||||
|
*
|
||||||
|
* @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto
|
||||||
|
* the same queue multiple times from a single interrupt. The first call
|
||||||
|
* should always pass in pdFALSE. Subsequent calls should pass in
|
||||||
|
* the value returned from the previous call.
|
||||||
|
*
|
||||||
|
* @return pdTRUE if a co-routine was woken by posting onto the queue. This is
|
||||||
|
* used by the ISR to determine if a context switch may be required following
|
||||||
|
* the ISR.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // A co-routine that blocks on a queue waiting for characters to be received.
|
||||||
|
* static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* char cRxedChar;
|
||||||
|
* BaseType_t xResult;
|
||||||
|
*
|
||||||
|
* // All co-routines must start with a call to crSTART().
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Wait for data to become available on the queue. This assumes the
|
||||||
|
* // queue xCommsRxQueue has already been created!
|
||||||
|
* crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
|
||||||
|
*
|
||||||
|
* // Was a character received?
|
||||||
|
* if( xResult == pdPASS )
|
||||||
|
* {
|
||||||
|
* // Process the character here.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // All co-routines must end with a call to crEND().
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // An ISR that uses a queue to send characters received on a serial port to
|
||||||
|
* // a co-routine.
|
||||||
|
* void vUART_ISR( void )
|
||||||
|
* {
|
||||||
|
* char cRxedChar;
|
||||||
|
* BaseType_t xCRWokenByPost = pdFALSE;
|
||||||
|
*
|
||||||
|
* // We loop around reading characters until there are none left in the UART.
|
||||||
|
* while( UART_RX_REG_NOT_EMPTY() )
|
||||||
|
* {
|
||||||
|
* // Obtain the character from the UART.
|
||||||
|
* cRxedChar = UART_RX_REG;
|
||||||
|
*
|
||||||
|
* // Post the character onto a queue. xCRWokenByPost will be pdFALSE
|
||||||
|
* // the first time around the loop. If the post causes a co-routine
|
||||||
|
* // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
|
||||||
|
* // In this manner we can ensure that if more than one co-routine is
|
||||||
|
* // blocked on the queue only one is woken by this ISR no matter how
|
||||||
|
* // many characters are posted to the queue.
|
||||||
|
* xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) \
|
||||||
|
xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) )
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* croutine. h
|
||||||
|
* @code{c}
|
||||||
|
* crQUEUE_SEND_FROM_ISR(
|
||||||
|
* QueueHandle_t pxQueue,
|
||||||
|
* void *pvBuffer,
|
||||||
|
* BaseType_t * pxCoRoutineWoken
|
||||||
|
* )
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
|
||||||
|
* co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
|
||||||
|
* functions used by tasks.
|
||||||
|
*
|
||||||
|
* crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
|
||||||
|
* pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
|
||||||
|
* xQueueReceiveFromISR() can only be used to pass data between a task and and
|
||||||
|
* ISR.
|
||||||
|
*
|
||||||
|
* crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data
|
||||||
|
* from a queue that is being used from within a co-routine (a co-routine
|
||||||
|
* posted to the queue).
|
||||||
|
*
|
||||||
|
* See the co-routine section of the WEB documentation for information on
|
||||||
|
* passing data between tasks and co-routines and between ISR's and
|
||||||
|
* co-routines.
|
||||||
|
*
|
||||||
|
* @param xQueue The handle to the queue on which the item is to be posted.
|
||||||
|
*
|
||||||
|
* @param pvBuffer A pointer to a buffer into which the received item will be
|
||||||
|
* placed. The size of the items the queue will hold was defined when the
|
||||||
|
* queue was created, so this many bytes will be copied from the queue into
|
||||||
|
* pvBuffer.
|
||||||
|
*
|
||||||
|
* @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become
|
||||||
|
* available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a
|
||||||
|
* co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise
|
||||||
|
* *pxCoRoutineWoken will remain unchanged.
|
||||||
|
*
|
||||||
|
* @return pdTRUE an item was successfully received from the queue, otherwise
|
||||||
|
* pdFALSE.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // A co-routine that posts a character to a queue then blocks for a fixed
|
||||||
|
* // period. The character is incremented each time.
|
||||||
|
* static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
|
||||||
|
* {
|
||||||
|
* // cChar holds its value while this co-routine is blocked and must therefore
|
||||||
|
* // be declared static.
|
||||||
|
* static char cCharToTx = 'a';
|
||||||
|
* BaseType_t xResult;
|
||||||
|
*
|
||||||
|
* // All co-routines must start with a call to crSTART().
|
||||||
|
* crSTART( xHandle );
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Send the next character to the queue.
|
||||||
|
* crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
|
||||||
|
*
|
||||||
|
* if( xResult == pdPASS )
|
||||||
|
* {
|
||||||
|
* // The character was successfully posted to the queue.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // Could not post the character to the queue.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Enable the UART Tx interrupt to cause an interrupt in this
|
||||||
|
* // hypothetical UART. The interrupt will obtain the character
|
||||||
|
* // from the queue and send it.
|
||||||
|
* ENABLE_RX_INTERRUPT();
|
||||||
|
*
|
||||||
|
* // Increment to the next character then block for a fixed period.
|
||||||
|
* // cCharToTx will maintain its value across the delay as it is
|
||||||
|
* // declared static.
|
||||||
|
* cCharToTx++;
|
||||||
|
* if( cCharToTx > 'x' )
|
||||||
|
* {
|
||||||
|
* cCharToTx = 'a';
|
||||||
|
* }
|
||||||
|
* crDELAY( 100 );
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // All co-routines must end with a call to crEND().
|
||||||
|
* crEND();
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // An ISR that uses a queue to receive characters to send on a UART.
|
||||||
|
* void vUART_ISR( void )
|
||||||
|
* {
|
||||||
|
* char cCharToTx;
|
||||||
|
* BaseType_t xCRWokenByPost = pdFALSE;
|
||||||
|
*
|
||||||
|
* while( UART_TX_REG_EMPTY() )
|
||||||
|
* {
|
||||||
|
* // Are there any characters in the queue waiting to be sent?
|
||||||
|
* // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
|
||||||
|
* // is woken by the post - ensuring that only a single co-routine is
|
||||||
|
* // woken no matter how many times we go around this loop.
|
||||||
|
* if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
|
||||||
|
* {
|
||||||
|
* SEND_CHARACTER( cCharToTx );
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR
|
||||||
|
* \ingroup Tasks
|
||||||
|
*/
|
||||||
|
#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) \
|
||||||
|
xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This function is intended for internal use by the co-routine macros only.
|
||||||
|
* The macro nature of the co-routine implementation requires that the
|
||||||
|
* prototype appears here. The function should not be used by application
|
||||||
|
* writers.
|
||||||
|
*
|
||||||
|
* Removes the current co-routine from its ready list and places it in the
|
||||||
|
* appropriate delayed list.
|
||||||
|
*/
|
||||||
|
void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay,
|
||||||
|
List_t * pxEventList );
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This function is intended for internal use by the queue implementation only.
|
||||||
|
* The function should not be used by application writers.
|
||||||
|
*
|
||||||
|
* Removes the highest priority co-routine from the event list and places it in
|
||||||
|
* the pending ready list.
|
||||||
|
*/
|
||||||
|
BaseType_t xCoRoutineRemoveFromEventList( const List_t * pxEventList );
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* CO_ROUTINE_H */
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef DEPRECATED_DEFINITIONS_H
|
||||||
|
#define DEPRECATED_DEFINITIONS_H
|
||||||
|
|
||||||
|
|
||||||
|
/* Each FreeRTOS port has a unique portmacro.h header file. Originally a
|
||||||
|
* pre-processor definition was used to ensure the pre-processor found the correct
|
||||||
|
* portmacro.h file for the port being used. That scheme was deprecated in favour
|
||||||
|
* of setting the compiler's include path such that it found the correct
|
||||||
|
* portmacro.h file - removing the need for the constant and allowing the
|
||||||
|
* portmacro.h file to be located anywhere in relation to the port being used. The
|
||||||
|
* definitions below remain in the code for backward compatibility only. New
|
||||||
|
* projects should not use them. */
|
||||||
|
|
||||||
|
#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT
|
||||||
|
#include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h"
|
||||||
|
typedef void ( __interrupt __far * pxISR )();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT
|
||||||
|
#include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h"
|
||||||
|
typedef void ( __interrupt __far * pxISR )();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_MEGA_AVR
|
||||||
|
#include "../portable/GCC/ATMega323/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef IAR_MEGA_AVR
|
||||||
|
#include "../portable/IAR/ATMega323/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef MPLAB_PIC24_PORT
|
||||||
|
#include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef MPLAB_DSPIC_PORT
|
||||||
|
#include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef MPLAB_PIC18F_PORT
|
||||||
|
#include "../../Source/portable/MPLAB/PIC18F/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef MPLAB_PIC32MX_PORT
|
||||||
|
#include "../../Source/portable/MPLAB/PIC32MX/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _FEDPICC
|
||||||
|
#include "libFreeRTOS/Include/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SDCC_CYGNAL
|
||||||
|
#include "../../Source/portable/SDCC/Cygnal/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_ARM7
|
||||||
|
#include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_ARM7_ECLIPSE
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef ROWLEY_LPC23xx
|
||||||
|
#include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef IAR_MSP430
|
||||||
|
#include "..\..\Source\portable\IAR\MSP430\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_MSP430
|
||||||
|
#include "../../Source/portable/GCC/MSP430F449/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef ROWLEY_MSP430
|
||||||
|
#include "../../Source/portable/Rowley/MSP430F449/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef ARM7_LPC21xx_KEIL_RVDS
|
||||||
|
#include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SAM7_GCC
|
||||||
|
#include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SAM7_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SAM9XE_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef LPC2000_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\LPC2000\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef STR71X_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\STR71x\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef STR75X_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\STR75x\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef STR75X_GCC
|
||||||
|
#include "..\..\Source\portable\GCC\STR75x\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef STR91X_IAR
|
||||||
|
#include "..\..\Source\portable\IAR\STR91x\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_H8S
|
||||||
|
#include "../../Source/portable/GCC/H8S2329/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_AT91FR40008
|
||||||
|
#include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef RVDS_ARMCM3_LM3S102
|
||||||
|
#include "../../Source/portable/RVDS/ARM_CM3/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_ARMCM3_LM3S102
|
||||||
|
#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_ARMCM3
|
||||||
|
#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef IAR_ARM_CM3
|
||||||
|
#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef IAR_ARMCM3_LM
|
||||||
|
#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef HCS12_CODE_WARRIOR
|
||||||
|
#include "../../Source/portable/CodeWarrior/HCS12/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef MICROBLAZE_GCC
|
||||||
|
#include "../../Source/portable/GCC/MicroBlaze/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef TERN_EE
|
||||||
|
#include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_HCS12
|
||||||
|
#include "../../Source/portable/GCC/HCS12/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_MCF5235
|
||||||
|
#include "../../Source/portable/GCC/MCF5235/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef COLDFIRE_V2_GCC
|
||||||
|
#include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef COLDFIRE_V2_CODEWARRIOR
|
||||||
|
#include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_PPC405
|
||||||
|
#include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GCC_PPC440
|
||||||
|
#include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _16FX_SOFTUNE
|
||||||
|
#include "..\..\Source\portable\Softune\MB96340\portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef BCC_INDUSTRIAL_PC_PORT
|
||||||
|
|
||||||
|
/* A short file name has to be used in place of the normal
|
||||||
|
* FreeRTOSConfig.h when using the Borland compiler. */
|
||||||
|
#include "frconfig.h"
|
||||||
|
#include "..\portable\BCC\16BitDOS\PC\prtmacro.h"
|
||||||
|
typedef void ( __interrupt __far * pxISR )();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef BCC_FLASH_LITE_186_PORT
|
||||||
|
|
||||||
|
/* A short file name has to be used in place of the normal
|
||||||
|
* FreeRTOSConfig.h when using the Borland compiler. */
|
||||||
|
#include "frconfig.h"
|
||||||
|
#include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h"
|
||||||
|
typedef void ( __interrupt __far * pxISR )();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __GNUC__
|
||||||
|
#ifdef __AVR32_AVR32A__
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __ICCAVR32__
|
||||||
|
#ifdef __CORE__
|
||||||
|
#if __CORE__ == __AVR32A__
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __91467D
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __96340
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef __IAR_V850ES_Fx3__
|
||||||
|
#include "../../Source/portable/IAR/V850ES/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_V850ES_Jx3__
|
||||||
|
#include "../../Source/portable/IAR/V850ES/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_V850ES_Jx3_L__
|
||||||
|
#include "../../Source/portable/IAR/V850ES/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_V850ES_Jx2__
|
||||||
|
#include "../../Source/portable/IAR/V850ES/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_V850ES_Hx2__
|
||||||
|
#include "../../Source/portable/IAR/V850ES/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_78K0R_Kx3__
|
||||||
|
#include "../../Source/portable/IAR/78K0R/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __IAR_78K0R_Kx3L__
|
||||||
|
#include "../../Source/portable/IAR/78K0R/portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* DEPRECATED_DEFINITIONS_H */
|
||||||
@@ -0,0 +1,777 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef EVENT_GROUPS_H
|
||||||
|
#define EVENT_GROUPS_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "include FreeRTOS.h" must appear in source files before "include event_groups.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* FreeRTOS includes. */
|
||||||
|
#include "timers.h"
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event group is a collection of bits to which an application can assign a
|
||||||
|
* meaning. For example, an application may create an event group to convey
|
||||||
|
* the status of various CAN bus related events in which bit 0 might mean "A CAN
|
||||||
|
* message has been received and is ready for processing", bit 1 might mean "The
|
||||||
|
* application has queued a message that is ready for sending onto the CAN
|
||||||
|
* network", and bit 2 might mean "It is time to send a SYNC message onto the
|
||||||
|
* CAN network" etc. A task can then test the bit values to see which events
|
||||||
|
* are active, and optionally enter the Blocked state to wait for a specified
|
||||||
|
* bit or a group of specified bits to be active. To continue the CAN bus
|
||||||
|
* example, a CAN controlling task can enter the Blocked state (and therefore
|
||||||
|
* not consume any processing time) until either bit 0, bit 1 or bit 2 are
|
||||||
|
* active, at which time the bit that was actually active would inform the task
|
||||||
|
* which action it had to take (process a received message, send a message, or
|
||||||
|
* send a SYNC).
|
||||||
|
*
|
||||||
|
* The event groups implementation contains intelligence to avoid race
|
||||||
|
* conditions that would otherwise occur were an application to use a simple
|
||||||
|
* variable for the same purpose. This is particularly important with respect
|
||||||
|
* to when a bit within an event group is to be cleared, and when bits have to
|
||||||
|
* be set and then tested atomically - as is the case where event groups are
|
||||||
|
* used to create a synchronisation point between multiple tasks (a
|
||||||
|
* 'rendezvous').
|
||||||
|
*
|
||||||
|
* \defgroup EventGroup
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
*
|
||||||
|
* Type by which event groups are referenced. For example, a call to
|
||||||
|
* xEventGroupCreate() returns an EventGroupHandle_t variable that can then
|
||||||
|
* be used as a parameter to other event group functions.
|
||||||
|
*
|
||||||
|
* \defgroup EventGroupHandle_t EventGroupHandle_t
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
struct EventGroupDef_t;
|
||||||
|
typedef struct EventGroupDef_t * EventGroupHandle_t;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The type that holds event bits always matches TickType_t - therefore the
|
||||||
|
* number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1,
|
||||||
|
* 32 bits if set to 0.
|
||||||
|
*
|
||||||
|
* \defgroup EventBits_t EventBits_t
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
typedef TickType_t EventBits_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventGroupHandle_t xEventGroupCreate( void );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Create a new event group.
|
||||||
|
*
|
||||||
|
* Internally, within the FreeRTOS implementation, event groups use a [small]
|
||||||
|
* block of memory, in which the event group's structure is stored. If an event
|
||||||
|
* groups is created using xEventGroupCreate() then the required memory is
|
||||||
|
* automatically dynamically allocated inside the xEventGroupCreate() function.
|
||||||
|
* (see https://www.FreeRTOS.org/a00111.html). If an event group is created
|
||||||
|
* using xEventGroupCreateStatic() then the application writer must instead
|
||||||
|
* provide the memory that will get used by the event group.
|
||||||
|
* xEventGroupCreateStatic() therefore allows an event group to be created
|
||||||
|
* without using any dynamic memory allocation.
|
||||||
|
*
|
||||||
|
* Although event groups are not related to ticks, for internal implementation
|
||||||
|
* reasons the number of bits available for use in an event group is dependent
|
||||||
|
* on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If
|
||||||
|
* configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit
|
||||||
|
* 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has
|
||||||
|
* 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store
|
||||||
|
* event bits within an event group.
|
||||||
|
*
|
||||||
|
* @return If the event group was created then a handle to the event group is
|
||||||
|
* returned. If there was insufficient FreeRTOS heap available to create the
|
||||||
|
* event group then NULL is returned. See https://www.FreeRTOS.org/a00111.html
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Declare a variable to hold the created event group.
|
||||||
|
* EventGroupHandle_t xCreatedEventGroup;
|
||||||
|
*
|
||||||
|
* // Attempt to create the event group.
|
||||||
|
* xCreatedEventGroup = xEventGroupCreate();
|
||||||
|
*
|
||||||
|
* // Was the event group created successfully?
|
||||||
|
* if( xCreatedEventGroup == NULL )
|
||||||
|
* {
|
||||||
|
* // The event group was not created because there was insufficient
|
||||||
|
* // FreeRTOS heap available.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // The event group was created.
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupCreate xEventGroupCreate
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
#if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
|
||||||
|
EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Create a new event group.
|
||||||
|
*
|
||||||
|
* Internally, within the FreeRTOS implementation, event groups use a [small]
|
||||||
|
* block of memory, in which the event group's structure is stored. If an event
|
||||||
|
* groups is created using xEventGroupCreate() then the required memory is
|
||||||
|
* automatically dynamically allocated inside the xEventGroupCreate() function.
|
||||||
|
* (see https://www.FreeRTOS.org/a00111.html). If an event group is created
|
||||||
|
* using xEventGroupCreateStatic() then the application writer must instead
|
||||||
|
* provide the memory that will get used by the event group.
|
||||||
|
* xEventGroupCreateStatic() therefore allows an event group to be created
|
||||||
|
* without using any dynamic memory allocation.
|
||||||
|
*
|
||||||
|
* Although event groups are not related to ticks, for internal implementation
|
||||||
|
* reasons the number of bits available for use in an event group is dependent
|
||||||
|
* on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If
|
||||||
|
* configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit
|
||||||
|
* 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has
|
||||||
|
* 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store
|
||||||
|
* event bits within an event group.
|
||||||
|
*
|
||||||
|
* @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type
|
||||||
|
* StaticEventGroup_t, which will be then be used to hold the event group's data
|
||||||
|
* structures, removing the need for the memory to be allocated dynamically.
|
||||||
|
*
|
||||||
|
* @return If the event group was created then a handle to the event group is
|
||||||
|
* returned. If pxEventGroupBuffer was NULL then NULL is returned.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // StaticEventGroup_t is a publicly accessible structure that has the same
|
||||||
|
* // size and alignment requirements as the real event group structure. It is
|
||||||
|
* // provided as a mechanism for applications to know the size of the event
|
||||||
|
* // group (which is dependent on the architecture and configuration file
|
||||||
|
* // settings) without breaking the strict data hiding policy by exposing the
|
||||||
|
* // real event group internals. This StaticEventGroup_t variable is passed
|
||||||
|
* // into the xSemaphoreCreateEventGroupStatic() function and is used to store
|
||||||
|
* // the event group's data structures
|
||||||
|
* StaticEventGroup_t xEventGroupBuffer;
|
||||||
|
*
|
||||||
|
* // Create the event group without dynamically allocating any memory.
|
||||||
|
* xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer );
|
||||||
|
* @endcode
|
||||||
|
*/
|
||||||
|
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
|
||||||
|
EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
|
||||||
|
* const EventBits_t uxBitsToWaitFor,
|
||||||
|
* const BaseType_t xClearOnExit,
|
||||||
|
* const BaseType_t xWaitForAllBits,
|
||||||
|
* const TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* [Potentially] block to wait for one or more bits to be set within a
|
||||||
|
* previously created event group.
|
||||||
|
*
|
||||||
|
* This function cannot be called from an interrupt.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are being tested. The
|
||||||
|
* event group must have previously been created using a call to
|
||||||
|
* xEventGroupCreate().
|
||||||
|
*
|
||||||
|
* @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test
|
||||||
|
* inside the event group. For example, to wait for bit 0 and/or bit 2 set
|
||||||
|
* uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set
|
||||||
|
* uxBitsToWaitFor to 0x07. Etc.
|
||||||
|
*
|
||||||
|
* @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within
|
||||||
|
* uxBitsToWaitFor that are set within the event group will be cleared before
|
||||||
|
* xEventGroupWaitBits() returns if the wait condition was met (if the function
|
||||||
|
* returns for a reason other than a timeout). If xClearOnExit is set to
|
||||||
|
* pdFALSE then the bits set in the event group are not altered when the call to
|
||||||
|
* xEventGroupWaitBits() returns.
|
||||||
|
*
|
||||||
|
* @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then
|
||||||
|
* xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor
|
||||||
|
* are set or the specified block time expires. If xWaitForAllBits is set to
|
||||||
|
* pdFALSE then xEventGroupWaitBits() will return when any one of the bits set
|
||||||
|
* in uxBitsToWaitFor is set or the specified block time expires. The block
|
||||||
|
* time is specified by the xTicksToWait parameter.
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait
|
||||||
|
* for one/all (depending on the xWaitForAllBits value) of the bits specified by
|
||||||
|
* uxBitsToWaitFor to become set.
|
||||||
|
*
|
||||||
|
* @return The value of the event group at the time either the bits being waited
|
||||||
|
* for became set, or the block time expired. Test the return value to know
|
||||||
|
* which bits were set. If xEventGroupWaitBits() returned because its timeout
|
||||||
|
* expired then not all the bits being waited for will be set. If
|
||||||
|
* xEventGroupWaitBits() returned because the bits it was waiting for were set
|
||||||
|
* then the returned value is the event group value before any bits were
|
||||||
|
* automatically cleared in the case that xClearOnExit parameter was set to
|
||||||
|
* pdTRUE.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* #define BIT_0 ( 1 << 0 )
|
||||||
|
* #define BIT_4 ( 1 << 4 )
|
||||||
|
*
|
||||||
|
* void aFunction( EventGroupHandle_t xEventGroup )
|
||||||
|
* {
|
||||||
|
* EventBits_t uxBits;
|
||||||
|
* const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
|
||||||
|
*
|
||||||
|
* // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
|
||||||
|
* // the event group. Clear the bits before exiting.
|
||||||
|
* uxBits = xEventGroupWaitBits(
|
||||||
|
* xEventGroup, // The event group being tested.
|
||||||
|
* BIT_0 | BIT_4, // The bits within the event group to wait for.
|
||||||
|
* pdTRUE, // BIT_0 and BIT_4 should be cleared before returning.
|
||||||
|
* pdFALSE, // Don't wait for both bits, either bit will do.
|
||||||
|
* xTicksToWait ); // Wait a maximum of 100ms for either bit to be set.
|
||||||
|
*
|
||||||
|
* if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
|
||||||
|
* {
|
||||||
|
* // xEventGroupWaitBits() returned because both bits were set.
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_0 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // xEventGroupWaitBits() returned because just BIT_0 was set.
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_4 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // xEventGroupWaitBits() returned because just BIT_4 was set.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // xEventGroupWaitBits() returned because xTicksToWait ticks passed
|
||||||
|
* // without either BIT_0 or BIT_4 becoming set.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupWaitBits xEventGroupWaitBits
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
const BaseType_t xClearOnExit,
|
||||||
|
const BaseType_t xWaitForAllBits,
|
||||||
|
TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Clear bits within an event group. This function cannot be called from an
|
||||||
|
* interrupt.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are to be cleared.
|
||||||
|
*
|
||||||
|
* @param uxBitsToClear A bitwise value that indicates the bit or bits to clear
|
||||||
|
* in the event group. For example, to clear bit 3 only, set uxBitsToClear to
|
||||||
|
* 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09.
|
||||||
|
*
|
||||||
|
* @return The value of the event group before the specified bits were cleared.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* #define BIT_0 ( 1 << 0 )
|
||||||
|
* #define BIT_4 ( 1 << 4 )
|
||||||
|
*
|
||||||
|
* void aFunction( EventGroupHandle_t xEventGroup )
|
||||||
|
* {
|
||||||
|
* EventBits_t uxBits;
|
||||||
|
*
|
||||||
|
* // Clear bit 0 and bit 4 in xEventGroup.
|
||||||
|
* uxBits = xEventGroupClearBits(
|
||||||
|
* xEventGroup, // The event group being updated.
|
||||||
|
* BIT_0 | BIT_4 );// The bits being cleared.
|
||||||
|
*
|
||||||
|
* if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
|
||||||
|
* {
|
||||||
|
* // Both bit 0 and bit 4 were set before xEventGroupClearBits() was
|
||||||
|
* // called. Both will now be clear (not set).
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_0 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // Bit 0 was set before xEventGroupClearBits() was called. It will
|
||||||
|
* // now be clear.
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_4 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // Bit 4 was set before xEventGroupClearBits() was called. It will
|
||||||
|
* // now be clear.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // Neither bit 0 nor bit 4 were set in the first place.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupClearBits xEventGroupClearBits
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* A version of xEventGroupClearBits() that can be called from an interrupt.
|
||||||
|
*
|
||||||
|
* Setting bits in an event group is not a deterministic operation because there
|
||||||
|
* are an unknown number of tasks that may be waiting for the bit or bits being
|
||||||
|
* set. FreeRTOS does not allow nondeterministic operations to be performed
|
||||||
|
* while interrupts are disabled, so protects event groups that are accessed
|
||||||
|
* from tasks by suspending the scheduler rather than disabling interrupts. As
|
||||||
|
* a result event groups cannot be accessed directly from an interrupt service
|
||||||
|
* routine. Therefore xEventGroupClearBitsFromISR() sends a message to the
|
||||||
|
* timer task to have the clear operation performed in the context of the timer
|
||||||
|
* task.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are to be cleared.
|
||||||
|
*
|
||||||
|
* @param uxBitsToClear A bitwise value that indicates the bit or bits to clear.
|
||||||
|
* For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3
|
||||||
|
* and bit 0 set uxBitsToClear to 0x09.
|
||||||
|
*
|
||||||
|
* @return If the request to execute the function was posted successfully then
|
||||||
|
* pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned
|
||||||
|
* if the timer service queue was full.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* #define BIT_0 ( 1 << 0 )
|
||||||
|
* #define BIT_4 ( 1 << 4 )
|
||||||
|
*
|
||||||
|
* // An event group which it is assumed has already been created by a call to
|
||||||
|
* // xEventGroupCreate().
|
||||||
|
* EventGroupHandle_t xEventGroup;
|
||||||
|
*
|
||||||
|
* void anInterruptHandler( void )
|
||||||
|
* {
|
||||||
|
* // Clear bit 0 and bit 4 in xEventGroup.
|
||||||
|
* xResult = xEventGroupClearBitsFromISR(
|
||||||
|
* xEventGroup, // The event group being updated.
|
||||||
|
* BIT_0 | BIT_4 ); // The bits being set.
|
||||||
|
*
|
||||||
|
* if( xResult == pdPASS )
|
||||||
|
* {
|
||||||
|
* // The message was posted successfully.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
|
||||||
|
#else
|
||||||
|
#define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) \
|
||||||
|
xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Set bits within an event group.
|
||||||
|
* This function cannot be called from an interrupt. xEventGroupSetBitsFromISR()
|
||||||
|
* is a version that can be called from an interrupt.
|
||||||
|
*
|
||||||
|
* Setting bits in an event group will automatically unblock tasks that are
|
||||||
|
* blocked waiting for the bits.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are to be set.
|
||||||
|
*
|
||||||
|
* @param uxBitsToSet A bitwise value that indicates the bit or bits to set.
|
||||||
|
* For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3
|
||||||
|
* and bit 0 set uxBitsToSet to 0x09.
|
||||||
|
*
|
||||||
|
* @return The value of the event group at the time the call to
|
||||||
|
* xEventGroupSetBits() returns. There are two reasons why the returned value
|
||||||
|
* might have the bits specified by the uxBitsToSet parameter cleared. First,
|
||||||
|
* if setting a bit results in a task that was waiting for the bit leaving the
|
||||||
|
* blocked state then it is possible the bit will be cleared automatically
|
||||||
|
* (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any
|
||||||
|
* unblocked (or otherwise Ready state) task that has a priority above that of
|
||||||
|
* the task that called xEventGroupSetBits() will execute and may change the
|
||||||
|
* event group value before the call to xEventGroupSetBits() returns.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* #define BIT_0 ( 1 << 0 )
|
||||||
|
* #define BIT_4 ( 1 << 4 )
|
||||||
|
*
|
||||||
|
* void aFunction( EventGroupHandle_t xEventGroup )
|
||||||
|
* {
|
||||||
|
* EventBits_t uxBits;
|
||||||
|
*
|
||||||
|
* // Set bit 0 and bit 4 in xEventGroup.
|
||||||
|
* uxBits = xEventGroupSetBits(
|
||||||
|
* xEventGroup, // The event group being updated.
|
||||||
|
* BIT_0 | BIT_4 );// The bits being set.
|
||||||
|
*
|
||||||
|
* if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
|
||||||
|
* {
|
||||||
|
* // Both bit 0 and bit 4 remained set when the function returned.
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_0 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // Bit 0 remained set when the function returned, but bit 4 was
|
||||||
|
* // cleared. It might be that bit 4 was cleared automatically as a
|
||||||
|
* // task that was waiting for bit 4 was removed from the Blocked
|
||||||
|
* // state.
|
||||||
|
* }
|
||||||
|
* else if( ( uxBits & BIT_4 ) != 0 )
|
||||||
|
* {
|
||||||
|
* // Bit 4 remained set when the function returned, but bit 0 was
|
||||||
|
* // cleared. It might be that bit 0 was cleared automatically as a
|
||||||
|
* // task that was waiting for bit 0 was removed from the Blocked
|
||||||
|
* // state.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // Neither bit 0 nor bit 4 remained set. It might be that a task
|
||||||
|
* // was waiting for both of the bits to be set, and the bits were
|
||||||
|
* // cleared as the task left the Blocked state.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupSetBits xEventGroupSetBits
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* A version of xEventGroupSetBits() that can be called from an interrupt.
|
||||||
|
*
|
||||||
|
* Setting bits in an event group is not a deterministic operation because there
|
||||||
|
* are an unknown number of tasks that may be waiting for the bit or bits being
|
||||||
|
* set. FreeRTOS does not allow nondeterministic operations to be performed in
|
||||||
|
* interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR()
|
||||||
|
* sends a message to the timer task to have the set operation performed in the
|
||||||
|
* context of the timer task - where a scheduler lock is used in place of a
|
||||||
|
* critical section.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are to be set.
|
||||||
|
*
|
||||||
|
* @param uxBitsToSet A bitwise value that indicates the bit or bits to set.
|
||||||
|
* For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3
|
||||||
|
* and bit 0 set uxBitsToSet to 0x09.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken As mentioned above, calling this function
|
||||||
|
* will result in a message being sent to the timer daemon task. If the
|
||||||
|
* priority of the timer daemon task is higher than the priority of the
|
||||||
|
* currently running task (the task the interrupt interrupted) then
|
||||||
|
* *pxHigherPriorityTaskWoken will be set to pdTRUE by
|
||||||
|
* xEventGroupSetBitsFromISR(), indicating that a context switch should be
|
||||||
|
* requested before the interrupt exits. For that reason
|
||||||
|
* *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the
|
||||||
|
* example code below.
|
||||||
|
*
|
||||||
|
* @return If the request to execute the function was posted successfully then
|
||||||
|
* pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned
|
||||||
|
* if the timer service queue was full.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* #define BIT_0 ( 1 << 0 )
|
||||||
|
* #define BIT_4 ( 1 << 4 )
|
||||||
|
*
|
||||||
|
* // An event group which it is assumed has already been created by a call to
|
||||||
|
* // xEventGroupCreate().
|
||||||
|
* EventGroupHandle_t xEventGroup;
|
||||||
|
*
|
||||||
|
* void anInterruptHandler( void )
|
||||||
|
* {
|
||||||
|
* BaseType_t xHigherPriorityTaskWoken, xResult;
|
||||||
|
*
|
||||||
|
* // xHigherPriorityTaskWoken must be initialised to pdFALSE.
|
||||||
|
* xHigherPriorityTaskWoken = pdFALSE;
|
||||||
|
*
|
||||||
|
* // Set bit 0 and bit 4 in xEventGroup.
|
||||||
|
* xResult = xEventGroupSetBitsFromISR(
|
||||||
|
* xEventGroup, // The event group being updated.
|
||||||
|
* BIT_0 | BIT_4 // The bits being set.
|
||||||
|
* &xHigherPriorityTaskWoken );
|
||||||
|
*
|
||||||
|
* // Was the message posted successfully?
|
||||||
|
* if( xResult == pdPASS )
|
||||||
|
* {
|
||||||
|
* // If xHigherPriorityTaskWoken is now set to pdTRUE then a context
|
||||||
|
* // switch should be requested. The macro used is port specific and
|
||||||
|
* // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
|
||||||
|
* // refer to the documentation page for the port being used.
|
||||||
|
* portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet,
|
||||||
|
BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
|
||||||
|
#else
|
||||||
|
#define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) \
|
||||||
|
xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup,
|
||||||
|
* const EventBits_t uxBitsToSet,
|
||||||
|
* const EventBits_t uxBitsToWaitFor,
|
||||||
|
* TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Atomically set bits within an event group, then wait for a combination of
|
||||||
|
* bits to be set within the same event group. This functionality is typically
|
||||||
|
* used to synchronise multiple tasks, where each task has to wait for the other
|
||||||
|
* tasks to reach a synchronisation point before proceeding.
|
||||||
|
*
|
||||||
|
* This function cannot be used from an interrupt.
|
||||||
|
*
|
||||||
|
* The function will return before its block time expires if the bits specified
|
||||||
|
* by the uxBitsToWait parameter are set, or become set within that time. In
|
||||||
|
* this case all the bits specified by uxBitsToWait will be automatically
|
||||||
|
* cleared before the function returns.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group in which the bits are being tested. The
|
||||||
|
* event group must have previously been created using a call to
|
||||||
|
* xEventGroupCreate().
|
||||||
|
*
|
||||||
|
* @param uxBitsToSet The bits to set in the event group before determining
|
||||||
|
* if, and possibly waiting for, all the bits specified by the uxBitsToWait
|
||||||
|
* parameter are set.
|
||||||
|
*
|
||||||
|
* @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test
|
||||||
|
* inside the event group. For example, to wait for bit 0 and bit 2 set
|
||||||
|
* uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set
|
||||||
|
* uxBitsToWaitFor to 0x07. Etc.
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait
|
||||||
|
* for all of the bits specified by uxBitsToWaitFor to become set.
|
||||||
|
*
|
||||||
|
* @return The value of the event group at the time either the bits being waited
|
||||||
|
* for became set, or the block time expired. Test the return value to know
|
||||||
|
* which bits were set. If xEventGroupSync() returned because its timeout
|
||||||
|
* expired then not all the bits being waited for will be set. If
|
||||||
|
* xEventGroupSync() returned because all the bits it was waiting for were
|
||||||
|
* set then the returned value is the event group value before any bits were
|
||||||
|
* automatically cleared.
|
||||||
|
*
|
||||||
|
* Example usage:
|
||||||
|
* @code{c}
|
||||||
|
* // Bits used by the three tasks.
|
||||||
|
* #define TASK_0_BIT ( 1 << 0 )
|
||||||
|
* #define TASK_1_BIT ( 1 << 1 )
|
||||||
|
* #define TASK_2_BIT ( 1 << 2 )
|
||||||
|
*
|
||||||
|
* #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
|
||||||
|
*
|
||||||
|
* // Use an event group to synchronise three tasks. It is assumed this event
|
||||||
|
* // group has already been created elsewhere.
|
||||||
|
* EventGroupHandle_t xEventBits;
|
||||||
|
*
|
||||||
|
* void vTask0( void *pvParameters )
|
||||||
|
* {
|
||||||
|
* EventBits_t uxReturn;
|
||||||
|
* TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
|
||||||
|
*
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Perform task functionality here.
|
||||||
|
*
|
||||||
|
* // Set bit 0 in the event flag to note this task has reached the
|
||||||
|
* // sync point. The other two tasks will set the other two bits defined
|
||||||
|
* // by ALL_SYNC_BITS. All three tasks have reached the synchronisation
|
||||||
|
* // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms
|
||||||
|
* // for this to happen.
|
||||||
|
* uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
|
||||||
|
*
|
||||||
|
* if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
|
||||||
|
* {
|
||||||
|
* // All three tasks reached the synchronisation point before the call
|
||||||
|
* // to xEventGroupSync() timed out.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* void vTask1( void *pvParameters )
|
||||||
|
* {
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Perform task functionality here.
|
||||||
|
*
|
||||||
|
* // Set bit 1 in the event flag to note this task has reached the
|
||||||
|
* // synchronisation point. The other two tasks will set the other two
|
||||||
|
* // bits defined by ALL_SYNC_BITS. All three tasks have reached the
|
||||||
|
* // synchronisation point when all the ALL_SYNC_BITS are set. Wait
|
||||||
|
* // indefinitely for this to happen.
|
||||||
|
* xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
|
||||||
|
*
|
||||||
|
* // xEventGroupSync() was called with an indefinite block time, so
|
||||||
|
* // this task will only reach here if the synchronisation was made by all
|
||||||
|
* // three tasks, so there is no need to test the return value.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* void vTask2( void *pvParameters )
|
||||||
|
* {
|
||||||
|
* for( ;; )
|
||||||
|
* {
|
||||||
|
* // Perform task functionality here.
|
||||||
|
*
|
||||||
|
* // Set bit 2 in the event flag to note this task has reached the
|
||||||
|
* // synchronisation point. The other two tasks will set the other two
|
||||||
|
* // bits defined by ALL_SYNC_BITS. All three tasks have reached the
|
||||||
|
* // synchronisation point when all the ALL_SYNC_BITS are set. Wait
|
||||||
|
* // indefinitely for this to happen.
|
||||||
|
* xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
|
||||||
|
*
|
||||||
|
* // xEventGroupSync() was called with an indefinite block time, so
|
||||||
|
* // this task will only reach here if the synchronisation was made by all
|
||||||
|
* // three tasks, so there is no need to test the return value.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xEventGroupSync xEventGroupSync
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Returns the current value of the bits in an event group. This function
|
||||||
|
* cannot be used from an interrupt.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group being queried.
|
||||||
|
*
|
||||||
|
* @return The event group bits at the time xEventGroupGetBits() was called.
|
||||||
|
*
|
||||||
|
* \defgroup xEventGroupGetBits xEventGroupGetBits
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* A version of xEventGroupGetBits() that can be called from an ISR.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group being queried.
|
||||||
|
*
|
||||||
|
* @return The event group bits at the time xEventGroupGetBitsFromISR() was called.
|
||||||
|
*
|
||||||
|
* \defgroup xEventGroupGetBitsFromISR xEventGroupGetBitsFromISR
|
||||||
|
* \ingroup EventGroup
|
||||||
|
*/
|
||||||
|
EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* event_groups.h
|
||||||
|
* @code{c}
|
||||||
|
* void xEventGroupDelete( EventGroupHandle_t xEventGroup );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Delete an event group that was previously created by a call to
|
||||||
|
* xEventGroupCreate(). Tasks that are blocked on the event group will be
|
||||||
|
* unblocked and obtain 0 as the event group's value.
|
||||||
|
*
|
||||||
|
* @param xEventGroup The event group being deleted.
|
||||||
|
*/
|
||||||
|
void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/* For internal use only. */
|
||||||
|
void vEventGroupSetBitsCallback( void * pvEventGroup,
|
||||||
|
const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION;
|
||||||
|
void vEventGroupClearBitsCallback( void * pvEventGroup,
|
||||||
|
const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
UBaseType_t uxEventGroupGetNumber( void * xEventGroup ) PRIVILEGED_FUNCTION;
|
||||||
|
void vEventGroupSetNumber( void * xEventGroup,
|
||||||
|
UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* EVENT_GROUPS_H */
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This is the list implementation used by the scheduler. While it is tailored
|
||||||
|
* heavily for the schedulers needs, it is also available for use by
|
||||||
|
* application code.
|
||||||
|
*
|
||||||
|
* list_ts can only store pointers to list_item_ts. Each ListItem_t contains a
|
||||||
|
* numeric value (xItemValue). Most of the time the lists are sorted in
|
||||||
|
* ascending item value order.
|
||||||
|
*
|
||||||
|
* Lists are created already containing one list item. The value of this
|
||||||
|
* item is the maximum possible that can be stored, it is therefore always at
|
||||||
|
* the end of the list and acts as a marker. The list member pxHead always
|
||||||
|
* points to this marker - even though it is at the tail of the list. This
|
||||||
|
* is because the tail contains a wrap back pointer to the true head of
|
||||||
|
* the list.
|
||||||
|
*
|
||||||
|
* In addition to it's value, each list item contains a pointer to the next
|
||||||
|
* item in the list (pxNext), a pointer to the list it is in (pxContainer)
|
||||||
|
* and a pointer to back to the object that contains it. These later two
|
||||||
|
* pointers are included for efficiency of list manipulation. There is
|
||||||
|
* effectively a two way link between the object containing the list item and
|
||||||
|
* the list item itself.
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* \page ListIntroduction List Implementation
|
||||||
|
* \ingroup FreeRTOSIntro
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef LIST_H
|
||||||
|
#define LIST_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "FreeRTOS.h must be included before list.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The list structure members are modified from within interrupts, and therefore
|
||||||
|
* by rights should be declared volatile. However, they are only modified in a
|
||||||
|
* functionally atomic way (within critical sections of with the scheduler
|
||||||
|
* suspended) and are either passed by reference into a function or indexed via
|
||||||
|
* a volatile variable. Therefore, in all use cases tested so far, the volatile
|
||||||
|
* qualifier can be omitted in order to provide a moderate performance
|
||||||
|
* improvement without adversely affecting functional behaviour. The assembly
|
||||||
|
* instructions generated by the IAR, ARM and GCC compilers when the respective
|
||||||
|
* compiler's options were set for maximum optimisation has been inspected and
|
||||||
|
* deemed to be as intended. That said, as compiler technology advances, and
|
||||||
|
* especially if aggressive cross module optimisation is used (a use case that
|
||||||
|
* has not been exercised to any great extend) then it is feasible that the
|
||||||
|
* volatile qualifier will be needed for correct optimisation. It is expected
|
||||||
|
* that a compiler removing essential code because, without the volatile
|
||||||
|
* qualifier on the list structure members and with aggressive cross module
|
||||||
|
* optimisation, the compiler deemed the code unnecessary will result in
|
||||||
|
* complete and obvious failure of the scheduler. If this is ever experienced
|
||||||
|
* then the volatile qualifier can be inserted in the relevant places within the
|
||||||
|
* list structures by simply defining configLIST_VOLATILE to volatile in
|
||||||
|
* FreeRTOSConfig.h (as per the example at the bottom of this comment block).
|
||||||
|
* If configLIST_VOLATILE is not defined then the preprocessor directives below
|
||||||
|
* will simply #define configLIST_VOLATILE away completely.
|
||||||
|
*
|
||||||
|
* To use volatile list structure members then add the following line to
|
||||||
|
* FreeRTOSConfig.h (without the quotes):
|
||||||
|
* "#define configLIST_VOLATILE volatile"
|
||||||
|
*/
|
||||||
|
#ifndef configLIST_VOLATILE
|
||||||
|
#define configLIST_VOLATILE
|
||||||
|
#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/* Macros that can be used to place known values within the list structures,
|
||||||
|
* then check that the known values do not get corrupted during the execution of
|
||||||
|
* the application. These may catch the list data structures being overwritten in
|
||||||
|
* memory. They will not catch data errors caused by incorrect configuration or
|
||||||
|
* use of FreeRTOS.*/
|
||||||
|
#if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 )
|
||||||
|
/* Define the macros to do nothing. */
|
||||||
|
#define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE
|
||||||
|
#define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE
|
||||||
|
#define listFIRST_LIST_INTEGRITY_CHECK_VALUE
|
||||||
|
#define listSECOND_LIST_INTEGRITY_CHECK_VALUE
|
||||||
|
#define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
|
||||||
|
#define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
|
||||||
|
#define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList )
|
||||||
|
#define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList )
|
||||||
|
#define listTEST_LIST_ITEM_INTEGRITY( pxItem )
|
||||||
|
#define listTEST_LIST_INTEGRITY( pxList )
|
||||||
|
#else /* if ( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) */
|
||||||
|
/* Define macros that add new members into the list structures. */
|
||||||
|
#define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1;
|
||||||
|
#define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2;
|
||||||
|
#define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1;
|
||||||
|
#define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2;
|
||||||
|
|
||||||
|
/* Define macros that set the new structure members to known values. */
|
||||||
|
#define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
|
||||||
|
#define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
|
||||||
|
#define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
|
||||||
|
#define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
|
||||||
|
|
||||||
|
/* Define macros that will assert if one of the structure members does not
|
||||||
|
* contain its expected value. */
|
||||||
|
#define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
|
||||||
|
#define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
|
||||||
|
#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Definition of the only type of object that a list can contain.
|
||||||
|
*/
|
||||||
|
struct xLIST;
|
||||||
|
struct xLIST_ITEM
|
||||||
|
{
|
||||||
|
listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in ascending order. */
|
||||||
|
struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */
|
||||||
|
struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */
|
||||||
|
void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */
|
||||||
|
struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */
|
||||||
|
listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
};
|
||||||
|
typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */
|
||||||
|
|
||||||
|
struct xMINI_LIST_ITEM
|
||||||
|
{
|
||||||
|
listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
configLIST_VOLATILE TickType_t xItemValue;
|
||||||
|
struct xLIST_ITEM * configLIST_VOLATILE pxNext;
|
||||||
|
struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;
|
||||||
|
};
|
||||||
|
typedef struct xMINI_LIST_ITEM MiniListItem_t;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Definition of the type of queue used by the scheduler.
|
||||||
|
*/
|
||||||
|
typedef struct xLIST
|
||||||
|
{
|
||||||
|
listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
volatile UBaseType_t uxNumberOfItems;
|
||||||
|
ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */
|
||||||
|
MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */
|
||||||
|
listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
} List_t;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to set the owner of a list item. The owner of a list item
|
||||||
|
* is the object (usually a TCB) that contains the list item.
|
||||||
|
*
|
||||||
|
* \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to get the owner of a list item. The owner of a list item
|
||||||
|
* is the object (usually a TCB) that contains the list item.
|
||||||
|
*
|
||||||
|
* \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to set the value of the list item. In most cases the value is
|
||||||
|
* used to sort the list in ascending order.
|
||||||
|
*
|
||||||
|
* \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to retrieve the value of the list item. The value can
|
||||||
|
* represent anything - for example the priority of a task, or the time at
|
||||||
|
* which a task should be unblocked.
|
||||||
|
*
|
||||||
|
* \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to retrieve the value of the list item at the head of a given
|
||||||
|
* list.
|
||||||
|
*
|
||||||
|
* \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Return the list item at the head of the list.
|
||||||
|
*
|
||||||
|
* \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Return the next list item.
|
||||||
|
*
|
||||||
|
* \page listGET_NEXT listGET_NEXT
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Return the list item that marks the end of the list
|
||||||
|
*
|
||||||
|
* \page listGET_END_MARKER listGET_END_MARKER
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to determine if a list contains any items. The macro will
|
||||||
|
* only have the value true if the list is empty.
|
||||||
|
*
|
||||||
|
* \page listLIST_IS_EMPTY listLIST_IS_EMPTY
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access macro to return the number of items in the list.
|
||||||
|
*/
|
||||||
|
#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access function to obtain the owner of the next entry in a list.
|
||||||
|
*
|
||||||
|
* The list member pxIndex is used to walk through a list. Calling
|
||||||
|
* listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list
|
||||||
|
* and returns that entry's pxOwner parameter. Using multiple calls to this
|
||||||
|
* function it is therefore possible to move through every item contained in
|
||||||
|
* a list.
|
||||||
|
*
|
||||||
|
* The pxOwner parameter of a list item is a pointer to the object that owns
|
||||||
|
* the list item. In the scheduler this is normally a task control block.
|
||||||
|
* The pxOwner parameter effectively creates a two way link between the list
|
||||||
|
* item and its owner.
|
||||||
|
*
|
||||||
|
* @param pxTCB pxTCB is set to the address of the owner of the next list item.
|
||||||
|
* @param pxList The list from which the next item owner is to be returned.
|
||||||
|
*
|
||||||
|
* \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \
|
||||||
|
{ \
|
||||||
|
List_t * const pxConstList = ( pxList ); \
|
||||||
|
/* Increment the index to the next item and return the item, ensuring */ \
|
||||||
|
/* we don't return the marker used at the end of the list. */ \
|
||||||
|
( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \
|
||||||
|
if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \
|
||||||
|
{ \
|
||||||
|
( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \
|
||||||
|
} \
|
||||||
|
( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Version of uxListRemove() that does not return a value. Provided as a slight
|
||||||
|
* optimisation for xTaskIncrementTick() by being inline.
|
||||||
|
*
|
||||||
|
* Remove an item from a list. The list item has a pointer to the list that
|
||||||
|
* it is in, so only the list item need be passed into the function.
|
||||||
|
*
|
||||||
|
* @param uxListRemove The item to be removed. The item will remove itself from
|
||||||
|
* the list pointed to by it's pxContainer parameter.
|
||||||
|
*
|
||||||
|
* @return The number of items that remain in the list after the list item has
|
||||||
|
* been removed.
|
||||||
|
*
|
||||||
|
* \page listREMOVE_ITEM listREMOVE_ITEM
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listREMOVE_ITEM( pxItemToRemove ) \
|
||||||
|
{ \
|
||||||
|
/* The list item knows which list it is in. Obtain the list from the list \
|
||||||
|
* item. */ \
|
||||||
|
List_t * const pxList = ( pxItemToRemove )->pxContainer; \
|
||||||
|
\
|
||||||
|
( pxItemToRemove )->pxNext->pxPrevious = ( pxItemToRemove )->pxPrevious; \
|
||||||
|
( pxItemToRemove )->pxPrevious->pxNext = ( pxItemToRemove )->pxNext; \
|
||||||
|
/* Make sure the index is left pointing to a valid item. */ \
|
||||||
|
if( pxList->pxIndex == ( pxItemToRemove ) ) \
|
||||||
|
{ \
|
||||||
|
pxList->pxIndex = ( pxItemToRemove )->pxPrevious; \
|
||||||
|
} \
|
||||||
|
\
|
||||||
|
( pxItemToRemove )->pxContainer = NULL; \
|
||||||
|
( pxList->uxNumberOfItems )--; \
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Inline version of vListInsertEnd() to provide slight optimisation for
|
||||||
|
* xTaskIncrementTick().
|
||||||
|
*
|
||||||
|
* Insert a list item into a list. The item will be inserted in a position
|
||||||
|
* such that it will be the last item within the list returned by multiple
|
||||||
|
* calls to listGET_OWNER_OF_NEXT_ENTRY.
|
||||||
|
*
|
||||||
|
* The list member pxIndex is used to walk through a list. Calling
|
||||||
|
* listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list.
|
||||||
|
* Placing an item in a list using vListInsertEnd effectively places the item
|
||||||
|
* in the list position pointed to by pxIndex. This means that every other
|
||||||
|
* item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before
|
||||||
|
* the pxIndex parameter again points to the item being inserted.
|
||||||
|
*
|
||||||
|
* @param pxList The list into which the item is to be inserted.
|
||||||
|
*
|
||||||
|
* @param pxNewListItem The list item to be inserted into the list.
|
||||||
|
*
|
||||||
|
* \page listINSERT_END listINSERT_END
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listINSERT_END( pxList, pxNewListItem ) \
|
||||||
|
{ \
|
||||||
|
ListItem_t * const pxIndex = ( pxList )->pxIndex; \
|
||||||
|
\
|
||||||
|
/* Only effective when configASSERT() is also defined, these tests may catch \
|
||||||
|
* the list data structures being overwritten in memory. They will not catch \
|
||||||
|
* data errors caused by incorrect configuration or use of FreeRTOS. */ \
|
||||||
|
listTEST_LIST_INTEGRITY( ( pxList ) ); \
|
||||||
|
listTEST_LIST_ITEM_INTEGRITY( ( pxNewListItem ) ); \
|
||||||
|
\
|
||||||
|
/* Insert a new list item into ( pxList ), but rather than sort the list, \
|
||||||
|
* makes the new list item the last item to be removed by a call to \
|
||||||
|
* listGET_OWNER_OF_NEXT_ENTRY(). */ \
|
||||||
|
( pxNewListItem )->pxNext = pxIndex; \
|
||||||
|
( pxNewListItem )->pxPrevious = pxIndex->pxPrevious; \
|
||||||
|
\
|
||||||
|
pxIndex->pxPrevious->pxNext = ( pxNewListItem ); \
|
||||||
|
pxIndex->pxPrevious = ( pxNewListItem ); \
|
||||||
|
\
|
||||||
|
/* Remember which list the item is in. */ \
|
||||||
|
( pxNewListItem )->pxContainer = ( pxList ); \
|
||||||
|
\
|
||||||
|
( ( pxList )->uxNumberOfItems )++; \
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Access function to obtain the owner of the first entry in a list. Lists
|
||||||
|
* are normally sorted in ascending item value order.
|
||||||
|
*
|
||||||
|
* This function returns the pxOwner member of the first item in the list.
|
||||||
|
* The pxOwner parameter of a list item is a pointer to the object that owns
|
||||||
|
* the list item. In the scheduler this is normally a task control block.
|
||||||
|
* The pxOwner parameter effectively creates a two way link between the list
|
||||||
|
* item and its owner.
|
||||||
|
*
|
||||||
|
* @param pxList The list from which the owner of the head item is to be
|
||||||
|
* returned.
|
||||||
|
*
|
||||||
|
* \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( ( &( ( pxList )->xListEnd ) )->pxNext->pvOwner )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Check to see if a list item is within a list. The list item maintains a
|
||||||
|
* "container" pointer that points to the list it is in. All this macro does
|
||||||
|
* is check to see if the container and the list match.
|
||||||
|
*
|
||||||
|
* @param pxList The list we want to know if the list item is within.
|
||||||
|
* @param pxListItem The list item we want to know if is in the list.
|
||||||
|
* @return pdTRUE if the list item is in the list, otherwise pdFALSE.
|
||||||
|
*/
|
||||||
|
#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Return the list a list item is contained within (referenced from).
|
||||||
|
*
|
||||||
|
* @param pxListItem The list item being queried.
|
||||||
|
* @return A pointer to the List_t object that references the pxListItem
|
||||||
|
*/
|
||||||
|
#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* This provides a crude means of knowing if a list has been initialised, as
|
||||||
|
* pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise()
|
||||||
|
* function.
|
||||||
|
*/
|
||||||
|
#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY )
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Must be called before a list is used! This initialises all the members
|
||||||
|
* of the list structure and inserts the xListEnd item into the list as a
|
||||||
|
* marker to the back of the list.
|
||||||
|
*
|
||||||
|
* @param pxList Pointer to the list being initialised.
|
||||||
|
*
|
||||||
|
* \page vListInitialise vListInitialise
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Must be called before a list item is used. This sets the list container to
|
||||||
|
* null so the item does not think that it is already contained in a list.
|
||||||
|
*
|
||||||
|
* @param pxItem Pointer to the list item being initialised.
|
||||||
|
*
|
||||||
|
* \page vListInitialiseItem vListInitialiseItem
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Insert a list item into a list. The item will be inserted into the list in
|
||||||
|
* a position determined by its item value (ascending item value order).
|
||||||
|
*
|
||||||
|
* @param pxList The list into which the item is to be inserted.
|
||||||
|
*
|
||||||
|
* @param pxNewListItem The item that is to be placed in the list.
|
||||||
|
*
|
||||||
|
* \page vListInsert vListInsert
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
void vListInsert( List_t * const pxList,
|
||||||
|
ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Insert a list item into a list. The item will be inserted in a position
|
||||||
|
* such that it will be the last item within the list returned by multiple
|
||||||
|
* calls to listGET_OWNER_OF_NEXT_ENTRY.
|
||||||
|
*
|
||||||
|
* The list member pxIndex is used to walk through a list. Calling
|
||||||
|
* listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list.
|
||||||
|
* Placing an item in a list using vListInsertEnd effectively places the item
|
||||||
|
* in the list position pointed to by pxIndex. This means that every other
|
||||||
|
* item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before
|
||||||
|
* the pxIndex parameter again points to the item being inserted.
|
||||||
|
*
|
||||||
|
* @param pxList The list into which the item is to be inserted.
|
||||||
|
*
|
||||||
|
* @param pxNewListItem The list item to be inserted into the list.
|
||||||
|
*
|
||||||
|
* \page vListInsertEnd vListInsertEnd
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
void vListInsertEnd( List_t * const pxList,
|
||||||
|
ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Remove an item from a list. The list item has a pointer to the list that
|
||||||
|
* it is in, so only the list item need be passed into the function.
|
||||||
|
*
|
||||||
|
* @param uxListRemove The item to be removed. The item will remove itself from
|
||||||
|
* the list pointed to by it's pxContainer parameter.
|
||||||
|
*
|
||||||
|
* @return The number of items that remain in the list after the list item has
|
||||||
|
* been removed.
|
||||||
|
*
|
||||||
|
* \page uxListRemove uxListRemove
|
||||||
|
* \ingroup LinkedList
|
||||||
|
*/
|
||||||
|
UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* ifndef LIST_H */
|
||||||
@@ -0,0 +1,823 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Message buffers build functionality on top of FreeRTOS stream buffers.
|
||||||
|
* Whereas stream buffers are used to send a continuous stream of data from one
|
||||||
|
* task or interrupt to another, message buffers are used to send variable
|
||||||
|
* length discrete messages from one task or interrupt to another. Their
|
||||||
|
* implementation is light weight, making them particularly suited for interrupt
|
||||||
|
* to task and core to core communication scenarios.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xMessageBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xMessageBufferRead()) inside a critical section and set the receive
|
||||||
|
* timeout to 0.
|
||||||
|
*
|
||||||
|
* Message buffers hold variable length messages. To enable that, when a
|
||||||
|
* message is written to the message buffer an additional sizeof( size_t ) bytes
|
||||||
|
* are also written to store the message's length (that happens internally, with
|
||||||
|
* the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit
|
||||||
|
* architecture, so writing a 10 byte message to a message buffer on a 32-bit
|
||||||
|
* architecture will actually reduce the available space in the message buffer
|
||||||
|
* by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length
|
||||||
|
* of the message).
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef FREERTOS_MESSAGE_BUFFER_H
|
||||||
|
#define FREERTOS_MESSAGE_BUFFER_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "include FreeRTOS.h must appear in source files before include message_buffer.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Message buffers are built onto of stream buffers. */
|
||||||
|
#include "stream_buffer.h"
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#if defined( __cplusplus )
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type by which message buffers are referenced. For example, a call to
|
||||||
|
* xMessageBufferCreate() returns an MessageBufferHandle_t variable that can
|
||||||
|
* then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(),
|
||||||
|
* etc.
|
||||||
|
*/
|
||||||
|
typedef void * MessageBufferHandle_t;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Creates a new message buffer using dynamically allocated memory. See
|
||||||
|
* xMessageBufferCreateStatic() for a version that uses statically allocated
|
||||||
|
* memory (memory that is allocated at compile time).
|
||||||
|
*
|
||||||
|
* configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in
|
||||||
|
* FreeRTOSConfig.h for xMessageBufferCreate() to be available.
|
||||||
|
*
|
||||||
|
* @param xBufferSizeBytes The total number of bytes (not messages) the message
|
||||||
|
* buffer will be able to hold at any one time. When a message is written to
|
||||||
|
* the message buffer an additional sizeof( size_t ) bytes are also written to
|
||||||
|
* store the message's length. sizeof( size_t ) is typically 4 bytes on a
|
||||||
|
* 32-bit architecture, so on most 32-bit architectures a 10 byte message will
|
||||||
|
* take up 14 bytes of message buffer space.
|
||||||
|
*
|
||||||
|
* @return If NULL is returned, then the message buffer cannot be created
|
||||||
|
* because there is insufficient heap memory available for FreeRTOS to allocate
|
||||||
|
* the message buffer data structures and storage area. A non-NULL value being
|
||||||
|
* returned indicates that the message buffer has been created successfully -
|
||||||
|
* the returned value should be stored as the handle to the created message
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
*
|
||||||
|
* void vAFunction( void )
|
||||||
|
* {
|
||||||
|
* MessageBufferHandle_t xMessageBuffer;
|
||||||
|
* const size_t xMessageBufferSizeBytes = 100;
|
||||||
|
*
|
||||||
|
* // Create a message buffer that can hold 100 bytes. The memory used to hold
|
||||||
|
* // both the message buffer structure and the messages themselves is allocated
|
||||||
|
* // dynamically. Each message added to the buffer consumes an additional 4
|
||||||
|
* // bytes which are used to hold the lengh of the message.
|
||||||
|
* xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );
|
||||||
|
*
|
||||||
|
* if( xMessageBuffer == NULL )
|
||||||
|
* {
|
||||||
|
* // There was not enough heap memory space available to create the
|
||||||
|
* // message buffer.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // The message buffer was created successfully and can now be used.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferCreate xMessageBufferCreate
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferCreate( xBufferSizeBytes ) \
|
||||||
|
( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes,
|
||||||
|
* uint8_t *pucMessageBufferStorageArea,
|
||||||
|
* StaticMessageBuffer_t *pxStaticMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
* Creates a new message buffer using statically allocated memory. See
|
||||||
|
* xMessageBufferCreate() for a version that uses dynamically allocated memory.
|
||||||
|
*
|
||||||
|
* @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the
|
||||||
|
* pucMessageBufferStorageArea parameter. When a message is written to the
|
||||||
|
* message buffer an additional sizeof( size_t ) bytes are also written to store
|
||||||
|
* the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit
|
||||||
|
* architecture, so on most 32-bit architecture a 10 byte message will take up
|
||||||
|
* 14 bytes of message buffer space. The maximum number of bytes that can be
|
||||||
|
* stored in the message buffer is actually (xBufferSizeBytes - 1).
|
||||||
|
*
|
||||||
|
* @param pucMessageBufferStorageArea Must point to a uint8_t array that is at
|
||||||
|
* least xBufferSizeBytes big. This is the array to which messages are
|
||||||
|
* copied when they are written to the message buffer.
|
||||||
|
*
|
||||||
|
* @param pxStaticMessageBuffer Must point to a variable of type
|
||||||
|
* StaticMessageBuffer_t, which will be used to hold the message buffer's data
|
||||||
|
* structure.
|
||||||
|
*
|
||||||
|
* @return If the message buffer is created successfully then a handle to the
|
||||||
|
* created message buffer is returned. If either pucMessageBufferStorageArea or
|
||||||
|
* pxStaticmessageBuffer are NULL then NULL is returned.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
*
|
||||||
|
* // Used to dimension the array used to hold the messages. The available space
|
||||||
|
* // will actually be one less than this, so 999.
|
||||||
|
#define STORAGE_SIZE_BYTES 1000
|
||||||
|
*
|
||||||
|
* // Defines the memory that will actually hold the messages within the message
|
||||||
|
* // buffer.
|
||||||
|
* static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
|
||||||
|
*
|
||||||
|
* // The variable used to hold the message buffer structure.
|
||||||
|
* StaticMessageBuffer_t xMessageBufferStruct;
|
||||||
|
*
|
||||||
|
* void MyFunction( void )
|
||||||
|
* {
|
||||||
|
* MessageBufferHandle_t xMessageBuffer;
|
||||||
|
*
|
||||||
|
* xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucStorageBuffer ),
|
||||||
|
* ucStorageBuffer,
|
||||||
|
* &xMessageBufferStruct );
|
||||||
|
*
|
||||||
|
* // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer
|
||||||
|
* // parameters were NULL, xMessageBuffer will not be NULL, and can be used to
|
||||||
|
* // reference the created message buffer in other message buffer API calls.
|
||||||
|
*
|
||||||
|
* // Other code that uses the message buffer can go here.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) \
|
||||||
|
( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer,
|
||||||
|
* const void *pvTxData,
|
||||||
|
* size_t xDataLengthBytes,
|
||||||
|
* TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Sends a discrete message to the message buffer. The message can be any
|
||||||
|
* length that fits within the buffer's free space, and is copied into the
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xMessageBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xMessageBufferRead()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xMessageBufferSend() to write to a message buffer from a task. Use
|
||||||
|
* xMessageBufferSendFromISR() to write to a message buffer from an interrupt
|
||||||
|
* service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer to which a message is
|
||||||
|
* being sent.
|
||||||
|
*
|
||||||
|
* @param pvTxData A pointer to the message that is to be copied into the
|
||||||
|
* message buffer.
|
||||||
|
*
|
||||||
|
* @param xDataLengthBytes The length of the message. That is, the number of
|
||||||
|
* bytes to copy from pvTxData into the message buffer. When a message is
|
||||||
|
* written to the message buffer an additional sizeof( size_t ) bytes are also
|
||||||
|
* written to store the message's length. sizeof( size_t ) is typically 4 bytes
|
||||||
|
* on a 32-bit architecture, so on most 32-bit architecture setting
|
||||||
|
* xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
|
||||||
|
* bytes (20 bytes of message data and 4 bytes to hold the message length).
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time the calling task should remain
|
||||||
|
* in the Blocked state to wait for enough space to become available in the
|
||||||
|
* message buffer, should the message buffer have insufficient space when
|
||||||
|
* xMessageBufferSend() is called. The calling task will never block if
|
||||||
|
* xTicksToWait is zero. The block time is specified in tick periods, so the
|
||||||
|
* absolute time it represents is dependent on the tick frequency. The macro
|
||||||
|
* pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into
|
||||||
|
* a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause
|
||||||
|
* the task to wait indefinitely (without timing out), provided
|
||||||
|
* INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any
|
||||||
|
* CPU time when they are in the Blocked state.
|
||||||
|
*
|
||||||
|
* @return The number of bytes written to the message buffer. If the call to
|
||||||
|
* xMessageBufferSend() times out before there was enough space to write the
|
||||||
|
* message into the message buffer then zero is returned. If the call did not
|
||||||
|
* time out then xDataLengthBytes is returned.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* void vAFunction( MessageBufferHandle_t xMessageBuffer )
|
||||||
|
* {
|
||||||
|
* size_t xBytesSent;
|
||||||
|
* uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
|
||||||
|
* char *pcStringToSend = "String to send";
|
||||||
|
* const TickType_t x100ms = pdMS_TO_TICKS( 100 );
|
||||||
|
*
|
||||||
|
* // Send an array to the message buffer, blocking for a maximum of 100ms to
|
||||||
|
* // wait for enough space to be available in the message buffer.
|
||||||
|
* xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != sizeof( ucArrayToSend ) )
|
||||||
|
* {
|
||||||
|
* // The call to xMessageBufferSend() times out before there was enough
|
||||||
|
* // space in the buffer for the data to be written.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Send the string to the message buffer. Return immediately if there is
|
||||||
|
* // not enough space in the buffer.
|
||||||
|
* xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != strlen( pcStringToSend ) )
|
||||||
|
* {
|
||||||
|
* // The string could not be added to the message buffer because there was
|
||||||
|
* // not enough free space in the buffer.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferSend xMessageBufferSend
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) \
|
||||||
|
xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer,
|
||||||
|
* const void *pvTxData,
|
||||||
|
* size_t xDataLengthBytes,
|
||||||
|
* BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Interrupt safe version of the API function that sends a discrete message to
|
||||||
|
* the message buffer. The message can be any length that fits within the
|
||||||
|
* buffer's free space, and is copied into the buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xMessageBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xMessageBufferRead()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xMessageBufferSend() to write to a message buffer from a task. Use
|
||||||
|
* xMessageBufferSendFromISR() to write to a message buffer from an interrupt
|
||||||
|
* service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer to which a message is
|
||||||
|
* being sent.
|
||||||
|
*
|
||||||
|
* @param pvTxData A pointer to the message that is to be copied into the
|
||||||
|
* message buffer.
|
||||||
|
*
|
||||||
|
* @param xDataLengthBytes The length of the message. That is, the number of
|
||||||
|
* bytes to copy from pvTxData into the message buffer. When a message is
|
||||||
|
* written to the message buffer an additional sizeof( size_t ) bytes are also
|
||||||
|
* written to store the message's length. sizeof( size_t ) is typically 4 bytes
|
||||||
|
* on a 32-bit architecture, so on most 32-bit architecture setting
|
||||||
|
* xDataLengthBytes to 20 will reduce the free space in the message buffer by 24
|
||||||
|
* bytes (20 bytes of message data and 4 bytes to hold the message length).
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken It is possible that a message buffer will
|
||||||
|
* have a task blocked on it waiting for data. Calling
|
||||||
|
* xMessageBufferSendFromISR() can make data available, and so cause a task that
|
||||||
|
* was waiting for data to leave the Blocked state. If calling
|
||||||
|
* xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the
|
||||||
|
* unblocked task has a priority higher than the currently executing task (the
|
||||||
|
* task that was interrupted), then, internally, xMessageBufferSendFromISR()
|
||||||
|
* will set *pxHigherPriorityTaskWoken to pdTRUE. If
|
||||||
|
* xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a
|
||||||
|
* context switch should be performed before the interrupt is exited. This will
|
||||||
|
* ensure that the interrupt returns directly to the highest priority Ready
|
||||||
|
* state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it
|
||||||
|
* is passed into the function. See the code example below for an example.
|
||||||
|
*
|
||||||
|
* @return The number of bytes actually written to the message buffer. If the
|
||||||
|
* message buffer didn't have enough free space for the message to be stored
|
||||||
|
* then 0 is returned, otherwise xDataLengthBytes is returned.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* // A message buffer that has already been created.
|
||||||
|
* MessageBufferHandle_t xMessageBuffer;
|
||||||
|
*
|
||||||
|
* void vAnInterruptServiceRoutine( void )
|
||||||
|
* {
|
||||||
|
* size_t xBytesSent;
|
||||||
|
* char *pcStringToSend = "String to send";
|
||||||
|
* BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
|
||||||
|
*
|
||||||
|
* // Attempt to send the string to the message buffer.
|
||||||
|
* xBytesSent = xMessageBufferSendFromISR( xMessageBuffer,
|
||||||
|
* ( void * ) pcStringToSend,
|
||||||
|
* strlen( pcStringToSend ),
|
||||||
|
* &xHigherPriorityTaskWoken );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != strlen( pcStringToSend ) )
|
||||||
|
* {
|
||||||
|
* // The string could not be added to the message buffer because there was
|
||||||
|
* // not enough free space in the buffer.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // If xHigherPriorityTaskWoken was set to pdTRUE inside
|
||||||
|
* // xMessageBufferSendFromISR() then a task that has a priority above the
|
||||||
|
* // priority of the currently executing task was unblocked and a context
|
||||||
|
* // switch should be performed to ensure the ISR returns to the unblocked
|
||||||
|
* // task. In most FreeRTOS ports this is done by simply passing
|
||||||
|
* // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the
|
||||||
|
* // variables value, and perform the context switch if necessary. Check the
|
||||||
|
* // documentation for the port in use for port specific instructions.
|
||||||
|
* portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) \
|
||||||
|
xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer,
|
||||||
|
* void *pvRxData,
|
||||||
|
* size_t xBufferLengthBytes,
|
||||||
|
* TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Receives a discrete message from a message buffer. Messages can be of
|
||||||
|
* variable length and are copied out of the buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xMessageBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xMessageBufferRead()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xMessageBufferReceive() to read from a message buffer from a task. Use
|
||||||
|
* xMessageBufferReceiveFromISR() to read from a message buffer from an
|
||||||
|
* interrupt service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer from which a message
|
||||||
|
* is being received.
|
||||||
|
*
|
||||||
|
* @param pvRxData A pointer to the buffer into which the received message is
|
||||||
|
* to be copied.
|
||||||
|
*
|
||||||
|
* @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData
|
||||||
|
* parameter. This sets the maximum length of the message that can be received.
|
||||||
|
* If xBufferLengthBytes is too small to hold the next message then the message
|
||||||
|
* will be left in the message buffer and 0 will be returned.
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time the task should remain in the
|
||||||
|
* Blocked state to wait for a message, should the message buffer be empty.
|
||||||
|
* xMessageBufferReceive() will return immediately if xTicksToWait is zero and
|
||||||
|
* the message buffer is empty. The block time is specified in tick periods, so
|
||||||
|
* the absolute time it represents is dependent on the tick frequency. The
|
||||||
|
* macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds
|
||||||
|
* into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will
|
||||||
|
* cause the task to wait indefinitely (without timing out), provided
|
||||||
|
* INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any
|
||||||
|
* CPU time when they are in the Blocked state.
|
||||||
|
*
|
||||||
|
* @return The length, in bytes, of the message read from the message buffer, if
|
||||||
|
* any. If xMessageBufferReceive() times out before a message became available
|
||||||
|
* then zero is returned. If the length of the message is greater than
|
||||||
|
* xBufferLengthBytes then the message will be left in the message buffer and
|
||||||
|
* zero is returned.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* void vAFunction( MessageBuffer_t xMessageBuffer )
|
||||||
|
* {
|
||||||
|
* uint8_t ucRxData[ 20 ];
|
||||||
|
* size_t xReceivedBytes;
|
||||||
|
* const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
|
||||||
|
*
|
||||||
|
* // Receive the next message from the message buffer. Wait in the Blocked
|
||||||
|
* // state (so not using any CPU processing time) for a maximum of 100ms for
|
||||||
|
* // a message to become available.
|
||||||
|
* xReceivedBytes = xMessageBufferReceive( xMessageBuffer,
|
||||||
|
* ( void * ) ucRxData,
|
||||||
|
* sizeof( ucRxData ),
|
||||||
|
* xBlockTime );
|
||||||
|
*
|
||||||
|
* if( xReceivedBytes > 0 )
|
||||||
|
* {
|
||||||
|
* // A ucRxData contains a message that is xReceivedBytes long. Process
|
||||||
|
* // the message here....
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferReceive xMessageBufferReceive
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) \
|
||||||
|
xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait )
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer,
|
||||||
|
* void *pvRxData,
|
||||||
|
* size_t xBufferLengthBytes,
|
||||||
|
* BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* An interrupt safe version of the API function that receives a discrete
|
||||||
|
* message from a message buffer. Messages can be of variable length and are
|
||||||
|
* copied out of the buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xMessageBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xMessageBufferRead()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xMessageBufferReceive() to read from a message buffer from a task. Use
|
||||||
|
* xMessageBufferReceiveFromISR() to read from a message buffer from an
|
||||||
|
* interrupt service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer from which a message
|
||||||
|
* is being received.
|
||||||
|
*
|
||||||
|
* @param pvRxData A pointer to the buffer into which the received message is
|
||||||
|
* to be copied.
|
||||||
|
*
|
||||||
|
* @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData
|
||||||
|
* parameter. This sets the maximum length of the message that can be received.
|
||||||
|
* If xBufferLengthBytes is too small to hold the next message then the message
|
||||||
|
* will be left in the message buffer and 0 will be returned.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken It is possible that a message buffer will
|
||||||
|
* have a task blocked on it waiting for space to become available. Calling
|
||||||
|
* xMessageBufferReceiveFromISR() can make space available, and so cause a task
|
||||||
|
* that is waiting for space to leave the Blocked state. If calling
|
||||||
|
* xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and
|
||||||
|
* the unblocked task has a priority higher than the currently executing task
|
||||||
|
* (the task that was interrupted), then, internally,
|
||||||
|
* xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE.
|
||||||
|
* If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a
|
||||||
|
* context switch should be performed before the interrupt is exited. That will
|
||||||
|
* ensure the interrupt returns directly to the highest priority Ready state
|
||||||
|
* task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is
|
||||||
|
* passed into the function. See the code example below for an example.
|
||||||
|
*
|
||||||
|
* @return The length, in bytes, of the message read from the message buffer, if
|
||||||
|
* any.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* // A message buffer that has already been created.
|
||||||
|
* MessageBuffer_t xMessageBuffer;
|
||||||
|
*
|
||||||
|
* void vAnInterruptServiceRoutine( void )
|
||||||
|
* {
|
||||||
|
* uint8_t ucRxData[ 20 ];
|
||||||
|
* size_t xReceivedBytes;
|
||||||
|
* BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
|
||||||
|
*
|
||||||
|
* // Receive the next message from the message buffer.
|
||||||
|
* xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer,
|
||||||
|
* ( void * ) ucRxData,
|
||||||
|
* sizeof( ucRxData ),
|
||||||
|
* &xHigherPriorityTaskWoken );
|
||||||
|
*
|
||||||
|
* if( xReceivedBytes > 0 )
|
||||||
|
* {
|
||||||
|
* // A ucRxData contains a message that is xReceivedBytes long. Process
|
||||||
|
* // the message here....
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // If xHigherPriorityTaskWoken was set to pdTRUE inside
|
||||||
|
* // xMessageBufferReceiveFromISR() then a task that has a priority above the
|
||||||
|
* // priority of the currently executing task was unblocked and a context
|
||||||
|
* // switch should be performed to ensure the ISR returns to the unblocked
|
||||||
|
* // task. In most FreeRTOS ports this is done by simply passing
|
||||||
|
* // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the
|
||||||
|
* // variables value, and perform the context switch if necessary. Check the
|
||||||
|
* // documentation for the port in use for port specific instructions.
|
||||||
|
* portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) \
|
||||||
|
xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Deletes a message buffer that was previously created using a call to
|
||||||
|
* xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message
|
||||||
|
* buffer was created using dynamic memory (that is, by xMessageBufferCreate()),
|
||||||
|
* then the allocated memory is freed.
|
||||||
|
*
|
||||||
|
* A message buffer handle must not be used after the message buffer has been
|
||||||
|
* deleted.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer to be deleted.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#define vMessageBufferDelete( xMessageBuffer ) \
|
||||||
|
vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Tests to see if a message buffer is full. A message buffer is full if it
|
||||||
|
* cannot accept any more messages, of any size, until space is made available
|
||||||
|
* by a message being removed from the message buffer.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer being queried.
|
||||||
|
*
|
||||||
|
* @return If the message buffer referenced by xMessageBuffer is full then
|
||||||
|
* pdTRUE is returned. Otherwise pdFALSE is returned.
|
||||||
|
*/
|
||||||
|
#define xMessageBufferIsFull( xMessageBuffer ) \
|
||||||
|
xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Tests to see if a message buffer is empty (does not contain any messages).
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer being queried.
|
||||||
|
*
|
||||||
|
* @return If the message buffer referenced by xMessageBuffer is empty then
|
||||||
|
* pdTRUE is returned. Otherwise pdFALSE is returned.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#define xMessageBufferIsEmpty( xMessageBuffer ) \
|
||||||
|
xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Resets a message buffer to its initial empty state, discarding any message it
|
||||||
|
* contained.
|
||||||
|
*
|
||||||
|
* A message buffer can only be reset if there are no tasks blocked on it.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer being reset.
|
||||||
|
*
|
||||||
|
* @return If the message buffer was reset then pdPASS is returned. If the
|
||||||
|
* message buffer could not be reset because either there was a task blocked on
|
||||||
|
* the message queue to wait for space to become available, or to wait for a
|
||||||
|
* a message to be available, then pdFAIL is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xMessageBufferReset xMessageBufferReset
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferReset( xMessageBuffer ) \
|
||||||
|
xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer )
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
* Returns the number of bytes of free space in the message buffer.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer being queried.
|
||||||
|
*
|
||||||
|
* @return The number of bytes that can be written to the message buffer before
|
||||||
|
* the message buffer would be full. When a message is written to the message
|
||||||
|
* buffer an additional sizeof( size_t ) bytes are also written to store the
|
||||||
|
* message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit
|
||||||
|
* architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size
|
||||||
|
* of the largest message that can be written to the message buffer is 6 bytes.
|
||||||
|
*
|
||||||
|
* \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferSpaceAvailable( xMessageBuffer ) \
|
||||||
|
xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer )
|
||||||
|
#define xMessageBufferSpacesAvailable( xMessageBuffer ) \
|
||||||
|
xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) /* Corrects typo in original macro name. */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
* @code{c}
|
||||||
|
* size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer );
|
||||||
|
* @endcode
|
||||||
|
* Returns the length (in bytes) of the next message in a message buffer.
|
||||||
|
* Useful if xMessageBufferReceive() returned 0 because the size of the buffer
|
||||||
|
* passed into xMessageBufferReceive() was too small to hold the next message.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the message buffer being queried.
|
||||||
|
*
|
||||||
|
* @return The length (in bytes) of the next message in the message buffer, or 0
|
||||||
|
* if the message buffer is empty.
|
||||||
|
*
|
||||||
|
* \defgroup xMessageBufferNextLengthBytes xMessageBufferNextLengthBytes
|
||||||
|
* \ingroup MessageBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferNextLengthBytes( xMessageBuffer ) \
|
||||||
|
xStreamBufferNextMessageLengthBytes( ( StreamBufferHandle_t ) xMessageBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* For advanced users only.
|
||||||
|
*
|
||||||
|
* The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when
|
||||||
|
* data is sent to a message buffer or stream buffer. If there was a task that
|
||||||
|
* was blocked on the message or stream buffer waiting for data to arrive then
|
||||||
|
* the sbSEND_COMPLETED() macro sends a notification to the task to remove it
|
||||||
|
* from the Blocked state. xMessageBufferSendCompletedFromISR() does the same
|
||||||
|
* thing. It is provided to enable application writers to implement their own
|
||||||
|
* version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
|
||||||
|
*
|
||||||
|
* See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for
|
||||||
|
* additional information.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the stream buffer to which data was
|
||||||
|
* written.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be
|
||||||
|
* initialised to pdFALSE before it is passed into
|
||||||
|
* xMessageBufferSendCompletedFromISR(). If calling
|
||||||
|
* xMessageBufferSendCompletedFromISR() removes a task from the Blocked state,
|
||||||
|
* and the task has a priority above the priority of the currently running task,
|
||||||
|
* then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a
|
||||||
|
* context switch should be performed before exiting the ISR.
|
||||||
|
*
|
||||||
|
* @return If a task was removed from the Blocked state then pdTRUE is returned.
|
||||||
|
* Otherwise pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \
|
||||||
|
xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* message_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xMessageBuffer, BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* For advanced users only.
|
||||||
|
*
|
||||||
|
* The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when
|
||||||
|
* data is read out of a message buffer or stream buffer. If there was a task
|
||||||
|
* that was blocked on the message or stream buffer waiting for data to arrive
|
||||||
|
* then the sbRECEIVE_COMPLETED() macro sends a notification to the task to
|
||||||
|
* remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR()
|
||||||
|
* does the same thing. It is provided to enable application writers to
|
||||||
|
* implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT
|
||||||
|
* ANY OTHER TIME.
|
||||||
|
*
|
||||||
|
* See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for
|
||||||
|
* additional information.
|
||||||
|
*
|
||||||
|
* @param xMessageBuffer The handle of the stream buffer from which data was
|
||||||
|
* read.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be
|
||||||
|
* initialised to pdFALSE before it is passed into
|
||||||
|
* xMessageBufferReceiveCompletedFromISR(). If calling
|
||||||
|
* xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state,
|
||||||
|
* and the task has a priority above the priority of the currently running task,
|
||||||
|
* then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a
|
||||||
|
* context switch should be performed before exiting the ISR.
|
||||||
|
*
|
||||||
|
* @return If a task was removed from the Blocked state then pdTRUE is returned.
|
||||||
|
* Otherwise pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) \
|
||||||
|
xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken )
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#if defined( __cplusplus )
|
||||||
|
} /* extern "C" */
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* When the MPU is used the standard (non MPU) API functions are mapped to
|
||||||
|
* equivalents that start "MPU_", the prototypes for which are defined in this
|
||||||
|
* header files. This will cause the application code to call the MPU_ version
|
||||||
|
* which wraps the non-MPU version with privilege promoting then demoting code,
|
||||||
|
* so the kernel code always runs will full privileges.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef MPU_PROTOTYPES_H
|
||||||
|
#define MPU_PROTOTYPES_H
|
||||||
|
|
||||||
|
/* MPU versions of tasks.h API functions. */
|
||||||
|
BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode,
|
||||||
|
const char * const pcName,
|
||||||
|
const uint16_t usStackDepth,
|
||||||
|
void * const pvParameters,
|
||||||
|
UBaseType_t uxPriority,
|
||||||
|
TaskHandle_t * const pxCreatedTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode,
|
||||||
|
const char * const pcName,
|
||||||
|
const uint32_t ulStackDepth,
|
||||||
|
void * const pvParameters,
|
||||||
|
UBaseType_t uxPriority,
|
||||||
|
StackType_t * const puxStackBuffer,
|
||||||
|
StaticTask_t * const pxTaskBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskDelayUntil( TickType_t * const pxPreviousWakeTime,
|
||||||
|
const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskGetInfo( TaskHandle_t xTask,
|
||||||
|
TaskStatus_t * pxTaskStatus,
|
||||||
|
BaseType_t xGetFreeStackSpace,
|
||||||
|
eTaskState eState ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskPrioritySet( TaskHandle_t xTask,
|
||||||
|
UBaseType_t uxNewPriority ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskStartScheduler( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskSuspendAll( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskResumeAll( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xTaskGetHandle( const char * pcNameToQuery ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask,
|
||||||
|
TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet,
|
||||||
|
BaseType_t xIndex,
|
||||||
|
void * pvValue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery,
|
||||||
|
BaseType_t xIndex ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask,
|
||||||
|
void * pvParameter ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray,
|
||||||
|
const UBaseType_t uxArraySize,
|
||||||
|
configRUN_TIME_COUNTER_TYPE * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL;
|
||||||
|
configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimeCounter( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
configRUN_TIME_COUNTER_TYPE MPU_ulTaskGetIdleRunTimePercent( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskList( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskGetRunTimeStats( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify,
|
||||||
|
UBaseType_t uxIndexToNotify,
|
||||||
|
uint32_t ulValue,
|
||||||
|
eNotifyAction eAction,
|
||||||
|
uint32_t * pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskGenericNotifyWait( UBaseType_t uxIndexToWaitOn,
|
||||||
|
uint32_t ulBitsToClearOnEntry,
|
||||||
|
uint32_t ulBitsToClearOnExit,
|
||||||
|
uint32_t * pulNotificationValue,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
uint32_t MPU_ulTaskGenericNotifyTake( UBaseType_t uxIndexToWaitOn,
|
||||||
|
BaseType_t xClearCountOnExit,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskGenericNotifyStateClear( TaskHandle_t xTask,
|
||||||
|
UBaseType_t uxIndexToClear ) FREERTOS_SYSTEM_CALL;
|
||||||
|
uint32_t MPU_ulTaskGenericNotifyValueClear( TaskHandle_t xTask,
|
||||||
|
UBaseType_t uxIndexToClear,
|
||||||
|
uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskIncrementTick( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut,
|
||||||
|
TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTaskMissedYield( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) FREERTOS_SYSTEM_CALL;
|
||||||
|
|
||||||
|
/* MPU versions of queue.h API functions. */
|
||||||
|
BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue,
|
||||||
|
const void * const pvItemToQueue,
|
||||||
|
TickType_t xTicksToWait,
|
||||||
|
const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue,
|
||||||
|
void * const pvBuffer,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue,
|
||||||
|
void * const pvBuffer,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vQueueDelete( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType,
|
||||||
|
StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount,
|
||||||
|
const UBaseType_t uxInitialCount ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount,
|
||||||
|
const UBaseType_t uxInitialCount,
|
||||||
|
StaticQueue_t * pxStaticQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vQueueAddToRegistry( QueueHandle_t xQueue,
|
||||||
|
const char * pcName ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength,
|
||||||
|
const UBaseType_t uxItemSize,
|
||||||
|
const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength,
|
||||||
|
const UBaseType_t uxItemSize,
|
||||||
|
uint8_t * pucQueueStorage,
|
||||||
|
StaticQueue_t * pxStaticQueue,
|
||||||
|
const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore,
|
||||||
|
QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore,
|
||||||
|
QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL;
|
||||||
|
QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet,
|
||||||
|
const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue,
|
||||||
|
BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue,
|
||||||
|
UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL;
|
||||||
|
|
||||||
|
/* MPU versions of timers.h API functions. */
|
||||||
|
TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName,
|
||||||
|
const TickType_t xTimerPeriodInTicks,
|
||||||
|
const UBaseType_t uxAutoReload,
|
||||||
|
void * const pvTimerID,
|
||||||
|
TimerCallbackFunction_t pxCallbackFunction ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName,
|
||||||
|
const TickType_t xTimerPeriodInTicks,
|
||||||
|
const UBaseType_t uxAutoReload,
|
||||||
|
void * const pvTimerID,
|
||||||
|
TimerCallbackFunction_t pxCallbackFunction,
|
||||||
|
StaticTimer_t * pxTimerBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTimerSetTimerID( TimerHandle_t xTimer,
|
||||||
|
void * pvNewID ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend,
|
||||||
|
void * pvParameter1,
|
||||||
|
uint32_t ulParameter2,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vTimerSetReloadMode( TimerHandle_t xTimer,
|
||||||
|
const UBaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTimerCreateTimerTask( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer,
|
||||||
|
const BaseType_t xCommandID,
|
||||||
|
const TickType_t xOptionalValue,
|
||||||
|
BaseType_t * const pxHigherPriorityTaskWoken,
|
||||||
|
const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
|
||||||
|
/* MPU versions of event_group.h API functions. */
|
||||||
|
EventGroupHandle_t MPU_xEventGroupCreate( void ) FREERTOS_SYSTEM_CALL;
|
||||||
|
EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t * pxEventGroupBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
const BaseType_t xClearOnExit,
|
||||||
|
const BaseType_t xWaitForAllBits,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL;
|
||||||
|
EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL;
|
||||||
|
EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup,
|
||||||
|
const EventBits_t uxBitsToSet,
|
||||||
|
const EventBits_t uxBitsToWaitFor,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) FREERTOS_SYSTEM_CALL;
|
||||||
|
UBaseType_t MPU_uxEventGroupGetNumber( void * xEventGroup ) FREERTOS_SYSTEM_CALL;
|
||||||
|
|
||||||
|
/* MPU versions of message/stream_buffer.h API functions. */
|
||||||
|
size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
const void * pvTxData,
|
||||||
|
size_t xDataLengthBytes,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
void * pvRxData,
|
||||||
|
size_t xBufferLengthBytes,
|
||||||
|
TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL;
|
||||||
|
size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL;
|
||||||
|
StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes,
|
||||||
|
size_t xTriggerLevelBytes,
|
||||||
|
BaseType_t xIsMessageBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
|
||||||
|
size_t xTriggerLevelBytes,
|
||||||
|
BaseType_t xIsMessageBuffer,
|
||||||
|
uint8_t * const pucStreamBufferStorageArea,
|
||||||
|
StaticStreamBuffer_t * const pxStaticStreamBuffer ) FREERTOS_SYSTEM_CALL;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#endif /* MPU_PROTOTYPES_H */
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef MPU_WRAPPERS_H
|
||||||
|
#define MPU_WRAPPERS_H
|
||||||
|
|
||||||
|
/* This file redefines API functions to be called through a wrapper macro, but
|
||||||
|
* only for ports that are using the MPU. */
|
||||||
|
#if ( portUSING_MPU_WRAPPERS == 1 )
|
||||||
|
|
||||||
|
/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is
|
||||||
|
* included from queue.c or task.c to prevent it from having an effect within
|
||||||
|
* those files. */
|
||||||
|
#ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Map standard (non MPU) API functions to equivalents that start
|
||||||
|
* "MPU_". This will cause the application code to call the MPU_
|
||||||
|
* version, which wraps the non-MPU version with privilege promoting
|
||||||
|
* then demoting code, so the kernel code always runs will full
|
||||||
|
* privileges.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Map standard tasks.h API functions to the MPU equivalents. */
|
||||||
|
#define xTaskCreate MPU_xTaskCreate
|
||||||
|
#define xTaskCreateStatic MPU_xTaskCreateStatic
|
||||||
|
#define vTaskDelete MPU_vTaskDelete
|
||||||
|
#define vTaskDelay MPU_vTaskDelay
|
||||||
|
#define xTaskDelayUntil MPU_xTaskDelayUntil
|
||||||
|
#define xTaskAbortDelay MPU_xTaskAbortDelay
|
||||||
|
#define uxTaskPriorityGet MPU_uxTaskPriorityGet
|
||||||
|
#define eTaskGetState MPU_eTaskGetState
|
||||||
|
#define vTaskGetInfo MPU_vTaskGetInfo
|
||||||
|
#define vTaskPrioritySet MPU_vTaskPrioritySet
|
||||||
|
#define vTaskSuspend MPU_vTaskSuspend
|
||||||
|
#define vTaskResume MPU_vTaskResume
|
||||||
|
#define vTaskSuspendAll MPU_vTaskSuspendAll
|
||||||
|
#define xTaskResumeAll MPU_xTaskResumeAll
|
||||||
|
#define xTaskGetTickCount MPU_xTaskGetTickCount
|
||||||
|
#define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks
|
||||||
|
#define pcTaskGetName MPU_pcTaskGetName
|
||||||
|
#define xTaskGetHandle MPU_xTaskGetHandle
|
||||||
|
#define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark
|
||||||
|
#define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2
|
||||||
|
#define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag
|
||||||
|
#define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag
|
||||||
|
#define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer
|
||||||
|
#define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer
|
||||||
|
#define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook
|
||||||
|
#define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle
|
||||||
|
#define uxTaskGetSystemState MPU_uxTaskGetSystemState
|
||||||
|
#define vTaskList MPU_vTaskList
|
||||||
|
#define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats
|
||||||
|
#define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter
|
||||||
|
#define ulTaskGetIdleRunTimePercent MPU_ulTaskGetIdleRunTimePercent
|
||||||
|
#define xTaskGenericNotify MPU_xTaskGenericNotify
|
||||||
|
#define xTaskGenericNotifyWait MPU_xTaskGenericNotifyWait
|
||||||
|
#define ulTaskGenericNotifyTake MPU_ulTaskGenericNotifyTake
|
||||||
|
#define xTaskGenericNotifyStateClear MPU_xTaskGenericNotifyStateClear
|
||||||
|
#define ulTaskGenericNotifyValueClear MPU_ulTaskGenericNotifyValueClear
|
||||||
|
#define xTaskCatchUpTicks MPU_xTaskCatchUpTicks
|
||||||
|
|
||||||
|
#define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle
|
||||||
|
#define vTaskSetTimeOutState MPU_vTaskSetTimeOutState
|
||||||
|
#define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut
|
||||||
|
#define xTaskGetSchedulerState MPU_xTaskGetSchedulerState
|
||||||
|
|
||||||
|
/* Map standard queue.h API functions to the MPU equivalents. */
|
||||||
|
#define xQueueGenericSend MPU_xQueueGenericSend
|
||||||
|
#define xQueueReceive MPU_xQueueReceive
|
||||||
|
#define xQueuePeek MPU_xQueuePeek
|
||||||
|
#define xQueueSemaphoreTake MPU_xQueueSemaphoreTake
|
||||||
|
#define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting
|
||||||
|
#define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable
|
||||||
|
#define vQueueDelete MPU_vQueueDelete
|
||||||
|
#define xQueueCreateMutex MPU_xQueueCreateMutex
|
||||||
|
#define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic
|
||||||
|
#define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore
|
||||||
|
#define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic
|
||||||
|
#define xQueueGetMutexHolder MPU_xQueueGetMutexHolder
|
||||||
|
#define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive
|
||||||
|
#define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive
|
||||||
|
#define xQueueGenericCreate MPU_xQueueGenericCreate
|
||||||
|
#define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic
|
||||||
|
#define xQueueCreateSet MPU_xQueueCreateSet
|
||||||
|
#define xQueueAddToSet MPU_xQueueAddToSet
|
||||||
|
#define xQueueRemoveFromSet MPU_xQueueRemoveFromSet
|
||||||
|
#define xQueueSelectFromSet MPU_xQueueSelectFromSet
|
||||||
|
#define xQueueGenericReset MPU_xQueueGenericReset
|
||||||
|
|
||||||
|
#if ( configQUEUE_REGISTRY_SIZE > 0 )
|
||||||
|
#define vQueueAddToRegistry MPU_vQueueAddToRegistry
|
||||||
|
#define vQueueUnregisterQueue MPU_vQueueUnregisterQueue
|
||||||
|
#define pcQueueGetName MPU_pcQueueGetName
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Map standard timer.h API functions to the MPU equivalents. */
|
||||||
|
#define xTimerCreate MPU_xTimerCreate
|
||||||
|
#define xTimerCreateStatic MPU_xTimerCreateStatic
|
||||||
|
#define pvTimerGetTimerID MPU_pvTimerGetTimerID
|
||||||
|
#define vTimerSetTimerID MPU_vTimerSetTimerID
|
||||||
|
#define xTimerIsTimerActive MPU_xTimerIsTimerActive
|
||||||
|
#define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle
|
||||||
|
#define xTimerPendFunctionCall MPU_xTimerPendFunctionCall
|
||||||
|
#define pcTimerGetName MPU_pcTimerGetName
|
||||||
|
#define vTimerSetReloadMode MPU_vTimerSetReloadMode
|
||||||
|
#define uxTimerGetReloadMode MPU_uxTimerGetReloadMode
|
||||||
|
#define xTimerGetPeriod MPU_xTimerGetPeriod
|
||||||
|
#define xTimerGetExpiryTime MPU_xTimerGetExpiryTime
|
||||||
|
#define xTimerGenericCommand MPU_xTimerGenericCommand
|
||||||
|
|
||||||
|
/* Map standard event_group.h API functions to the MPU equivalents. */
|
||||||
|
#define xEventGroupCreate MPU_xEventGroupCreate
|
||||||
|
#define xEventGroupCreateStatic MPU_xEventGroupCreateStatic
|
||||||
|
#define xEventGroupWaitBits MPU_xEventGroupWaitBits
|
||||||
|
#define xEventGroupClearBits MPU_xEventGroupClearBits
|
||||||
|
#define xEventGroupSetBits MPU_xEventGroupSetBits
|
||||||
|
#define xEventGroupSync MPU_xEventGroupSync
|
||||||
|
#define vEventGroupDelete MPU_vEventGroupDelete
|
||||||
|
|
||||||
|
/* Map standard message/stream_buffer.h API functions to the MPU
|
||||||
|
* equivalents. */
|
||||||
|
#define xStreamBufferSend MPU_xStreamBufferSend
|
||||||
|
#define xStreamBufferReceive MPU_xStreamBufferReceive
|
||||||
|
#define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes
|
||||||
|
#define vStreamBufferDelete MPU_vStreamBufferDelete
|
||||||
|
#define xStreamBufferIsFull MPU_xStreamBufferIsFull
|
||||||
|
#define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty
|
||||||
|
#define xStreamBufferReset MPU_xStreamBufferReset
|
||||||
|
#define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable
|
||||||
|
#define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable
|
||||||
|
#define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel
|
||||||
|
#define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate
|
||||||
|
#define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic
|
||||||
|
|
||||||
|
|
||||||
|
/* Remove the privileged function macro, but keep the PRIVILEGED_DATA
|
||||||
|
* macro so applications can place data in privileged access sections
|
||||||
|
* (useful when using statically allocated objects). */
|
||||||
|
#define PRIVILEGED_FUNCTION
|
||||||
|
#define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) )
|
||||||
|
#define FREERTOS_SYSTEM_CALL
|
||||||
|
|
||||||
|
#else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */
|
||||||
|
|
||||||
|
/* Ensure API functions go in the privileged execution section. */
|
||||||
|
#define PRIVILEGED_FUNCTION __attribute__( ( section( "privileged_functions" ) ) )
|
||||||
|
#define PRIVILEGED_DATA __attribute__( ( section( "privileged_data" ) ) )
|
||||||
|
#define FREERTOS_SYSTEM_CALL __attribute__( ( section( "freertos_system_calls" ) ) )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Calls the port specific code to raise the privilege.
|
||||||
|
*
|
||||||
|
* Sets xRunningPrivileged to pdFALSE if privilege was raised, else sets
|
||||||
|
* it to pdTRUE.
|
||||||
|
*/
|
||||||
|
#define xPortRaisePrivilege( xRunningPrivileged ) \
|
||||||
|
{ \
|
||||||
|
/* Check whether the processor is already privileged. */ \
|
||||||
|
xRunningPrivileged = portIS_PRIVILEGED(); \
|
||||||
|
\
|
||||||
|
/* If the processor is not already privileged, raise privilege. */ \
|
||||||
|
if( xRunningPrivileged == pdFALSE ) \
|
||||||
|
{ \
|
||||||
|
portRAISE_PRIVILEGE(); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief If xRunningPrivileged is not pdTRUE, calls the port specific
|
||||||
|
* code to reset the privilege, otherwise does nothing.
|
||||||
|
*/
|
||||||
|
#define vPortResetPrivilege( xRunningPrivileged ) \
|
||||||
|
{ \
|
||||||
|
if( xRunningPrivileged == pdFALSE ) \
|
||||||
|
{ \
|
||||||
|
portRESET_PRIVILEGE(); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */
|
||||||
|
|
||||||
|
#else /* portUSING_MPU_WRAPPERS */
|
||||||
|
|
||||||
|
#define PRIVILEGED_FUNCTION
|
||||||
|
#define PRIVILEGED_DATA
|
||||||
|
#define FREERTOS_SYSTEM_CALL
|
||||||
|
|
||||||
|
#endif /* portUSING_MPU_WRAPPERS */
|
||||||
|
|
||||||
|
|
||||||
|
#endif /* MPU_WRAPPERS_H */
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------
|
||||||
|
* Portable layer API. Each function must be defined for each port.
|
||||||
|
*----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#ifndef PORTABLE_H
|
||||||
|
#define PORTABLE_H
|
||||||
|
|
||||||
|
/* Each FreeRTOS port has a unique portmacro.h header file. Originally a
|
||||||
|
* pre-processor definition was used to ensure the pre-processor found the correct
|
||||||
|
* portmacro.h file for the port being used. That scheme was deprecated in favour
|
||||||
|
* of setting the compiler's include path such that it found the correct
|
||||||
|
* portmacro.h file - removing the need for the constant and allowing the
|
||||||
|
* portmacro.h file to be located anywhere in relation to the port being used.
|
||||||
|
* Purely for reasons of backward compatibility the old method is still valid, but
|
||||||
|
* to make it clear that new projects should not use it, support for the port
|
||||||
|
* specific constants has been moved into the deprecated_definitions.h header
|
||||||
|
* file. */
|
||||||
|
#include "deprecated_definitions.h"
|
||||||
|
|
||||||
|
/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h
|
||||||
|
* did not result in a portmacro.h header file being included - and it should be
|
||||||
|
* included here. In this case the path to the correct portmacro.h header file
|
||||||
|
* must be set in the compiler's include path. */
|
||||||
|
#ifndef portENTER_CRITICAL
|
||||||
|
#include "portmacro.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if portBYTE_ALIGNMENT == 32
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x001f )
|
||||||
|
#elif portBYTE_ALIGNMENT == 16
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x000f )
|
||||||
|
#elif portBYTE_ALIGNMENT == 8
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x0007 )
|
||||||
|
#elif portBYTE_ALIGNMENT == 4
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x0003 )
|
||||||
|
#elif portBYTE_ALIGNMENT == 2
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x0001 )
|
||||||
|
#elif portBYTE_ALIGNMENT == 1
|
||||||
|
#define portBYTE_ALIGNMENT_MASK ( 0x0000 )
|
||||||
|
#else /* if portBYTE_ALIGNMENT == 32 */
|
||||||
|
#error "Invalid portBYTE_ALIGNMENT definition"
|
||||||
|
#endif /* if portBYTE_ALIGNMENT == 32 */
|
||||||
|
|
||||||
|
#ifndef portUSING_MPU_WRAPPERS
|
||||||
|
#define portUSING_MPU_WRAPPERS 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portNUM_CONFIGURABLE_REGIONS
|
||||||
|
#define portNUM_CONFIGURABLE_REGIONS 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portHAS_STACK_OVERFLOW_CHECKING
|
||||||
|
#define portHAS_STACK_OVERFLOW_CHECKING 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portARCH_NAME
|
||||||
|
#define portARCH_NAME NULL
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef configSTACK_ALLOCATION_FROM_SEPARATE_HEAP
|
||||||
|
/* Defaults to 0 for backward compatibility. */
|
||||||
|
#define configSTACK_ALLOCATION_FROM_SEPARATE_HEAP 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#include "mpu_wrappers.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Setup the stack of a new task so it is ready to be placed under the
|
||||||
|
* scheduler control. The registers have to be placed on the stack in
|
||||||
|
* the order that the port expects to find them.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#if ( portUSING_MPU_WRAPPERS == 1 )
|
||||||
|
#if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
|
||||||
|
StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
|
||||||
|
StackType_t * pxEndOfStack,
|
||||||
|
TaskFunction_t pxCode,
|
||||||
|
void * pvParameters,
|
||||||
|
BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION;
|
||||||
|
#else
|
||||||
|
StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
|
||||||
|
TaskFunction_t pxCode,
|
||||||
|
void * pvParameters,
|
||||||
|
BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
#else /* if ( portUSING_MPU_WRAPPERS == 1 ) */
|
||||||
|
#if ( portHAS_STACK_OVERFLOW_CHECKING == 1 )
|
||||||
|
StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
|
||||||
|
StackType_t * pxEndOfStack,
|
||||||
|
TaskFunction_t pxCode,
|
||||||
|
void * pvParameters ) PRIVILEGED_FUNCTION;
|
||||||
|
#else
|
||||||
|
StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
|
||||||
|
TaskFunction_t pxCode,
|
||||||
|
void * pvParameters ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
#endif /* if ( portUSING_MPU_WRAPPERS == 1 ) */
|
||||||
|
|
||||||
|
/* Used by heap_5.c to define the start address and size of each memory region
|
||||||
|
* that together comprise the total FreeRTOS heap space. */
|
||||||
|
typedef struct HeapRegion
|
||||||
|
{
|
||||||
|
uint8_t * pucStartAddress;
|
||||||
|
size_t xSizeInBytes;
|
||||||
|
} HeapRegion_t;
|
||||||
|
|
||||||
|
/* Used to pass information about the heap out of vPortGetHeapStats(). */
|
||||||
|
typedef struct xHeapStats
|
||||||
|
{
|
||||||
|
size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */
|
||||||
|
size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */
|
||||||
|
size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */
|
||||||
|
size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */
|
||||||
|
size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */
|
||||||
|
size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */
|
||||||
|
size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */
|
||||||
|
} HeapStats_t;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Used to define multiple heap regions for use by heap_5.c. This function
|
||||||
|
* must be called before any calls to pvPortMalloc() - not creating a task,
|
||||||
|
* queue, semaphore, mutex, software timer, event group, etc. will result in
|
||||||
|
* pvPortMalloc being called.
|
||||||
|
*
|
||||||
|
* pxHeapRegions passes in an array of HeapRegion_t structures - each of which
|
||||||
|
* defines a region of memory that can be used as the heap. The array is
|
||||||
|
* terminated by a HeapRegions_t structure that has a size of 0. The region
|
||||||
|
* with the lowest start address must appear first in the array.
|
||||||
|
*/
|
||||||
|
void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Returns a HeapStats_t structure filled with information about the current
|
||||||
|
* heap state.
|
||||||
|
*/
|
||||||
|
void vPortGetHeapStats( HeapStats_t * pxHeapStats );
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Map to the memory management routines required for the port.
|
||||||
|
*/
|
||||||
|
void * pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION;
|
||||||
|
void vPortFree( void * pv ) PRIVILEGED_FUNCTION;
|
||||||
|
void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION;
|
||||||
|
size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION;
|
||||||
|
size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
#if ( configSTACK_ALLOCATION_FROM_SEPARATE_HEAP == 1 )
|
||||||
|
void * pvPortMallocStack( size_t xSize ) PRIVILEGED_FUNCTION;
|
||||||
|
void vPortFreeStack( void * pv ) PRIVILEGED_FUNCTION;
|
||||||
|
#else
|
||||||
|
#define pvPortMallocStack pvPortMalloc
|
||||||
|
#define vPortFreeStack vPortFree
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Setup the hardware ready for the scheduler to take control. This generally
|
||||||
|
* sets up a tick interrupt and sets timers for the correct tick frequency.
|
||||||
|
*/
|
||||||
|
BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Undo any hardware/ISR setup that was performed by xPortStartScheduler() so
|
||||||
|
* the hardware is left in its original condition after the scheduler stops
|
||||||
|
* executing.
|
||||||
|
*/
|
||||||
|
void vPortEndScheduler( void ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The structures and methods of manipulating the MPU are contained within the
|
||||||
|
* port layer.
|
||||||
|
*
|
||||||
|
* Fills the xMPUSettings structure with the memory region information
|
||||||
|
* contained in xRegions.
|
||||||
|
*/
|
||||||
|
#if ( portUSING_MPU_WRAPPERS == 1 )
|
||||||
|
struct xMEMORY_REGION;
|
||||||
|
void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings,
|
||||||
|
const struct xMEMORY_REGION * const xRegions,
|
||||||
|
StackType_t * pxBottomOfStack,
|
||||||
|
uint32_t ulStackDepth ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* PORTABLE_H */
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef PROJDEFS_H
|
||||||
|
#define PROJDEFS_H
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Defines the prototype to which task functions must conform. Defined in this
|
||||||
|
* file to ensure the type is known before portable.h is included.
|
||||||
|
*/
|
||||||
|
typedef void (* TaskFunction_t)( void * );
|
||||||
|
|
||||||
|
/* Converts a time in milliseconds to a time in ticks. This macro can be
|
||||||
|
* overridden by a macro of the same name defined in FreeRTOSConfig.h in case the
|
||||||
|
* definition here is not suitable for your application. */
|
||||||
|
#ifndef pdMS_TO_TICKS
|
||||||
|
#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define pdFALSE ( ( BaseType_t ) 0 )
|
||||||
|
#define pdTRUE ( ( BaseType_t ) 1 )
|
||||||
|
|
||||||
|
#define pdPASS ( pdTRUE )
|
||||||
|
#define pdFAIL ( pdFALSE )
|
||||||
|
#define errQUEUE_EMPTY ( ( BaseType_t ) 0 )
|
||||||
|
#define errQUEUE_FULL ( ( BaseType_t ) 0 )
|
||||||
|
|
||||||
|
/* FreeRTOS error definitions. */
|
||||||
|
#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 )
|
||||||
|
#define errQUEUE_BLOCKED ( -4 )
|
||||||
|
#define errQUEUE_YIELD ( -5 )
|
||||||
|
|
||||||
|
/* Macros used for basic data corruption checks. */
|
||||||
|
#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES
|
||||||
|
#define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ( configUSE_16_BIT_TICKS == 1 )
|
||||||
|
#define pdINTEGRITY_CHECK_VALUE 0x5a5a
|
||||||
|
#else
|
||||||
|
#define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* The following errno values are used by FreeRTOS+ components, not FreeRTOS
|
||||||
|
* itself. */
|
||||||
|
#define pdFREERTOS_ERRNO_NONE 0 /* No errors */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */
|
||||||
|
#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */
|
||||||
|
#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */
|
||||||
|
#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */
|
||||||
|
#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */
|
||||||
|
#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */
|
||||||
|
#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */
|
||||||
|
#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */
|
||||||
|
#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */
|
||||||
|
#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */
|
||||||
|
#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */
|
||||||
|
#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */
|
||||||
|
#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */
|
||||||
|
#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */
|
||||||
|
#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */
|
||||||
|
#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */
|
||||||
|
#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */
|
||||||
|
#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */
|
||||||
|
#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */
|
||||||
|
#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */
|
||||||
|
#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */
|
||||||
|
#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */
|
||||||
|
#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */
|
||||||
|
#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */
|
||||||
|
#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */
|
||||||
|
#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */
|
||||||
|
#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */
|
||||||
|
#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */
|
||||||
|
#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */
|
||||||
|
#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */
|
||||||
|
#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */
|
||||||
|
#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */
|
||||||
|
|
||||||
|
/* The following endian values are used by FreeRTOS+ components, not FreeRTOS
|
||||||
|
* itself. */
|
||||||
|
#define pdFREERTOS_LITTLE_ENDIAN 0
|
||||||
|
#define pdFREERTOS_BIG_ENDIAN 1
|
||||||
|
|
||||||
|
/* Re-defining endian values for generic naming. */
|
||||||
|
#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN
|
||||||
|
#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN
|
||||||
|
|
||||||
|
|
||||||
|
#endif /* PROJDEFS_H */
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,137 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef STACK_MACROS_H
|
||||||
|
#define STACK_MACROS_H
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Call the stack overflow hook function if the stack of the task being swapped
|
||||||
|
* out is currently overflowed, or looks like it might have overflowed in the
|
||||||
|
* past.
|
||||||
|
*
|
||||||
|
* Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check
|
||||||
|
* the current stack state only - comparing the current top of stack value to
|
||||||
|
* the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1
|
||||||
|
* will also cause the last few stack bytes to be checked to ensure the value
|
||||||
|
* to which the bytes were set when the task was created have not been
|
||||||
|
* overwritten. Note this second test does not guarantee that an overflowed
|
||||||
|
* stack will always be recognised.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* portSTACK_LIMIT_PADDING is a number of extra words to consider to be in
|
||||||
|
* use on the stack.
|
||||||
|
*/
|
||||||
|
#ifndef portSTACK_LIMIT_PADDING
|
||||||
|
#define portSTACK_LIMIT_PADDING 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) )
|
||||||
|
|
||||||
|
/* Only the current stack state is to be checked. */
|
||||||
|
#define taskCHECK_FOR_STACK_OVERFLOW() \
|
||||||
|
{ \
|
||||||
|
/* Is the currently saved stack pointer within the stack limit? */ \
|
||||||
|
if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack + portSTACK_LIMIT_PADDING ) \
|
||||||
|
{ \
|
||||||
|
vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) )
|
||||||
|
|
||||||
|
/* Only the current stack state is to be checked. */
|
||||||
|
#define taskCHECK_FOR_STACK_OVERFLOW() \
|
||||||
|
{ \
|
||||||
|
\
|
||||||
|
/* Is the currently saved stack pointer within the stack limit? */ \
|
||||||
|
if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack - portSTACK_LIMIT_PADDING ) \
|
||||||
|
{ \
|
||||||
|
vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
|
||||||
|
|
||||||
|
#define taskCHECK_FOR_STACK_OVERFLOW() \
|
||||||
|
{ \
|
||||||
|
const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \
|
||||||
|
const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \
|
||||||
|
\
|
||||||
|
if( ( pulStack[ 0 ] != ulCheckValue ) || \
|
||||||
|
( pulStack[ 1 ] != ulCheckValue ) || \
|
||||||
|
( pulStack[ 2 ] != ulCheckValue ) || \
|
||||||
|
( pulStack[ 3 ] != ulCheckValue ) ) \
|
||||||
|
{ \
|
||||||
|
vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
|
||||||
|
|
||||||
|
#define taskCHECK_FOR_STACK_OVERFLOW() \
|
||||||
|
{ \
|
||||||
|
int8_t * pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \
|
||||||
|
static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
|
||||||
|
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
|
||||||
|
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
|
||||||
|
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
|
||||||
|
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \
|
||||||
|
\
|
||||||
|
\
|
||||||
|
pcEndOfStack -= sizeof( ucExpectedStackBytes ); \
|
||||||
|
\
|
||||||
|
/* Has the extremity of the task stack ever been written over? */ \
|
||||||
|
if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \
|
||||||
|
{ \
|
||||||
|
vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
|
||||||
|
} \
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* Remove stack overflow macro if not being used. */
|
||||||
|
#ifndef taskCHECK_FOR_STACK_OVERFLOW
|
||||||
|
#define taskCHECK_FOR_STACK_OVERFLOW()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#endif /* STACK_MACROS_H */
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef FREERTOS_STDINT
|
||||||
|
#define FREERTOS_STDINT
|
||||||
|
|
||||||
|
/*******************************************************************************
|
||||||
|
* THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions
|
||||||
|
* necessary to build the FreeRTOS code. It is provided to allow FreeRTOS to be
|
||||||
|
* built using compilers that do not provide their own stdint.h definition.
|
||||||
|
*
|
||||||
|
* To use this file:
|
||||||
|
*
|
||||||
|
* 1) Copy this file into the directory that contains your FreeRTOSConfig.h
|
||||||
|
* header file, as that directory will already be in the compiler's include
|
||||||
|
* path.
|
||||||
|
*
|
||||||
|
* 2) Rename the copied file stdint.h.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef signed char int8_t;
|
||||||
|
typedef unsigned char uint8_t;
|
||||||
|
typedef short int16_t;
|
||||||
|
typedef unsigned short uint16_t;
|
||||||
|
typedef long int32_t;
|
||||||
|
typedef unsigned long uint32_t;
|
||||||
|
|
||||||
|
#ifndef SIZE_MAX
|
||||||
|
#define SIZE_MAX ( ( size_t ) -1 )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* FREERTOS_STDINT */
|
||||||
@@ -0,0 +1,869 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Stream buffers are used to send a continuous stream of data from one task or
|
||||||
|
* interrupt to another. Their implementation is light weight, making them
|
||||||
|
* particularly suited for interrupt to task and core to core communication
|
||||||
|
* scenarios.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xStreamBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xStreamBufferReceive()) inside a critical section section and set the
|
||||||
|
* receive block time to 0.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef STREAM_BUFFER_H
|
||||||
|
#define STREAM_BUFFER_H
|
||||||
|
|
||||||
|
#ifndef INC_FREERTOS_H
|
||||||
|
#error "include FreeRTOS.h must appear in source files before include stream_buffer.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#if defined( __cplusplus )
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type by which stream buffers are referenced. For example, a call to
|
||||||
|
* xStreamBufferCreate() returns an StreamBufferHandle_t variable that can
|
||||||
|
* then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(),
|
||||||
|
* etc.
|
||||||
|
*/
|
||||||
|
struct StreamBufferDef_t;
|
||||||
|
typedef struct StreamBufferDef_t * StreamBufferHandle_t;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Creates a new stream buffer using dynamically allocated memory. See
|
||||||
|
* xStreamBufferCreateStatic() for a version that uses statically allocated
|
||||||
|
* memory (memory that is allocated at compile time).
|
||||||
|
*
|
||||||
|
* configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in
|
||||||
|
* FreeRTOSConfig.h for xStreamBufferCreate() to be available.
|
||||||
|
*
|
||||||
|
* @param xBufferSizeBytes The total number of bytes the stream buffer will be
|
||||||
|
* able to hold at any one time.
|
||||||
|
*
|
||||||
|
* @param xTriggerLevelBytes The number of bytes that must be in the stream
|
||||||
|
* buffer before a task that is blocked on the stream buffer to wait for data is
|
||||||
|
* moved out of the blocked state. For example, if a task is blocked on a read
|
||||||
|
* of an empty stream buffer that has a trigger level of 1 then the task will be
|
||||||
|
* unblocked when a single byte is written to the buffer or the task's block
|
||||||
|
* time expires. As another example, if a task is blocked on a read of an empty
|
||||||
|
* stream buffer that has a trigger level of 10 then the task will not be
|
||||||
|
* unblocked until the stream buffer contains at least 10 bytes or the task's
|
||||||
|
* block time expires. If a reading task's block time expires before the
|
||||||
|
* trigger level is reached then the task will still receive however many bytes
|
||||||
|
* are actually available. Setting a trigger level of 0 will result in a
|
||||||
|
* trigger level of 1 being used. It is not valid to specify a trigger level
|
||||||
|
* that is greater than the buffer size.
|
||||||
|
*
|
||||||
|
* @return If NULL is returned, then the stream buffer cannot be created
|
||||||
|
* because there is insufficient heap memory available for FreeRTOS to allocate
|
||||||
|
* the stream buffer data structures and storage area. A non-NULL value being
|
||||||
|
* returned indicates that the stream buffer has been created successfully -
|
||||||
|
* the returned value should be stored as the handle to the created stream
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
*
|
||||||
|
* void vAFunction( void )
|
||||||
|
* {
|
||||||
|
* StreamBufferHandle_t xStreamBuffer;
|
||||||
|
* const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10;
|
||||||
|
*
|
||||||
|
* // Create a stream buffer that can hold 100 bytes. The memory used to hold
|
||||||
|
* // both the stream buffer structure and the data in the stream buffer is
|
||||||
|
* // allocated dynamically.
|
||||||
|
* xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel );
|
||||||
|
*
|
||||||
|
* if( xStreamBuffer == NULL )
|
||||||
|
* {
|
||||||
|
* // There was not enough heap memory space available to create the
|
||||||
|
* // stream buffer.
|
||||||
|
* }
|
||||||
|
* else
|
||||||
|
* {
|
||||||
|
* // The stream buffer was created successfully and can now be used.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferCreate xStreamBufferCreate
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes,
|
||||||
|
* size_t xTriggerLevelBytes,
|
||||||
|
* uint8_t *pucStreamBufferStorageArea,
|
||||||
|
* StaticStreamBuffer_t *pxStaticStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
* Creates a new stream buffer using statically allocated memory. See
|
||||||
|
* xStreamBufferCreate() for a version that uses dynamically allocated memory.
|
||||||
|
*
|
||||||
|
* configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for
|
||||||
|
* xStreamBufferCreateStatic() to be available.
|
||||||
|
*
|
||||||
|
* @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the
|
||||||
|
* pucStreamBufferStorageArea parameter.
|
||||||
|
*
|
||||||
|
* @param xTriggerLevelBytes The number of bytes that must be in the stream
|
||||||
|
* buffer before a task that is blocked on the stream buffer to wait for data is
|
||||||
|
* moved out of the blocked state. For example, if a task is blocked on a read
|
||||||
|
* of an empty stream buffer that has a trigger level of 1 then the task will be
|
||||||
|
* unblocked when a single byte is written to the buffer or the task's block
|
||||||
|
* time expires. As another example, if a task is blocked on a read of an empty
|
||||||
|
* stream buffer that has a trigger level of 10 then the task will not be
|
||||||
|
* unblocked until the stream buffer contains at least 10 bytes or the task's
|
||||||
|
* block time expires. If a reading task's block time expires before the
|
||||||
|
* trigger level is reached then the task will still receive however many bytes
|
||||||
|
* are actually available. Setting a trigger level of 0 will result in a
|
||||||
|
* trigger level of 1 being used. It is not valid to specify a trigger level
|
||||||
|
* that is greater than the buffer size.
|
||||||
|
*
|
||||||
|
* @param pucStreamBufferStorageArea Must point to a uint8_t array that is at
|
||||||
|
* least xBufferSizeBytes big. This is the array to which streams are
|
||||||
|
* copied when they are written to the stream buffer.
|
||||||
|
*
|
||||||
|
* @param pxStaticStreamBuffer Must point to a variable of type
|
||||||
|
* StaticStreamBuffer_t, which will be used to hold the stream buffer's data
|
||||||
|
* structure.
|
||||||
|
*
|
||||||
|
* @return If the stream buffer is created successfully then a handle to the
|
||||||
|
* created stream buffer is returned. If either pucStreamBufferStorageArea or
|
||||||
|
* pxStaticstreamBuffer are NULL then NULL is returned.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
*
|
||||||
|
* // Used to dimension the array used to hold the streams. The available space
|
||||||
|
* // will actually be one less than this, so 999.
|
||||||
|
#define STORAGE_SIZE_BYTES 1000
|
||||||
|
*
|
||||||
|
* // Defines the memory that will actually hold the streams within the stream
|
||||||
|
* // buffer.
|
||||||
|
* static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
|
||||||
|
*
|
||||||
|
* // The variable used to hold the stream buffer structure.
|
||||||
|
* StaticStreamBuffer_t xStreamBufferStruct;
|
||||||
|
*
|
||||||
|
* void MyFunction( void )
|
||||||
|
* {
|
||||||
|
* StreamBufferHandle_t xStreamBuffer;
|
||||||
|
* const size_t xTriggerLevel = 1;
|
||||||
|
*
|
||||||
|
* xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucStorageBuffer ),
|
||||||
|
* xTriggerLevel,
|
||||||
|
* ucStorageBuffer,
|
||||||
|
* &xStreamBufferStruct );
|
||||||
|
*
|
||||||
|
* // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer
|
||||||
|
* // parameters were NULL, xStreamBuffer will not be NULL, and can be used to
|
||||||
|
* // reference the created stream buffer in other stream buffer API calls.
|
||||||
|
*
|
||||||
|
* // Other code that uses the stream buffer can go here.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) \
|
||||||
|
xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer )
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
* const void *pvTxData,
|
||||||
|
* size_t xDataLengthBytes,
|
||||||
|
* TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Sends bytes to a stream buffer. The bytes are copied into the stream buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xStreamBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xStreamBufferReceive()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xStreamBufferSend() to write to a stream buffer from a task. Use
|
||||||
|
* xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
|
||||||
|
* service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer to which a stream is
|
||||||
|
* being sent.
|
||||||
|
*
|
||||||
|
* @param pvTxData A pointer to the buffer that holds the bytes to be copied
|
||||||
|
* into the stream buffer.
|
||||||
|
*
|
||||||
|
* @param xDataLengthBytes The maximum number of bytes to copy from pvTxData
|
||||||
|
* into the stream buffer.
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time the task should remain in the
|
||||||
|
* Blocked state to wait for enough space to become available in the stream
|
||||||
|
* buffer, should the stream buffer contain too little space to hold the
|
||||||
|
* another xDataLengthBytes bytes. The block time is specified in tick periods,
|
||||||
|
* so the absolute time it represents is dependent on the tick frequency. The
|
||||||
|
* macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds
|
||||||
|
* into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will
|
||||||
|
* cause the task to wait indefinitely (without timing out), provided
|
||||||
|
* INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out
|
||||||
|
* before it can write all xDataLengthBytes into the buffer it will still write
|
||||||
|
* as many bytes as possible. A task does not use any CPU time when it is in
|
||||||
|
* the blocked state.
|
||||||
|
*
|
||||||
|
* @return The number of bytes written to the stream buffer. If a task times
|
||||||
|
* out before it can write all xDataLengthBytes into the buffer it will still
|
||||||
|
* write as many bytes as possible.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* void vAFunction( StreamBufferHandle_t xStreamBuffer )
|
||||||
|
* {
|
||||||
|
* size_t xBytesSent;
|
||||||
|
* uint8_t ucArrayToSend[] = { 0, 1, 2, 3 };
|
||||||
|
* char *pcStringToSend = "String to send";
|
||||||
|
* const TickType_t x100ms = pdMS_TO_TICKS( 100 );
|
||||||
|
*
|
||||||
|
* // Send an array to the stream buffer, blocking for a maximum of 100ms to
|
||||||
|
* // wait for enough space to be available in the stream buffer.
|
||||||
|
* xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != sizeof( ucArrayToSend ) )
|
||||||
|
* {
|
||||||
|
* // The call to xStreamBufferSend() times out before there was enough
|
||||||
|
* // space in the buffer for the data to be written, but it did
|
||||||
|
* // successfully write xBytesSent bytes.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // Send the string to the stream buffer. Return immediately if there is not
|
||||||
|
* // enough space in the buffer.
|
||||||
|
* xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != strlen( pcStringToSend ) )
|
||||||
|
* {
|
||||||
|
* // The entire string could not be added to the stream buffer because
|
||||||
|
* // there was not enough free space in the buffer, but xBytesSent bytes
|
||||||
|
* // were sent. Could try again to send the remaining bytes.
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferSend xStreamBufferSend
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
const void * pvTxData,
|
||||||
|
size_t xDataLengthBytes,
|
||||||
|
TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
* const void *pvTxData,
|
||||||
|
* size_t xDataLengthBytes,
|
||||||
|
* BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Interrupt safe version of the API function that sends a stream of bytes to
|
||||||
|
* the stream buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xStreamBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xStreamBufferReceive()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xStreamBufferSend() to write to a stream buffer from a task. Use
|
||||||
|
* xStreamBufferSendFromISR() to write to a stream buffer from an interrupt
|
||||||
|
* service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer to which a stream is
|
||||||
|
* being sent.
|
||||||
|
*
|
||||||
|
* @param pvTxData A pointer to the data that is to be copied into the stream
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* @param xDataLengthBytes The maximum number of bytes to copy from pvTxData
|
||||||
|
* into the stream buffer.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken It is possible that a stream buffer will
|
||||||
|
* have a task blocked on it waiting for data. Calling
|
||||||
|
* xStreamBufferSendFromISR() can make data available, and so cause a task that
|
||||||
|
* was waiting for data to leave the Blocked state. If calling
|
||||||
|
* xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the
|
||||||
|
* unblocked task has a priority higher than the currently executing task (the
|
||||||
|
* task that was interrupted), then, internally, xStreamBufferSendFromISR()
|
||||||
|
* will set *pxHigherPriorityTaskWoken to pdTRUE. If
|
||||||
|
* xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a
|
||||||
|
* context switch should be performed before the interrupt is exited. This will
|
||||||
|
* ensure that the interrupt returns directly to the highest priority Ready
|
||||||
|
* state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it
|
||||||
|
* is passed into the function. See the example code below for an example.
|
||||||
|
*
|
||||||
|
* @return The number of bytes actually written to the stream buffer, which will
|
||||||
|
* be less than xDataLengthBytes if the stream buffer didn't have enough free
|
||||||
|
* space for all the bytes to be written.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* // A stream buffer that has already been created.
|
||||||
|
* StreamBufferHandle_t xStreamBuffer;
|
||||||
|
*
|
||||||
|
* void vAnInterruptServiceRoutine( void )
|
||||||
|
* {
|
||||||
|
* size_t xBytesSent;
|
||||||
|
* char *pcStringToSend = "String to send";
|
||||||
|
* BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
|
||||||
|
*
|
||||||
|
* // Attempt to send the string to the stream buffer.
|
||||||
|
* xBytesSent = xStreamBufferSendFromISR( xStreamBuffer,
|
||||||
|
* ( void * ) pcStringToSend,
|
||||||
|
* strlen( pcStringToSend ),
|
||||||
|
* &xHigherPriorityTaskWoken );
|
||||||
|
*
|
||||||
|
* if( xBytesSent != strlen( pcStringToSend ) )
|
||||||
|
* {
|
||||||
|
* // There was not enough free space in the stream buffer for the entire
|
||||||
|
* // string to be written, ut xBytesSent bytes were written.
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // If xHigherPriorityTaskWoken was set to pdTRUE inside
|
||||||
|
* // xStreamBufferSendFromISR() then a task that has a priority above the
|
||||||
|
* // priority of the currently executing task was unblocked and a context
|
||||||
|
* // switch should be performed to ensure the ISR returns to the unblocked
|
||||||
|
* // task. In most FreeRTOS ports this is done by simply passing
|
||||||
|
* // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
|
||||||
|
* // variables value, and perform the context switch if necessary. Check the
|
||||||
|
* // documentation for the port in use for port specific instructions.
|
||||||
|
* taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
const void * pvTxData,
|
||||||
|
size_t xDataLengthBytes,
|
||||||
|
BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
* void *pvRxData,
|
||||||
|
* size_t xBufferLengthBytes,
|
||||||
|
* TickType_t xTicksToWait );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Receives bytes from a stream buffer.
|
||||||
|
*
|
||||||
|
* ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer
|
||||||
|
* implementation (so also the message buffer implementation, as message buffers
|
||||||
|
* are built on top of stream buffers) assumes there is only one task or
|
||||||
|
* interrupt that will write to the buffer (the writer), and only one task or
|
||||||
|
* interrupt that will read from the buffer (the reader). It is safe for the
|
||||||
|
* writer and reader to be different tasks or interrupts, but, unlike other
|
||||||
|
* FreeRTOS objects, it is not safe to have multiple different writers or
|
||||||
|
* multiple different readers. If there are to be multiple different writers
|
||||||
|
* then the application writer must place each call to a writing API function
|
||||||
|
* (such as xStreamBufferSend()) inside a critical section and set the send
|
||||||
|
* block time to 0. Likewise, if there are to be multiple different readers
|
||||||
|
* then the application writer must place each call to a reading API function
|
||||||
|
* (such as xStreamBufferReceive()) inside a critical section and set the receive
|
||||||
|
* block time to 0.
|
||||||
|
*
|
||||||
|
* Use xStreamBufferReceive() to read from a stream buffer from a task. Use
|
||||||
|
* xStreamBufferReceiveFromISR() to read from a stream buffer from an
|
||||||
|
* interrupt service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer from which bytes are to
|
||||||
|
* be received.
|
||||||
|
*
|
||||||
|
* @param pvRxData A pointer to the buffer into which the received bytes will be
|
||||||
|
* copied.
|
||||||
|
*
|
||||||
|
* @param xBufferLengthBytes The length of the buffer pointed to by the
|
||||||
|
* pvRxData parameter. This sets the maximum number of bytes to receive in one
|
||||||
|
* call. xStreamBufferReceive will return as many bytes as possible up to a
|
||||||
|
* maximum set by xBufferLengthBytes.
|
||||||
|
*
|
||||||
|
* @param xTicksToWait The maximum amount of time the task should remain in the
|
||||||
|
* Blocked state to wait for data to become available if the stream buffer is
|
||||||
|
* empty. xStreamBufferReceive() will return immediately if xTicksToWait is
|
||||||
|
* zero. The block time is specified in tick periods, so the absolute time it
|
||||||
|
* represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can
|
||||||
|
* be used to convert a time specified in milliseconds into a time specified in
|
||||||
|
* ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait
|
||||||
|
* indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1
|
||||||
|
* in FreeRTOSConfig.h. A task does not use any CPU time when it is in the
|
||||||
|
* Blocked state.
|
||||||
|
*
|
||||||
|
* @return The number of bytes actually read from the stream buffer, which will
|
||||||
|
* be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed
|
||||||
|
* out before xBufferLengthBytes were available.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* void vAFunction( StreamBuffer_t xStreamBuffer )
|
||||||
|
* {
|
||||||
|
* uint8_t ucRxData[ 20 ];
|
||||||
|
* size_t xReceivedBytes;
|
||||||
|
* const TickType_t xBlockTime = pdMS_TO_TICKS( 20 );
|
||||||
|
*
|
||||||
|
* // Receive up to another sizeof( ucRxData ) bytes from the stream buffer.
|
||||||
|
* // Wait in the Blocked state (so not using any CPU processing time) for a
|
||||||
|
* // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be
|
||||||
|
* // available.
|
||||||
|
* xReceivedBytes = xStreamBufferReceive( xStreamBuffer,
|
||||||
|
* ( void * ) ucRxData,
|
||||||
|
* sizeof( ucRxData ),
|
||||||
|
* xBlockTime );
|
||||||
|
*
|
||||||
|
* if( xReceivedBytes > 0 )
|
||||||
|
* {
|
||||||
|
* // A ucRxData contains another xRecievedBytes bytes of data, which can
|
||||||
|
* // be processed here....
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferReceive xStreamBufferReceive
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
void * pvRxData,
|
||||||
|
size_t xBufferLengthBytes,
|
||||||
|
TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
* void *pvRxData,
|
||||||
|
* size_t xBufferLengthBytes,
|
||||||
|
* BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* An interrupt safe version of the API function that receives bytes from a
|
||||||
|
* stream buffer.
|
||||||
|
*
|
||||||
|
* Use xStreamBufferReceive() to read bytes from a stream buffer from a task.
|
||||||
|
* Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an
|
||||||
|
* interrupt service routine (ISR).
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer from which a stream
|
||||||
|
* is being received.
|
||||||
|
*
|
||||||
|
* @param pvRxData A pointer to the buffer into which the received bytes are
|
||||||
|
* copied.
|
||||||
|
*
|
||||||
|
* @param xBufferLengthBytes The length of the buffer pointed to by the
|
||||||
|
* pvRxData parameter. This sets the maximum number of bytes to receive in one
|
||||||
|
* call. xStreamBufferReceive will return as many bytes as possible up to a
|
||||||
|
* maximum set by xBufferLengthBytes.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken It is possible that a stream buffer will
|
||||||
|
* have a task blocked on it waiting for space to become available. Calling
|
||||||
|
* xStreamBufferReceiveFromISR() can make space available, and so cause a task
|
||||||
|
* that is waiting for space to leave the Blocked state. If calling
|
||||||
|
* xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and
|
||||||
|
* the unblocked task has a priority higher than the currently executing task
|
||||||
|
* (the task that was interrupted), then, internally,
|
||||||
|
* xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE.
|
||||||
|
* If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a
|
||||||
|
* context switch should be performed before the interrupt is exited. That will
|
||||||
|
* ensure the interrupt returns directly to the highest priority Ready state
|
||||||
|
* task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is
|
||||||
|
* passed into the function. See the code example below for an example.
|
||||||
|
*
|
||||||
|
* @return The number of bytes read from the stream buffer, if any.
|
||||||
|
*
|
||||||
|
* Example use:
|
||||||
|
* @code{c}
|
||||||
|
* // A stream buffer that has already been created.
|
||||||
|
* StreamBuffer_t xStreamBuffer;
|
||||||
|
*
|
||||||
|
* void vAnInterruptServiceRoutine( void )
|
||||||
|
* {
|
||||||
|
* uint8_t ucRxData[ 20 ];
|
||||||
|
* size_t xReceivedBytes;
|
||||||
|
* BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE.
|
||||||
|
*
|
||||||
|
* // Receive the next stream from the stream buffer.
|
||||||
|
* xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer,
|
||||||
|
* ( void * ) ucRxData,
|
||||||
|
* sizeof( ucRxData ),
|
||||||
|
* &xHigherPriorityTaskWoken );
|
||||||
|
*
|
||||||
|
* if( xReceivedBytes > 0 )
|
||||||
|
* {
|
||||||
|
* // ucRxData contains xReceivedBytes read from the stream buffer.
|
||||||
|
* // Process the stream here....
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* // If xHigherPriorityTaskWoken was set to pdTRUE inside
|
||||||
|
* // xStreamBufferReceiveFromISR() then a task that has a priority above the
|
||||||
|
* // priority of the currently executing task was unblocked and a context
|
||||||
|
* // switch should be performed to ensure the ISR returns to the unblocked
|
||||||
|
* // task. In most FreeRTOS ports this is done by simply passing
|
||||||
|
* // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the
|
||||||
|
* // variables value, and perform the context switch if necessary. Check the
|
||||||
|
* // documentation for the port in use for port specific instructions.
|
||||||
|
* taskYIELD_FROM_ISR( xHigherPriorityTaskWoken );
|
||||||
|
* }
|
||||||
|
* @endcode
|
||||||
|
* \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
void * pvRxData,
|
||||||
|
size_t xBufferLengthBytes,
|
||||||
|
BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Deletes a stream buffer that was previously created using a call to
|
||||||
|
* xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream
|
||||||
|
* buffer was created using dynamic memory (that is, by xStreamBufferCreate()),
|
||||||
|
* then the allocated memory is freed.
|
||||||
|
*
|
||||||
|
* A stream buffer handle must not be used after the stream buffer has been
|
||||||
|
* deleted.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer to be deleted.
|
||||||
|
*
|
||||||
|
* \defgroup vStreamBufferDelete vStreamBufferDelete
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Queries a stream buffer to see if it is full. A stream buffer is full if it
|
||||||
|
* does not have any free space, and therefore cannot accept any more data.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being queried.
|
||||||
|
*
|
||||||
|
* @return If the stream buffer is full then pdTRUE is returned. Otherwise
|
||||||
|
* pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferIsFull xStreamBufferIsFull
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Queries a stream buffer to see if it is empty. A stream buffer is empty if
|
||||||
|
* it does not contain any data.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being queried.
|
||||||
|
*
|
||||||
|
* @return If the stream buffer is empty then pdTRUE is returned. Otherwise
|
||||||
|
* pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Resets a stream buffer to its initial, empty, state. Any data that was in
|
||||||
|
* the stream buffer is discarded. A stream buffer can only be reset if there
|
||||||
|
* are no tasks blocked waiting to either send to or receive from the stream
|
||||||
|
* buffer.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being reset.
|
||||||
|
*
|
||||||
|
* @return If the stream buffer is reset then pdPASS is returned. If there was
|
||||||
|
* a task blocked waiting to send to or read from the stream buffer then the
|
||||||
|
* stream buffer is not reset and pdFAIL is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferReset xStreamBufferReset
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Queries a stream buffer to see how much free space it contains, which is
|
||||||
|
* equal to the amount of data that can be sent to the stream buffer before it
|
||||||
|
* is full.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being queried.
|
||||||
|
*
|
||||||
|
* @return The number of bytes that can be written to the stream buffer before
|
||||||
|
* the stream buffer would be full.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* Queries a stream buffer to see how much data it contains, which is equal to
|
||||||
|
* the number of bytes that can be read from the stream buffer before the stream
|
||||||
|
* buffer would be empty.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being queried.
|
||||||
|
*
|
||||||
|
* @return The number of bytes that can be read from the stream buffer before
|
||||||
|
* the stream buffer would be empty.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* A stream buffer's trigger level is the number of bytes that must be in the
|
||||||
|
* stream buffer before a task that is blocked on the stream buffer to
|
||||||
|
* wait for data is moved out of the blocked state. For example, if a task is
|
||||||
|
* blocked on a read of an empty stream buffer that has a trigger level of 1
|
||||||
|
* then the task will be unblocked when a single byte is written to the buffer
|
||||||
|
* or the task's block time expires. As another example, if a task is blocked
|
||||||
|
* on a read of an empty stream buffer that has a trigger level of 10 then the
|
||||||
|
* task will not be unblocked until the stream buffer contains at least 10 bytes
|
||||||
|
* or the task's block time expires. If a reading task's block time expires
|
||||||
|
* before the trigger level is reached then the task will still receive however
|
||||||
|
* many bytes are actually available. Setting a trigger level of 0 will result
|
||||||
|
* in a trigger level of 1 being used. It is not valid to specify a trigger
|
||||||
|
* level that is greater than the buffer size.
|
||||||
|
*
|
||||||
|
* A trigger level is set when the stream buffer is created, and can be modified
|
||||||
|
* using xStreamBufferSetTriggerLevel().
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer being updated.
|
||||||
|
*
|
||||||
|
* @param xTriggerLevel The new trigger level for the stream buffer.
|
||||||
|
*
|
||||||
|
* @return If xTriggerLevel was less than or equal to the stream buffer's length
|
||||||
|
* then the trigger level will be updated and pdTRUE is returned. Otherwise
|
||||||
|
* pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
size_t xTriggerLevel ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* For advanced users only.
|
||||||
|
*
|
||||||
|
* The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when
|
||||||
|
* data is sent to a message buffer or stream buffer. If there was a task that
|
||||||
|
* was blocked on the message or stream buffer waiting for data to arrive then
|
||||||
|
* the sbSEND_COMPLETED() macro sends a notification to the task to remove it
|
||||||
|
* from the Blocked state. xStreamBufferSendCompletedFromISR() does the same
|
||||||
|
* thing. It is provided to enable application writers to implement their own
|
||||||
|
* version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME.
|
||||||
|
*
|
||||||
|
* See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for
|
||||||
|
* additional information.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer to which data was
|
||||||
|
* written.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be
|
||||||
|
* initialised to pdFALSE before it is passed into
|
||||||
|
* xStreamBufferSendCompletedFromISR(). If calling
|
||||||
|
* xStreamBufferSendCompletedFromISR() removes a task from the Blocked state,
|
||||||
|
* and the task has a priority above the priority of the currently running task,
|
||||||
|
* then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a
|
||||||
|
* context switch should be performed before exiting the ISR.
|
||||||
|
*
|
||||||
|
* @return If a task was removed from the Blocked state then pdTRUE is returned.
|
||||||
|
* Otherwise pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* stream_buffer.h
|
||||||
|
*
|
||||||
|
* @code{c}
|
||||||
|
* BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken );
|
||||||
|
* @endcode
|
||||||
|
*
|
||||||
|
* For advanced users only.
|
||||||
|
*
|
||||||
|
* The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when
|
||||||
|
* data is read out of a message buffer or stream buffer. If there was a task
|
||||||
|
* that was blocked on the message or stream buffer waiting for data to arrive
|
||||||
|
* then the sbRECEIVE_COMPLETED() macro sends a notification to the task to
|
||||||
|
* remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR()
|
||||||
|
* does the same thing. It is provided to enable application writers to
|
||||||
|
* implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT
|
||||||
|
* ANY OTHER TIME.
|
||||||
|
*
|
||||||
|
* See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for
|
||||||
|
* additional information.
|
||||||
|
*
|
||||||
|
* @param xStreamBuffer The handle of the stream buffer from which data was
|
||||||
|
* read.
|
||||||
|
*
|
||||||
|
* @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be
|
||||||
|
* initialised to pdFALSE before it is passed into
|
||||||
|
* xStreamBufferReceiveCompletedFromISR(). If calling
|
||||||
|
* xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state,
|
||||||
|
* and the task has a priority above the priority of the currently running task,
|
||||||
|
* then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a
|
||||||
|
* context switch should be performed before exiting the ISR.
|
||||||
|
*
|
||||||
|
* @return If a task was removed from the Blocked state then pdTRUE is returned.
|
||||||
|
* Otherwise pdFALSE is returned.
|
||||||
|
*
|
||||||
|
* \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR
|
||||||
|
* \ingroup StreamBufferManagement
|
||||||
|
*/
|
||||||
|
BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
BaseType_t * pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/* Functions below here are not part of the public API. */
|
||||||
|
StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes,
|
||||||
|
size_t xTriggerLevelBytes,
|
||||||
|
BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes,
|
||||||
|
size_t xTriggerLevelBytes,
|
||||||
|
BaseType_t xIsMessageBuffer,
|
||||||
|
uint8_t * const pucStreamBufferStorageArea,
|
||||||
|
StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
#if ( configUSE_TRACE_FACILITY == 1 )
|
||||||
|
void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer,
|
||||||
|
UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION;
|
||||||
|
UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* *INDENT-OFF* */
|
||||||
|
#if defined( __cplusplus )
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
/* *INDENT-ON* */
|
||||||
|
|
||||||
|
#endif /* !defined( STREAM_BUFFER_H ) */
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+215
@@ -0,0 +1,215 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
|
||||||
|
* all the API functions to use the MPU wrappers. That should only be done when
|
||||||
|
* task.h is included from an application file. */
|
||||||
|
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
|
||||||
|
|
||||||
|
#include "FreeRTOS.h"
|
||||||
|
#include "list.h"
|
||||||
|
|
||||||
|
/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
|
||||||
|
* because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be
|
||||||
|
* defined for the header files above, but not in this file, in order to
|
||||||
|
* generate the correct privileged Vs unprivileged linkage and placement. */
|
||||||
|
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------
|
||||||
|
* PUBLIC LIST API documented in list.h
|
||||||
|
*----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vListInitialise( List_t * const pxList )
|
||||||
|
{
|
||||||
|
/* The list structure contains a list item which is used to mark the
|
||||||
|
* end of the list. To initialise the list the list end is inserted
|
||||||
|
* as the only list entry. */
|
||||||
|
pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
|
||||||
|
|
||||||
|
/* The list end value is the highest possible value in the list to
|
||||||
|
* ensure it remains at the end of the list. */
|
||||||
|
pxList->xListEnd.xItemValue = portMAX_DELAY;
|
||||||
|
|
||||||
|
/* The list end next and previous pointers point to itself so we know
|
||||||
|
* when the list is empty. */
|
||||||
|
pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
|
||||||
|
pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
|
||||||
|
|
||||||
|
pxList->uxNumberOfItems = ( UBaseType_t ) 0U;
|
||||||
|
|
||||||
|
/* Write known values into the list if
|
||||||
|
* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList );
|
||||||
|
listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList );
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vListInitialiseItem( ListItem_t * const pxItem )
|
||||||
|
{
|
||||||
|
/* Make sure the list item is not recorded as being on a list. */
|
||||||
|
pxItem->pxContainer = NULL;
|
||||||
|
|
||||||
|
/* Write known values into the list item if
|
||||||
|
* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
|
||||||
|
listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
|
||||||
|
listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vListInsertEnd( List_t * const pxList,
|
||||||
|
ListItem_t * const pxNewListItem )
|
||||||
|
{
|
||||||
|
ListItem_t * const pxIndex = pxList->pxIndex;
|
||||||
|
|
||||||
|
/* Only effective when configASSERT() is also defined, these tests may catch
|
||||||
|
* the list data structures being overwritten in memory. They will not catch
|
||||||
|
* data errors caused by incorrect configuration or use of FreeRTOS. */
|
||||||
|
listTEST_LIST_INTEGRITY( pxList );
|
||||||
|
listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
|
||||||
|
|
||||||
|
/* Insert a new list item into pxList, but rather than sort the list,
|
||||||
|
* makes the new list item the last item to be removed by a call to
|
||||||
|
* listGET_OWNER_OF_NEXT_ENTRY(). */
|
||||||
|
pxNewListItem->pxNext = pxIndex;
|
||||||
|
pxNewListItem->pxPrevious = pxIndex->pxPrevious;
|
||||||
|
|
||||||
|
/* Only used during decision coverage testing. */
|
||||||
|
mtCOVERAGE_TEST_DELAY();
|
||||||
|
|
||||||
|
pxIndex->pxPrevious->pxNext = pxNewListItem;
|
||||||
|
pxIndex->pxPrevious = pxNewListItem;
|
||||||
|
|
||||||
|
/* Remember which list the item is in. */
|
||||||
|
pxNewListItem->pxContainer = pxList;
|
||||||
|
|
||||||
|
( pxList->uxNumberOfItems )++;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vListInsert( List_t * const pxList,
|
||||||
|
ListItem_t * const pxNewListItem )
|
||||||
|
{
|
||||||
|
ListItem_t * pxIterator;
|
||||||
|
const TickType_t xValueOfInsertion = pxNewListItem->xItemValue;
|
||||||
|
|
||||||
|
/* Only effective when configASSERT() is also defined, these tests may catch
|
||||||
|
* the list data structures being overwritten in memory. They will not catch
|
||||||
|
* data errors caused by incorrect configuration or use of FreeRTOS. */
|
||||||
|
listTEST_LIST_INTEGRITY( pxList );
|
||||||
|
listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
|
||||||
|
|
||||||
|
/* Insert the new list item into the list, sorted in xItemValue order.
|
||||||
|
*
|
||||||
|
* If the list already contains a list item with the same item value then the
|
||||||
|
* new list item should be placed after it. This ensures that TCBs which are
|
||||||
|
* stored in ready lists (all of which have the same xItemValue value) get a
|
||||||
|
* share of the CPU. However, if the xItemValue is the same as the back marker
|
||||||
|
* the iteration loop below will not end. Therefore the value is checked
|
||||||
|
* first, and the algorithm slightly modified if necessary. */
|
||||||
|
if( xValueOfInsertion == portMAX_DELAY )
|
||||||
|
{
|
||||||
|
pxIterator = pxList->xListEnd.pxPrevious;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* *** NOTE ***********************************************************
|
||||||
|
* If you find your application is crashing here then likely causes are
|
||||||
|
* listed below. In addition see https://www.FreeRTOS.org/FAQHelp.html for
|
||||||
|
* more tips, and ensure configASSERT() is defined!
|
||||||
|
* https://www.FreeRTOS.org/a00110.html#configASSERT
|
||||||
|
*
|
||||||
|
* 1) Stack overflow -
|
||||||
|
* see https://www.FreeRTOS.org/Stacks-and-stack-overflow-checking.html
|
||||||
|
* 2) Incorrect interrupt priority assignment, especially on Cortex-M
|
||||||
|
* parts where numerically high priority values denote low actual
|
||||||
|
* interrupt priorities, which can seem counter intuitive. See
|
||||||
|
* https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html and the definition
|
||||||
|
* of configMAX_SYSCALL_INTERRUPT_PRIORITY on
|
||||||
|
* https://www.FreeRTOS.org/a00110.html
|
||||||
|
* 3) Calling an API function from within a critical section or when
|
||||||
|
* the scheduler is suspended, or calling an API function that does
|
||||||
|
* not end in "FromISR" from an interrupt.
|
||||||
|
* 4) Using a queue or semaphore before it has been initialised or
|
||||||
|
* before the scheduler has been started (are interrupts firing
|
||||||
|
* before vTaskStartScheduler() has been called?).
|
||||||
|
* 5) If the FreeRTOS port supports interrupt nesting then ensure that
|
||||||
|
* the priority of the tick interrupt is at or below
|
||||||
|
* configMAX_SYSCALL_INTERRUPT_PRIORITY.
|
||||||
|
**********************************************************************/
|
||||||
|
|
||||||
|
for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */
|
||||||
|
{
|
||||||
|
/* There is nothing to do here, just iterating to the wanted
|
||||||
|
* insertion position. */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pxNewListItem->pxNext = pxIterator->pxNext;
|
||||||
|
pxNewListItem->pxNext->pxPrevious = pxNewListItem;
|
||||||
|
pxNewListItem->pxPrevious = pxIterator;
|
||||||
|
pxIterator->pxNext = pxNewListItem;
|
||||||
|
|
||||||
|
/* Remember which list the item is in. This allows fast removal of the
|
||||||
|
* item later. */
|
||||||
|
pxNewListItem->pxContainer = pxList;
|
||||||
|
|
||||||
|
( pxList->uxNumberOfItems )++;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove )
|
||||||
|
{
|
||||||
|
/* The list item knows which list it is in. Obtain the list from the list
|
||||||
|
* item. */
|
||||||
|
List_t * const pxList = pxItemToRemove->pxContainer;
|
||||||
|
|
||||||
|
pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious;
|
||||||
|
pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext;
|
||||||
|
|
||||||
|
/* Only used during decision coverage testing. */
|
||||||
|
mtCOVERAGE_TEST_DELAY();
|
||||||
|
|
||||||
|
/* Make sure the index is left pointing to a valid item. */
|
||||||
|
if( pxList->pxIndex == pxItemToRemove )
|
||||||
|
{
|
||||||
|
pxList->pxIndex = pxItemToRemove->pxPrevious;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
pxItemToRemove->pxContainer = NULL;
|
||||||
|
( pxList->uxNumberOfItems )--;
|
||||||
|
|
||||||
|
return pxList->uxNumberOfItems;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
[{000214A0-0000-0000-C000-000000000046}]
|
||||||
|
Prop3=19,11
|
||||||
|
[InternetShortcut]
|
||||||
|
IDList=
|
||||||
|
URL=https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
+150
@@ -0,0 +1,150 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The FreeRTOS kernel's RISC-V port is split between the the code that is
|
||||||
|
* common across all currently supported RISC-V chips (implementations of the
|
||||||
|
* RISC-V ISA), and code that tailors the port to a specific RISC-V chip:
|
||||||
|
*
|
||||||
|
* + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that
|
||||||
|
* is common to all currently supported RISC-V chips. There is only one
|
||||||
|
* portASM.S file because the same file is built for all RISC-V target chips.
|
||||||
|
*
|
||||||
|
* + Header files called freertos_risc_v_chip_specific_extensions.h contain the
|
||||||
|
* code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V
|
||||||
|
* chip. There are multiple freertos_risc_v_chip_specific_extensions.h files
|
||||||
|
* as there are multiple RISC-V chip implementations.
|
||||||
|
*
|
||||||
|
* !!!NOTE!!!
|
||||||
|
* TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h
|
||||||
|
* HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the
|
||||||
|
* compiler's!) include path. For example, if the chip in use includes a core
|
||||||
|
* local interrupter (CLINT) and does not include any chip specific register
|
||||||
|
* extensions then add the path below to the assembler's include path:
|
||||||
|
* FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef __FREERTOS_RISC_V_EXTENSIONS_H__
|
||||||
|
#define __FREERTOS_RISC_V_EXTENSIONS_H__
|
||||||
|
|
||||||
|
#define portasmHAS_SIFIVE_CLINT 0
|
||||||
|
#define portasmHAS_MTIME 0
|
||||||
|
/* if you want to use FPU, please define ARCH_FPU and enable float point and ABI of gcc */
|
||||||
|
#define ARCH_FPU 0
|
||||||
|
|
||||||
|
|
||||||
|
#if ARCH_FPU
|
||||||
|
#define portasmADDITIONAL_CONTEXT_SIZE 32 /* Must be even number on 32-bit cores. */
|
||||||
|
.macro portasmSAVE_ADDITIONAL_REGISTERS
|
||||||
|
addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE* portWORD_SIZE)
|
||||||
|
fsw f0, 1*portWORD_SIZE(sp)
|
||||||
|
fsw f1, 2*portWORD_SIZE(sp)
|
||||||
|
fsw f2, 3*portWORD_SIZE(sp)
|
||||||
|
fsw f3, 4*portWORD_SIZE(sp)
|
||||||
|
fsw f4, 5*portWORD_SIZE(sp)
|
||||||
|
fsw f5, 6*portWORD_SIZE(sp)
|
||||||
|
fsw f6, 7*portWORD_SIZE(sp)
|
||||||
|
fsw f7, 8*portWORD_SIZE(sp)
|
||||||
|
fsw f8, 9*portWORD_SIZE(sp)
|
||||||
|
fsw f9, 10*portWORD_SIZE(sp)
|
||||||
|
fsw f10, 11*portWORD_SIZE(sp)
|
||||||
|
fsw f11, 12*portWORD_SIZE(sp)
|
||||||
|
fsw f12, 13*portWORD_SIZE(sp)
|
||||||
|
fsw f13, 14*portWORD_SIZE(sp)
|
||||||
|
fsw f14, 15*portWORD_SIZE(sp)
|
||||||
|
fsw f15, 16*portWORD_SIZE(sp)
|
||||||
|
fsw f16, 17*portWORD_SIZE(sp)
|
||||||
|
fsw f17, 18*portWORD_SIZE(sp)
|
||||||
|
fsw f18, 19*portWORD_SIZE(sp)
|
||||||
|
fsw f19, 20*portWORD_SIZE(sp)
|
||||||
|
fsw f20, 21*portWORD_SIZE(sp)
|
||||||
|
fsw f21, 22*portWORD_SIZE(sp)
|
||||||
|
fsw f22, 23*portWORD_SIZE(sp)
|
||||||
|
fsw f23, 24*portWORD_SIZE(sp)
|
||||||
|
fsw f24, 25*portWORD_SIZE(sp)
|
||||||
|
fsw f25, 26*portWORD_SIZE(sp)
|
||||||
|
fsw f26, 27*portWORD_SIZE(sp)
|
||||||
|
fsw f27, 28*portWORD_SIZE(sp)
|
||||||
|
fsw f28, 29*portWORD_SIZE(sp)
|
||||||
|
fsw f29, 30*portWORD_SIZE(sp)
|
||||||
|
fsw f30, 31*portWORD_SIZE(sp)
|
||||||
|
fsw f31, 32*portWORD_SIZE(sp)
|
||||||
|
.endm
|
||||||
|
|
||||||
|
.macro portasmRESTORE_ADDITIONAL_REGISTERS
|
||||||
|
flw f0, 1*portWORD_SIZE(sp)
|
||||||
|
flw f1, 2*portWORD_SIZE(sp)
|
||||||
|
flw f2, 3*portWORD_SIZE(sp)
|
||||||
|
flw f3, 4*portWORD_SIZE(sp)
|
||||||
|
flw f4, 5*portWORD_SIZE(sp)
|
||||||
|
flw f5, 6*portWORD_SIZE(sp)
|
||||||
|
flw f6, 7*portWORD_SIZE(sp)
|
||||||
|
flw f7, 8*portWORD_SIZE(sp)
|
||||||
|
flw f8, 9*portWORD_SIZE(sp)
|
||||||
|
flw f9, 10*portWORD_SIZE(sp)
|
||||||
|
flw f10, 11*portWORD_SIZE(sp)
|
||||||
|
flw f11, 12*portWORD_SIZE(sp)
|
||||||
|
flw f12, 13*portWORD_SIZE(sp)
|
||||||
|
flw f13, 14*portWORD_SIZE(sp)
|
||||||
|
flw f14, 15*portWORD_SIZE(sp)
|
||||||
|
flw f15, 16*portWORD_SIZE(sp)
|
||||||
|
flw f16, 17*portWORD_SIZE(sp)
|
||||||
|
flw f17, 18*portWORD_SIZE(sp)
|
||||||
|
flw f18, 19*portWORD_SIZE(sp)
|
||||||
|
flw f19, 20*portWORD_SIZE(sp)
|
||||||
|
flw f20, 21*portWORD_SIZE(sp)
|
||||||
|
flw f21, 22*portWORD_SIZE(sp)
|
||||||
|
flw f22, 23*portWORD_SIZE(sp)
|
||||||
|
flw f23, 24*portWORD_SIZE(sp)
|
||||||
|
flw f24, 25*portWORD_SIZE(sp)
|
||||||
|
flw f25, 26*portWORD_SIZE(sp)
|
||||||
|
flw f26, 27*portWORD_SIZE(sp)
|
||||||
|
flw f27, 28*portWORD_SIZE(sp)
|
||||||
|
flw f28, 29*portWORD_SIZE(sp)
|
||||||
|
flw f29, 30*portWORD_SIZE(sp)
|
||||||
|
flw f30, 31*portWORD_SIZE(sp)
|
||||||
|
flw f31, 32*portWORD_SIZE(sp)
|
||||||
|
addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE* portWORD_SIZE)
|
||||||
|
.endm
|
||||||
|
#else
|
||||||
|
#define portasmADDITIONAL_CONTEXT_SIZE 0 /* Must be even number on 32-bit cores. */
|
||||||
|
|
||||||
|
|
||||||
|
.macro portasmSAVE_ADDITIONAL_REGISTERS
|
||||||
|
/* No additional registers to save, so this macro does nothing. */
|
||||||
|
.endm
|
||||||
|
|
||||||
|
.macro portasmRESTORE_ADDITIONAL_REGISTERS
|
||||||
|
/* No additional registers to restore, so this macro does nothing. */
|
||||||
|
.endm
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/*
|
||||||
|
* The FreeRTOS kernel's RISC-V port is split between the the code that is
|
||||||
|
* common across all currently supported RISC-V chips (implementations of the
|
||||||
|
* RISC-V ISA), and code that tailors the port to a specific RISC-V chip:
|
||||||
|
*
|
||||||
|
* + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that
|
||||||
|
* is common to all currently supported RISC-V chips. There is only one
|
||||||
|
* portASM.S file because the same file is built for all RISC-V target chips.
|
||||||
|
*
|
||||||
|
* + Header files called freertos_risc_v_chip_specific_extensions.h contain the
|
||||||
|
* code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V
|
||||||
|
* chip. There are multiple freertos_risc_v_chip_specific_extensions.h files
|
||||||
|
* as there are multiple RISC-V chip implementations.
|
||||||
|
*
|
||||||
|
* !!!NOTE!!!
|
||||||
|
* TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h
|
||||||
|
* HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the
|
||||||
|
* compiler's!) include path. For example, if the chip in use includes a core
|
||||||
|
* local interrupter (CLINT) and does not include any chip specific register
|
||||||
|
* extensions then add the path below to the assembler's include path:
|
||||||
|
* FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions
|
||||||
|
*
|
||||||
|
*/
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The FreeRTOS kernel's RISC-V port is split between the the code that is
|
||||||
|
* common across all currently supported RISC-V chips (implementations of the
|
||||||
|
* RISC-V ISA), and code that tailors the port to a specific RISC-V chip:
|
||||||
|
*
|
||||||
|
* + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that
|
||||||
|
* is common to all currently supported RISC-V chips. There is only one
|
||||||
|
* portASM.S file because the same file is built for all RISC-V target chips.
|
||||||
|
*
|
||||||
|
* + Header files called freertos_risc_v_chip_specific_extensions.h contain the
|
||||||
|
* code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V
|
||||||
|
* chip. There are multiple freertos_risc_v_chip_specific_extensions.h files
|
||||||
|
* as there are multiple RISC-V chip implementations.
|
||||||
|
*
|
||||||
|
* !!!NOTE!!!
|
||||||
|
* TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h
|
||||||
|
* HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the
|
||||||
|
* compiler's!) include path. For example, if the chip in use includes a core
|
||||||
|
* local interrupter (CLINT) and does not include any chip specific register
|
||||||
|
* extensions then add the path below to the assembler's include path:
|
||||||
|
* FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef __FREERTOS_RISC_V_EXTENSIONS_H__
|
||||||
|
#define __FREERTOS_RISC_V_EXTENSIONS_H__
|
||||||
|
|
||||||
|
#define portasmHAS_SIFIVE_CLINT 0
|
||||||
|
#define portasmHAS_MTIME 0
|
||||||
|
/* if you want to use FPU, please define ARCH_FPU and enable float point and ABI of gcc */
|
||||||
|
#define ARCH_FPU 0
|
||||||
|
|
||||||
|
|
||||||
|
#if ARCH_FPU
|
||||||
|
#define portasmADDITIONAL_CONTEXT_SIZE 32 /* Must be even number on 32-bit cores. */
|
||||||
|
.macro portasmSAVE_ADDITIONAL_REGISTERS
|
||||||
|
addi sp, sp, -(portasmADDITIONAL_CONTEXT_SIZE* portWORD_SIZE)
|
||||||
|
fsw f0, 1*portWORD_SIZE(sp)
|
||||||
|
fsw f1, 2*portWORD_SIZE(sp)
|
||||||
|
fsw f2, 3*portWORD_SIZE(sp)
|
||||||
|
fsw f3, 4*portWORD_SIZE(sp)
|
||||||
|
fsw f4, 5*portWORD_SIZE(sp)
|
||||||
|
fsw f5, 6*portWORD_SIZE(sp)
|
||||||
|
fsw f6, 7*portWORD_SIZE(sp)
|
||||||
|
fsw f7, 8*portWORD_SIZE(sp)
|
||||||
|
fsw f8, 9*portWORD_SIZE(sp)
|
||||||
|
fsw f9, 10*portWORD_SIZE(sp)
|
||||||
|
fsw f10, 11*portWORD_SIZE(sp)
|
||||||
|
fsw f11, 12*portWORD_SIZE(sp)
|
||||||
|
fsw f12, 13*portWORD_SIZE(sp)
|
||||||
|
fsw f13, 14*portWORD_SIZE(sp)
|
||||||
|
fsw f14, 15*portWORD_SIZE(sp)
|
||||||
|
fsw f15, 16*portWORD_SIZE(sp)
|
||||||
|
fsw f16, 17*portWORD_SIZE(sp)
|
||||||
|
fsw f17, 18*portWORD_SIZE(sp)
|
||||||
|
fsw f18, 19*portWORD_SIZE(sp)
|
||||||
|
fsw f19, 20*portWORD_SIZE(sp)
|
||||||
|
fsw f20, 21*portWORD_SIZE(sp)
|
||||||
|
fsw f21, 22*portWORD_SIZE(sp)
|
||||||
|
fsw f22, 23*portWORD_SIZE(sp)
|
||||||
|
fsw f23, 24*portWORD_SIZE(sp)
|
||||||
|
fsw f24, 25*portWORD_SIZE(sp)
|
||||||
|
fsw f25, 26*portWORD_SIZE(sp)
|
||||||
|
fsw f26, 27*portWORD_SIZE(sp)
|
||||||
|
fsw f27, 28*portWORD_SIZE(sp)
|
||||||
|
fsw f28, 29*portWORD_SIZE(sp)
|
||||||
|
fsw f29, 30*portWORD_SIZE(sp)
|
||||||
|
fsw f30, 31*portWORD_SIZE(sp)
|
||||||
|
fsw f31, 32*portWORD_SIZE(sp)
|
||||||
|
.endm
|
||||||
|
|
||||||
|
.macro portasmRESTORE_ADDITIONAL_REGISTERS
|
||||||
|
flw f0, 1*portWORD_SIZE(sp)
|
||||||
|
flw f1, 2*portWORD_SIZE(sp)
|
||||||
|
flw f2, 3*portWORD_SIZE(sp)
|
||||||
|
flw f3, 4*portWORD_SIZE(sp)
|
||||||
|
flw f4, 5*portWORD_SIZE(sp)
|
||||||
|
flw f5, 6*portWORD_SIZE(sp)
|
||||||
|
flw f6, 7*portWORD_SIZE(sp)
|
||||||
|
flw f7, 8*portWORD_SIZE(sp)
|
||||||
|
flw f8, 9*portWORD_SIZE(sp)
|
||||||
|
flw f9, 10*portWORD_SIZE(sp)
|
||||||
|
flw f10, 11*portWORD_SIZE(sp)
|
||||||
|
flw f11, 12*portWORD_SIZE(sp)
|
||||||
|
flw f12, 13*portWORD_SIZE(sp)
|
||||||
|
flw f13, 14*portWORD_SIZE(sp)
|
||||||
|
flw f14, 15*portWORD_SIZE(sp)
|
||||||
|
flw f15, 16*portWORD_SIZE(sp)
|
||||||
|
flw f16, 17*portWORD_SIZE(sp)
|
||||||
|
flw f17, 18*portWORD_SIZE(sp)
|
||||||
|
flw f18, 19*portWORD_SIZE(sp)
|
||||||
|
flw f19, 20*portWORD_SIZE(sp)
|
||||||
|
flw f20, 21*portWORD_SIZE(sp)
|
||||||
|
flw f21, 22*portWORD_SIZE(sp)
|
||||||
|
flw f22, 23*portWORD_SIZE(sp)
|
||||||
|
flw f23, 24*portWORD_SIZE(sp)
|
||||||
|
flw f24, 25*portWORD_SIZE(sp)
|
||||||
|
flw f25, 26*portWORD_SIZE(sp)
|
||||||
|
flw f26, 27*portWORD_SIZE(sp)
|
||||||
|
flw f27, 28*portWORD_SIZE(sp)
|
||||||
|
flw f28, 29*portWORD_SIZE(sp)
|
||||||
|
flw f29, 30*portWORD_SIZE(sp)
|
||||||
|
flw f30, 31*portWORD_SIZE(sp)
|
||||||
|
flw f31, 32*portWORD_SIZE(sp)
|
||||||
|
addi sp, sp, (portasmADDITIONAL_CONTEXT_SIZE* portWORD_SIZE)
|
||||||
|
.endm
|
||||||
|
#else
|
||||||
|
#define portasmADDITIONAL_CONTEXT_SIZE 0 /* Must be even number on 32-bit cores. */
|
||||||
|
|
||||||
|
|
||||||
|
.macro portasmSAVE_ADDITIONAL_REGISTERS
|
||||||
|
/* No additional registers to save, so this macro does nothing. */
|
||||||
|
.endm
|
||||||
|
|
||||||
|
.macro portasmRESTORE_ADDITIONAL_REGISTERS
|
||||||
|
/* No additional registers to restore, so this macro does nothing. */
|
||||||
|
.endm
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* __FREERTOS_RISC_V_EXTENSIONS_H__ */
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------
|
||||||
|
* Implementation of functions defined in portable.h for the RISC-V RV32 port.
|
||||||
|
*----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* Scheduler includes. */
|
||||||
|
#include "FreeRTOS.h"
|
||||||
|
#include "task.h"
|
||||||
|
#include "portmacro.h"
|
||||||
|
|
||||||
|
/* Standard includes. */
|
||||||
|
#include "string.h"
|
||||||
|
|
||||||
|
#ifdef configCLINT_BASE_ADDRESS
|
||||||
|
#warning The configCLINT_BASE_ADDRESS constant has been deprecated. configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS are currently being derived from the (possibly 0) configCLINT_BASE_ADDRESS setting. Please update to define configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS dirctly in place of configCLINT_BASE_ADDRESS. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef configMTIME_BASE_ADDRESS
|
||||||
|
#warning configMTIME_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a memory-mapped mtime register then set configMTIME_BASE_ADDRESS to the mapped address. Otherwise set configMTIME_BASE_ADDRESS to 0. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef configMTIMECMP_BASE_ADDRESS
|
||||||
|
#warning configMTIMECMP_BASE_ADDRESS must be defined in FreeRTOSConfig.h. If the target chip includes a memory-mapped mtimecmp register then set configMTIMECMP_BASE_ADDRESS to the mapped address. Otherwise set configMTIMECMP_BASE_ADDRESS to 0. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Let the user override the pre-loading of the initial LR with the address of
|
||||||
|
prvTaskExitError() in case it messes up unwinding of the stack in the
|
||||||
|
debugger. */
|
||||||
|
#ifdef configTASK_RETURN_ADDRESS
|
||||||
|
#define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
|
||||||
|
#else
|
||||||
|
#define portTASK_RETURN_ADDRESS prvTaskExitError
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* The stack used by interrupt service routines. Set configISR_STACK_SIZE_WORDS
|
||||||
|
to use a statically allocated array as the interrupt stack. Alternative leave
|
||||||
|
configISR_STACK_SIZE_WORDS undefined and update the linker script so that a
|
||||||
|
linker variable names __freertos_irq_stack_top has the same value as the top
|
||||||
|
of the stack used by main. Using the linker script method will repurpose the
|
||||||
|
stack that was used by main before the scheduler was started for use as the
|
||||||
|
interrupt stack after the scheduler has started. */
|
||||||
|
#ifdef configISR_STACK_SIZE_WORDS
|
||||||
|
static __attribute__ ((aligned(16))) StackType_t xISRStack[ configISR_STACK_SIZE_WORDS ] = { 0 };
|
||||||
|
const StackType_t xISRStackTop = ( StackType_t ) &( xISRStack[ configISR_STACK_SIZE_WORDS & ~portBYTE_ALIGNMENT_MASK ] );
|
||||||
|
|
||||||
|
/* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for
|
||||||
|
the task stacks, and so will legitimately appear in many positions within
|
||||||
|
the ISR stack. */
|
||||||
|
#define portISR_STACK_FILL_BYTE 0xee
|
||||||
|
#else
|
||||||
|
/* __freertos_irq_stack_top define by .ld file */
|
||||||
|
extern const uint32_t __freertos_irq_stack_top[];
|
||||||
|
const StackType_t xISRStackTop = ( StackType_t ) __freertos_irq_stack_top;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
|
||||||
|
/*
|
||||||
|
* Setup the timer to generate the tick interrupts. The implementation in this
|
||||||
|
* file is weak to allow application writers to change the timer used to
|
||||||
|
* generate the tick interrupt.
|
||||||
|
*/
|
||||||
|
void vPortSetupTimerInterrupt( void ) __attribute__(( weak ));
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
#if( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 )
|
||||||
|
/* Used to program the machine timer compare register. */
|
||||||
|
uint64_t ullNextTime = 0ULL;
|
||||||
|
const uint64_t *pullNextTime = &ullNextTime;
|
||||||
|
const uint64_t uxTimerIncrementsForOneTick = ( uint64_t) ( ( configCPU_CLOCK_HZ )/( configTICK_RATE_HZ ) ); /* Assumes increment won't go over 32-bits. */
|
||||||
|
uint64_t const ullMachineTimerCompareRegisterBase = configMTIMECMP_BASE_ADDRESS;
|
||||||
|
volatile uint64_t * pullMachineTimerCompareRegister = NULL;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Set configCHECK_FOR_STACK_OVERFLOW to 3 to add ISR stack checking to task
|
||||||
|
stack checking. A problem in the ISR stack will trigger an assert, not call the
|
||||||
|
stack overflow hook function (because the stack overflow hook is specific to a
|
||||||
|
task stack, not the ISR stack). */
|
||||||
|
#if defined( configISR_STACK_SIZE_WORDS ) && ( configCHECK_FOR_STACK_OVERFLOW > 2 )
|
||||||
|
#warning This path not tested, or even compiled yet.
|
||||||
|
|
||||||
|
static const uint8_t ucExpectedStackBytes[] = {
|
||||||
|
portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \
|
||||||
|
portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \
|
||||||
|
portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \
|
||||||
|
portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, \
|
||||||
|
portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE }; \
|
||||||
|
|
||||||
|
#define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) )
|
||||||
|
#else
|
||||||
|
/* Define the function away. */
|
||||||
|
#define portCHECK_ISR_STACK()
|
||||||
|
#endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#if( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 )
|
||||||
|
|
||||||
|
void vPortSetupTimerInterrupt( void )
|
||||||
|
{
|
||||||
|
uint32_t ulCurrentTimeHigh, ulCurrentTimeLow;
|
||||||
|
volatile uint32_t * const pulTimeHigh = ( volatile uint32_t * const ) ( ( configMTIME_BASE_ADDRESS ) + 4UL ); /* 8-byte typer so high 32-bit word is 4 bytes up. */
|
||||||
|
volatile uint32_t * const pulTimeLow = ( volatile uint32_t * const ) ( configMTIME_BASE_ADDRESS );
|
||||||
|
volatile uint32_t ulHartId;
|
||||||
|
|
||||||
|
__asm volatile( "csrr %0, mhartid" : "=r"( ulHartId ) );
|
||||||
|
pullMachineTimerCompareRegister = ( volatile uint64_t * ) ( ullMachineTimerCompareRegisterBase + ( ulHartId * sizeof( uint64_t ) ) );
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
ulCurrentTimeHigh = *pulTimeHigh;
|
||||||
|
ulCurrentTimeLow = *pulTimeLow;
|
||||||
|
} while( ulCurrentTimeHigh != *pulTimeHigh );
|
||||||
|
|
||||||
|
ullNextTime = ( uint64_t ) ulCurrentTimeHigh;
|
||||||
|
ullNextTime <<= 32ULL; /* High 4-byte word is 32-bits up. */
|
||||||
|
ullNextTime |= ( uint64_t ) ulCurrentTimeLow;
|
||||||
|
ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick;
|
||||||
|
*pullMachineTimerCompareRegister = ullNextTime;
|
||||||
|
|
||||||
|
/* Prepare the time to use after the next tick interrupt. */
|
||||||
|
ullNextTime += ( uint64_t ) uxTimerIncrementsForOneTick;
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
/* just for wch's systick,don't have mtime */
|
||||||
|
void vPortSetupTimerInterrupt( void )
|
||||||
|
{
|
||||||
|
/* set software is lowest priority */
|
||||||
|
NVIC_SetPriority(Software_IRQn,0xf0);
|
||||||
|
/* set systick is lowest priority */
|
||||||
|
NVIC_SetPriority(SysTicK_IRQn,0xf0);
|
||||||
|
|
||||||
|
SysTick->CTLR= 0;
|
||||||
|
SysTick->SR = 0;
|
||||||
|
SysTick->CNT = 0;
|
||||||
|
SysTick->CMP = configCPU_CLOCK_HZ/configTICK_RATE_HZ;
|
||||||
|
SysTick->CTLR= 0xf;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIME_BASE_ADDRESS != 0 ) */
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
BaseType_t xPortStartScheduler( void )
|
||||||
|
{
|
||||||
|
extern void xPortStartFirstTask( void );
|
||||||
|
|
||||||
|
#if( configASSERT_DEFINED == 1 )
|
||||||
|
{
|
||||||
|
volatile uint32_t mtvec = 0;
|
||||||
|
|
||||||
|
/* Check the least significant two bits of mtvec are 0b11 - indicating
|
||||||
|
multiply vector mode. */
|
||||||
|
__asm volatile( "csrr %0, mtvec" : "=r"( mtvec ) );
|
||||||
|
configASSERT( ( mtvec & 0x03UL ) == 0x3 );
|
||||||
|
|
||||||
|
/* Check alignment of the interrupt stack - which is the same as the
|
||||||
|
stack that was being used by main() prior to the scheduler being
|
||||||
|
started. */
|
||||||
|
configASSERT( ( xISRStackTop & portBYTE_ALIGNMENT_MASK ) == 0 );
|
||||||
|
|
||||||
|
#ifdef configISR_STACK_SIZE_WORDS
|
||||||
|
{
|
||||||
|
memset( ( void * ) xISRStack, portISR_STACK_FILL_BYTE, sizeof( xISRStack ) );
|
||||||
|
}
|
||||||
|
#endif /* configISR_STACK_SIZE_WORDS */
|
||||||
|
}
|
||||||
|
#endif /* configASSERT_DEFINED */
|
||||||
|
|
||||||
|
/* If there is a CLINT then it is ok to use the default implementation
|
||||||
|
in this file, otherwise vPortSetupTimerInterrupt() must be implemented to
|
||||||
|
configure whichever clock is to be used to generate the tick interrupt. */
|
||||||
|
vPortSetupTimerInterrupt();
|
||||||
|
|
||||||
|
#if( ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 ) )
|
||||||
|
{
|
||||||
|
/* Enable mtime and external interrupts. 1<<7 for timer interrupt, 1<<11
|
||||||
|
for external interrupt. _RB_ What happens here when mtime is not present as
|
||||||
|
with pulpino? */
|
||||||
|
NVIC_EnableIRQ(SysTicK_IRQn);
|
||||||
|
NVIC_EnableIRQ(Software_IRQn);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
{
|
||||||
|
/* Enable external interrupts,global interrupt is enabled at first task start. */
|
||||||
|
NVIC_EnableIRQ(SysTicK_IRQn);
|
||||||
|
NVIC_EnableIRQ(Software_IRQn);
|
||||||
|
}
|
||||||
|
#endif /* ( configMTIME_BASE_ADDRESS != 0 ) && ( configMTIMECMP_BASE_ADDRESS != 0 ) */
|
||||||
|
|
||||||
|
/* Initialise the critical nesting count ready for the first task. */
|
||||||
|
uxCriticalNesting = 0;
|
||||||
|
xPortStartFirstTask();
|
||||||
|
|
||||||
|
/* Should not get here as after calling xPortStartFirstTask() only tasks
|
||||||
|
should be executing. */
|
||||||
|
return pdFAIL;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vPortEndScheduler( void )
|
||||||
|
{
|
||||||
|
/* Not implemented. */
|
||||||
|
for( ;; );
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
void SysTick_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
|
||||||
|
void SysTick_Handler( void )
|
||||||
|
{
|
||||||
|
GET_INT_SP();
|
||||||
|
portDISABLE_INTERRUPTS();
|
||||||
|
SysTick->SR=0;
|
||||||
|
if( xTaskIncrementTick() != pdFALSE )
|
||||||
|
{
|
||||||
|
portYIELD();
|
||||||
|
}
|
||||||
|
portENABLE_INTERRUPTS();
|
||||||
|
FREE_INT_SP();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
void vPortEnterCritical( void )
|
||||||
|
{
|
||||||
|
portDISABLE_INTERRUPTS();
|
||||||
|
uxCriticalNesting++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
void vPortExitCritical( void )
|
||||||
|
{
|
||||||
|
configASSERT( uxCriticalNesting );
|
||||||
|
uxCriticalNesting--;
|
||||||
|
|
||||||
|
if( uxCriticalNesting == 0 )
|
||||||
|
{
|
||||||
|
portENABLE_INTERRUPTS();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
portUBASE_TYPE xPortSetInterruptMask(void)
|
||||||
|
{
|
||||||
|
portUBASE_TYPE uvalue=0;
|
||||||
|
__asm volatile("csrrw %0, mstatus, %1":"=r"(uvalue):"r"(0x7800));
|
||||||
|
return uvalue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
void vPortClearInterruptMask(portUBASE_TYPE uvalue)
|
||||||
|
{
|
||||||
|
__asm volatile("csrw mstatus, %0"::"r"(uvalue));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The FreeRTOS kernel's RISC-V port is split between the the code that is
|
||||||
|
* common across all currently supported RISC-V chips (implementations of the
|
||||||
|
* RISC-V ISA), and code which tailors the port to a specific RISC-V chip:
|
||||||
|
*
|
||||||
|
* + The code that is common to all RISC-V chips is implemented in
|
||||||
|
* FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S. There is only one
|
||||||
|
* portASM.S file because the same file is used no matter which RISC-V chip is
|
||||||
|
* in use.
|
||||||
|
*
|
||||||
|
* + The code that tailors the kernel's RISC-V port to a specific RISC-V
|
||||||
|
* chip is implemented in freertos_risc_v_chip_specific_extensions.h. There
|
||||||
|
* is one freertos_risc_v_chip_specific_extensions.h that can be used with any
|
||||||
|
* RISC-V chip that both includes a standard CLINT and does not add to the
|
||||||
|
* base set of RISC-V registers. There are additional
|
||||||
|
* freertos_risc_v_chip_specific_extensions.h files for RISC-V implementations
|
||||||
|
* that do not include a standard CLINT or do add to the base set of RISC-V
|
||||||
|
* registers.
|
||||||
|
*
|
||||||
|
* CARE MUST BE TAKEN TO INCLDUE THE CORRECT
|
||||||
|
* freertos_risc_v_chip_specific_extensions.h HEADER FILE FOR THE CHIP
|
||||||
|
* IN USE. To include the correct freertos_risc_v_chip_specific_extensions.h
|
||||||
|
* header file ensure the path to the correct header file is in the assembler's
|
||||||
|
* include path.
|
||||||
|
*
|
||||||
|
* This freertos_risc_v_chip_specific_extensions.h is for use on RISC-V chips
|
||||||
|
* that include a standard CLINT and do not add to the base set of RISC-V
|
||||||
|
* registers.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#if __riscv_xlen == 64
|
||||||
|
#define portWORD_SIZE 8
|
||||||
|
#define store_x sd
|
||||||
|
#define load_x ld
|
||||||
|
#elif __riscv_xlen == 32
|
||||||
|
#define store_x sw
|
||||||
|
#define load_x lw
|
||||||
|
#define portWORD_SIZE 4
|
||||||
|
#else
|
||||||
|
#error Assembler did not define __riscv_xlen
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* we define float registers at specific_extensions.h, V30x support hardware floating point unit
|
||||||
|
can be enable by defined ARCH_FPU*/
|
||||||
|
#include "freertos_risc_v_chip_specific_extensions.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* Check the freertos_risc_v_chip_specific_extensions.h and/or command line
|
||||||
|
definitions. */
|
||||||
|
#if defined( portasmHAS_CLINT ) && defined( portasmHAS_MTIME )
|
||||||
|
#error The portasmHAS_CLINT constant has been deprecated. Please replace it with portasmHAS_MTIME. portasmHAS_CLINT and portasmHAS_MTIME cannot both be defined at once. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef portasmHAS_CLINT
|
||||||
|
#warning The portasmHAS_CLINT constant has been deprecated. Please replace it with portasmHAS_MTIME and portasmHAS_SIFIVE_CLINT. For now portasmHAS_MTIME and portasmHAS_SIFIVE_CLINT are derived from portasmHAS_CLINT. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#define portasmHAS_MTIME portasmHAS_CLINT
|
||||||
|
#define portasmHAS_SIFIVE_CLINT portasmHAS_CLINT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portasmHAS_MTIME
|
||||||
|
#error freertos_risc_v_chip_specific_extensions.h must define portasmHAS_MTIME to either 1 (MTIME clock present) or 0 (MTIME clock not present). See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portasmHANDLE_INTERRUPT /* don't need this define */
|
||||||
|
# #error portasmHANDLE_INTERRUPT must be defined to the function to be called to handle external/peripheral interrupts. portasmHANDLE_INTERRUPT can be defined on the assembler command line or in the appropriate freertos_risc_v_chip_specific_extensions.h header file. https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef portasmHAS_SIFIVE_CLINT
|
||||||
|
#define portasmHAS_SIFIVE_CLINT 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Only the standard core registers are stored by default. Any additional
|
||||||
|
registers must be saved by the portasmSAVE_ADDITIONAL_REGISTERS and
|
||||||
|
portasmRESTORE_ADDITIONAL_REGISTERS macros - which can be defined in a chip
|
||||||
|
specific version of freertos_risc_v_chip_specific_extensions.h. See the notes
|
||||||
|
at the top of this file. */
|
||||||
|
#define portCONTEXT_SIZE ( 30 * portWORD_SIZE )
|
||||||
|
|
||||||
|
.global xPortStartFirstTask
|
||||||
|
.global SW_Handler
|
||||||
|
.global pxPortInitialiseStack
|
||||||
|
|
||||||
|
.extern pxCurrentTCB
|
||||||
|
.extern vTaskSwitchContext
|
||||||
|
.extern xISRStackTop
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
.align 8
|
||||||
|
.func
|
||||||
|
SW_Handler:
|
||||||
|
addi sp, sp, -portCONTEXT_SIZE
|
||||||
|
store_x x1, 1 * portWORD_SIZE( sp )
|
||||||
|
store_x x5, 2 * portWORD_SIZE( sp )
|
||||||
|
store_x x6, 3 * portWORD_SIZE( sp )
|
||||||
|
store_x x7, 4 * portWORD_SIZE( sp )
|
||||||
|
store_x x8, 5 * portWORD_SIZE( sp )
|
||||||
|
store_x x9, 6 * portWORD_SIZE( sp )
|
||||||
|
store_x x10, 7 * portWORD_SIZE( sp )
|
||||||
|
store_x x11, 8 * portWORD_SIZE( sp )
|
||||||
|
store_x x12, 9 * portWORD_SIZE( sp )
|
||||||
|
store_x x13, 10 * portWORD_SIZE( sp )
|
||||||
|
store_x x14, 11 * portWORD_SIZE( sp )
|
||||||
|
store_x x15, 12 * portWORD_SIZE( sp )
|
||||||
|
store_x x16, 13 * portWORD_SIZE( sp )
|
||||||
|
store_x x17, 14 * portWORD_SIZE( sp )
|
||||||
|
store_x x18, 15 * portWORD_SIZE( sp )
|
||||||
|
store_x x19, 16 * portWORD_SIZE( sp )
|
||||||
|
store_x x20, 17 * portWORD_SIZE( sp )
|
||||||
|
store_x x21, 18 * portWORD_SIZE( sp )
|
||||||
|
store_x x22, 19 * portWORD_SIZE( sp )
|
||||||
|
store_x x23, 20 * portWORD_SIZE( sp )
|
||||||
|
store_x x24, 21 * portWORD_SIZE( sp )
|
||||||
|
store_x x25, 22 * portWORD_SIZE( sp )
|
||||||
|
store_x x26, 23 * portWORD_SIZE( sp )
|
||||||
|
store_x x27, 24 * portWORD_SIZE( sp )
|
||||||
|
store_x x28, 25 * portWORD_SIZE( sp )
|
||||||
|
store_x x29, 26 * portWORD_SIZE( sp )
|
||||||
|
store_x x30, 27 * portWORD_SIZE( sp )
|
||||||
|
store_x x31, 28 * portWORD_SIZE( sp )
|
||||||
|
|
||||||
|
csrr t0, mstatus /* Required for MPIE bit. */
|
||||||
|
store_x t0, 29 * portWORD_SIZE( sp )
|
||||||
|
|
||||||
|
portasmSAVE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to save any registers unique to the RISC-V implementation. */
|
||||||
|
|
||||||
|
load_x t0, pxCurrentTCB /* Load pxCurrentTCB. */
|
||||||
|
store_x sp, 0( t0 ) /* Write sp to first TCB member. */
|
||||||
|
|
||||||
|
csrr a1, mepc
|
||||||
|
store_x a1, 0( sp ) /* Save updated exception return address. */
|
||||||
|
|
||||||
|
addi a1, x0, 0x20
|
||||||
|
csrs 0x804, a1
|
||||||
|
|
||||||
|
load_x sp, xISRStackTop /* Switch to ISR stack before function call. */
|
||||||
|
jal vTaskSwitchContext
|
||||||
|
|
||||||
|
processed_source:
|
||||||
|
load_x t1, pxCurrentTCB /* Load pxCurrentTCB. */
|
||||||
|
load_x sp, 0( t1 ) /* Read sp from first TCB member. */
|
||||||
|
|
||||||
|
/* Load mret with the address of the next instruction in the task to run next. */
|
||||||
|
load_x t0, 0( sp )
|
||||||
|
csrw mepc, t0
|
||||||
|
|
||||||
|
portasmRESTORE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to restore any registers unique to the RISC-V implementation. */
|
||||||
|
|
||||||
|
/* Load mstatus with the interrupt enable bits used by the task. */
|
||||||
|
load_x t0, 29 * portWORD_SIZE( sp )
|
||||||
|
csrw mstatus, t0 /* Required for MPIE bit. */
|
||||||
|
|
||||||
|
load_x x1, 1 * portWORD_SIZE( sp )
|
||||||
|
load_x x5, 2 * portWORD_SIZE( sp ) /* t0 */
|
||||||
|
load_x x6, 3 * portWORD_SIZE( sp ) /* t1 */
|
||||||
|
load_x x7, 4 * portWORD_SIZE( sp ) /* t2 */
|
||||||
|
load_x x8, 5 * portWORD_SIZE( sp ) /* s0/fp */
|
||||||
|
load_x x9, 6 * portWORD_SIZE( sp ) /* s1 */
|
||||||
|
load_x x10, 7 * portWORD_SIZE( sp ) /* a0 */
|
||||||
|
load_x x11, 8 * portWORD_SIZE( sp ) /* a1 */
|
||||||
|
load_x x12, 9 * portWORD_SIZE( sp ) /* a2 */
|
||||||
|
load_x x13, 10 * portWORD_SIZE( sp ) /* a3 */
|
||||||
|
load_x x14, 11 * portWORD_SIZE( sp ) /* a4 */
|
||||||
|
load_x x15, 12 * portWORD_SIZE( sp ) /* a5 */
|
||||||
|
load_x x16, 13 * portWORD_SIZE( sp ) /* a6 */
|
||||||
|
load_x x17, 14 * portWORD_SIZE( sp ) /* a7 */
|
||||||
|
load_x x18, 15 * portWORD_SIZE( sp ) /* s2 */
|
||||||
|
load_x x19, 16 * portWORD_SIZE( sp ) /* s3 */
|
||||||
|
load_x x20, 17 * portWORD_SIZE( sp ) /* s4 */
|
||||||
|
load_x x21, 18 * portWORD_SIZE( sp ) /* s5 */
|
||||||
|
load_x x22, 19 * portWORD_SIZE( sp ) /* s6 */
|
||||||
|
load_x x23, 20 * portWORD_SIZE( sp ) /* s7 */
|
||||||
|
load_x x24, 21 * portWORD_SIZE( sp ) /* s8 */
|
||||||
|
load_x x25, 22 * portWORD_SIZE( sp ) /* s9 */
|
||||||
|
load_x x26, 23 * portWORD_SIZE( sp ) /* s10 */
|
||||||
|
load_x x27, 24 * portWORD_SIZE( sp ) /* s11 */
|
||||||
|
load_x x28, 25 * portWORD_SIZE( sp ) /* t3 */
|
||||||
|
load_x x29, 26 * portWORD_SIZE( sp ) /* t4 */
|
||||||
|
load_x x30, 27 * portWORD_SIZE( sp ) /* t5 */
|
||||||
|
load_x x31, 28 * portWORD_SIZE( sp ) /* t6 */
|
||||||
|
addi sp, sp, portCONTEXT_SIZE
|
||||||
|
|
||||||
|
mret
|
||||||
|
.endfunc
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
.align 8
|
||||||
|
.func
|
||||||
|
xPortStartFirstTask:
|
||||||
|
|
||||||
|
/* if it is an assembly entry code, the SP offset value is determined by the assembly code,
|
||||||
|
but the C code is determined by the compiler, so we subtract 512 here as a reservation.
|
||||||
|
When entering the interrupt function of C code, the compiler automatically presses the stack
|
||||||
|
into the task stack. We can only change the SP value used by the calling function after switching
|
||||||
|
the interrupt stack.This problem can be solved by modifying the interrupt to the assembly entry,
|
||||||
|
and there is no need to reserve 512 bytes. You only need to switch the interrupt stack at the
|
||||||
|
beginning of the interrupt function */
|
||||||
|
lw t0, xISRStackTop
|
||||||
|
addi t0, t0, -512
|
||||||
|
csrw mscratch,t0
|
||||||
|
|
||||||
|
load_x sp, pxCurrentTCB /* Load pxCurrentTCB. */
|
||||||
|
load_x sp, 0( sp ) /* Read sp from first TCB member. */
|
||||||
|
|
||||||
|
load_x x1, 0( sp ) /* Note for starting the scheduler the exception return address is used as the function return address. */
|
||||||
|
|
||||||
|
portasmRESTORE_ADDITIONAL_REGISTERS /* Defined in freertos_risc_v_chip_specific_extensions.h to restore any registers unique to the RISC-V implementation. */
|
||||||
|
|
||||||
|
load_x x6, 3 * portWORD_SIZE( sp ) /* t1 */
|
||||||
|
load_x x7, 4 * portWORD_SIZE( sp ) /* t2 */
|
||||||
|
load_x x8, 5 * portWORD_SIZE( sp ) /* s0/fp */
|
||||||
|
load_x x9, 6 * portWORD_SIZE( sp ) /* s1 */
|
||||||
|
load_x x10, 7 * portWORD_SIZE( sp ) /* a0 */
|
||||||
|
load_x x11, 8 * portWORD_SIZE( sp ) /* a1 */
|
||||||
|
load_x x12, 9 * portWORD_SIZE( sp ) /* a2 */
|
||||||
|
load_x x13, 10 * portWORD_SIZE( sp ) /* a3 */
|
||||||
|
load_x x14, 11 * portWORD_SIZE( sp ) /* a4 */
|
||||||
|
load_x x15, 12 * portWORD_SIZE( sp ) /* a5 */
|
||||||
|
load_x x16, 13 * portWORD_SIZE( sp ) /* a6 */
|
||||||
|
load_x x17, 14 * portWORD_SIZE( sp ) /* a7 */
|
||||||
|
load_x x18, 15 * portWORD_SIZE( sp ) /* s2 */
|
||||||
|
load_x x19, 16 * portWORD_SIZE( sp ) /* s3 */
|
||||||
|
load_x x20, 17 * portWORD_SIZE( sp ) /* s4 */
|
||||||
|
load_x x21, 18 * portWORD_SIZE( sp ) /* s5 */
|
||||||
|
load_x x22, 19 * portWORD_SIZE( sp ) /* s6 */
|
||||||
|
load_x x23, 20 * portWORD_SIZE( sp ) /* s7 */
|
||||||
|
load_x x24, 21 * portWORD_SIZE( sp ) /* s8 */
|
||||||
|
load_x x25, 22 * portWORD_SIZE( sp ) /* s9 */
|
||||||
|
load_x x26, 23 * portWORD_SIZE( sp ) /* s10 */
|
||||||
|
load_x x27, 24 * portWORD_SIZE( sp ) /* s11 */
|
||||||
|
load_x x28, 25 * portWORD_SIZE( sp ) /* t3 */
|
||||||
|
load_x x29, 26 * portWORD_SIZE( sp ) /* t4 */
|
||||||
|
load_x x30, 27 * portWORD_SIZE( sp ) /* t5 */
|
||||||
|
load_x x31, 28 * portWORD_SIZE( sp ) /* t6 */
|
||||||
|
|
||||||
|
load_x x5, 29 * portWORD_SIZE( sp ) /* Initial mstatus into x5 (t0) */
|
||||||
|
addi x5, x5, 0x08 /* Set MIE bit so the first task starts with interrupts enabled - required as returns with ret not eret. */
|
||||||
|
csrrw x0, mstatus, x5 /* Interrupts enabled from here! */
|
||||||
|
load_x x5, 2 * portWORD_SIZE( sp ) /* Initial x5 (t0) value. */
|
||||||
|
|
||||||
|
addi sp, sp, portCONTEXT_SIZE
|
||||||
|
ret
|
||||||
|
.endfunc
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Unlike other ports pxPortInitialiseStack() is written in assembly code as it
|
||||||
|
* needs access to the portasmADDITIONAL_CONTEXT_SIZE constant. The prototype
|
||||||
|
* for the function is as per the other ports:
|
||||||
|
* StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters );
|
||||||
|
*
|
||||||
|
* As per the standard RISC-V ABI pxTopcOfStack is passed in in a0, pxCode in
|
||||||
|
* a1, and pvParameters in a2. The new top of stack is passed out in a0.
|
||||||
|
*
|
||||||
|
* RISC-V maps registers to ABI names as follows (X1 to X31 integer registers
|
||||||
|
* for the 'I' profile, X1 to X15 for the 'E' profile, currently I assumed).
|
||||||
|
*
|
||||||
|
* Register ABI Name Description Saver
|
||||||
|
* x0 zero Hard-wired zero -
|
||||||
|
* x1 ra Return address Caller
|
||||||
|
* x2 sp Stack pointer Callee
|
||||||
|
* x3 gp Global pointer -
|
||||||
|
* x4 tp Thread pointer -
|
||||||
|
* x5-7 t0-2 Temporaries Caller
|
||||||
|
* x8 s0/fp Saved register/Frame pointer Callee
|
||||||
|
* x9 s1 Saved register Callee
|
||||||
|
* x10-11 a0-1 Function Arguments/return values Caller
|
||||||
|
* x12-17 a2-7 Function arguments Caller
|
||||||
|
* x18-27 s2-11 Saved registers Callee
|
||||||
|
* x28-31 t3-6 Temporaries Caller
|
||||||
|
*
|
||||||
|
* The RISC-V context is saved t FreeRTOS tasks in the following stack frame,
|
||||||
|
* where the global and thread pointers are currently assumed to be constant so
|
||||||
|
* are not saved:
|
||||||
|
*
|
||||||
|
* mstatus
|
||||||
|
* x31
|
||||||
|
* x30
|
||||||
|
* x29
|
||||||
|
* x28
|
||||||
|
* x27
|
||||||
|
* x26
|
||||||
|
* x25
|
||||||
|
* x24
|
||||||
|
* x23
|
||||||
|
* x22
|
||||||
|
* x21
|
||||||
|
* x20
|
||||||
|
* x19
|
||||||
|
* x18
|
||||||
|
* x17
|
||||||
|
* x16
|
||||||
|
* x15
|
||||||
|
* x14
|
||||||
|
* x13
|
||||||
|
* x12
|
||||||
|
* x11
|
||||||
|
* pvParameters
|
||||||
|
* x9
|
||||||
|
* x8
|
||||||
|
* x7
|
||||||
|
* x6
|
||||||
|
* x5
|
||||||
|
* portTASK_RETURN_ADDRESS
|
||||||
|
* [chip specific registers go here]
|
||||||
|
* pxCode
|
||||||
|
*/
|
||||||
|
.align 8
|
||||||
|
.func
|
||||||
|
pxPortInitialiseStack:
|
||||||
|
|
||||||
|
csrr t0, mstatus /* Obtain current mstatus value. */
|
||||||
|
andi t0, t0, ~0x8 /* Ensure interrupts are disabled when the stack is restored within an ISR. Required when a task is created after the schedulre has been started, otherwise interrupts would be disabled anyway. */
|
||||||
|
addi t1, x0, 0x788 /* Generate the value 0x7880, which are the MPIE, MPP and FS bits to set in mstatus. */
|
||||||
|
slli t1, t1, 4
|
||||||
|
or t0, t0, t1 /* Set MPIE and MPP bits in mstatus value. */
|
||||||
|
|
||||||
|
addi a0, a0, -portWORD_SIZE
|
||||||
|
store_x t0, 0(a0) /* mstatus onto the stack. */
|
||||||
|
addi a0, a0, -(22 * portWORD_SIZE) /* Space for registers x11-x31. */
|
||||||
|
store_x a2, 0(a0) /* Task parameters (pvParameters parameter) goes into register X10/a0 on the stack. */
|
||||||
|
addi a0, a0, -(6 * portWORD_SIZE) /* Space for registers x5-x9. */
|
||||||
|
store_x x0, 0(a0) /* Return address onto the stack, could be portTASK_RETURN_ADDRESS */
|
||||||
|
addi t0, x0, portasmADDITIONAL_CONTEXT_SIZE /* The number of chip specific additional registers. */
|
||||||
|
chip_specific_stack_frame: /* First add any chip specific registers to the stack frame being created. */
|
||||||
|
beq t0, x0, 1f /* No more chip specific registers to save. */
|
||||||
|
addi a0, a0, -portWORD_SIZE /* Make space for chip specific register. */
|
||||||
|
store_x x0, 0(a0) /* Give the chip specific register an initial value of zero. */
|
||||||
|
addi t0, t0, -1 /* Decrement the count of chip specific registers remaining. */
|
||||||
|
j chip_specific_stack_frame /* Until no more chip specific registers. */
|
||||||
|
1:
|
||||||
|
addi a0, a0, -portWORD_SIZE
|
||||||
|
store_x a1, 0(a0) /* mret value (pxCode parameter) onto the stack. */
|
||||||
|
ret
|
||||||
|
.endfunc
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef PORTMACRO_H
|
||||||
|
#define PORTMACRO_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------
|
||||||
|
* Port specific definitions.
|
||||||
|
*
|
||||||
|
* The settings in this file configure FreeRTOS correctly for the
|
||||||
|
* given hardware and compiler.
|
||||||
|
*
|
||||||
|
* These settings should not be altered.
|
||||||
|
*-----------------------------------------------------------
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Type definitions. */
|
||||||
|
#if __riscv_xlen == 64
|
||||||
|
#define portSTACK_TYPE uint64_t
|
||||||
|
#define portBASE_TYPE int64_t
|
||||||
|
#define portUBASE_TYPE uint64_t
|
||||||
|
#define portMAX_DELAY ( TickType_t ) 0xffffffffffffffffUL
|
||||||
|
#define portPOINTER_SIZE_TYPE uint64_t
|
||||||
|
#elif __riscv_xlen == 32
|
||||||
|
#define portSTACK_TYPE uint32_t
|
||||||
|
#define portBASE_TYPE int32_t
|
||||||
|
#define portUBASE_TYPE uint32_t
|
||||||
|
#define portMAX_DELAY ( TickType_t ) 0xffffffffUL
|
||||||
|
#else
|
||||||
|
#error Assembler did not define __riscv_xlen
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
typedef portSTACK_TYPE StackType_t;
|
||||||
|
typedef portBASE_TYPE BaseType_t;
|
||||||
|
typedef portUBASE_TYPE UBaseType_t;
|
||||||
|
typedef portUBASE_TYPE TickType_t;
|
||||||
|
|
||||||
|
/* Legacy type definitions. */
|
||||||
|
#define portCHAR char
|
||||||
|
#define portFLOAT float
|
||||||
|
#define portDOUBLE double
|
||||||
|
#define portLONG long
|
||||||
|
#define portSHORT short
|
||||||
|
|
||||||
|
/* 32-bit tick type on a 32-bit architecture, so reads of the tick count do
|
||||||
|
not need to be guarded with a critical section. */
|
||||||
|
#define portTICK_TYPE_IS_ATOMIC 1
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* Architecture specifics. */
|
||||||
|
#define portSTACK_GROWTH ( -1 )
|
||||||
|
#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ )
|
||||||
|
#ifdef __riscv64
|
||||||
|
#error This is the RV32 port that has not yet been adapted for 64.
|
||||||
|
#define portBYTE_ALIGNMENT 16
|
||||||
|
#else
|
||||||
|
#define portBYTE_ALIGNMENT 16
|
||||||
|
#endif
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
|
||||||
|
/* Scheduler utilities. */
|
||||||
|
extern void vTaskSwitchContext( void );
|
||||||
|
#define portYIELD() NVIC_SetPendingIRQ(Software_IRQn)
|
||||||
|
#define portEND_SWITCHING_ISR( xSwitchRequired ) do { if( xSwitchRequired ) portYIELD(); } while( 0 )
|
||||||
|
#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x )
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
|
||||||
|
/* Critical section management. */
|
||||||
|
extern void vPortEnterCritical( void );
|
||||||
|
extern void vPortExitCritical( void );
|
||||||
|
extern portUBASE_TYPE xPortSetInterruptMask(void);
|
||||||
|
extern void vPortClearInterruptMask(portUBASE_TYPE uvalue);
|
||||||
|
|
||||||
|
#define portSET_INTERRUPT_MASK_FROM_ISR() xPortSetInterruptMask()
|
||||||
|
#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) vPortClearInterruptMask(uxSavedStatusValue)
|
||||||
|
#define portDISABLE_INTERRUPTS() __asm volatile( "csrw mstatus,%0" ::"r"(0x7800) )
|
||||||
|
#define portENABLE_INTERRUPTS() __asm volatile( "csrw mstatus,%0" ::"r"(0x7888) )
|
||||||
|
#define portENTER_CRITICAL() vPortEnterCritical()
|
||||||
|
#define portEXIT_CRITICAL() vPortExitCritical()
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* switch interrupt sp, sp is saved at first task switch. */
|
||||||
|
|
||||||
|
#define GET_INT_SP() __asm volatile("csrrw sp,mscratch,sp")
|
||||||
|
#define FREE_INT_SP() __asm volatile("csrrw sp,mscratch,sp")
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
|
||||||
|
|
||||||
|
/* Architecture specific optimisations. */
|
||||||
|
#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
|
||||||
|
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 )
|
||||||
|
|
||||||
|
/* Check the configuration. */
|
||||||
|
#if( configMAX_PRIORITIES > 32 )
|
||||||
|
#error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Store/clear the ready priorities in a bit map. */
|
||||||
|
#define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) )
|
||||||
|
#define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) )
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - __builtin_clz( uxReadyPriorities ) )
|
||||||
|
|
||||||
|
#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
|
||||||
|
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* Task function macros as described on the FreeRTOS.org WEB site. These are
|
||||||
|
not necessary for to use this port. They are defined so the common demo files
|
||||||
|
(which build with all the ports) will build. */
|
||||||
|
#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
|
||||||
|
#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
#define portNOP() __asm volatile ( " nop " )
|
||||||
|
|
||||||
|
#define portINLINE __inline
|
||||||
|
|
||||||
|
#ifndef portFORCE_INLINE
|
||||||
|
#define portFORCE_INLINE inline __attribute__(( always_inline))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" )
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
|
||||||
|
/* configCLINT_BASE_ADDRESS is a legacy definition that was replaced by the
|
||||||
|
configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS definitions. For
|
||||||
|
backward compatibility derive the newer definitions from the old if the old
|
||||||
|
definition is found. */
|
||||||
|
#if defined( configCLINT_BASE_ADDRESS ) && !defined( configMTIME_BASE_ADDRESS ) && ( configCLINT_BASE_ADDRESS == 0 )
|
||||||
|
/* Legacy case where configCLINT_BASE_ADDRESS was defined as 0 to indicate
|
||||||
|
there was no CLINT. Equivalent now is to set the MTIME and MTIMECMP
|
||||||
|
addresses to 0. */
|
||||||
|
#define configMTIME_BASE_ADDRESS ( 0 )
|
||||||
|
#define configMTIMECMP_BASE_ADDRESS ( 0 )
|
||||||
|
#elif defined( configCLINT_BASE_ADDRESS ) && !defined( configMTIME_BASE_ADDRESS )
|
||||||
|
/* Legacy case where configCLINT_BASE_ADDRESS was set to the base address of
|
||||||
|
the CLINT. Equivalent now is to derive the MTIME and MTIMECMP addresses
|
||||||
|
from the CLINT address. */
|
||||||
|
#define configMTIME_BASE_ADDRESS ( ( configCLINT_BASE_ADDRESS ) + 0xBFF8UL )
|
||||||
|
#define configMTIMECMP_BASE_ADDRESS ( ( configCLINT_BASE_ADDRESS ) + 0x4000UL )
|
||||||
|
#elif !defined( configMTIME_BASE_ADDRESS ) || !defined( configMTIMECMP_BASE_ADDRESS )
|
||||||
|
#error configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS must be defined in FreeRTOSConfig.h. Set them to zero if there is no MTIME (machine time) clock. See https://www.FreeRTOS.org/Using-FreeRTOS-on-RISC-V.html
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* PORTMACRO_H */
|
||||||
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/*
|
||||||
|
* The FreeRTOS kernel's RISC-V port is split between the the code that is
|
||||||
|
* common across all currently supported RISC-V chips (implementations of the
|
||||||
|
* RISC-V ISA), and code that tailors the port to a specific RISC-V chip:
|
||||||
|
*
|
||||||
|
* + FreeRTOS\Source\portable\GCC\RISC-V-RV32\portASM.S contains the code that
|
||||||
|
* is common to all currently supported RISC-V chips. There is only one
|
||||||
|
* portASM.S file because the same file is built for all RISC-V target chips.
|
||||||
|
*
|
||||||
|
* + Header files called freertos_risc_v_chip_specific_extensions.h contain the
|
||||||
|
* code that tailors the FreeRTOS kernel's RISC-V port to a specific RISC-V
|
||||||
|
* chip. There are multiple freertos_risc_v_chip_specific_extensions.h files
|
||||||
|
* as there are multiple RISC-V chip implementations.
|
||||||
|
*
|
||||||
|
* !!!NOTE!!!
|
||||||
|
* TAKE CARE TO INCLUDE THE CORRECT freertos_risc_v_chip_specific_extensions.h
|
||||||
|
* HEADER FILE FOR THE CHIP IN USE. This is done using the assembler's (not the
|
||||||
|
* compiler's!) include path. For example, if the chip in use includes a core
|
||||||
|
* local interrupter (CLINT) and does not include any chip specific register
|
||||||
|
* extensions then add the path below to the assembler's include path:
|
||||||
|
* FreeRTOS\Source\portable\GCC\RISC-V-RV32\chip_specific_extensions\RV32I_CLINT_no_extensions
|
||||||
|
*
|
||||||
|
*/
|
||||||
@@ -0,0 +1,504 @@
|
|||||||
|
/*
|
||||||
|
* FreeRTOS Kernel V10.4.6
|
||||||
|
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* https://www.FreeRTOS.org
|
||||||
|
* https://github.com/FreeRTOS
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* A sample implementation of pvPortMalloc() and vPortFree() that combines
|
||||||
|
* (coalescences) adjacent memory blocks as they are freed, and in so doing
|
||||||
|
* limits memory fragmentation.
|
||||||
|
*
|
||||||
|
* See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the
|
||||||
|
* memory management pages of https://www.FreeRTOS.org for more information.
|
||||||
|
*/
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
|
||||||
|
* all the API functions to use the MPU wrappers. That should only be done when
|
||||||
|
* task.h is included from an application file. */
|
||||||
|
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
|
||||||
|
|
||||||
|
#include "FreeRTOS.h"
|
||||||
|
#include "task.h"
|
||||||
|
|
||||||
|
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
|
||||||
|
|
||||||
|
#if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
|
||||||
|
#error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Block sizes must not get too small. */
|
||||||
|
#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
|
||||||
|
|
||||||
|
/* Assumes 8bit bytes! */
|
||||||
|
#define heapBITS_PER_BYTE ( ( size_t ) 8 )
|
||||||
|
|
||||||
|
/* Allocate the memory for the heap. */
|
||||||
|
#if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
|
||||||
|
|
||||||
|
/* The application writer has already defined the array used for the RTOS
|
||||||
|
* heap - probably so it can be placed in a special segment or address. */
|
||||||
|
extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
|
||||||
|
#else
|
||||||
|
PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
|
||||||
|
#endif /* configAPPLICATION_ALLOCATED_HEAP */
|
||||||
|
|
||||||
|
/* Define the linked list structure. This is used to link free blocks in order
|
||||||
|
* of their memory address. */
|
||||||
|
typedef struct A_BLOCK_LINK
|
||||||
|
{
|
||||||
|
struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */
|
||||||
|
size_t xBlockSize; /*<< The size of the free block. */
|
||||||
|
} BlockLink_t;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Inserts a block of memory that is being freed into the correct position in
|
||||||
|
* the list of free memory blocks. The block being freed will be merged with
|
||||||
|
* the block in front it and/or the block behind it if the memory blocks are
|
||||||
|
* adjacent to each other.
|
||||||
|
*/
|
||||||
|
static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Called automatically to setup the required heap structures the first time
|
||||||
|
* pvPortMalloc() is called.
|
||||||
|
*/
|
||||||
|
static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* The size of the structure placed at the beginning of each allocated memory
|
||||||
|
* block must by correctly byte aligned. */
|
||||||
|
static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
|
||||||
|
|
||||||
|
/* Create a couple of list links to mark the start and end of the list. */
|
||||||
|
PRIVILEGED_DATA static BlockLink_t xStart, * pxEnd = NULL;
|
||||||
|
|
||||||
|
/* Keeps track of the number of calls to allocate and free memory as well as the
|
||||||
|
* number of free bytes remaining, but says nothing about fragmentation. */
|
||||||
|
PRIVILEGED_DATA static size_t xFreeBytesRemaining = 0U;
|
||||||
|
PRIVILEGED_DATA static size_t xMinimumEverFreeBytesRemaining = 0U;
|
||||||
|
PRIVILEGED_DATA static size_t xNumberOfSuccessfulAllocations = 0;
|
||||||
|
PRIVILEGED_DATA static size_t xNumberOfSuccessfulFrees = 0;
|
||||||
|
|
||||||
|
/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
|
||||||
|
* member of an BlockLink_t structure is set then the block belongs to the
|
||||||
|
* application. When the bit is free the block is still part of the free heap
|
||||||
|
* space. */
|
||||||
|
PRIVILEGED_DATA static size_t xBlockAllocatedBit = 0;
|
||||||
|
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void * pvPortMalloc( size_t xWantedSize )
|
||||||
|
{
|
||||||
|
BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink;
|
||||||
|
void * pvReturn = NULL;
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
/* If this is the first call to malloc then the heap will require
|
||||||
|
* initialisation to setup the list of free blocks. */
|
||||||
|
if( pxEnd == NULL )
|
||||||
|
{
|
||||||
|
prvHeapInit();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Check the requested block size is not so large that the top bit is
|
||||||
|
* set. The top bit of the block size member of the BlockLink_t structure
|
||||||
|
* is used to determine who owns the block - the application or the
|
||||||
|
* kernel, so it must be free. */
|
||||||
|
if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
|
||||||
|
{
|
||||||
|
/* The wanted size must be increased so it can contain a BlockLink_t
|
||||||
|
* structure in addition to the requested amount of bytes. */
|
||||||
|
if( ( xWantedSize > 0 ) &&
|
||||||
|
( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */
|
||||||
|
{
|
||||||
|
xWantedSize += xHeapStructSize;
|
||||||
|
|
||||||
|
/* Ensure that blocks are always aligned. */
|
||||||
|
if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
|
||||||
|
{
|
||||||
|
/* Byte alignment required. Check for overflow. */
|
||||||
|
if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) )
|
||||||
|
> xWantedSize )
|
||||||
|
{
|
||||||
|
xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
|
||||||
|
configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
xWantedSize = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
xWantedSize = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
|
||||||
|
{
|
||||||
|
/* Traverse the list from the start (lowest address) block until
|
||||||
|
* one of adequate size is found. */
|
||||||
|
pxPreviousBlock = &xStart;
|
||||||
|
pxBlock = xStart.pxNextFreeBlock;
|
||||||
|
|
||||||
|
while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
|
||||||
|
{
|
||||||
|
pxPreviousBlock = pxBlock;
|
||||||
|
pxBlock = pxBlock->pxNextFreeBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* If the end marker was reached then a block of adequate size
|
||||||
|
* was not found. */
|
||||||
|
if( pxBlock != pxEnd )
|
||||||
|
{
|
||||||
|
/* Return the memory space pointed to - jumping over the
|
||||||
|
* BlockLink_t structure at its start. */
|
||||||
|
pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
|
||||||
|
|
||||||
|
/* This block is being returned for use so must be taken out
|
||||||
|
* of the list of free blocks. */
|
||||||
|
pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
|
||||||
|
|
||||||
|
/* If the block is larger than required it can be split into
|
||||||
|
* two. */
|
||||||
|
if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
|
||||||
|
{
|
||||||
|
/* This block is to be split into two. Create a new
|
||||||
|
* block following the number of bytes requested. The void
|
||||||
|
* cast is used to prevent byte alignment warnings from the
|
||||||
|
* compiler. */
|
||||||
|
pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
|
||||||
|
configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
|
||||||
|
|
||||||
|
/* Calculate the sizes of two blocks split from the
|
||||||
|
* single block. */
|
||||||
|
pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
|
||||||
|
pxBlock->xBlockSize = xWantedSize;
|
||||||
|
|
||||||
|
/* Insert the new block into the list of free blocks. */
|
||||||
|
prvInsertBlockIntoFreeList( pxNewBlockLink );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
xFreeBytesRemaining -= pxBlock->xBlockSize;
|
||||||
|
|
||||||
|
if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
|
||||||
|
{
|
||||||
|
xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The block is being returned - it is allocated and owned
|
||||||
|
* by the application and has no "next" block. */
|
||||||
|
pxBlock->xBlockSize |= xBlockAllocatedBit;
|
||||||
|
pxBlock->pxNextFreeBlock = NULL;
|
||||||
|
xNumberOfSuccessfulAllocations++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
traceMALLOC( pvReturn, xWantedSize );
|
||||||
|
}
|
||||||
|
( void ) xTaskResumeAll();
|
||||||
|
|
||||||
|
#if ( configUSE_MALLOC_FAILED_HOOK == 1 )
|
||||||
|
{
|
||||||
|
if( pvReturn == NULL )
|
||||||
|
{
|
||||||
|
extern void vApplicationMallocFailedHook( void );
|
||||||
|
vApplicationMallocFailedHook();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
|
||||||
|
|
||||||
|
configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
|
||||||
|
return pvReturn;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vPortFree( void * pv )
|
||||||
|
{
|
||||||
|
uint8_t * puc = ( uint8_t * ) pv;
|
||||||
|
BlockLink_t * pxLink;
|
||||||
|
|
||||||
|
if( pv != NULL )
|
||||||
|
{
|
||||||
|
/* The memory being freed will have an BlockLink_t structure immediately
|
||||||
|
* before it. */
|
||||||
|
puc -= xHeapStructSize;
|
||||||
|
|
||||||
|
/* This casting is to keep the compiler from issuing warnings. */
|
||||||
|
pxLink = ( void * ) puc;
|
||||||
|
|
||||||
|
/* Check the block is actually allocated. */
|
||||||
|
configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
|
||||||
|
configASSERT( pxLink->pxNextFreeBlock == NULL );
|
||||||
|
|
||||||
|
if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
|
||||||
|
{
|
||||||
|
if( pxLink->pxNextFreeBlock == NULL )
|
||||||
|
{
|
||||||
|
/* The block is being returned to the heap - it is no longer
|
||||||
|
* allocated. */
|
||||||
|
pxLink->xBlockSize &= ~xBlockAllocatedBit;
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
/* Add this block to the list of free blocks. */
|
||||||
|
xFreeBytesRemaining += pxLink->xBlockSize;
|
||||||
|
traceFREE( pv, pxLink->xBlockSize );
|
||||||
|
prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
|
||||||
|
xNumberOfSuccessfulFrees++;
|
||||||
|
}
|
||||||
|
( void ) xTaskResumeAll();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
size_t xPortGetFreeHeapSize( void )
|
||||||
|
{
|
||||||
|
return xFreeBytesRemaining;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
size_t xPortGetMinimumEverFreeHeapSize( void )
|
||||||
|
{
|
||||||
|
return xMinimumEverFreeBytesRemaining;
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vPortInitialiseBlocks( void )
|
||||||
|
{
|
||||||
|
/* This just exists to keep the linker quiet. */
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
|
||||||
|
{
|
||||||
|
BlockLink_t * pxFirstFreeBlock;
|
||||||
|
uint8_t * pucAlignedHeap;
|
||||||
|
size_t uxAddress;
|
||||||
|
size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
|
||||||
|
|
||||||
|
/* Ensure the heap starts on a correctly aligned boundary. */
|
||||||
|
uxAddress = ( size_t ) ucHeap;
|
||||||
|
|
||||||
|
if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
|
||||||
|
{
|
||||||
|
uxAddress += ( portBYTE_ALIGNMENT - 1 );
|
||||||
|
uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
|
||||||
|
xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;
|
||||||
|
}
|
||||||
|
|
||||||
|
pucAlignedHeap = ( uint8_t * ) uxAddress;
|
||||||
|
|
||||||
|
/* xStart is used to hold a pointer to the first item in the list of free
|
||||||
|
* blocks. The void cast is used to prevent compiler warnings. */
|
||||||
|
xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
|
||||||
|
xStart.xBlockSize = ( size_t ) 0;
|
||||||
|
|
||||||
|
/* pxEnd is used to mark the end of the list of free blocks and is inserted
|
||||||
|
* at the end of the heap space. */
|
||||||
|
uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;
|
||||||
|
uxAddress -= xHeapStructSize;
|
||||||
|
uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
|
||||||
|
pxEnd = ( void * ) uxAddress;
|
||||||
|
pxEnd->xBlockSize = 0;
|
||||||
|
pxEnd->pxNextFreeBlock = NULL;
|
||||||
|
|
||||||
|
/* To start with there is a single free block that is sized to take up the
|
||||||
|
* entire heap space, minus the space taken by pxEnd. */
|
||||||
|
pxFirstFreeBlock = ( void * ) pucAlignedHeap;
|
||||||
|
pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;
|
||||||
|
pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
|
||||||
|
|
||||||
|
/* Only one block exists - and it covers the entire usable heap space. */
|
||||||
|
xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
|
||||||
|
xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
|
||||||
|
|
||||||
|
/* Work out the position of the top bit in a size_t variable. */
|
||||||
|
xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
|
||||||
|
{
|
||||||
|
BlockLink_t * pxIterator;
|
||||||
|
uint8_t * puc;
|
||||||
|
|
||||||
|
/* Iterate through the list until a block is found that has a higher address
|
||||||
|
* than the block being inserted. */
|
||||||
|
for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
|
||||||
|
{
|
||||||
|
/* Nothing to do here, just iterate to the right position. */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do the block being inserted, and the block it is being inserted after
|
||||||
|
* make a contiguous block of memory? */
|
||||||
|
puc = ( uint8_t * ) pxIterator;
|
||||||
|
|
||||||
|
if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
|
||||||
|
{
|
||||||
|
pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
|
||||||
|
pxBlockToInsert = pxIterator;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Do the block being inserted, and the block it is being inserted before
|
||||||
|
* make a contiguous block of memory? */
|
||||||
|
puc = ( uint8_t * ) pxBlockToInsert;
|
||||||
|
|
||||||
|
if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
|
||||||
|
{
|
||||||
|
if( pxIterator->pxNextFreeBlock != pxEnd )
|
||||||
|
{
|
||||||
|
/* Form one big block from the two blocks. */
|
||||||
|
pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
|
||||||
|
pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
pxBlockToInsert->pxNextFreeBlock = pxEnd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* If the block being inserted plugged a gab, so was merged with the block
|
||||||
|
* before and the block after, then it's pxNextFreeBlock pointer will have
|
||||||
|
* already been set, and should not be set here as that would make it point
|
||||||
|
* to itself. */
|
||||||
|
if( pxIterator != pxBlockToInsert )
|
||||||
|
{
|
||||||
|
pxIterator->pxNextFreeBlock = pxBlockToInsert;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mtCOVERAGE_TEST_MARKER();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/*-----------------------------------------------------------*/
|
||||||
|
|
||||||
|
void vPortGetHeapStats( HeapStats_t * pxHeapStats )
|
||||||
|
{
|
||||||
|
BlockLink_t * pxBlock;
|
||||||
|
size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
|
||||||
|
|
||||||
|
vTaskSuspendAll();
|
||||||
|
{
|
||||||
|
pxBlock = xStart.pxNextFreeBlock;
|
||||||
|
|
||||||
|
/* pxBlock will be NULL if the heap has not been initialised. The heap
|
||||||
|
* is initialised automatically when the first allocation is made. */
|
||||||
|
if( pxBlock != NULL )
|
||||||
|
{
|
||||||
|
do
|
||||||
|
{
|
||||||
|
/* Increment the number of blocks and record the largest block seen
|
||||||
|
* so far. */
|
||||||
|
xBlocks++;
|
||||||
|
|
||||||
|
if( pxBlock->xBlockSize > xMaxSize )
|
||||||
|
{
|
||||||
|
xMaxSize = pxBlock->xBlockSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
if( pxBlock->xBlockSize < xMinSize )
|
||||||
|
{
|
||||||
|
xMinSize = pxBlock->xBlockSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Move to the next block in the chain until the last block is
|
||||||
|
* reached. */
|
||||||
|
pxBlock = pxBlock->pxNextFreeBlock;
|
||||||
|
} while( pxBlock != pxEnd );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
( void ) xTaskResumeAll();
|
||||||
|
|
||||||
|
pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
|
||||||
|
pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
|
||||||
|
pxHeapStats->xNumberOfFreeBlocks = xBlocks;
|
||||||
|
|
||||||
|
taskENTER_CRITICAL();
|
||||||
|
{
|
||||||
|
pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
|
||||||
|
pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
|
||||||
|
pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
|
||||||
|
pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
|
||||||
|
}
|
||||||
|
taskEXIT_CRITICAL();
|
||||||
|
}
|
||||||
+3075
File diff suppressed because it is too large
Load Diff
+5442
File diff suppressed because it is too large
Load Diff
+1119
File diff suppressed because it is too large
Load Diff
+168
@@ -0,0 +1,168 @@
|
|||||||
|
ENTRY( _start )
|
||||||
|
|
||||||
|
__stack_size = 2048;
|
||||||
|
|
||||||
|
PROVIDE( _stack_size = __stack_size );
|
||||||
|
|
||||||
|
|
||||||
|
MEMORY
|
||||||
|
{
|
||||||
|
FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 128K
|
||||||
|
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 192K
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
SECTIONS
|
||||||
|
{
|
||||||
|
|
||||||
|
.init :
|
||||||
|
{
|
||||||
|
_sinit = .;
|
||||||
|
. = ALIGN(4);
|
||||||
|
KEEP(*(SORT_NONE(.init)))
|
||||||
|
. = ALIGN(4);
|
||||||
|
_einit = .;
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.vector :
|
||||||
|
{
|
||||||
|
*(.vector);
|
||||||
|
. = ALIGN(64);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.text :
|
||||||
|
{
|
||||||
|
. = ALIGN(4);
|
||||||
|
*(.text)
|
||||||
|
*(.text.*)
|
||||||
|
*(.rodata)
|
||||||
|
*(.rodata*)
|
||||||
|
*(.gnu.linkonce.t.*)
|
||||||
|
. = ALIGN(4);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.fini :
|
||||||
|
{
|
||||||
|
KEEP(*(SORT_NONE(.fini)))
|
||||||
|
. = ALIGN(4);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
PROVIDE( _etext = . );
|
||||||
|
PROVIDE( _eitcm = . );
|
||||||
|
|
||||||
|
.preinit_array :
|
||||||
|
{
|
||||||
|
PROVIDE_HIDDEN (__preinit_array_start = .);
|
||||||
|
KEEP (*(.preinit_array))
|
||||||
|
PROVIDE_HIDDEN (__preinit_array_end = .);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.init_array :
|
||||||
|
{
|
||||||
|
PROVIDE_HIDDEN (__init_array_start = .);
|
||||||
|
KEEP (*(SORT_BY_INIT_PRIORITY(.init_array.*) SORT_BY_INIT_PRIORITY(.ctors.*)))
|
||||||
|
KEEP (*(.init_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .ctors))
|
||||||
|
PROVIDE_HIDDEN (__init_array_end = .);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.fini_array :
|
||||||
|
{
|
||||||
|
PROVIDE_HIDDEN (__fini_array_start = .);
|
||||||
|
KEEP (*(SORT_BY_INIT_PRIORITY(.fini_array.*) SORT_BY_INIT_PRIORITY(.dtors.*)))
|
||||||
|
KEEP (*(.fini_array EXCLUDE_FILE (*crtbegin.o *crtbegin?.o *crtend.o *crtend?.o ) .dtors))
|
||||||
|
PROVIDE_HIDDEN (__fini_array_end = .);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.ctors :
|
||||||
|
{
|
||||||
|
/* gcc uses crtbegin.o to find the start of
|
||||||
|
the constructors, so we make sure it is
|
||||||
|
first. Because this is a wildcard, it
|
||||||
|
doesn't matter if the user does not
|
||||||
|
actually link against crtbegin.o; the
|
||||||
|
linker won't look for a file to match a
|
||||||
|
wildcard. The wildcard also means that it
|
||||||
|
doesn't matter which directory crtbegin.o
|
||||||
|
is in. */
|
||||||
|
KEEP (*crtbegin.o(.ctors))
|
||||||
|
KEEP (*crtbegin?.o(.ctors))
|
||||||
|
/* We don't want to include the .ctor section from
|
||||||
|
the crtend.o file until after the sorted ctors.
|
||||||
|
The .ctor section from the crtend file contains the
|
||||||
|
end of ctors marker and it must be last */
|
||||||
|
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors))
|
||||||
|
KEEP (*(SORT(.ctors.*)))
|
||||||
|
KEEP (*(.ctors))
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.dtors :
|
||||||
|
{
|
||||||
|
KEEP (*crtbegin.o(.dtors))
|
||||||
|
KEEP (*crtbegin?.o(.dtors))
|
||||||
|
KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .dtors))
|
||||||
|
KEEP (*(SORT(.dtors.*)))
|
||||||
|
KEEP (*(.dtors))
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.dalign :
|
||||||
|
{
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE(_data_vma = .);
|
||||||
|
} >RAM AT>FLASH
|
||||||
|
|
||||||
|
.dlalign :
|
||||||
|
{
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE(_data_lma = .);
|
||||||
|
} >FLASH AT>FLASH
|
||||||
|
|
||||||
|
.data :
|
||||||
|
{
|
||||||
|
*(.gnu.linkonce.r.*)
|
||||||
|
*(.data .data.*)
|
||||||
|
*(.gnu.linkonce.d.*)
|
||||||
|
. = ALIGN(8);
|
||||||
|
PROVIDE( __global_pointer$ = . + 0x800 );
|
||||||
|
*(.sdata .sdata.*)
|
||||||
|
*(.sdata2.*)
|
||||||
|
*(.gnu.linkonce.s.*)
|
||||||
|
. = ALIGN(8);
|
||||||
|
*(.srodata.cst16)
|
||||||
|
*(.srodata.cst8)
|
||||||
|
*(.srodata.cst4)
|
||||||
|
*(.srodata.cst2)
|
||||||
|
*(.srodata .srodata.*)
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE( _edata = .);
|
||||||
|
} >RAM AT>FLASH
|
||||||
|
|
||||||
|
.bss :
|
||||||
|
{
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE( _sbss = .);
|
||||||
|
*(.sbss*)
|
||||||
|
*(.gnu.linkonce.sb.*)
|
||||||
|
*(.bss*)
|
||||||
|
*(.gnu.linkonce.b.*)
|
||||||
|
*(COMMON*)
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE( _ebss = .);
|
||||||
|
} >RAM AT>FLASH
|
||||||
|
|
||||||
|
PROVIDE( _end = _ebss);
|
||||||
|
PROVIDE( end = . );
|
||||||
|
|
||||||
|
.stack ORIGIN(RAM) + LENGTH(RAM) - __stack_size :
|
||||||
|
{
|
||||||
|
PROVIDE( _heap_end = . );
|
||||||
|
. = ALIGN(4);
|
||||||
|
PROVIDE(_susrstack = . );
|
||||||
|
. = . + __stack_size;
|
||||||
|
PROVIDE( _eusrstack = .);
|
||||||
|
__freertos_irq_stack_top = .;
|
||||||
|
} >RAM
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
================================================================================
|
||||||
|
END USER LICENSE AGREEMENT
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
Copyright (c) QDX. All rights reserved.
|
||||||
|
|
||||||
|
This End User License Agreement ("Agreement") is a legal agreement between you
|
||||||
|
(either an individual or a single entity) and QDX regarding the use of the
|
||||||
|
source code and accompanying documentation (hereinafter referred to as the
|
||||||
|
"Software Source Code").
|
||||||
|
|
||||||
|
By obtaining, using, or modifying the Software Source Code, you agree to be
|
||||||
|
bound by the terms and conditions of this Agreement. If you do not agree, do
|
||||||
|
not use the Software Source Code.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
1. COPYRIGHT AND OWNERSHIP
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
All title, copyrights, and other intellectual property rights in and to the
|
||||||
|
Software Source Code (including but not limited to its design concepts,
|
||||||
|
algorithms, data structures, implementation, and related documentation) are
|
||||||
|
owned by QDX. The Software Source Code is protected by copyright laws and
|
||||||
|
international copyright treaties.
|
||||||
|
QDX reserves the right of final interpretation regarding the terms of this
|
||||||
|
Agreement and the scope of use of the Software Source Code.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
2. GRANT OF LICENSE AND RESTRICTIONS
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
Subject to your compliance with this Agreement, QDX grants you a limited,
|
||||||
|
non-transferable, and non-exclusive right to use and modify the Software Source
|
||||||
|
Code under specific business contexts.
|
||||||
|
|
||||||
|
* Authorized Scope:
|
||||||
|
The open use of this Software Source Code is strictly limited to the specific,
|
||||||
|
formally authorized commercial project and its directly related program or
|
||||||
|
feature development (including debugging, compiling, and system integration).
|
||||||
|
|
||||||
|
* Strict Prohibitions:
|
||||||
|
Without the express written permission of QDX, it is strictly prohibited to
|
||||||
|
use this Software Source Code for any unauthorized commercial projects,
|
||||||
|
products, open-source releases, or to disclose it to any unauthorized third
|
||||||
|
parties. You may not package this code independently for sale, rental, or
|
||||||
|
distribution for competitive commercial purposes.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
3. DISCLAIMER OF WARRANTIES ("AS IS")
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
* No Warranties:
|
||||||
|
The Software Source Code and its associated documentation are provided "AS IS",
|
||||||
|
without warranty of any kind. QDX makes no express or implied warranties,
|
||||||
|
including, but not limited to, the implied warranties of merchantability,
|
||||||
|
fitness for a particular purpose, or non-infringement.
|
||||||
|
|
||||||
|
* No Liability for Variants and Performance:
|
||||||
|
QDX shall not be responsible for the performance, quality, security,
|
||||||
|
commercial consequences, or any software failures resulting from any variants
|
||||||
|
(including new features, refactoring, or ported code snippets) created by you
|
||||||
|
during your use or modification of the Software Source Code.
|
||||||
|
|
||||||
|
* Limitation of Liability:
|
||||||
|
In no event shall QDX be liable for any direct, indirect, incidental, special,
|
||||||
|
or punitive damages (including, but not limited to, loss of profits, business
|
||||||
|
interruption, loss of data, or loss of business information) arising out of
|
||||||
|
the use or inability to use the Software Source Code, even if QDX has been
|
||||||
|
advised of the possibility of such damages.
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
4. LEGAL EFFECT
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
QDX holds the final authority and right of interpretation concerning any
|
||||||
|
disputes arising from or related to this Agreement according to the law. If you
|
||||||
|
fail to comply with any terms of this Agreement, QDX reserves the right to
|
||||||
|
terminate your use authorization immediately and pursue legal responsibility for
|
||||||
|
any economic damages.
|
||||||
|
|
||||||
|
By acquiring and utilizing this Software Source Code, you acknowledge that you
|
||||||
|
have read, understood, and agreed to be strictly bound by all the authorization
|
||||||
|
and disclaimer clauses set forth above.
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_port.c
|
||||||
|
* @brief FreeRTOS + WCHNET implementation of the QDX HAL (qdx_port.h)
|
||||||
|
*
|
||||||
|
* Bridges the WCHNET proprietary TCP/IP stack with the blocking/thread-based
|
||||||
|
* interface expected by qdx_tcp_logic. Uses binary semaphores and ring buffers
|
||||||
|
* to convert WCHNET async callbacks into blocking recv semantics.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "qdx_port.h"
|
||||||
|
#include "wchnet.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
|
||||||
|
#include "FreeRTOS.h"
|
||||||
|
#include "task.h"
|
||||||
|
#include "semphr.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Ring-Buffer for receive data
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
#define RX_RING_SIZE 2920 /* == WCHNET_TCP_MSS * 2 */
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint8_t buf[RX_RING_SIZE];
|
||||||
|
uint16_t head; /* write index */
|
||||||
|
uint16_t tail; /* read index */
|
||||||
|
uint16_t count; /* bytes stored */
|
||||||
|
} RxRingBuf_t;
|
||||||
|
|
||||||
|
static void ring_init(RxRingBuf_t *r)
|
||||||
|
{
|
||||||
|
r->head = 0;
|
||||||
|
r->tail = 0;
|
||||||
|
r->count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t ring_available(const RxRingBuf_t *r)
|
||||||
|
{
|
||||||
|
return r->count;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t ring_write(RxRingBuf_t *r, const uint8_t *data, uint16_t len)
|
||||||
|
{
|
||||||
|
uint16_t free = RX_RING_SIZE - r->count;
|
||||||
|
if (len > free) len = free;
|
||||||
|
|
||||||
|
for (uint16_t i = 0; i < len; i++) {
|
||||||
|
r->buf[r->head] = data[i];
|
||||||
|
r->head = (r->head + 1) % RX_RING_SIZE;
|
||||||
|
}
|
||||||
|
r->count += len;
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t ring_read(RxRingBuf_t *r, uint8_t *data, uint16_t max_len)
|
||||||
|
{
|
||||||
|
uint16_t to_read = (r->count < max_len) ? r->count : max_len;
|
||||||
|
|
||||||
|
for (uint16_t i = 0; i < to_read; i++) {
|
||||||
|
data[i] = r->buf[r->tail];
|
||||||
|
r->tail = (r->tail + 1) % RX_RING_SIZE;
|
||||||
|
}
|
||||||
|
r->count -= to_read;
|
||||||
|
return to_read;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Socket Context — maps WCHNET socket ID to qdx_socket_t
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
#define MAX_SOCKETS 2
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
uint8_t in_use;
|
||||||
|
uint8_t wchnet_sock_id;
|
||||||
|
volatile uint8_t connected;
|
||||||
|
RxRingBuf_t rx_ring;
|
||||||
|
SemaphoreHandle_t rx_sem; /* binary sem: data available */
|
||||||
|
SemaphoreHandle_t connect_sem; /* binary sem: connect complete */
|
||||||
|
} SocketCtx_t;
|
||||||
|
|
||||||
|
static SocketCtx_t g_sock_ctx[MAX_SOCKETS];
|
||||||
|
|
||||||
|
/* WCHNET per-socket receive buffers (required by WCHNET_ModifyRecvBuf) */
|
||||||
|
extern u8 SocketRecvBuf[WCHNET_MAX_SOCKET_NUM][RECE_BUF_LEN];
|
||||||
|
|
||||||
|
/* WCHNET mutex for thread-safe access to WCHNET APIs */
|
||||||
|
static SemaphoreHandle_t g_wchnet_mutex;
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal helpers
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
static SocketCtx_t *alloc_sock_ctx(void)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < MAX_SOCKETS; i++) {
|
||||||
|
if (!g_sock_ctx[i].in_use) {
|
||||||
|
memset(&g_sock_ctx[i], 0, sizeof(SocketCtx_t));
|
||||||
|
g_sock_ctx[i].in_use = 1;
|
||||||
|
ring_init(&g_sock_ctx[i].rx_ring);
|
||||||
|
g_sock_ctx[i].rx_sem = xSemaphoreCreateBinary();
|
||||||
|
g_sock_ctx[i].connect_sem = xSemaphoreCreateBinary();
|
||||||
|
return &g_sock_ctx[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void free_sock_ctx(SocketCtx_t *ctx)
|
||||||
|
{
|
||||||
|
if (!ctx) return;
|
||||||
|
if (ctx->rx_sem) { vSemaphoreDelete(ctx->rx_sem); ctx->rx_sem = NULL; }
|
||||||
|
if (ctx->connect_sem) { vSemaphoreDelete(ctx->connect_sem); ctx->connect_sem = NULL; }
|
||||||
|
ctx->in_use = 0;
|
||||||
|
ctx->connected = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static SocketCtx_t *find_ctx_by_wchnet_id(uint8_t sockid)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < MAX_SOCKETS; i++) {
|
||||||
|
if (g_sock_ctx[i].in_use && g_sock_ctx[i].wchnet_sock_id == sockid)
|
||||||
|
return &g_sock_ctx[i];
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse dotted-decimal IP string to 4-byte array */
|
||||||
|
static int parse_ip(const char *ip_str, uint8_t ip[4])
|
||||||
|
{
|
||||||
|
unsigned int a, b, c, d;
|
||||||
|
int n = 0, idx = 0;
|
||||||
|
const char *p = ip_str;
|
||||||
|
|
||||||
|
a = b = c = d = 0;
|
||||||
|
uint32_t vals[4] = {0};
|
||||||
|
while (*p && idx < 4) {
|
||||||
|
if (*p >= '0' && *p <= '9') {
|
||||||
|
vals[idx] = vals[idx] * 10 + (*p - '0');
|
||||||
|
} else if (*p == '.') {
|
||||||
|
idx++;
|
||||||
|
} else {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
if (idx != 3) return -1;
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
if (vals[i] > 255) return -1;
|
||||||
|
ip[i] = (uint8_t)vals[i];
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Public: called from WCHNET_HandleSockInt (task context)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
void qdx_port_sock_recv_notify(uint8_t sockid)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = find_ctx_by_wchnet_id(sockid);
|
||||||
|
if (!ctx) return;
|
||||||
|
|
||||||
|
/* Read data from WCHNET into ring buffer */
|
||||||
|
uint8_t tmp[512];
|
||||||
|
uint32_t len;
|
||||||
|
uint32_t total = 0;
|
||||||
|
while (1) {
|
||||||
|
len = sizeof(tmp);
|
||||||
|
uint8_t err = WCHNET_SocketRecv(sockid, tmp, &len);
|
||||||
|
if (len == 0) break;
|
||||||
|
ring_write(&ctx->rx_ring, tmp, (uint16_t)len);
|
||||||
|
total += len;
|
||||||
|
if (err != WCHNET_ERR_SUCCESS) break;
|
||||||
|
}
|
||||||
|
DBG_HB("recv_notify sock%d: %u bytes, ring=%u\r\n",
|
||||||
|
sockid, (unsigned)total, (unsigned)ring_available(&ctx->rx_ring));
|
||||||
|
/* Wake blocking recv thread */
|
||||||
|
xSemaphoreGive(ctx->rx_sem);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_sock_connect_notify(uint8_t sockid)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = find_ctx_by_wchnet_id(sockid);
|
||||||
|
if (!ctx) return;
|
||||||
|
ctx->connected = 1;
|
||||||
|
DBG_NET("connect_notify sock%d\r\n", sockid);
|
||||||
|
xSemaphoreGive(ctx->connect_sem);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_sock_disconnect_notify(uint8_t sockid)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = find_ctx_by_wchnet_id(sockid);
|
||||||
|
if (!ctx) return;
|
||||||
|
ctx->connected = 0;
|
||||||
|
DBG_NET("disconnect_notify sock%d\r\n", sockid);
|
||||||
|
/* Wake recv thread so it can detect disconnect */
|
||||||
|
xSemaphoreGive(ctx->rx_sem);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Init — call once before scheduler starts
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
void qdx_port_init(void)
|
||||||
|
{
|
||||||
|
memset(g_sock_ctx, 0, sizeof(g_sock_ctx));
|
||||||
|
g_wchnet_mutex = xSemaphoreCreateMutex();
|
||||||
|
DBG_INIT("qdx_port init done, mutex=%p\r\n", g_wchnet_mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Time & Delay
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
uint32_t qdx_port_get_tick_ms(void)
|
||||||
|
{
|
||||||
|
return xTaskGetTickCount() * portTICK_PERIOD_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_delay_ms(uint32_t ms)
|
||||||
|
{
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Mutex
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
qdx_mutex_t qdx_port_mutex_create(void)
|
||||||
|
{
|
||||||
|
return (qdx_mutex_t)xSemaphoreCreateMutex();
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_lock(qdx_mutex_t mutex)
|
||||||
|
{
|
||||||
|
if (mutex)
|
||||||
|
xSemaphoreTake((SemaphoreHandle_t)mutex, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_unlock(qdx_mutex_t mutex)
|
||||||
|
{
|
||||||
|
if (mutex)
|
||||||
|
xSemaphoreGive((SemaphoreHandle_t)mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_delete(qdx_mutex_t mutex)
|
||||||
|
{
|
||||||
|
if (mutex)
|
||||||
|
vSemaphoreDelete((SemaphoreHandle_t)mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Thread
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
int8_t qdx_port_thread_create(const char *name, qdx_thread_entry_t entry,
|
||||||
|
void *arg, uint32_t stack_size, uint8_t priority)
|
||||||
|
{
|
||||||
|
/* stack_size from caller is in bytes; xTaskCreate expects words */
|
||||||
|
uint32_t stack_words = stack_size / sizeof(StackType_t);
|
||||||
|
if (stack_words < configMINIMAL_STACK_SIZE)
|
||||||
|
stack_words = configMINIMAL_STACK_SIZE;
|
||||||
|
|
||||||
|
BaseType_t ret = xTaskCreate((TaskFunction_t)entry, name,
|
||||||
|
(uint16_t)stack_words, arg,
|
||||||
|
(UBaseType_t)priority, NULL);
|
||||||
|
DBG_INIT("thread_create \"%s\" stack=%d pri=%d -> %s\r\n",
|
||||||
|
name, (int)stack_words, (int)priority, (ret == pdPASS) ? "OK" : "FAIL");
|
||||||
|
return (ret == pdPASS) ? 0 : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* TCP Socket — connect / send / recv / close
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
qdx_socket_t qdx_port_tcp_connect(const char *ip, uint16_t port)
|
||||||
|
{
|
||||||
|
uint8_t dest_ip[4];
|
||||||
|
if (parse_ip(ip, dest_ip) != 0) {
|
||||||
|
DBG_ERR("bad IP \"%s\"\r\n", ip);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
DBG_NET("connecting to %s:%d\r\n", ip, port);
|
||||||
|
|
||||||
|
SocketCtx_t *ctx = alloc_sock_ctx();
|
||||||
|
if (!ctx) {
|
||||||
|
DBG_ERR("no free SocketCtx\r\n");
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
SOCK_INF sock_inf;
|
||||||
|
memset(&sock_inf, 0, sizeof(sock_inf));
|
||||||
|
sock_inf.ProtoType = PROTO_TYPE_TCP;
|
||||||
|
sock_inf.SourPort = 0; /* let WCHNET assign ephemeral port */
|
||||||
|
sock_inf.DesPort = port;
|
||||||
|
memcpy(sock_inf.IPAddr, dest_ip, 4);
|
||||||
|
|
||||||
|
DBG_NET("SOCK_INF: proto=%d dst=%d.%d.%d.%d:%d\r\n",
|
||||||
|
sock_inf.ProtoType,
|
||||||
|
sock_inf.IPAddr[0], sock_inf.IPAddr[1],
|
||||||
|
sock_inf.IPAddr[2], sock_inf.IPAddr[3],
|
||||||
|
sock_inf.DesPort);
|
||||||
|
|
||||||
|
uint8_t wchnet_id = 0;
|
||||||
|
|
||||||
|
xSemaphoreTake(g_wchnet_mutex, portMAX_DELAY);
|
||||||
|
uint8_t err = WCHNET_SocketCreat(&wchnet_id, &sock_inf);
|
||||||
|
xSemaphoreGive(g_wchnet_mutex);
|
||||||
|
|
||||||
|
if (err != WCHNET_ERR_SUCCESS) {
|
||||||
|
DBG_ERR("SocketCreat fail %02X\r\n", err);
|
||||||
|
free_sock_ctx(ctx);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
DBG_NET("SocketCreat OK, wchnet_id=%d\r\n", wchnet_id);
|
||||||
|
|
||||||
|
ctx->wchnet_sock_id = wchnet_id;
|
||||||
|
|
||||||
|
/* Assign WCHNET receive buffer */
|
||||||
|
WCHNET_ModifyRecvBuf(wchnet_id,
|
||||||
|
(uint32_t)SocketRecvBuf[wchnet_id], RECE_BUF_LEN);
|
||||||
|
|
||||||
|
xSemaphoreTake(g_wchnet_mutex, portMAX_DELAY);
|
||||||
|
err = WCHNET_SocketConnect(wchnet_id);
|
||||||
|
xSemaphoreGive(g_wchnet_mutex);
|
||||||
|
|
||||||
|
if (err != WCHNET_ERR_SUCCESS) {
|
||||||
|
DBG_ERR("SocketConnect fail %02X\r\n", err);
|
||||||
|
WCHNET_SocketClose(wchnet_id, TCP_CLOSE_RST);
|
||||||
|
free_sock_ctx(ctx);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
DBG_NET("SocketConnect OK (err=0x%02X), waiting connect_sem (5s)...\r\n", err);
|
||||||
|
|
||||||
|
/* Block until SINT_STAT_CONNECT or 5s timeout */
|
||||||
|
uint32_t t0 = xTaskGetTickCount();
|
||||||
|
BaseType_t sem_ret = xSemaphoreTake(ctx->connect_sem, pdMS_TO_TICKS(5000));
|
||||||
|
uint32_t elapsed = (xTaskGetTickCount() - t0) * portTICK_PERIOD_MS;
|
||||||
|
|
||||||
|
if (sem_ret != pdTRUE) {
|
||||||
|
DBG_ERR("connect_sem TIMEOUT after %d ms -> %d.%d.%d.%d:%d\r\n",
|
||||||
|
(int)elapsed, dest_ip[0], dest_ip[1], dest_ip[2], dest_ip[3], port);
|
||||||
|
DBG_ERR(" ctx->connected=%d wchnet_id=%d\r\n", ctx->connected, wchnet_id);
|
||||||
|
WCHNET_SocketClose(wchnet_id, TCP_CLOSE_RST);
|
||||||
|
free_sock_ctx(ctx);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
DBG_NET("connect_sem got after %d ms, connected=%d\r\n", (int)elapsed, ctx->connected);
|
||||||
|
|
||||||
|
if (!ctx->connected) {
|
||||||
|
WCHNET_SocketClose(wchnet_id, TCP_CLOSE_RST);
|
||||||
|
free_sock_ctx(ctx);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if KEEPALIVE_ENABLE
|
||||||
|
WCHNET_SocketSetKeepLive(wchnet_id, ENABLE);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
DBG_NET("connected sock %d -> %d.%d.%d.%d:%d\r\n",
|
||||||
|
wchnet_id, dest_ip[0], dest_ip[1], dest_ip[2], dest_ip[3], port);
|
||||||
|
return (qdx_socket_t)ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t qdx_port_tcp_send(qdx_socket_t sock, const uint8_t *data, uint32_t len)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = (SocketCtx_t *)sock;
|
||||||
|
if (!ctx || !ctx->connected)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
uint32_t total_sent = 0;
|
||||||
|
const uint8_t *ptr = data;
|
||||||
|
uint32_t remaining = len;
|
||||||
|
uint8_t retries = 0;
|
||||||
|
|
||||||
|
while (remaining > 0) {
|
||||||
|
uint32_t send_len = remaining;
|
||||||
|
|
||||||
|
xSemaphoreTake(g_wchnet_mutex, portMAX_DELAY);
|
||||||
|
uint8_t err = WCHNET_SocketSend(ctx->wchnet_sock_id, (uint8_t *)ptr, &send_len);
|
||||||
|
xSemaphoreGive(g_wchnet_mutex);
|
||||||
|
|
||||||
|
if (err != WCHNET_ERR_SUCCESS && send_len == 0) {
|
||||||
|
/* WCHNET send buffer full — yield so wchnet task can flush */
|
||||||
|
if (++retries > 50) {
|
||||||
|
DBG_ERR("send fail after retries, err=0x%02X\r\n", err);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
retries = 0;
|
||||||
|
ptr += send_len;
|
||||||
|
remaining -= send_len;
|
||||||
|
total_sent += send_len;
|
||||||
|
|
||||||
|
if (remaining > 0) {
|
||||||
|
/* Partial send — yield to let wchnet task drain the buffer */
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(2));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int32_t)total_sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t qdx_port_tcp_recv(qdx_socket_t sock, uint8_t *buf, uint32_t max_len)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = (SocketCtx_t *)sock;
|
||||||
|
if (!ctx)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* Check ring buffer first */
|
||||||
|
uint16_t got = ring_read(&ctx->rx_ring, buf, (uint16_t)max_len);
|
||||||
|
if (got > 0)
|
||||||
|
return (int32_t)got;
|
||||||
|
|
||||||
|
/* No data — check if disconnected */
|
||||||
|
if (!ctx->connected)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* Block on semaphore up to 100ms */
|
||||||
|
xSemaphoreTake(ctx->rx_sem, pdMS_TO_TICKS(100));
|
||||||
|
|
||||||
|
/* Try again after wake */
|
||||||
|
got = ring_read(&ctx->rx_ring, buf, (uint16_t)max_len);
|
||||||
|
if (got > 0)
|
||||||
|
return (int32_t)got;
|
||||||
|
|
||||||
|
/* Still no data — disconnected? */
|
||||||
|
if (!ctx->connected)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
return 0; /* timeout, no data */
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_tcp_close(qdx_socket_t sock)
|
||||||
|
{
|
||||||
|
SocketCtx_t *ctx = (SocketCtx_t *)sock;
|
||||||
|
if (!ctx) return;
|
||||||
|
|
||||||
|
if (ctx->in_use) {
|
||||||
|
xSemaphoreTake(g_wchnet_mutex, portMAX_DELAY);
|
||||||
|
/* Use TCP_CLOSE_RST to immediately release the WCHNET socket slot.
|
||||||
|
* TCP_CLOSE_NORMAL (0) causes TIME_WAIT which holds the slot for
|
||||||
|
* an extended period, preventing reconnection with only 2 sockets. */
|
||||||
|
WCHNET_SocketClose(ctx->wchnet_sock_id, TCP_CLOSE_RST);
|
||||||
|
xSemaphoreGive(g_wchnet_mutex);
|
||||||
|
}
|
||||||
|
ring_init(&ctx->rx_ring);
|
||||||
|
free_sock_ctx(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* WCHNET global lock — exposed for task_wchnet_entry in main.c
|
||||||
|
* All WCHNET API calls must be serialized through this mutex.
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
void qdx_port_net_lock(void)
|
||||||
|
{
|
||||||
|
if (g_wchnet_mutex)
|
||||||
|
xSemaphoreTake(g_wchnet_mutex, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_net_unlock(void)
|
||||||
|
{
|
||||||
|
if (g_wchnet_mutex)
|
||||||
|
xSemaphoreGive(g_wchnet_mutex);
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_port.h
|
||||||
|
* @brief Hardware/OS Abstraction Layer (HAL) for QDX Network Stack
|
||||||
|
*
|
||||||
|
* Provides platform-independent interfaces for network socket operations,
|
||||||
|
* timing, mutexes, and threading. Users must implement these functions
|
||||||
|
* based on their specific MCU OS (e.g., FreeRTOS, LwIP, RT-Thread).
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef QDX_PORT_H
|
||||||
|
#define QDX_PORT_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Multi-Level Debug Print System
|
||||||
|
*
|
||||||
|
* Verbosity levels (set DBG_LEVEL to control output volume):
|
||||||
|
* 0 = NONE — all debug prints disabled
|
||||||
|
* 1 = ERR — errors only
|
||||||
|
* 2 = BRIEF — + server config / network events (recommended)
|
||||||
|
* 3 = NORMAL — + trigger / data / init events (default)
|
||||||
|
* 4 = VERBOSE — + heartbeat / detailed internals
|
||||||
|
*
|
||||||
|
* Category macros — each prints when DBG_LEVEL >= its threshold:
|
||||||
|
* DBG_ERR (>=1) Errors, HardFault, CRC fail, bad frames
|
||||||
|
* DBG_CFG (>=2) Server-received config (Config2D/1D/Common, DevID, ACK, DetResult)
|
||||||
|
* DBG_NET (>=2) TCP connect/disconnect, PHY change, socket events
|
||||||
|
* DBG_TRIG (>=3) Trigger events (ext/int), burst start/complete
|
||||||
|
* DBG_DATA (>=3) Frame send results (2D/1D/TEMP_REQ)
|
||||||
|
* DBG_INIT (>=3) Boot-time init messages (sensor, DVP, WCHNET)
|
||||||
|
* DBG_HB (>=4) Heartbeat prints (high-frequency, debug only)
|
||||||
|
* ============================================================ */
|
||||||
|
#define DBG_LEVEL_NONE 0
|
||||||
|
#define DBG_LEVEL_ERR 1
|
||||||
|
#define DBG_LEVEL_BRIEF 2
|
||||||
|
#define DBG_LEVEL_NORMAL 3
|
||||||
|
#define DBG_LEVEL_VERBOSE 4
|
||||||
|
|
||||||
|
/* >>> Change this single value to control output volume <<< */
|
||||||
|
#define DBG_LEVEL DBG_LEVEL_NORMAL
|
||||||
|
|
||||||
|
#define DBG_PRINT_(threshold, tag, fmt, ...) \
|
||||||
|
do { if (DBG_LEVEL >= (threshold)) printf(tag fmt, ##__VA_ARGS__); } while(0)
|
||||||
|
|
||||||
|
#define DBG_ERR(fmt, ...) DBG_PRINT_(DBG_LEVEL_ERR, "[ERR] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_CFG(fmt, ...) DBG_PRINT_(DBG_LEVEL_BRIEF, "[CFG] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_NET(fmt, ...) DBG_PRINT_(DBG_LEVEL_BRIEF, "[NET] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_TRIG(fmt, ...) DBG_PRINT_(DBG_LEVEL_NORMAL, "[TRIG] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_DATA(fmt, ...) DBG_PRINT_(DBG_LEVEL_NORMAL, "[DATA] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_INIT(fmt, ...) DBG_PRINT_(DBG_LEVEL_NORMAL, "[INIT] ", fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_HB(fmt, ...) DBG_PRINT_(DBG_LEVEL_VERBOSE, "[HB] ", fmt, ##__VA_ARGS__)
|
||||||
|
|
||||||
|
/* Legacy compatibility aliases — avoid using in new code */
|
||||||
|
#define DBG_PORT(fmt, ...) DBG_INIT(fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_LOGIC(fmt, ...) DBG_CFG(fmt, ##__VA_ARGS__)
|
||||||
|
#define DBG_APP(fmt, ...) DBG_DATA(fmt, ##__VA_ARGS__)
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Time & Delay
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get absolute system uptime/ticks in milliseconds.
|
||||||
|
* @return Milliseconds since system boot.
|
||||||
|
*/
|
||||||
|
uint32_t qdx_port_get_tick_ms(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Blocking delay in milliseconds.
|
||||||
|
* @param ms Delay time
|
||||||
|
*/
|
||||||
|
void qdx_port_delay_ms(uint32_t ms);
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Network (TCP Socket)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* Opaque handle for sockets dependent on underlying IP stack */
|
||||||
|
typedef void *qdx_socket_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Create and connect a TCP socket to a remote host.
|
||||||
|
* @param ip Str IP address of the server (e.g., "192.168.1.10")
|
||||||
|
* @param port Remote port
|
||||||
|
* @return Valid socket handle on success, or NULL on failure.
|
||||||
|
*/
|
||||||
|
qdx_socket_t qdx_port_tcp_connect(const char *ip, uint16_t port);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Close a TCP socket.
|
||||||
|
* @param sock Socket handle
|
||||||
|
*/
|
||||||
|
void qdx_port_tcp_close(qdx_socket_t sock);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Send data over TCP socket.
|
||||||
|
* @param sock Socket handle
|
||||||
|
* @param data Data buffer to send
|
||||||
|
* @param len Length of data in bytes
|
||||||
|
* @return Number of bytes sent, or < 0 for error.
|
||||||
|
*/
|
||||||
|
int32_t qdx_port_tcp_send(qdx_socket_t sock, const uint8_t *data, uint32_t len);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Receive data from TCP socket (Non-blocking or specific timeout).
|
||||||
|
* @param sock Socket handle
|
||||||
|
* @param buf Buffer to store received data
|
||||||
|
* @param max_len Maximum buffer size
|
||||||
|
* @return Number of bytes received. Return 0 if timeout/empty. Return < 0 for
|
||||||
|
* connection closed/error.
|
||||||
|
*/
|
||||||
|
int32_t qdx_port_tcp_recv(qdx_socket_t sock, uint8_t *buf, uint32_t max_len);
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Mutex & Threading
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* Opaque handle for mutex */
|
||||||
|
typedef void *qdx_mutex_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Create a recursive or standard mutex.
|
||||||
|
* @return Mutex handle, or NULL on failure.
|
||||||
|
*/
|
||||||
|
qdx_mutex_t qdx_port_mutex_create(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Lock a mutex.
|
||||||
|
* @param mutex Mutex handle
|
||||||
|
*/
|
||||||
|
void qdx_port_mutex_lock(qdx_mutex_t mutex);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Unlock a mutex.
|
||||||
|
* @param mutex Mutex handle
|
||||||
|
*/
|
||||||
|
void qdx_port_mutex_unlock(qdx_mutex_t mutex);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Delete a mutex.
|
||||||
|
* @param mutex Mutex handle
|
||||||
|
*/
|
||||||
|
void qdx_port_mutex_delete(qdx_mutex_t mutex);
|
||||||
|
|
||||||
|
/* Thread entry callback definition */
|
||||||
|
typedef void (*qdx_thread_entry_t)(void *arg);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Create a background thread/task.
|
||||||
|
* @param name Task name
|
||||||
|
* @param entry Task entry function
|
||||||
|
* @param arg Task argument
|
||||||
|
* @param stack_size Requested stack size in bytes
|
||||||
|
* @param priority Task priority
|
||||||
|
* @return 0 on success, < 0 on failure.
|
||||||
|
*/
|
||||||
|
int8_t qdx_port_thread_create(const char *name, qdx_thread_entry_t entry,
|
||||||
|
void *arg, uint32_t stack_size, uint8_t priority);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* QDX_PORT_H */
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_port_template.c
|
||||||
|
* @brief Template Implementation of the HAL Port for QDX Network Stack
|
||||||
|
*
|
||||||
|
* Instructions:
|
||||||
|
* 1. Rename this file to qdx_port.c in your MCU project.
|
||||||
|
* 2. Implement these functions using your specific OS/Network APIs
|
||||||
|
* (e.g., LwIP, FreeRTOS, RT-Thread, CMSIS-OS).
|
||||||
|
* 3. Ensure qdx_port_tcp_recv is non-blocking or uses a short timeout,
|
||||||
|
* so the background thread can periodically check connection status.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "qdx_port.h"
|
||||||
|
#include <stddef.h> /* For NULL */
|
||||||
|
/* Include your system headers here
|
||||||
|
* #include "FreeRTOS.h"
|
||||||
|
* #include "task.h"
|
||||||
|
* #include "lwip/sockets.h"
|
||||||
|
* #include "lwip/sys.h"
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Time & Delay
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
uint32_t qdx_port_get_tick_ms(void) {
|
||||||
|
/* TODO: Return current system uptime in milliseconds.
|
||||||
|
* Example (FreeRTOS): return (uint32_t)(xTaskGetTickCount() *
|
||||||
|
* portTICK_PERIOD_MS); Example (HAL): return HAL_GetTick();
|
||||||
|
*/
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_delay_ms(uint32_t ms) {
|
||||||
|
/* TODO: Block current thread for ms milliseconds.
|
||||||
|
* Example (FreeRTOS): vTaskDelay(pdMS_TO_TICKS(ms));
|
||||||
|
* Example (HAL): HAL_Delay(ms);
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Network (TCP Socket)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
qdx_socket_t qdx_port_tcp_connect(const char *ip, uint16_t port) {
|
||||||
|
/* TODO: Create socket and connect to IP:PORT.
|
||||||
|
* Example (LwIP/BSD Sockets):
|
||||||
|
* int sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
|
* if (sock < 0) return NULL;
|
||||||
|
* struct sockaddr_in dest_addr;
|
||||||
|
* dest_addr.sin_addr.s_addr = inet_addr(ip);
|
||||||
|
* dest_addr.sin_family = AF_INET;
|
||||||
|
* dest_addr.sin_port = htons(port);
|
||||||
|
* if (connect(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) == 0)
|
||||||
|
* {
|
||||||
|
* // Optional: Set receive timeout
|
||||||
|
* return (qdx_socket_t)(intptr_t)sock;
|
||||||
|
* }
|
||||||
|
* close(sock);
|
||||||
|
*/
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_tcp_close(qdx_socket_t sock) {
|
||||||
|
/* TODO: Close the socket gracefully.
|
||||||
|
* Example:
|
||||||
|
* if (sock) {
|
||||||
|
* close((int)(intptr_t)sock);
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t qdx_port_tcp_send(qdx_socket_t sock, const uint8_t *data,
|
||||||
|
uint32_t len) {
|
||||||
|
/* TODO: Send data through the socket.
|
||||||
|
* Example:
|
||||||
|
* if (!sock) return -1;
|
||||||
|
* return send((int)(intptr_t)sock, data, len, 0);
|
||||||
|
*/
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t qdx_port_tcp_recv(qdx_socket_t sock, uint8_t *buf, uint32_t max_len) {
|
||||||
|
/* TODO: Receive data from the socket.
|
||||||
|
* Should return actual bytes read. If no bytes are available (timeout),
|
||||||
|
* return 0. If socket is closed or an error occurs, return < 0. Example: if
|
||||||
|
* (!sock) return -1;
|
||||||
|
* // Assume socket was set with SO_RCVTIMEO to prevent hanging forever
|
||||||
|
* int bytes = recv((int)(intptr_t)sock, buf, max_len, 0);
|
||||||
|
* if (bytes < 0) {
|
||||||
|
* if (errno == EAGAIN || errno == EWOULDBLOCK) return 0; // Timeout
|
||||||
|
* return -1; // Actual error
|
||||||
|
* }
|
||||||
|
* return bytes; // Includes bytes == 0 (graceful close) -> might want to
|
||||||
|
* map to -1
|
||||||
|
*/
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Mutex & Threading
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
qdx_mutex_t qdx_port_mutex_create(void) {
|
||||||
|
/* TODO: Create and return a mutex handle.
|
||||||
|
* Example (FreeRTOS):
|
||||||
|
* SemaphoreHandle_t mutex = xSemaphoreCreateMutex();
|
||||||
|
* return (qdx_mutex_t)mutex;
|
||||||
|
*/
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_lock(qdx_mutex_t mutex) {
|
||||||
|
/* TODO: Lock the given mutex.
|
||||||
|
* Example (FreeRTOS):
|
||||||
|
* if (mutex) xSemaphoreTake((SemaphoreHandle_t)mutex, portMAX_DELAY);
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_unlock(qdx_mutex_t mutex) {
|
||||||
|
/* TODO: Unlock the given mutex.
|
||||||
|
* Example (FreeRTOS):
|
||||||
|
* if (mutex) xSemaphoreGive((SemaphoreHandle_t)mutex);
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_port_mutex_delete(qdx_mutex_t mutex) {
|
||||||
|
/* TODO: Delete the given mutex.
|
||||||
|
* Example (FreeRTOS):
|
||||||
|
* if (mutex) vSemaphoreDelete((SemaphoreHandle_t)mutex);
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
int8_t qdx_port_thread_create(const char *name, qdx_thread_entry_t entry,
|
||||||
|
void *arg, uint32_t stack_size,
|
||||||
|
uint8_t priority) {
|
||||||
|
/* TODO: Create a background thread/task to run the entry function.
|
||||||
|
* Example (FreeRTOS):
|
||||||
|
* BaseType_t res = xTaskCreate(entry, name, stack_size /
|
||||||
|
* sizeof(StackType_t), arg, priority, NULL); return (res == pdPASS) ? 0 : -1;
|
||||||
|
*/
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_preprocess.c
|
||||||
|
* @brief Zero-Copy Image Preprocessing Implementation
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "qdx_preprocess.h"
|
||||||
|
#include "qdx_port.h"
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal State & Configuration Cache
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* Static allocation for column sums to avoid malloc */
|
||||||
|
#define PREPROCESS_MAX_WIDTH 256
|
||||||
|
static uint32_t g_col_sums[PREPROCESS_MAX_WIDTH];
|
||||||
|
static uint8_t g_is_initialized = 0;
|
||||||
|
|
||||||
|
/* 配置读写互斥锁,防止 Execute 与 Settings_Change 并发冲突 */
|
||||||
|
static qdx_mutex_t g_preprocess_mutex = NULL;
|
||||||
|
|
||||||
|
static struct {
|
||||||
|
Config2D_t cfg2d;
|
||||||
|
Config1D_t cfg1d;
|
||||||
|
ConfigCommon_t common;
|
||||||
|
} g_PreprocessCfg;
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* API Implementation
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
int8_t Preprocess_Init(uint16_t maxWidth, uint16_t maxHeight) {
|
||||||
|
(void)maxHeight; /* 列累加仅依赖宽度 */
|
||||||
|
|
||||||
|
if (maxWidth > PREPROCESS_MAX_WIDTH) {
|
||||||
|
return -1; /* 超出静态分配缓冲区上限 */
|
||||||
|
}
|
||||||
|
|
||||||
|
memset(g_col_sums, 0, sizeof(g_col_sums));
|
||||||
|
memset(&g_PreprocessCfg, 0, sizeof(g_PreprocessCfg));
|
||||||
|
|
||||||
|
/* 创建配置互斥锁 */
|
||||||
|
g_preprocess_mutex = qdx_port_mutex_create();
|
||||||
|
if (g_preprocess_mutex == NULL)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* 最小默认配置,防止除零或无限循环 */
|
||||||
|
g_PreprocessCfg.cfg2d.TargetWidth = 1;
|
||||||
|
g_PreprocessCfg.cfg2d.TargetHeight = 1;
|
||||||
|
|
||||||
|
g_is_initialized = 1;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int8_t Preprocess_Settings_Change(const Config2D_t *newConfig2D,
|
||||||
|
const Config1D_t *newConfig1D,
|
||||||
|
const ConfigCommon_t *newCommon) {
|
||||||
|
if (!g_is_initialized)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* 加锁保护配置更新,防止与 Execute 读取产生竞态 */
|
||||||
|
qdx_port_mutex_lock(g_preprocess_mutex);
|
||||||
|
|
||||||
|
if (newConfig2D)
|
||||||
|
memcpy(&g_PreprocessCfg.cfg2d, newConfig2D, sizeof(Config2D_t));
|
||||||
|
if (newConfig1D)
|
||||||
|
memcpy(&g_PreprocessCfg.cfg1d, newConfig1D, sizeof(Config1D_t));
|
||||||
|
if (newCommon)
|
||||||
|
memcpy(&g_PreprocessCfg.common, newCommon, sizeof(ConfigCommon_t));
|
||||||
|
|
||||||
|
/* 安全检查 */
|
||||||
|
if (g_PreprocessCfg.cfg2d.TargetWidth == 0)
|
||||||
|
g_PreprocessCfg.cfg2d.TargetWidth = 1;
|
||||||
|
if (g_PreprocessCfg.cfg2d.TargetHeight == 0)
|
||||||
|
g_PreprocessCfg.cfg2d.TargetHeight = 1;
|
||||||
|
|
||||||
|
qdx_port_mutex_unlock(g_preprocess_mutex);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int8_t Preprocess_Execute(const RawImageBuffer_t *input,
|
||||||
|
TcpTxBuffer_t *out_buffer,
|
||||||
|
PreprocessResult_t *output_meta) {
|
||||||
|
if (!g_is_initialized || !input || !input->pData || !out_buffer ||
|
||||||
|
!out_buffer->pBuffer || !output_meta)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* 加锁快照当前配置,最小化持锁时间 */
|
||||||
|
qdx_port_mutex_lock(g_preprocess_mutex);
|
||||||
|
uint16_t tgt_w = g_PreprocessCfg.cfg2d.TargetWidth;
|
||||||
|
uint16_t tgt_h = g_PreprocessCfg.cfg2d.TargetHeight;
|
||||||
|
int16_t thresh = g_PreprocessCfg.cfg2d.TriggerTemperatureThreshold;
|
||||||
|
qdx_port_mutex_unlock(g_preprocess_mutex);
|
||||||
|
|
||||||
|
uint16_t w = input->Width;
|
||||||
|
uint16_t h = input->Height;
|
||||||
|
|
||||||
|
/* 目标超过输入时回退到整幅图像 */
|
||||||
|
if (tgt_w > w)
|
||||||
|
tgt_w = w;
|
||||||
|
if (tgt_h > h)
|
||||||
|
tgt_h = h;
|
||||||
|
|
||||||
|
/* 输出缓冲区容量限制:等比缩小目标尺寸直到适合 */
|
||||||
|
uint32_t max_payload = out_buffer->TotalCapacity - out_buffer->HeadOffset;
|
||||||
|
if ((uint32_t)tgt_w * tgt_h * 2u > max_payload) {
|
||||||
|
uint16_t orig_w = tgt_w, orig_h = tgt_h;
|
||||||
|
while ((uint32_t)tgt_w * tgt_h * 2u > max_payload && (tgt_w > 1 || tgt_h > 1)) {
|
||||||
|
tgt_w = (tgt_w + 1) / 2;
|
||||||
|
tgt_h = (tgt_h + 1) / 2;
|
||||||
|
}
|
||||||
|
DBG_INIT("PP: target clamped %dx%d -> %dx%d (buf=%d)\r\n",
|
||||||
|
(int)orig_w, (int)orig_h, (int)tgt_w, (int)tgt_h, (int)max_payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t required_bytes = (uint32_t)tgt_w * tgt_h * 2u;
|
||||||
|
|
||||||
|
/* 判断是否需要滑窗计算,或直接导出全图 */
|
||||||
|
if (tgt_w == w && tgt_h == h) {
|
||||||
|
/* 无需滑窗,仅做温度过滤与整体统计 */
|
||||||
|
int16_t min_t = 32767;
|
||||||
|
int16_t max_t = -32768;
|
||||||
|
uint32_t total_sum = 0;
|
||||||
|
uint32_t pixels = w * h;
|
||||||
|
|
||||||
|
/* Write directly to out_buffer starting at HeadOffset */
|
||||||
|
uint8_t *dest_ptr = out_buffer->pBuffer + out_buffer->HeadOffset;
|
||||||
|
|
||||||
|
for (uint32_t i = 0; i < pixels; i++) {
|
||||||
|
int16_t raww_val = (int16_t)input->pData[i];
|
||||||
|
|
||||||
|
if (raww_val < min_t)
|
||||||
|
min_t = raww_val;
|
||||||
|
if (raww_val > max_t)
|
||||||
|
max_t = raww_val;
|
||||||
|
total_sum += raww_val;
|
||||||
|
|
||||||
|
/* Encode Original Raw Value (Little-Endian sequence into uint8_t) */
|
||||||
|
*dest_ptr++ = (uint8_t)(raww_val & 0xFF);
|
||||||
|
*dest_ptr++ = (uint8_t)((raww_val >> 8) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
output_meta->pValidData = out_buffer->pBuffer + out_buffer->HeadOffset;
|
||||||
|
output_meta->DataLength = pixels * 2;
|
||||||
|
output_meta->ValidWidth = w;
|
||||||
|
output_meta->ValidHeight = h;
|
||||||
|
output_meta->MinTemp = min_t;
|
||||||
|
output_meta->MaxTemp = max_t;
|
||||||
|
output_meta->AvgTemp = (int16_t)(total_sum / pixels);
|
||||||
|
output_meta->RoiTemp = output_meta->AvgTemp;
|
||||||
|
output_meta->Status = 0;
|
||||||
|
output_meta->FrameNumber = input->FrameNumber;
|
||||||
|
|
||||||
|
out_buffer->ValidPayloadLen = output_meta->DataLength;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------------
|
||||||
|
Perform Sliding Window Search for Average Temperature Target Region
|
||||||
|
------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
memset(g_col_sums, 0, w * sizeof(uint32_t));
|
||||||
|
uint32_t max_region_sum = 0;
|
||||||
|
uint16_t best_x = 0;
|
||||||
|
uint16_t best_y = 0;
|
||||||
|
|
||||||
|
for (uint16_t y = 0; y <= h - tgt_h; y++) {
|
||||||
|
|
||||||
|
/* Step 1: Initialize column sums for this row strip
|
||||||
|
If y == 0, we calculate the entire strip.
|
||||||
|
Otherwise, we subtract the top row that left, and add the bottom row that
|
||||||
|
entered. */
|
||||||
|
|
||||||
|
if (y == 0) {
|
||||||
|
for (uint16_t c = 0; c < w; c++) {
|
||||||
|
uint32_t col_total = 0;
|
||||||
|
for (uint16_t r = 0; r < tgt_h; r++) {
|
||||||
|
int16_t val = (int16_t)input->pData[r * w + c];
|
||||||
|
if (val < thresh)
|
||||||
|
val = 90;
|
||||||
|
col_total += val;
|
||||||
|
}
|
||||||
|
g_col_sums[c] = col_total;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
/* Slide down by 1 row */
|
||||||
|
for (uint16_t c = 0; c < w; c++) {
|
||||||
|
int16_t top_val = (int16_t)input->pData[(y - 1) * w + c];
|
||||||
|
int16_t bot_val = (int16_t)input->pData[(y + tgt_h - 1) * w + c];
|
||||||
|
|
||||||
|
if (top_val < thresh)
|
||||||
|
top_val = 90;
|
||||||
|
if (bot_val < thresh)
|
||||||
|
bot_val = 90;
|
||||||
|
|
||||||
|
g_col_sums[c] = g_col_sums[c] - top_val + bot_val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Step 2: Slide Across the Columns (Left to Right) */
|
||||||
|
uint32_t current_window_sum = 0;
|
||||||
|
|
||||||
|
/* Initialize first window */
|
||||||
|
for (uint16_t c = 0; c < tgt_w; c++) {
|
||||||
|
current_window_sum += g_col_sums[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current_window_sum > max_region_sum) {
|
||||||
|
max_region_sum = current_window_sum;
|
||||||
|
best_x = 0;
|
||||||
|
best_y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Slide Right */
|
||||||
|
for (uint16_t x = 1; x <= w - tgt_w; x++) {
|
||||||
|
current_window_sum =
|
||||||
|
current_window_sum - g_col_sums[x - 1] + g_col_sums[x + tgt_w - 1];
|
||||||
|
|
||||||
|
if (current_window_sum > max_region_sum) {
|
||||||
|
max_region_sum = current_window_sum;
|
||||||
|
best_x = x;
|
||||||
|
best_y = y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------------
|
||||||
|
Extract the Data
|
||||||
|
------------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
int16_t min_t = 32767;
|
||||||
|
int16_t max_t = -32768;
|
||||||
|
uint32_t total_sum = 0;
|
||||||
|
uint32_t pixels = tgt_w * tgt_h;
|
||||||
|
uint8_t *dest_ptr = out_buffer->pBuffer + out_buffer->HeadOffset;
|
||||||
|
|
||||||
|
for (uint16_t r = 0; r < tgt_h; r++) {
|
||||||
|
for (uint16_t c = 0; c < tgt_w; c++) {
|
||||||
|
/* Raw offset into original image */
|
||||||
|
uint32_t src_idx = (best_y + r) * w + (best_x + c);
|
||||||
|
int16_t raww_val = (int16_t)input->pData[src_idx];
|
||||||
|
|
||||||
|
if (raww_val < min_t)
|
||||||
|
min_t = raww_val;
|
||||||
|
if (raww_val > max_t)
|
||||||
|
max_t = raww_val;
|
||||||
|
total_sum += raww_val;
|
||||||
|
|
||||||
|
/* Output Original Raw Values */
|
||||||
|
*dest_ptr++ = (uint8_t)(raww_val & 0xFF);
|
||||||
|
*dest_ptr++ = (uint8_t)((raww_val >> 8) & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output_meta->pValidData = out_buffer->pBuffer + out_buffer->HeadOffset;
|
||||||
|
output_meta->DataLength = pixels * 2;
|
||||||
|
output_meta->ValidWidth = tgt_w;
|
||||||
|
output_meta->ValidHeight = tgt_h;
|
||||||
|
output_meta->MinTemp = min_t;
|
||||||
|
output_meta->MaxTemp = max_t;
|
||||||
|
output_meta->AvgTemp = (int16_t)(total_sum / pixels);
|
||||||
|
output_meta->RoiTemp = output_meta->AvgTemp;
|
||||||
|
output_meta->Status = 0;
|
||||||
|
output_meta->FrameNumber = input->FrameNumber;
|
||||||
|
|
||||||
|
out_buffer->ValidPayloadLen = output_meta->DataLength;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal Trigger Check
|
||||||
|
* ============================================================ */
|
||||||
|
int8_t Preprocess_CheckInternalTrigger2D(const RawImageBuffer_t *input) {
|
||||||
|
if (!g_is_initialized || !input || !input->pData)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
qdx_port_mutex_lock(g_preprocess_mutex);
|
||||||
|
uint16_t roi_x = g_PreprocessCfg.cfg2d.TriggerRoiX;
|
||||||
|
uint16_t roi_y = g_PreprocessCfg.cfg2d.TriggerRoiY;
|
||||||
|
uint16_t roi_w = g_PreprocessCfg.cfg2d.TriggerRoiW;
|
||||||
|
uint16_t roi_h = g_PreprocessCfg.cfg2d.TriggerRoiH;
|
||||||
|
uint8_t condition = g_PreprocessCfg.cfg2d.TriggerCondition;
|
||||||
|
int16_t thresh = g_PreprocessCfg.cfg2d.TriggerTemperatureThreshold;
|
||||||
|
qdx_port_mutex_unlock(g_preprocess_mutex);
|
||||||
|
|
||||||
|
uint16_t w = input->Width;
|
||||||
|
uint16_t h = input->Height;
|
||||||
|
|
||||||
|
/* Boundary Check & Clipping */
|
||||||
|
if (roi_w == 0 || roi_h == 0)
|
||||||
|
return 0;
|
||||||
|
if (roi_x >= w || roi_y >= h)
|
||||||
|
return 0;
|
||||||
|
if (roi_x + roi_w > w)
|
||||||
|
roi_w = w - roi_x;
|
||||||
|
if (roi_y + roi_h > h)
|
||||||
|
roi_h = h - roi_y;
|
||||||
|
|
||||||
|
int16_t max_temp = -32768;
|
||||||
|
int64_t sum_temp = 0;
|
||||||
|
uint32_t count = roi_w * roi_h;
|
||||||
|
|
||||||
|
for (uint16_t r = 0; r < roi_h; r++) {
|
||||||
|
for (uint16_t c = 0; c < roi_w; c++) {
|
||||||
|
int16_t val = (int16_t)input->pData[(roi_y + r) * w + (roi_x + c)];
|
||||||
|
|
||||||
|
/* Temperature Filtration Preprocessing */
|
||||||
|
if (val < thresh) {
|
||||||
|
val = 90; /* Treat as 9.0C */
|
||||||
|
}
|
||||||
|
|
||||||
|
if (val > max_temp)
|
||||||
|
max_temp = val;
|
||||||
|
sum_temp += val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int16_t calc_val = 0;
|
||||||
|
if (condition == 1) {
|
||||||
|
/* 1: Max */
|
||||||
|
calc_val = max_temp;
|
||||||
|
} else {
|
||||||
|
/* 0: Average */
|
||||||
|
calc_val = (int16_t)(sum_temp / count);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (calc_val >= thresh) {
|
||||||
|
return 1; /* Triggered */
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0; /* Not triggered */
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_preprocess.h
|
||||||
|
* @brief Zero-Copy Image Preprocessing for Thermal Imaging
|
||||||
|
*
|
||||||
|
* Includes Sliding Window Maximum/Average ROI search,
|
||||||
|
* Temperature filtering, and Data extraction.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef QDX_PREPROCESS_H
|
||||||
|
#define QDX_PREPROCESS_H
|
||||||
|
|
||||||
|
#include "qdx_protocol.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize static memory resources for sliding window calculations.
|
||||||
|
*
|
||||||
|
* Called once during system boot. Pre-allocates column accumulation arrays
|
||||||
|
* to prevent dynamic allocation during runtime.
|
||||||
|
*
|
||||||
|
* @param maxWidth The maximum supported width of the 2D input matrix
|
||||||
|
* @param maxHeight The maximum supported height of the 2D input matrix
|
||||||
|
* @return 0 on success, < 0 on failure.
|
||||||
|
*/
|
||||||
|
int8_t Preprocess_Init(uint16_t maxWidth, uint16_t maxHeight);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Execute the preprocessing pipeline on a raw frame.
|
||||||
|
*
|
||||||
|
* High-performance processing logic that reads `input`, applies thresholds,
|
||||||
|
* finds the best `TargetWidth x TargetHeight` ROI using sliding window arrays,
|
||||||
|
* and extracts that region into `out_buffer` starting precisely at
|
||||||
|
* `HeadOffset`.
|
||||||
|
*
|
||||||
|
* @param input Raw thermal image array
|
||||||
|
* @param out_buffer Pre-allocated transmission buffer wrapper
|
||||||
|
* @param output_meta Struct to fill with process results/metadata
|
||||||
|
* @return 0 if successful, < 0 if aborted (e.g., config invalid)
|
||||||
|
*/
|
||||||
|
int8_t Preprocess_Execute(const RawImageBuffer_t *input,
|
||||||
|
TcpTxBuffer_t *out_buffer,
|
||||||
|
PreprocessResult_t *output_meta);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Safely update internal preprocessing shadow parameters.
|
||||||
|
*
|
||||||
|
* @param newConfig2D Partial Configuration Update
|
||||||
|
* @param newConfig1D Partial Configuration Update
|
||||||
|
* @param newCommon General System Setup
|
||||||
|
* @return 0 on success.
|
||||||
|
*/
|
||||||
|
int8_t Preprocess_Settings_Change(const Config2D_t *newConfig2D,
|
||||||
|
const Config1D_t *newConfig1D,
|
||||||
|
const ConfigCommon_t *newCommon);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Check if the current frame triggers the internal 2D capture condition
|
||||||
|
*
|
||||||
|
* Evaluates the specified TriggerRoi region using either Max or Average
|
||||||
|
* temperature against the TriggerTemperatureThreshold.
|
||||||
|
*
|
||||||
|
* @param input Raw thermal image array
|
||||||
|
* @return 1 if trigger condition is met, 0 if not met, < 0 on error.
|
||||||
|
*/
|
||||||
|
int8_t Preprocess_CheckInternalTrigger2D(const RawImageBuffer_t *input);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* QDX_PREPROCESS_H */
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_protocol.c
|
||||||
|
* @brief Communication Protocol 2.0 Utility Implementations
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "qdx_protocol.h"
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Shift-Safe Serialization (Little-Endian)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
void qdx_write_u16_le(uint8_t *buf, uint16_t val) {
|
||||||
|
buf[0] = (uint8_t)(val & 0xFF);
|
||||||
|
buf[1] = (uint8_t)((val >> 8) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
void qdx_write_u32_le(uint8_t *buf, uint32_t val) {
|
||||||
|
buf[0] = (uint8_t)(val & 0xFF);
|
||||||
|
buf[1] = (uint8_t)((val >> 8) & 0xFF);
|
||||||
|
buf[2] = (uint8_t)((val >> 16) & 0xFF);
|
||||||
|
buf[3] = (uint8_t)((val >> 24) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t qdx_read_u16_le(const uint8_t *buf) {
|
||||||
|
return (uint16_t)(buf[0] | (buf[1] << 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t qdx_read_u32_le(const uint8_t *buf) {
|
||||||
|
/* 显式转型防止高位字节的符号位扩展 */
|
||||||
|
return ((uint32_t)buf[0]) | ((uint32_t)buf[1] << 8) |
|
||||||
|
((uint32_t)buf[2] << 16) | ((uint32_t)buf[3] << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* CRC16-MODBUS Checksum (Polynomial: 0xA001, Init: 0xFFFF)
|
||||||
|
* ============================================================ */
|
||||||
|
uint16_t qdx_crc16_modbus(const uint8_t *data, int len) {
|
||||||
|
uint16_t crc = 0xFFFF;
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
crc ^= data[i];
|
||||||
|
for (int j = 0; j < 8; j++) {
|
||||||
|
if (crc & 0x0001) {
|
||||||
|
crc >>= 1;
|
||||||
|
crc ^= 0xA001;
|
||||||
|
} else {
|
||||||
|
crc >>= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Build Frame (Header + TLV + Payload + CRC16)
|
||||||
|
* Uses strict byte shifting to prevent unaligned struct access on MCU.
|
||||||
|
* ============================================================ */
|
||||||
|
int qdx_build_frame(uint8_t *buf, uint8_t msg_class, uint8_t tlv_type,
|
||||||
|
const uint8_t *payload, uint16_t payload_len,
|
||||||
|
uint16_t dev_id, uint16_t seq, uint32_t timestamp,
|
||||||
|
uint8_t flags) {
|
||||||
|
|
||||||
|
flags |= FLAG_LAST_FRAGMENT;
|
||||||
|
uint16_t total_len = HEADER_SIZE + TLV_HEADER_SIZE + payload_len + CRC_SIZE;
|
||||||
|
|
||||||
|
/* 1. Fill FrameHeader (16 bytes) safely */
|
||||||
|
qdx_write_u16_le(buf + 0, PROTO_MAGIC); /* Magic */
|
||||||
|
buf[2] = PROTO_VERSION; /* Version */
|
||||||
|
qdx_write_u16_le(buf + 3, total_len); /* Length */
|
||||||
|
qdx_write_u16_le(buf + 5, seq); /* Sequence */
|
||||||
|
qdx_write_u32_le(buf + 7, timestamp); /* Timestamp */
|
||||||
|
buf[11] = 0x01; /* Source = MCU (0x01) */
|
||||||
|
qdx_write_u16_le(buf + 12, dev_id); /* DevID */
|
||||||
|
buf[14] = msg_class; /* Class */
|
||||||
|
buf[15] = flags; /* Flags */
|
||||||
|
|
||||||
|
/* 2. Fill TLV Header (3 bytes) safely */
|
||||||
|
buf[16] = tlv_type; /* TLV Type */
|
||||||
|
qdx_write_u16_le(buf + 17, payload_len); /* TLV Length */
|
||||||
|
|
||||||
|
/* 3. Copy Payload(使用 memmove 防止 payload 与 buf 重叠时的未定义行为) */
|
||||||
|
if (payload && payload_len > 0) {
|
||||||
|
memmove(buf + HEADER_SIZE + TLV_HEADER_SIZE, payload, payload_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 4. Append CRC16 */
|
||||||
|
uint16_t crc = qdx_crc16_modbus(buf, total_len - CRC_SIZE);
|
||||||
|
qdx_write_u16_le(buf + total_len - CRC_SIZE, crc);
|
||||||
|
|
||||||
|
return total_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* In-Place Frame Build (Header + CRC only, payload already in place)
|
||||||
|
* 用于零拷贝场景:payload(含 TLV + 数据)已填充在 buf[HEADER_SIZE] 处,
|
||||||
|
* 本函数仅写入 16 字节帧头并在尾部追加 CRC16。
|
||||||
|
* ============================================================ */
|
||||||
|
int qdx_build_frame_inplace(uint8_t *buf, uint8_t msg_class,
|
||||||
|
uint16_t payload_len, uint16_t dev_id, uint16_t seq,
|
||||||
|
uint32_t timestamp, uint8_t flags) {
|
||||||
|
|
||||||
|
flags |= FLAG_LAST_FRAGMENT;
|
||||||
|
uint16_t total_len = HEADER_SIZE + payload_len + CRC_SIZE;
|
||||||
|
|
||||||
|
/* 填写 16 字节帧头 */
|
||||||
|
qdx_write_u16_le(buf + 0, PROTO_MAGIC);
|
||||||
|
buf[2] = PROTO_VERSION;
|
||||||
|
qdx_write_u16_le(buf + 3, total_len);
|
||||||
|
qdx_write_u16_le(buf + 5, seq);
|
||||||
|
qdx_write_u32_le(buf + 7, timestamp);
|
||||||
|
buf[11] = 0x01; /* Source = MCU */
|
||||||
|
qdx_write_u16_le(buf + 12, dev_id);
|
||||||
|
buf[14] = msg_class;
|
||||||
|
buf[15] = flags;
|
||||||
|
|
||||||
|
/* payload 已在 buf[16..16+payload_len-1],无需拷贝 */
|
||||||
|
|
||||||
|
/* 追加 CRC16 */
|
||||||
|
uint16_t crc = qdx_crc16_modbus(buf, total_len - CRC_SIZE);
|
||||||
|
qdx_write_u16_le(buf + total_len - CRC_SIZE, crc);
|
||||||
|
|
||||||
|
return total_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Build Fragmented Frame (Header + Chunk + CRC16, NO TLV)
|
||||||
|
* ============================================================ */
|
||||||
|
int qdx_build_fragment_frame(uint8_t *buf, uint8_t msg_class,
|
||||||
|
const uint8_t *chunk, uint16_t chunk_len,
|
||||||
|
uint16_t dev_id, uint16_t seq, uint32_t timestamp,
|
||||||
|
uint8_t flags) {
|
||||||
|
|
||||||
|
uint16_t total_len = HEADER_SIZE + chunk_len + CRC_SIZE;
|
||||||
|
|
||||||
|
/* 1. Fill FrameHeader (16 bytes) safely */
|
||||||
|
qdx_write_u16_le(buf + 0, PROTO_MAGIC);
|
||||||
|
buf[2] = PROTO_VERSION;
|
||||||
|
qdx_write_u16_le(buf + 3, total_len);
|
||||||
|
qdx_write_u16_le(buf + 5, seq);
|
||||||
|
qdx_write_u32_le(buf + 7, timestamp);
|
||||||
|
buf[11] = 0x01; /* Source MCU */
|
||||||
|
qdx_write_u16_le(buf + 12, dev_id);
|
||||||
|
buf[14] = msg_class;
|
||||||
|
buf[15] = flags;
|
||||||
|
|
||||||
|
/* 2. Copy Payload Chunk(使用 memmove 应对潜在重叠) */
|
||||||
|
if (chunk && chunk_len > 0) {
|
||||||
|
memmove(buf + HEADER_SIZE, chunk, chunk_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 3. Append CRC16 */
|
||||||
|
uint16_t crc = qdx_crc16_modbus(buf, total_len - CRC_SIZE);
|
||||||
|
qdx_write_u16_le(buf + total_len - CRC_SIZE, crc);
|
||||||
|
|
||||||
|
return total_len;
|
||||||
|
}
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_protocol.h
|
||||||
|
* @brief Communication Protocol 2.0 Structures and Constants
|
||||||
|
*
|
||||||
|
* Platform-independent header for CH32 MCU and other systems.
|
||||||
|
* All structures use 1-byte alignment. Focuses on safe uint8_t
|
||||||
|
* serialization and avoiding hardware faults from unaligned access.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef QDX_PROTOCOL_H
|
||||||
|
#define QDX_PROTOCOL_H
|
||||||
|
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Protocol Constants
|
||||||
|
* ============================================================ */
|
||||||
|
#define PROTO_MAGIC 0x55AA /* Frame Header Magic */
|
||||||
|
#define PROTO_VERSION 0x20 /* Protocol Version v2.0 */
|
||||||
|
|
||||||
|
/* Message Classes (Class) */
|
||||||
|
#define CLASS_CONTROL 0x01 /* Configuration / Control */
|
||||||
|
#define CLASS_DATA 0x02 /* Real-time Data Report */
|
||||||
|
#define CLASS_RESPONSE 0x03 /* ACK / NACK / Error */
|
||||||
|
#define CLASS_SYSTEM 0x04 /* Handshake / Heartbeat / Sync */
|
||||||
|
|
||||||
|
/* TLV Types */
|
||||||
|
#define TYPE_HANDSHAKE 0x01
|
||||||
|
#define TYPE_HEARTBEAT 0x02
|
||||||
|
#define TYPE_SYNC_TIME 0x03
|
||||||
|
#define TYPE_DEVID_ASSIGN 0x05
|
||||||
|
#define TYPE_TEMP_FRAME 0x10
|
||||||
|
#define TYPE_RAW_FRAME 0x11
|
||||||
|
#define TYPE_CONFIG_COMMON 0x20
|
||||||
|
#define TYPE_CONFIG_2D 0x22
|
||||||
|
#define TYPE_CONFIG_1D 0x23
|
||||||
|
#define TYPE_ACK_PAYLOAD 0x30
|
||||||
|
#define TYPE_DETECTION_RESULT 0x40
|
||||||
|
|
||||||
|
/* Flags */
|
||||||
|
#define FLAG_PRIORITY_MASK 0x03
|
||||||
|
#define FLAG_COMPRESSED 0x04
|
||||||
|
#define FLAG_ENCRYPTED 0x08
|
||||||
|
#define FLAG_ACK_REQ 0x10
|
||||||
|
#define FLAG_LAST_FRAGMENT 0x20
|
||||||
|
|
||||||
|
/* Frame Structure Sizes */
|
||||||
|
#define HEADER_SIZE 16 /* FrameHeader_t size */
|
||||||
|
#define TLV_HEADER_SIZE 3 /* TLV_t size (Type + Length) */
|
||||||
|
#define CRC_SIZE 2 /* CRC16 size */
|
||||||
|
|
||||||
|
/* Fragmentation limit */
|
||||||
|
#define MAX_FRAGMENT_PAYLOAD 1400
|
||||||
|
|
||||||
|
/* Error Codes */
|
||||||
|
#define ERR_NONE 0x0000
|
||||||
|
#define ERR_CRC 0x1001
|
||||||
|
#define ERR_VERSION 0x1002
|
||||||
|
#define ERR_LENGTH 0x1003
|
||||||
|
#define ERR_AUTH 0x2001
|
||||||
|
#define ERR_BUSY 0x2002
|
||||||
|
#define ERR_DEV_ID_CONFLICT 0x2003
|
||||||
|
#define ERR_PARAM 0x3001
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal Protocol Structures (Packed to 1 byte)
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
#pragma pack(push, 1)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Frame Header (16 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t Magic;
|
||||||
|
uint8_t Version;
|
||||||
|
uint16_t Length;
|
||||||
|
uint16_t Sequence;
|
||||||
|
uint32_t Timestamp;
|
||||||
|
uint8_t Source;
|
||||||
|
uint16_t DevID;
|
||||||
|
uint8_t Class;
|
||||||
|
uint8_t Flags;
|
||||||
|
} FrameHeader_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief TLV Header (3 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint8_t Type;
|
||||||
|
uint16_t Length;
|
||||||
|
} TLV_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Handshake (46 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t ProtocolVersion;
|
||||||
|
uint8_t DeviceUUID[16];
|
||||||
|
uint8_t AuthToken[16];
|
||||||
|
char HardwareVersion[8];
|
||||||
|
char FirmwareVersion[8];
|
||||||
|
uint32_t Capabilities;
|
||||||
|
} Handshake_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Heartbeat (6 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t UpTime;
|
||||||
|
uint8_t CpuLoad;
|
||||||
|
uint8_t MemUsage;
|
||||||
|
} Heartbeat_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief ACK Payload (5 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t AckSeq;
|
||||||
|
uint8_t Status;
|
||||||
|
uint16_t ErrorCode;
|
||||||
|
} Ack_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Device ID Assignment (4 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t NewDevID;
|
||||||
|
uint16_t Reserved;
|
||||||
|
} DevIDAssignment_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Temperature Frame Header (18 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t FrameNumber;
|
||||||
|
uint16_t Width;
|
||||||
|
uint16_t Height;
|
||||||
|
int16_t MinTemp;
|
||||||
|
int16_t MaxTemp;
|
||||||
|
int16_t AvgTemp;
|
||||||
|
int16_t RoiTemp;
|
||||||
|
uint8_t FrameType;
|
||||||
|
uint8_t Status;
|
||||||
|
uint8_t Is2D;
|
||||||
|
uint8_t Reserved;
|
||||||
|
} TemperatureFrameHeader_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief 1D Temperature Point (4 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t TimeOffset;
|
||||||
|
uint16_t Temperature;
|
||||||
|
} TempPoint1D_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Detection Result (8 bytes)
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint32_t FrameNumber;
|
||||||
|
uint8_t Result;
|
||||||
|
uint8_t Reserved[3];
|
||||||
|
} DetectionResult_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Common Configuration
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
char PipelineId[16];
|
||||||
|
uint8_t PipelineType;
|
||||||
|
uint8_t WorkMode;
|
||||||
|
uint8_t ConfigTag;
|
||||||
|
uint8_t StrictnessLevel;
|
||||||
|
uint8_t IsCustomMode;
|
||||||
|
uint8_t Reserved[2];
|
||||||
|
} ConfigCommon_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief 2D Configuration
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint8_t Enabled;
|
||||||
|
uint8_t IsLive;
|
||||||
|
uint16_t DeviceId;
|
||||||
|
uint16_t Width;
|
||||||
|
uint16_t Height;
|
||||||
|
uint8_t Fps;
|
||||||
|
uint32_t Exposure;
|
||||||
|
uint8_t AutoExposure;
|
||||||
|
uint8_t MaskEnabled;
|
||||||
|
int16_t MaskThreshold;
|
||||||
|
uint16_t MaskWidth;
|
||||||
|
uint16_t MaskHeight;
|
||||||
|
int16_t Angle;
|
||||||
|
uint16_t TargetWidth;
|
||||||
|
uint16_t TargetHeight;
|
||||||
|
uint8_t TriggerMode;
|
||||||
|
uint8_t TriggerGpioLine;
|
||||||
|
uint16_t TriggerDelayMs;
|
||||||
|
uint8_t TriggerBurstCount;
|
||||||
|
uint16_t TriggerInternalIntervalMs;
|
||||||
|
int16_t TriggerTemperatureThreshold;
|
||||||
|
uint16_t TriggerDebounceIntervalMs;
|
||||||
|
uint8_t TriggerCondition;
|
||||||
|
uint16_t TriggerRoiX;
|
||||||
|
uint16_t TriggerRoiY;
|
||||||
|
uint16_t TriggerRoiW;
|
||||||
|
uint16_t TriggerRoiH;
|
||||||
|
uint16_t NGioDelay;
|
||||||
|
uint8_t OutputGpioLine;
|
||||||
|
uint8_t AlarmGpioLine;
|
||||||
|
uint16_t AlarmHoldMs;
|
||||||
|
uint8_t StoreNgImagesOnly;
|
||||||
|
uint8_t TrainingEnabled;
|
||||||
|
uint16_t TrainingSampleThreshold;
|
||||||
|
uint16_t ProcessingTimeoutMs;
|
||||||
|
uint8_t MaxProcessingQueueSize;
|
||||||
|
uint8_t Reserved;
|
||||||
|
} Config2D_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief 1D Configuration
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint8_t Enabled;
|
||||||
|
uint8_t RunMode;
|
||||||
|
uint8_t TriggerType;
|
||||||
|
uint16_t BufferSize;
|
||||||
|
int16_t TriggerTempLimit;
|
||||||
|
uint16_t StartPointsToRemove;
|
||||||
|
uint16_t ReferenceLength;
|
||||||
|
uint16_t HighTimerLimit;
|
||||||
|
uint16_t TimerCLimit;
|
||||||
|
uint8_t NgCountLimit;
|
||||||
|
uint16_t LSizeStart;
|
||||||
|
uint16_t RSizeStart;
|
||||||
|
uint16_t NGioDelay;
|
||||||
|
uint8_t OutputGpioLine;
|
||||||
|
uint8_t AlarmGpioLine;
|
||||||
|
uint16_t AlarmHoldMs;
|
||||||
|
} Config1D_t;
|
||||||
|
|
||||||
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Application Level Business Structures
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Raw Image Buffer provided by capture module
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint16_t *pData;
|
||||||
|
uint16_t Width;
|
||||||
|
uint16_t Height;
|
||||||
|
uint32_t FrameNumber;
|
||||||
|
} RawImageBuffer_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Preprocessing result metadata
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint8_t *pValidData;
|
||||||
|
uint32_t DataLength;
|
||||||
|
uint16_t ValidWidth;
|
||||||
|
uint16_t ValidHeight;
|
||||||
|
int16_t MinTemp;
|
||||||
|
int16_t MaxTemp;
|
||||||
|
int16_t AvgTemp;
|
||||||
|
int16_t RoiTemp;
|
||||||
|
uint8_t Status;
|
||||||
|
uint32_t FrameNumber;
|
||||||
|
} PreprocessResult_t;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Buffer wrapper for Zero-Copy TCP packet building
|
||||||
|
*/
|
||||||
|
typedef struct {
|
||||||
|
uint8_t *pBuffer;
|
||||||
|
uint32_t TotalCapacity;
|
||||||
|
uint32_t HeadOffset; /* Reserved header space for envelope */
|
||||||
|
uint32_t ValidPayloadLen;
|
||||||
|
} TcpTxBuffer_t;
|
||||||
|
|
||||||
|
/* System global config hook types */
|
||||||
|
typedef void (*ConfigUpdateCallback_t)(const ConfigCommon_t *common,
|
||||||
|
const Config2D_t *cfg2d,
|
||||||
|
const Config1D_t *cfg1d);
|
||||||
|
typedef void (*DetectionResultCallback_t)(uint32_t frameNumber,
|
||||||
|
uint8_t resultStatus);
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Protocol Utility Function Declarations
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
/* Calculate Modbus CRC16 */
|
||||||
|
uint16_t qdx_crc16_modbus(const uint8_t *data, int len);
|
||||||
|
|
||||||
|
/* Shift-safe write: 16-bit little-endian */
|
||||||
|
void qdx_write_u16_le(uint8_t *buf, uint16_t val);
|
||||||
|
|
||||||
|
/* Shift-safe write: 32-bit little-endian */
|
||||||
|
void qdx_write_u32_le(uint8_t *buf, uint32_t val);
|
||||||
|
|
||||||
|
/* Shift-safe read: 16-bit little-endian */
|
||||||
|
uint16_t qdx_read_u16_le(const uint8_t *buf);
|
||||||
|
|
||||||
|
/* Shift-safe read: 32-bit little-endian */
|
||||||
|
uint32_t qdx_read_u32_le(const uint8_t *buf);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Build a complete protocol frame using safe byte shifts.
|
||||||
|
*/
|
||||||
|
int qdx_build_frame(uint8_t *buf, uint8_t msg_class, uint8_t tlv_type,
|
||||||
|
const uint8_t *payload, uint16_t payload_len,
|
||||||
|
uint16_t dev_id, uint16_t seq, uint32_t timestamp,
|
||||||
|
uint8_t flags);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief In-place frame build: 仅填写帧头并追加 CRC,不拷贝 payload。
|
||||||
|
* 用于零拷贝场景,payload(含 TLV)已在 buf[HEADER_SIZE] 处就位。
|
||||||
|
*/
|
||||||
|
int qdx_build_frame_inplace(uint8_t *buf, uint8_t msg_class,
|
||||||
|
uint16_t payload_len, uint16_t dev_id, uint16_t seq,
|
||||||
|
uint32_t timestamp, uint8_t flags);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Build a fragmented payload frame (No TLV wrapper).
|
||||||
|
*/
|
||||||
|
int qdx_build_fragment_frame(uint8_t *buf, uint8_t msg_class,
|
||||||
|
const uint8_t *chunk, uint16_t chunk_len,
|
||||||
|
uint16_t dev_id, uint16_t seq, uint32_t timestamp,
|
||||||
|
uint8_t flags);
|
||||||
|
|
||||||
|
#endif /* QDX_PROTOCOL_H */
|
||||||
@@ -0,0 +1,771 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_tcp_logic.c
|
||||||
|
* @brief TCP Network Logic Implementation for MCU
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "qdx_tcp_logic.h"
|
||||||
|
#include "qdx_port.h"
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal State & Configuration Cache
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
#define RECV_BUF_SIZE 2048
|
||||||
|
#define MAX_FRAGMENT_PAYLOAD 1400
|
||||||
|
#define HEARTBEAT_INTERVAL_MS 2000
|
||||||
|
#define SERVER_TIMEOUT_MS 6000
|
||||||
|
#define RECONNECT_DELAY_MS 3000
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
qdx_socket_t sock;
|
||||||
|
uint32_t last_activity_ms;
|
||||||
|
uint32_t last_heartbeat_ms;
|
||||||
|
uint32_t last_reconnect_ms;
|
||||||
|
uint16_t sequence;
|
||||||
|
uint8_t is_connected;
|
||||||
|
uint8_t is_running;
|
||||||
|
const char *label;
|
||||||
|
uint8_t recv_buffer[RECV_BUF_SIZE * 2];
|
||||||
|
uint32_t recv_len;
|
||||||
|
} TcpStreamCtx_t;
|
||||||
|
|
||||||
|
static struct {
|
||||||
|
uint8_t uuid[16];
|
||||||
|
uint8_t auth_token[16];
|
||||||
|
uint16_t dev_id;
|
||||||
|
int32_t pending_new_dev_id;
|
||||||
|
uint32_t frame_count;
|
||||||
|
|
||||||
|
TcpStreamCtx_t control_stream;
|
||||||
|
TcpStreamCtx_t data_stream;
|
||||||
|
|
||||||
|
qdx_mutex_t config_mutex;
|
||||||
|
uint8_t has_valid_config;
|
||||||
|
ConfigCommon_t cached_common;
|
||||||
|
Config2D_t cached_cfg2d;
|
||||||
|
Config1D_t cached_cfg1d;
|
||||||
|
|
||||||
|
ConfigUpdateCallback_t config_cb;
|
||||||
|
DetectionResultCallback_t detect_cb;
|
||||||
|
TempFrameRequestCallback_t temp_req_cb;
|
||||||
|
} g_TcpLogic;
|
||||||
|
|
||||||
|
/* Server endpoint prototype - user would configure these, but we map to demo
|
||||||
|
* defaults */
|
||||||
|
static const char *SERVER_IP = "192.168.7.50";
|
||||||
|
static const uint16_t CONTROL_PORT = 5511;
|
||||||
|
static const uint16_t DATA_PORT = 5512;
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Internal Helpers
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
static void tcp_stream_init(TcpStreamCtx_t *ctx, const char *label) {
|
||||||
|
memset(ctx, 0, sizeof(TcpStreamCtx_t));
|
||||||
|
ctx->label = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tcp_stream_disconnect(TcpStreamCtx_t *ctx) {
|
||||||
|
DBG_NET("[%s] Disconnected\r\n", ctx->label);
|
||||||
|
ctx->is_connected = 0;
|
||||||
|
if (ctx->sock) {
|
||||||
|
qdx_port_tcp_close(ctx->sock);
|
||||||
|
ctx->sock = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int8_t tcp_stream_connect(TcpStreamCtx_t *ctx, const char *ip,
|
||||||
|
uint16_t port) {
|
||||||
|
DBG_NET("[%s] connecting %s:%d...\r\n", ctx->label, ip, port);
|
||||||
|
ctx->sock = qdx_port_tcp_connect(ip, port);
|
||||||
|
if (ctx->sock == NULL) {
|
||||||
|
DBG_ERR("[%s] connect FAILED\r\n", ctx->label);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx->is_connected = 1;
|
||||||
|
ctx->last_activity_ms = qdx_port_get_tick_ms();
|
||||||
|
ctx->last_heartbeat_ms = ctx->last_activity_ms;
|
||||||
|
ctx->recv_len = 0;
|
||||||
|
DBG_NET("[%s] Connected to %s:%d\r\n", ctx->label, ip, port);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int32_t tcp_send_frame(TcpStreamCtx_t *ctx, uint8_t msg_class,
|
||||||
|
uint8_t tlv_type, const uint8_t *payload,
|
||||||
|
uint16_t payload_len, uint8_t flags) {
|
||||||
|
if (!ctx->is_connected || ctx->sock == NULL)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
/* Max frame buffer for generic small control/heartbeat messages.
|
||||||
|
Note: Images use BuildAndSendTemperatureFrame instead of this. */
|
||||||
|
uint8_t buffer[1024];
|
||||||
|
if (HEADER_SIZE + TLV_HEADER_SIZE + payload_len + CRC_SIZE > sizeof(buffer)) {
|
||||||
|
return -1; /* Too large for generic send */
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t seq = ctx->sequence++;
|
||||||
|
int frame_len =
|
||||||
|
qdx_build_frame(buffer, msg_class, tlv_type, payload, payload_len,
|
||||||
|
g_TcpLogic.dev_id, seq, qdx_port_get_tick_ms(), flags);
|
||||||
|
|
||||||
|
int32_t sent = qdx_port_tcp_send(ctx->sock, buffer, frame_len);
|
||||||
|
if (sent < 0) {
|
||||||
|
tcp_stream_disconnect(ctx);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tcp_send_handshake(TcpStreamCtx_t *ctx) {
|
||||||
|
DBG_NET("[%s] Handshake (DevID=%d)\r\n", ctx->label, (int)g_TcpLogic.dev_id);
|
||||||
|
uint8_t payload[54];
|
||||||
|
memset(payload, 0, sizeof(payload));
|
||||||
|
qdx_write_u16_le(payload + 0, 0x0200);
|
||||||
|
memcpy(payload + 2, g_TcpLogic.uuid, 16);
|
||||||
|
memcpy(payload + 18, g_TcpLogic.auth_token, 16);
|
||||||
|
/* Safe string copy without relying on strncpy platform behavior */
|
||||||
|
const char *hw = "V1.0";
|
||||||
|
const char *fw = "V2.0";
|
||||||
|
for (int i = 0; i < 8 && hw[i]; i++)
|
||||||
|
payload[34 + i] = hw[i];
|
||||||
|
for (int i = 0; i < 8 && fw[i]; i++)
|
||||||
|
payload[42 + i] = fw[i];
|
||||||
|
qdx_write_u32_le(payload + 50, 0x07);
|
||||||
|
|
||||||
|
tcp_send_frame(ctx, CLASS_SYSTEM, TYPE_HANDSHAKE, payload, sizeof(payload),
|
||||||
|
FLAG_ACK_REQ);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tcp_send_heartbeat(TcpStreamCtx_t *ctx) {
|
||||||
|
uint8_t payload[6];
|
||||||
|
qdx_write_u32_le(payload + 0, qdx_port_get_tick_ms());
|
||||||
|
payload[4] = 10; /* Placeholder CpuLoad */
|
||||||
|
payload[5] = 20; /* Placeholder MemUsage */
|
||||||
|
|
||||||
|
tcp_send_frame(ctx, CLASS_SYSTEM, TYPE_HEARTBEAT, payload, sizeof(payload),
|
||||||
|
0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tcp_send_ack(TcpStreamCtx_t *ctx, uint16_t ack_seq, uint8_t status,
|
||||||
|
uint16_t error_code) {
|
||||||
|
uint8_t payload[5];
|
||||||
|
qdx_write_u16_le(payload + 0, ack_seq);
|
||||||
|
payload[2] = status;
|
||||||
|
qdx_write_u16_le(payload + 3, error_code);
|
||||||
|
|
||||||
|
tcp_send_frame(ctx, CLASS_RESPONSE, TYPE_ACK_PAYLOAD, payload,
|
||||||
|
sizeof(payload), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Receiving and Parsing
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
static void qdx_deserialize_config_common(ConfigCommon_t *cfg,
|
||||||
|
const uint8_t *val) {
|
||||||
|
/* PipelineId: 16 字节字符数组,逐字节拷贝 */
|
||||||
|
for (int i = 0; i < 16; i++)
|
||||||
|
cfg->PipelineId[i] = (char)val[i];
|
||||||
|
cfg->PipelineType = val[16];
|
||||||
|
cfg->WorkMode = val[17];
|
||||||
|
cfg->ConfigTag = val[18];
|
||||||
|
cfg->StrictnessLevel = val[19];
|
||||||
|
cfg->IsCustomMode = val[20];
|
||||||
|
cfg->Reserved[0] = val[21];
|
||||||
|
cfg->Reserved[1] = val[22];
|
||||||
|
}
|
||||||
|
|
||||||
|
static void qdx_deserialize_config2d(Config2D_t *cfg, const uint8_t *val) {
|
||||||
|
cfg->Enabled = val[0];
|
||||||
|
cfg->IsLive = val[1];
|
||||||
|
cfg->DeviceId = qdx_read_u16_le(val + 2);
|
||||||
|
cfg->Width = qdx_read_u16_le(val + 4);
|
||||||
|
cfg->Height = qdx_read_u16_le(val + 6);
|
||||||
|
cfg->Fps = val[8];
|
||||||
|
cfg->Exposure = qdx_read_u32_le(val + 9);
|
||||||
|
cfg->AutoExposure = val[13];
|
||||||
|
cfg->MaskEnabled = val[14];
|
||||||
|
cfg->MaskThreshold = (int16_t)qdx_read_u16_le(val + 15);
|
||||||
|
cfg->MaskWidth = qdx_read_u16_le(val + 17);
|
||||||
|
cfg->MaskHeight = qdx_read_u16_le(val + 19);
|
||||||
|
cfg->Angle = (int16_t)qdx_read_u16_le(val + 21);
|
||||||
|
cfg->TargetWidth = qdx_read_u16_le(val + 23);
|
||||||
|
cfg->TargetHeight = qdx_read_u16_le(val + 25);
|
||||||
|
cfg->TriggerMode = val[27];
|
||||||
|
cfg->TriggerGpioLine = val[28];
|
||||||
|
cfg->TriggerDelayMs = qdx_read_u16_le(val + 29);
|
||||||
|
cfg->TriggerBurstCount = val[31];
|
||||||
|
cfg->TriggerInternalIntervalMs = qdx_read_u16_le(val + 32);
|
||||||
|
cfg->TriggerTemperatureThreshold = (int16_t)qdx_read_u16_le(val + 34);
|
||||||
|
cfg->TriggerDebounceIntervalMs = qdx_read_u16_le(val + 36);
|
||||||
|
cfg->TriggerCondition = val[38];
|
||||||
|
cfg->TriggerRoiX = qdx_read_u16_le(val + 39);
|
||||||
|
cfg->TriggerRoiY = qdx_read_u16_le(val + 41);
|
||||||
|
cfg->TriggerRoiW = qdx_read_u16_le(val + 43);
|
||||||
|
cfg->TriggerRoiH = qdx_read_u16_le(val + 45);
|
||||||
|
cfg->NGioDelay = qdx_read_u16_le(val + 47);
|
||||||
|
cfg->OutputGpioLine = val[49];
|
||||||
|
cfg->AlarmGpioLine = val[50];
|
||||||
|
cfg->AlarmHoldMs = qdx_read_u16_le(val + 51);
|
||||||
|
cfg->StoreNgImagesOnly = val[53];
|
||||||
|
cfg->TrainingEnabled = val[54];
|
||||||
|
cfg->TrainingSampleThreshold = qdx_read_u16_le(val + 55);
|
||||||
|
cfg->ProcessingTimeoutMs = qdx_read_u16_le(val + 57);
|
||||||
|
cfg->MaxProcessingQueueSize = val[59];
|
||||||
|
cfg->Reserved = val[60];
|
||||||
|
}
|
||||||
|
|
||||||
|
static void qdx_deserialize_config1d(Config1D_t *cfg, const uint8_t *val) {
|
||||||
|
cfg->Enabled = val[0];
|
||||||
|
cfg->RunMode = val[1];
|
||||||
|
cfg->TriggerType = val[2];
|
||||||
|
cfg->BufferSize = qdx_read_u16_le(val + 3);
|
||||||
|
cfg->TriggerTempLimit = (int16_t)qdx_read_u16_le(val + 5);
|
||||||
|
cfg->StartPointsToRemove = qdx_read_u16_le(val + 7);
|
||||||
|
cfg->ReferenceLength = qdx_read_u16_le(val + 9);
|
||||||
|
cfg->HighTimerLimit = qdx_read_u16_le(val + 11);
|
||||||
|
cfg->TimerCLimit = qdx_read_u16_le(val + 13);
|
||||||
|
cfg->NgCountLimit = val[15];
|
||||||
|
cfg->LSizeStart = qdx_read_u16_le(val + 16);
|
||||||
|
cfg->RSizeStart = qdx_read_u16_le(val + 18);
|
||||||
|
cfg->NGioDelay = qdx_read_u16_le(val + 20);
|
||||||
|
cfg->OutputGpioLine = val[22];
|
||||||
|
cfg->AlarmGpioLine = val[23];
|
||||||
|
cfg->AlarmHoldMs = qdx_read_u16_le(val + 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void parse_and_dispatch_tlv(TcpStreamCtx_t *ctx, const uint8_t *packet,
|
||||||
|
uint16_t pkt_len) {
|
||||||
|
uint16_t hdr_seq = qdx_read_u16_le(packet + 5);
|
||||||
|
uint8_t hdr_flags = packet[15];
|
||||||
|
|
||||||
|
/* TLV Data starts after header (16 bytes) */
|
||||||
|
int offset = HEADER_SIZE;
|
||||||
|
int payload_len = pkt_len - HEADER_SIZE - CRC_SIZE;
|
||||||
|
int parsed_len = 0;
|
||||||
|
|
||||||
|
uint8_t cfg_updated = 0;
|
||||||
|
|
||||||
|
DBG_HB("[%s] TLV pkt: Seq=%d Len=%d\r\n", ctx->label,
|
||||||
|
hdr_seq, payload_len);
|
||||||
|
|
||||||
|
while (parsed_len <= payload_len - 3) {
|
||||||
|
uint8_t type = packet[offset];
|
||||||
|
uint16_t len = qdx_read_u16_le(packet + offset + 1);
|
||||||
|
|
||||||
|
DBG_HB("[%s] TLV: Type=0x%02X Len=%d\r\n", ctx->label, type, len);
|
||||||
|
|
||||||
|
if (parsed_len + 3 + len > payload_len) {
|
||||||
|
DBG_ERR("[%s] TLV truncated (need %d, have %d)\r\n",
|
||||||
|
ctx->label, len, payload_len - parsed_len - 3);
|
||||||
|
break; /* Malformed */
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *value = packet + offset + 3;
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case TYPE_HEARTBEAT: {
|
||||||
|
/* Server heartbeat response — update activity timestamp */
|
||||||
|
ctx->last_activity_ms = qdx_port_get_tick_ms();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_ACK_PAYLOAD: {
|
||||||
|
if (len >= 3) {
|
||||||
|
uint16_t ack_seq = qdx_read_u16_le(value);
|
||||||
|
uint8_t status = value[2];
|
||||||
|
uint16_t err_code = (len >= 5) ? qdx_read_u16_le(value + 3) : 0;
|
||||||
|
DBG_CFG("<< ACK: seq=%d status=%d err=0x%04x\r\n",
|
||||||
|
(int)ack_seq, (int)status, (int)err_code);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_DEVID_ASSIGN: {
|
||||||
|
if (len >= sizeof(DevIDAssignment_t)) {
|
||||||
|
uint16_t new_id = qdx_read_u16_le(value);
|
||||||
|
DBG_CFG("<< DevID assigned: %d -> %d\r\n",
|
||||||
|
(int)g_TcpLogic.dev_id, (int)new_id);
|
||||||
|
g_TcpLogic.pending_new_dev_id = new_id;
|
||||||
|
tcp_send_ack(ctx, hdr_seq, 0, 0);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_CONFIG_COMMON: {
|
||||||
|
if (len >= sizeof(ConfigCommon_t)) {
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
qdx_deserialize_config_common(&g_TcpLogic.cached_common, value);
|
||||||
|
g_TcpLogic.has_valid_config = 1;
|
||||||
|
cfg_updated = 1;
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
DBG_CFG("<< ConfigCommon: Mode=%d Tag=%d Strict=%d\r\n",
|
||||||
|
(int)g_TcpLogic.cached_common.WorkMode,
|
||||||
|
(int)g_TcpLogic.cached_common.ConfigTag,
|
||||||
|
(int)g_TcpLogic.cached_common.StrictnessLevel);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_CONFIG_2D: {
|
||||||
|
if (len >= sizeof(Config2D_t)) {
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
qdx_deserialize_config2d(&g_TcpLogic.cached_cfg2d, value);
|
||||||
|
g_TcpLogic.has_valid_config = 1;
|
||||||
|
cfg_updated = 1;
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
DBG_CFG("<< Config2D: En=%d %dx%d Tgt=%dx%d Fps=%d "
|
||||||
|
"Trig=%d Burst=%d Intv=%d Thresh=%d "
|
||||||
|
"ROI(%d,%d,%d,%d) NGio=%d\r\n",
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.Enabled,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.Width,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.Height,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TargetWidth,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TargetHeight,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.Fps,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerMode,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerBurstCount,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerInternalIntervalMs,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerTemperatureThreshold,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerRoiX,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerRoiY,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerRoiW,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.TriggerRoiH,
|
||||||
|
(int)g_TcpLogic.cached_cfg2d.NGioDelay);
|
||||||
|
} else {
|
||||||
|
DBG_ERR("<< Config2D bad len=%d (need %d)\r\n",
|
||||||
|
len, (int)sizeof(Config2D_t));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_CONFIG_1D: {
|
||||||
|
if (len >= sizeof(Config1D_t)) {
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
qdx_deserialize_config1d(&g_TcpLogic.cached_cfg1d, value);
|
||||||
|
g_TcpLogic.has_valid_config = 1;
|
||||||
|
cfg_updated = 1;
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
DBG_CFG("<< Config1D: En=%d RunMode=%d TrigType=%d "
|
||||||
|
"BufSz=%d TempLim=%d L=%d R=%d NGio=%d\r\n",
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.Enabled,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.RunMode,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.TriggerType,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.BufferSize,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.TriggerTempLimit,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.LSizeStart,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.RSizeStart,
|
||||||
|
(int)g_TcpLogic.cached_cfg1d.NGioDelay);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_TEMP_FRAME: {
|
||||||
|
DBG_CFG("<< TempFrame request (len=%d)\r\n", (int)len);
|
||||||
|
if (g_TcpLogic.temp_req_cb) {
|
||||||
|
uint8_t is2d = 0;
|
||||||
|
if (len >= 18) {
|
||||||
|
is2d = value[18];
|
||||||
|
}
|
||||||
|
DBG_CFG(" -> callback: is2D=%d\r\n", (int)is2d);
|
||||||
|
g_TcpLogic.temp_req_cb(is2d);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_DETECTION_RESULT: {
|
||||||
|
if (len >= sizeof(DetectionResult_t)) {
|
||||||
|
uint32_t frame_num = qdx_read_u32_le(value);
|
||||||
|
uint8_t result_status = value[4];
|
||||||
|
DBG_CFG("<< DetectionResult: frm=%d result=%d\r\n",
|
||||||
|
(int)frame_num, (int)result_status);
|
||||||
|
if (g_TcpLogic.detect_cb)
|
||||||
|
g_TcpLogic.detect_cb(frame_num, result_status);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case TYPE_HANDSHAKE:
|
||||||
|
/* Server echoes handshake info — safe to ignore */
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
DBG_ERR("Unknown TLV type=0x%02x len=%d\r\n", (int)type, (int)len);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
offset += (3 + len);
|
||||||
|
parsed_len += (3 + len);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cfg_updated && g_TcpLogic.config_cb && g_TcpLogic.has_valid_config) {
|
||||||
|
DBG_CFG("Config updated -> notify app\r\n");
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
g_TcpLogic.config_cb(&g_TcpLogic.cached_common, &g_TcpLogic.cached_cfg2d,
|
||||||
|
&g_TcpLogic.cached_cfg1d);
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hdr_flags & FLAG_ACK_REQ) {
|
||||||
|
tcp_send_ack(ctx, hdr_seq, 0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void tcp_process_rx_buffer(TcpStreamCtx_t *ctx) {
|
||||||
|
while (ctx->recv_len >= HEADER_SIZE) {
|
||||||
|
/* 1. Search for Magic 0x55AA */
|
||||||
|
int start_idx = -1;
|
||||||
|
for (uint32_t i = 0; i <= ctx->recv_len - 2; i++) {
|
||||||
|
if (ctx->recv_buffer[i] == 0xAA && ctx->recv_buffer[i + 1] == 0x55) {
|
||||||
|
start_idx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start_idx == -1) {
|
||||||
|
ctx->recv_buffer[0] = ctx->recv_buffer[ctx->recv_len - 1];
|
||||||
|
ctx->recv_len = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start_idx > 0) {
|
||||||
|
/* 缓冲区内部左移,源与目标重叠,必须使用 memmove */
|
||||||
|
memmove(ctx->recv_buffer, ctx->recv_buffer + start_idx,
|
||||||
|
ctx->recv_len - start_idx);
|
||||||
|
ctx->recv_len -= start_idx;
|
||||||
|
if (ctx->recv_len < HEADER_SIZE)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t version = ctx->recv_buffer[2];
|
||||||
|
uint16_t length = qdx_read_u16_le(ctx->recv_buffer + 3);
|
||||||
|
|
||||||
|
if (version != PROTO_VERSION || length < HEADER_SIZE + CRC_SIZE) {
|
||||||
|
DBG_ERR("[%s] bad header: ver=0x%02X(exp 0x%02X) len=%d\r\n",
|
||||||
|
ctx->label, version, PROTO_VERSION, length);
|
||||||
|
memmove(ctx->recv_buffer, ctx->recv_buffer + 2, ctx->recv_len - 2);
|
||||||
|
ctx->recv_len -= 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (length > sizeof(ctx->recv_buffer)) {
|
||||||
|
DBG_ERR("[%s] frame too large: %d > %d\r\n", ctx->label,
|
||||||
|
length, (int)sizeof(ctx->recv_buffer));
|
||||||
|
ctx->recv_len = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->recv_len < length) {
|
||||||
|
break; /* Need more data */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 2. Validate CRC */
|
||||||
|
uint16_t received_crc = qdx_read_u16_le(ctx->recv_buffer + length - 2);
|
||||||
|
uint16_t calculated_crc = qdx_crc16_modbus(ctx->recv_buffer, length - 2);
|
||||||
|
|
||||||
|
if (received_crc == calculated_crc) {
|
||||||
|
/* 3. Dispatch */
|
||||||
|
parse_and_dispatch_tlv(ctx, ctx->recv_buffer, length);
|
||||||
|
} else {
|
||||||
|
DBG_ERR("[%s] CRC fail: calc=0x%04X recv=0x%04X len=%d\r\n",
|
||||||
|
ctx->label, calculated_crc, received_crc, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 4. 移除已处理帧(缓冲区内部左移,必须 memmove) */
|
||||||
|
memmove(ctx->recv_buffer, ctx->recv_buffer + length,
|
||||||
|
ctx->recv_len - length);
|
||||||
|
ctx->recv_len -= length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void recv_thread_entry(void *arg) {
|
||||||
|
TcpStreamCtx_t *ctx = (TcpStreamCtx_t *)arg;
|
||||||
|
|
||||||
|
while (ctx->is_running) {
|
||||||
|
if (!ctx->is_connected) {
|
||||||
|
qdx_port_delay_ms(100);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Leave space for maximum TCP MTU read */
|
||||||
|
if (sizeof(ctx->recv_buffer) - ctx->recv_len > 0) {
|
||||||
|
int32_t bytes =
|
||||||
|
qdx_port_tcp_recv(ctx->sock, ctx->recv_buffer + ctx->recv_len,
|
||||||
|
sizeof(ctx->recv_buffer) - ctx->recv_len);
|
||||||
|
|
||||||
|
if (bytes > 0) {
|
||||||
|
ctx->recv_len += bytes;
|
||||||
|
ctx->last_activity_ms = qdx_port_get_tick_ms();
|
||||||
|
tcp_process_rx_buffer(ctx);
|
||||||
|
} else if (bytes < 0) {
|
||||||
|
/* Disconnected / Error */
|
||||||
|
tcp_stream_disconnect(ctx);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
/* Buffer completely full but no valid packet found. Prevent overflow
|
||||||
|
* lock. */
|
||||||
|
ctx->recv_len = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
qdx_port_delay_ms(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Main Background Manager
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
static void manager_thread_entry(void *arg) {
|
||||||
|
while (1) {
|
||||||
|
uint32_t now = qdx_port_get_tick_ms();
|
||||||
|
|
||||||
|
/* DevID Reassignment Handling */
|
||||||
|
if (g_TcpLogic.pending_new_dev_id >= 0) {
|
||||||
|
g_TcpLogic.dev_id = (uint16_t)g_TcpLogic.pending_new_dev_id;
|
||||||
|
g_TcpLogic.pending_new_dev_id = -1;
|
||||||
|
|
||||||
|
tcp_stream_disconnect(&g_TcpLogic.control_stream);
|
||||||
|
tcp_stream_disconnect(&g_TcpLogic.data_stream);
|
||||||
|
|
||||||
|
g_TcpLogic.control_stream.last_reconnect_ms = 0;
|
||||||
|
g_TcpLogic.data_stream.last_reconnect_ms = 0;
|
||||||
|
qdx_port_delay_ms(500);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Connection Management: Control Stream */
|
||||||
|
if (!g_TcpLogic.control_stream.is_connected) {
|
||||||
|
if (now - g_TcpLogic.control_stream.last_reconnect_ms >
|
||||||
|
RECONNECT_DELAY_MS) {
|
||||||
|
if (tcp_stream_connect(&g_TcpLogic.control_stream, SERVER_IP,
|
||||||
|
CONTROL_PORT) == 0) {
|
||||||
|
tcp_send_handshake(&g_TcpLogic.control_stream);
|
||||||
|
}
|
||||||
|
g_TcpLogic.control_stream.last_reconnect_ms = qdx_port_get_tick_ms();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Connection Management: Data Stream */
|
||||||
|
if (!g_TcpLogic.data_stream.is_connected) {
|
||||||
|
if (now - g_TcpLogic.data_stream.last_reconnect_ms > RECONNECT_DELAY_MS) {
|
||||||
|
if (tcp_stream_connect(&g_TcpLogic.data_stream, SERVER_IP, DATA_PORT) ==
|
||||||
|
0) {
|
||||||
|
tcp_send_handshake(&g_TcpLogic.data_stream);
|
||||||
|
}
|
||||||
|
g_TcpLogic.data_stream.last_reconnect_ms = qdx_port_get_tick_ms();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Heartbeat & Timeout checks */
|
||||||
|
if (g_TcpLogic.control_stream.is_connected) {
|
||||||
|
if (now - g_TcpLogic.control_stream.last_heartbeat_ms >
|
||||||
|
HEARTBEAT_INTERVAL_MS) {
|
||||||
|
tcp_send_heartbeat(&g_TcpLogic.control_stream);
|
||||||
|
g_TcpLogic.control_stream.last_heartbeat_ms = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_TcpLogic.data_stream.is_connected) {
|
||||||
|
if (now - g_TcpLogic.data_stream.last_heartbeat_ms >
|
||||||
|
HEARTBEAT_INTERVAL_MS) {
|
||||||
|
tcp_send_heartbeat(&g_TcpLogic.data_stream);
|
||||||
|
g_TcpLogic.data_stream.last_heartbeat_ms = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
qdx_port_delay_ms(100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Public API Implementations
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
int8_t TcpLogic_Init(const uint8_t *deviceUUID, const uint8_t *authToken) {
|
||||||
|
memset(&g_TcpLogic, 0, sizeof(g_TcpLogic));
|
||||||
|
|
||||||
|
if (deviceUUID)
|
||||||
|
memcpy(g_TcpLogic.uuid, deviceUUID, 16);
|
||||||
|
if (authToken)
|
||||||
|
memcpy(g_TcpLogic.auth_token, authToken, 16);
|
||||||
|
|
||||||
|
/* Default DevID = 101 */
|
||||||
|
g_TcpLogic.dev_id = 101;
|
||||||
|
g_TcpLogic.pending_new_dev_id = -1;
|
||||||
|
|
||||||
|
g_TcpLogic.config_mutex = qdx_port_mutex_create();
|
||||||
|
if (g_TcpLogic.config_mutex == NULL)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
tcp_stream_init(&g_TcpLogic.control_stream, "Control");
|
||||||
|
tcp_stream_init(&g_TcpLogic.data_stream, "Data");
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TcpLogic_Start(void) {
|
||||||
|
g_TcpLogic.control_stream.is_running = 1;
|
||||||
|
g_TcpLogic.data_stream.is_running = 1;
|
||||||
|
|
||||||
|
qdx_port_thread_create("tcp_mgr", manager_thread_entry, NULL, 2048, 3);
|
||||||
|
qdx_port_thread_create("tcp_rx_c", recv_thread_entry,
|
||||||
|
&g_TcpLogic.control_stream, 2048, 4);
|
||||||
|
qdx_port_thread_create("tcp_rx_d", recv_thread_entry, &g_TcpLogic.data_stream,
|
||||||
|
2048, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
int8_t TcpLogic_GetLatestConfig(ConfigCommon_t *out_common,
|
||||||
|
Config2D_t *out_cfg2d, Config1D_t *out_cfg1d) {
|
||||||
|
if (!out_common || !out_cfg2d || !out_cfg1d)
|
||||||
|
return -2;
|
||||||
|
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
if (!g_TcpLogic.has_valid_config) {
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(out_common, &g_TcpLogic.cached_common, sizeof(ConfigCommon_t));
|
||||||
|
memcpy(out_cfg2d, &g_TcpLogic.cached_cfg2d, sizeof(Config2D_t));
|
||||||
|
memcpy(out_cfg1d, &g_TcpLogic.cached_cfg1d, sizeof(Config1D_t));
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TcpLogic_RegisterConfigCallback(ConfigUpdateCallback_t cb) {
|
||||||
|
g_TcpLogic.config_cb = cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TcpLogic_RegisterDetectionCallback(DetectionResultCallback_t cb) {
|
||||||
|
g_TcpLogic.detect_cb = cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TcpLogic_RegisterTempFrameRequestCallback(TempFrameRequestCallback_t cb) {
|
||||||
|
g_TcpLogic.temp_req_cb = cb;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TcpLogic_InjectTestConfig(const ConfigCommon_t *common,
|
||||||
|
const Config2D_t *cfg2d,
|
||||||
|
const Config1D_t *cfg1d) {
|
||||||
|
qdx_port_mutex_lock(g_TcpLogic.config_mutex);
|
||||||
|
if (common) memcpy(&g_TcpLogic.cached_common, common, sizeof(*common));
|
||||||
|
if (cfg2d) memcpy(&g_TcpLogic.cached_cfg2d, cfg2d, sizeof(*cfg2d));
|
||||||
|
if (cfg1d) memcpy(&g_TcpLogic.cached_cfg1d, cfg1d, sizeof(*cfg1d));
|
||||||
|
g_TcpLogic.has_valid_config = 1;
|
||||||
|
qdx_port_mutex_unlock(g_TcpLogic.config_mutex);
|
||||||
|
if (g_TcpLogic.config_cb) {
|
||||||
|
g_TcpLogic.config_cb(&g_TcpLogic.cached_common,
|
||||||
|
&g_TcpLogic.cached_cfg2d,
|
||||||
|
&g_TcpLogic.cached_cfg1d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
* Zero-Copy Frame Building & Fragmentation for Temperature Data
|
||||||
|
* ============================================================ */
|
||||||
|
|
||||||
|
int8_t
|
||||||
|
TcpLogic_BuildAndSendTemperatureFrame(TcpTxBuffer_t *io_buffer,
|
||||||
|
const PreprocessResult_t *processMeta,
|
||||||
|
uint8_t frameType, uint8_t is2D) {
|
||||||
|
|
||||||
|
if (!g_TcpLogic.data_stream.is_connected || !io_buffer || !processMeta)
|
||||||
|
return -1;
|
||||||
|
if (io_buffer->ValidPayloadLen == 0)
|
||||||
|
return -2;
|
||||||
|
|
||||||
|
g_TcpLogic.frame_count++;
|
||||||
|
|
||||||
|
DBG_DATA(">> TempFrame #%d: %dx%d type=%d is2D=%d payload=%d\r\n",
|
||||||
|
(int)processMeta->FrameNumber,
|
||||||
|
(int)processMeta->ValidWidth, (int)processMeta->ValidHeight,
|
||||||
|
(int)frameType, (int)is2D, (int)io_buffer->ValidPayloadLen);
|
||||||
|
|
||||||
|
/* We need to prepend: TLV Header (3) + TemperatureFrameHeader_t (18) */
|
||||||
|
uint32_t tlv_wrapper_len = TLV_HEADER_SIZE + sizeof(TemperatureFrameHeader_t);
|
||||||
|
|
||||||
|
/* Ensure application left enough head room */
|
||||||
|
if (io_buffer->HeadOffset < HEADER_SIZE + tlv_wrapper_len) {
|
||||||
|
return -3; /* Not enough offset space allocated by user memory pool */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Start writing right before the application payload */
|
||||||
|
uint8_t *tlv_start =
|
||||||
|
io_buffer->pBuffer + io_buffer->HeadOffset - tlv_wrapper_len;
|
||||||
|
|
||||||
|
/* 1. Fill TLV Header manually via shift */
|
||||||
|
uint32_t tlv_value_len =
|
||||||
|
sizeof(TemperatureFrameHeader_t) + io_buffer->ValidPayloadLen;
|
||||||
|
tlv_start[0] = TYPE_TEMP_FRAME;
|
||||||
|
qdx_write_u16_le(tlv_start + 1, (uint16_t)tlv_value_len);
|
||||||
|
|
||||||
|
/* 2. Fill TemperatureFrameHeader manually via shift to avoid alignment
|
||||||
|
* faults
|
||||||
|
*/
|
||||||
|
uint8_t *temp_hdr = tlv_start + TLV_HEADER_SIZE;
|
||||||
|
qdx_write_u32_le(temp_hdr + 0, processMeta->FrameNumber);
|
||||||
|
qdx_write_u16_le(temp_hdr + 4, processMeta->ValidWidth);
|
||||||
|
qdx_write_u16_le(temp_hdr + 6, processMeta->ValidHeight);
|
||||||
|
qdx_write_u16_le(temp_hdr + 8, (uint16_t)processMeta->MinTemp);
|
||||||
|
qdx_write_u16_le(temp_hdr + 10, (uint16_t)processMeta->MaxTemp);
|
||||||
|
qdx_write_u16_le(temp_hdr + 12, (uint16_t)processMeta->AvgTemp);
|
||||||
|
qdx_write_u16_le(temp_hdr + 14, (uint16_t)processMeta->RoiTemp);
|
||||||
|
temp_hdr[16] = frameType;
|
||||||
|
temp_hdr[17] = processMeta->Status;
|
||||||
|
temp_hdr[18] = is2D;
|
||||||
|
temp_hdr[19] = 0; /* Reserved */
|
||||||
|
|
||||||
|
/* Total payload length is the entire TLV block */
|
||||||
|
uint32_t total_tlv_len = TLV_HEADER_SIZE + tlv_value_len;
|
||||||
|
|
||||||
|
/* 3. Handle Fragmentation if necessary */
|
||||||
|
if (total_tlv_len <= MAX_FRAGMENT_PAYLOAD) {
|
||||||
|
/* No fragmentation needed, build frame in place at the front */
|
||||||
|
uint8_t *frame_start = tlv_start - HEADER_SIZE;
|
||||||
|
uint16_t seq = g_TcpLogic.data_stream.sequence++;
|
||||||
|
|
||||||
|
int final_len = qdx_build_frame_inplace(
|
||||||
|
frame_start, CLASS_DATA, (uint16_t)total_tlv_len, g_TcpLogic.dev_id,
|
||||||
|
seq, qdx_port_get_tick_ms(), 0);
|
||||||
|
|
||||||
|
int32_t sent =
|
||||||
|
qdx_port_tcp_send(g_TcpLogic.data_stream.sock, frame_start, final_len);
|
||||||
|
return (sent >= 0) ? 0 : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fragmentation required.
|
||||||
|
Note: For zero-copy fragmentation, we send piece by piece.
|
||||||
|
We need an external buffer for each piece's frame header + CRC.
|
||||||
|
We can't easily prepend headers to later fragments inline. */
|
||||||
|
|
||||||
|
uint32_t offset = 0;
|
||||||
|
static uint8_t frag_buf[HEADER_SIZE + MAX_FRAGMENT_PAYLOAD + CRC_SIZE];
|
||||||
|
uint32_t frag_count =
|
||||||
|
(total_tlv_len + MAX_FRAGMENT_PAYLOAD - 1) / MAX_FRAGMENT_PAYLOAD;
|
||||||
|
|
||||||
|
DBG_DATA(">> Fragmented: %d frags, total=%d\r\n",
|
||||||
|
(int)frag_count, (int)total_tlv_len);
|
||||||
|
|
||||||
|
for (uint32_t i = 0; i < frag_count; i++) {
|
||||||
|
uint32_t chunk_len = total_tlv_len - offset;
|
||||||
|
if (chunk_len > MAX_FRAGMENT_PAYLOAD)
|
||||||
|
chunk_len = MAX_FRAGMENT_PAYLOAD;
|
||||||
|
|
||||||
|
uint8_t flags = (i == frag_count - 1) ? FLAG_LAST_FRAGMENT : 0;
|
||||||
|
uint16_t seq = g_TcpLogic.data_stream.sequence++;
|
||||||
|
|
||||||
|
/* We copy the chunk into frag_buf to append Header/CRC.
|
||||||
|
This involves ONE copy of the chunk, but it's small (1400 bytes at a
|
||||||
|
time), and ensures we don't need additional memory pools. */
|
||||||
|
int frame_len = qdx_build_fragment_frame(
|
||||||
|
frag_buf, CLASS_DATA, tlv_start + offset, (uint16_t)chunk_len,
|
||||||
|
g_TcpLogic.dev_id, seq, qdx_port_get_tick_ms(), flags);
|
||||||
|
|
||||||
|
int32_t sent =
|
||||||
|
qdx_port_tcp_send(g_TcpLogic.data_stream.sock, frag_buf, frame_len);
|
||||||
|
if (sent < 0) {
|
||||||
|
tcp_stream_disconnect(&g_TcpLogic.data_stream);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
offset += chunk_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/**
|
||||||
|
* @file qdx_tcp_logic.h
|
||||||
|
* @brief Zero-Copy TCP Network Logic and State Machine tailored for MCU
|
||||||
|
*
|
||||||
|
* Implements connection management (Dual Stream 5511/5512),
|
||||||
|
* packet handling, heartbeating, config caching, and callbacks.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef QDX_TCP_LOGIC_H
|
||||||
|
#define QDX_TCP_LOGIC_H
|
||||||
|
|
||||||
|
#include "qdx_protocol.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize the TCP logic module
|
||||||
|
*
|
||||||
|
* @param deviceUUID Provide standard UUID for the device.
|
||||||
|
* @param authToken Optional auth token for connections.
|
||||||
|
* @return 0 on success, < 0 on failure.
|
||||||
|
*/
|
||||||
|
int8_t TcpLogic_Init(const uint8_t *deviceUUID, const uint8_t *authToken);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Wait for and start non-blocking network connection attempts.
|
||||||
|
*
|
||||||
|
* It will spawn background threads for Control and Data streams
|
||||||
|
* connecting to the server.
|
||||||
|
*/
|
||||||
|
void TcpLogic_Start(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Encapsulate and send a temperature frame without generic memory copy.
|
||||||
|
*
|
||||||
|
* Uses the pre-filled `TcpTxBuffer_t` (containing image array) to prepend
|
||||||
|
* the required nested headers directly into the buffer offset.
|
||||||
|
*
|
||||||
|
* @param io_buffer The user-allocated buffer containing Image payload starting
|
||||||
|
* at HeadOffset
|
||||||
|
* @param processMeta Real-time analysis metadata for the image data
|
||||||
|
* @param frameType Frame type: 0=LIVE, 1=TRIGGER, 2=MASKED
|
||||||
|
* @param is2D 1 for 2D matrix, 0 for 1D array
|
||||||
|
* @return 0 successfully sent to transmission queue, < 0 if failed
|
||||||
|
*/
|
||||||
|
int8_t
|
||||||
|
TcpLogic_BuildAndSendTemperatureFrame(TcpTxBuffer_t *io_buffer,
|
||||||
|
const PreprocessResult_t *processMeta,
|
||||||
|
uint8_t frameType, uint8_t is2D);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Retrieves a distinct copy of the latest active configuration
|
||||||
|
* structure.
|
||||||
|
*
|
||||||
|
* Recommended for safe reads of configuration during offline or fallback
|
||||||
|
* scenarios. Requires pointers to pre-allocated Config* structures.
|
||||||
|
*
|
||||||
|
* @param out_common Required pointer to common config structure.
|
||||||
|
* @param out_cfg2d Required pointer to 2d config structure.
|
||||||
|
* @param out_cfg1d Required pointer to 1d config structure.
|
||||||
|
* @return 0 on success, -1 if no configuration has been stored or received.
|
||||||
|
*/
|
||||||
|
int8_t TcpLogic_GetLatestConfig(ConfigCommon_t *out_common,
|
||||||
|
Config2D_t *out_cfg2d, Config1D_t *out_cfg1d);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Register configuration parsing event callback.
|
||||||
|
*
|
||||||
|
* Fired immediately after the host sends a Configuration payload and it is
|
||||||
|
* safely cached to the internal registers.
|
||||||
|
*
|
||||||
|
* @param cb Callable function matching the interface
|
||||||
|
*/
|
||||||
|
void TcpLogic_RegisterConfigCallback(ConfigUpdateCallback_t cb);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Register remote decision consequence callback (e.g. Reject / Ok
|
||||||
|
* processing result).
|
||||||
|
*
|
||||||
|
* Fired shortly after the host finishes processing a sent 2D or 1D target
|
||||||
|
* frame.
|
||||||
|
*
|
||||||
|
* @param cb Callable function matching the interface
|
||||||
|
*/
|
||||||
|
void TcpLogic_RegisterDetectionCallback(DetectionResultCallback_t cb);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Callback for when host requests a temperature frame.
|
||||||
|
*
|
||||||
|
* Fired when the host sends a TYPE_TEMP_FRAME request (typically empty or
|
||||||
|
* carrying trigger context). The device should capture an image and reply by
|
||||||
|
* calling TcpLogic_BuildAndSendTemperatureFrame.
|
||||||
|
*
|
||||||
|
* @param is2dRequest Non-zero if request is specifically for 2D frame, zero if
|
||||||
|
* for 1D.
|
||||||
|
*/
|
||||||
|
typedef void (*TempFrameRequestCallback_t)(uint8_t is2dRequest);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Register host temperature frame request callback.
|
||||||
|
*
|
||||||
|
* @param cb Callable function matching the interface
|
||||||
|
*/
|
||||||
|
void TcpLogic_RegisterTempFrameRequestCallback(TempFrameRequestCallback_t cb);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Inject configuration directly (for test mode without server).
|
||||||
|
*
|
||||||
|
* Sets the internal config cache and fires the config callback.
|
||||||
|
* Only non-NULL parameters are updated.
|
||||||
|
*/
|
||||||
|
void TcpLogic_InjectTestConfig(const ConfigCommon_t *common,
|
||||||
|
const Config2D_t *cfg2d,
|
||||||
|
const Config1D_t *cfg1d);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* QDX_TCP_LOGIC_H */
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
/********************************** (C) COPYRIGHT ************* ******************
|
||||||
|
* File Name : eth_driver.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.3.0
|
||||||
|
* Date : 2022/06/02
|
||||||
|
* Description : This file contains the headers of the ETH Driver.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __ETH_DRIVER__
|
||||||
|
#define __ETH_DRIVER__
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "debug.h"
|
||||||
|
#include "wchnet.h"
|
||||||
|
|
||||||
|
/* 1: interrupt 0: polling in RMII or RGMII mode */
|
||||||
|
#define LINK_STAT_ACQUISITION_METHOD 0
|
||||||
|
|
||||||
|
#define PHY_ADDRESS 1
|
||||||
|
|
||||||
|
#define ETH_DMARxDesc_FrameLengthShift 16
|
||||||
|
|
||||||
|
#define ROM_CFG_USERADR_ID 0x1FFFF7E8
|
||||||
|
|
||||||
|
#define PHY_LINK_TASK_PERIOD 50
|
||||||
|
|
||||||
|
#define PHY_ANLPAR_SELECTOR_FIELD 0x1F
|
||||||
|
#define PHY_ANLPAR_SELECTOR_VALUE 0x01 /* 5B'00001 */
|
||||||
|
|
||||||
|
#define PHY_LINK_INIT 0x00
|
||||||
|
#define PHY_LINK_SUC_P (1<<0)
|
||||||
|
#define PHY_LINK_SUC_N (1<<1)
|
||||||
|
#define PHY_LINK_WAIT_SUC (1<<7)
|
||||||
|
|
||||||
|
#define PHY_PN_SWITCH_P (0<<2)
|
||||||
|
#define PHY_PN_SWITCH_N (1<<2)
|
||||||
|
#define PHY_PN_SWITCH_AUTO (2<<2)
|
||||||
|
|
||||||
|
#ifndef WCHNETTIMERPERIOD
|
||||||
|
#define WCHNETTIMERPERIOD 10 /* Timer period, in Ms. */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define GPIO_Output(a,b) \
|
||||||
|
GPIO_InitStructure.GPIO_Pin = b;\
|
||||||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;\
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;\
|
||||||
|
GPIO_Init(a, &GPIO_InitStructure)
|
||||||
|
|
||||||
|
#define GPIO_Input(a,b) \
|
||||||
|
GPIO_InitStructure.GPIO_Pin = b;\
|
||||||
|
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;\
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;\
|
||||||
|
GPIO_Init(a, &GPIO_InitStructure)
|
||||||
|
|
||||||
|
#define QUERY_STAT_FLAG ((LastQueryPhyTime == (LocalTime / 1000)) ? 0 : 1)
|
||||||
|
|
||||||
|
#define ACCELERATE_LINK_PROCESS() do{\
|
||||||
|
if((TRDetectStep < 2) && (ETH_ReadPHYRegister(gPHYAddress, PHY_ANLPAR) & PHY_ANLPAR_SELECTOR_FIELD))\
|
||||||
|
LinkTaskPeriod = 0;\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define UPDATE_LINKTASKPERIOD() do{\
|
||||||
|
if(TRDetectStep == 1)\
|
||||||
|
{\
|
||||||
|
RandVal = RandVal * 214017 + 2531017;\
|
||||||
|
LinkTaskPeriod = RandVal%100 + 50;\
|
||||||
|
}\
|
||||||
|
else {\
|
||||||
|
LinkTaskPeriod = 50;\
|
||||||
|
}\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_RESTART_AUTONEGOTIATION() do{\
|
||||||
|
RegVal = ETH_ReadPHYRegister(gPHYAddress, PHY_BCR);\
|
||||||
|
RegVal &= ~0x01;\
|
||||||
|
RegVal |= PHY_Restart_AutoNegotiation;\
|
||||||
|
ETH_WritePHYRegister( gPHYAddress, PHY_BCR, RegVal);\
|
||||||
|
RegVal = ETH_ReadPHYRegister(gPHYAddress, PHY_BCR);\
|
||||||
|
RegVal |= 0x03 | PHY_Restart_AutoNegotiation;\
|
||||||
|
ETH_WritePHYRegister( gPHYAddress, PHY_BCR, RegVal);\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_TR_SWITCH() do{\
|
||||||
|
phy_mdix = ETH_ReadPHYRegister(gPHYAddress, PHY_MDIX);\
|
||||||
|
if(phy_mdix & 0x01)\
|
||||||
|
{\
|
||||||
|
phy_mdix &= ~0x03;\
|
||||||
|
phy_mdix |= 1 << 1;\
|
||||||
|
}\
|
||||||
|
else\
|
||||||
|
{\
|
||||||
|
phy_mdix &= ~0x03;\
|
||||||
|
phy_mdix |= 1 << 0;\
|
||||||
|
}\
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, phy_mdix);\
|
||||||
|
PHY_RESTART_AUTONEGOTIATION();\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_TR_REVERSE() do{\
|
||||||
|
if(phyStatus)\
|
||||||
|
{\
|
||||||
|
RegVal = ETH_ReadPHYRegister(gPHYAddress, PHY_MDIX);\
|
||||||
|
if(RegVal & 0x01)\
|
||||||
|
{\
|
||||||
|
RegVal &= ~0x03;\
|
||||||
|
RegVal |= 1 << 1;\
|
||||||
|
}\
|
||||||
|
else{\
|
||||||
|
RegVal &= ~0x03;\
|
||||||
|
RegVal |= 1 << 0;\
|
||||||
|
}\
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, RegVal);\
|
||||||
|
}\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_PN_SWITCH(PNMode) do{\
|
||||||
|
if(PNMode == PHY_PN_SWITCH_AUTO)\
|
||||||
|
{\
|
||||||
|
phyPN = PHY_PN_SWITCH_AUTO;\
|
||||||
|
}\
|
||||||
|
else{\
|
||||||
|
phyPN = (ETH_ReadPHYRegister(gPHYAddress, PHY_MDIX) & (~(0x03 << 2))) | PNMode;\
|
||||||
|
}\
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, phyPN);\
|
||||||
|
phyPN = PNMode;\
|
||||||
|
PHY_RESTART_AUTONEGOTIATION();\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_NEGOTIATION_PARAM_INIT() do{\
|
||||||
|
phyStatus = 0;\
|
||||||
|
phySucCnt = 0;\
|
||||||
|
phyLinkCnt = 0;\
|
||||||
|
TRDetectStep = 0;\
|
||||||
|
PhyPolarityDetect = 0;\
|
||||||
|
phyLinkStatus = PHY_LINK_INIT;\
|
||||||
|
phyPN = PHY_PN_SWITCH_AUTO;\
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, phyPN);\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define PHY_LINK_RESET() do{\
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_BCR, PHY_Reset);\
|
||||||
|
PHY_NEGOTIATION_PARAM_INIT();\
|
||||||
|
}while(0)
|
||||||
|
|
||||||
|
#define LAST_NEGO_STAT 1 //0:auto-negotiate 1:Parallel detection
|
||||||
|
#define TURN_PN_POLARITY (1<<1) //0:P polarity 1:N polarity
|
||||||
|
|
||||||
|
extern ETH_DMADESCTypeDef *DMATxDescToSet;
|
||||||
|
extern ETH_DMADESCTypeDef *DMARxDescToGet;
|
||||||
|
extern SOCK_INF SocketInf[ ];
|
||||||
|
|
||||||
|
#define PHY_PAG_SEL 0x1F
|
||||||
|
|
||||||
|
void ETH_PHYLink( void );
|
||||||
|
void WCHNET_ETHIsr( void );
|
||||||
|
void WCHNET_MainTask( void );
|
||||||
|
void ETH_LedConfiguration(void);
|
||||||
|
void ETH_Init( uint8_t *macAddr );
|
||||||
|
void ETH_LedLinkSet( uint8_t mode );
|
||||||
|
void ETH_LedDataSet( uint8_t mode );
|
||||||
|
void WCHNET_TimeIsr( uint16_t timperiod );
|
||||||
|
void ETH_Configuration( uint8_t *macAddr );
|
||||||
|
uint8_t ETH_LibInit( uint8_t *ip, uint8_t *gwip, uint8_t *mask, uint8_t *macaddr);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,940 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : eth_driver.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.3.0
|
||||||
|
* Date : 2022/06/02
|
||||||
|
* Description : eth program body.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB]; /* MAC receive descriptor, 4-byte aligned*/
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMATxDscrTab[ETH_TXBUFNB]; /* MAC send descriptor, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACRxBuf[ETH_RXBUFNB*ETH_RX_BUF_SZE]; /* MAC receive buffer, 4-byte aligned */
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACTxBuf[ETH_TXBUFNB*ETH_TX_BUF_SZE]; /* MAC send buffer, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) SOCK_INF SocketInf[WCHNET_MAX_SOCKET_NUM]; /* Socket information table, 4-byte alignment */
|
||||||
|
const uint16_t MemNum[8] = {WCHNET_NUM_IPRAW,
|
||||||
|
WCHNET_NUM_UDP,
|
||||||
|
WCHNET_NUM_TCP,
|
||||||
|
WCHNET_NUM_TCP_LISTEN,
|
||||||
|
WCHNET_NUM_TCP_SEG,
|
||||||
|
WCHNET_NUM_IP_REASSDATA,
|
||||||
|
WCHNET_NUM_PBUF,
|
||||||
|
WCHNET_NUM_POOL_BUF
|
||||||
|
};
|
||||||
|
const uint16_t MemSize[8] = {WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IPRAW_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_UDP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB_LISTEN),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_SEG),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IP_REASSDATA),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF) + WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_POOL_BUF)
|
||||||
|
};
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Memp_Memory[WCHNET_MEMP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_Heap_Memory[WCHNET_RAM_HEAP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_ArpTable[WCHNET_RAM_ARP_TABLE_SIZE];
|
||||||
|
|
||||||
|
uint16_t gPHYAddress;
|
||||||
|
uint32_t volatile LocalTime;
|
||||||
|
uint32_t ChipId = 0;
|
||||||
|
|
||||||
|
ETH_DMADESCTypeDef *pDMARxSet;
|
||||||
|
ETH_DMADESCTypeDef *pDMATxSet;
|
||||||
|
|
||||||
|
/* PHY negotiation function */
|
||||||
|
uint8_t phyLinkStatus = 0;
|
||||||
|
uint8_t phyStatus = 0;
|
||||||
|
uint8_t phyLinkCnt = 0;
|
||||||
|
uint8_t phySucCnt = 0;
|
||||||
|
uint8_t phyPN = PHY_PN_SWITCH_AUTO;
|
||||||
|
uint8_t TRDetectStep = 0;
|
||||||
|
uint8_t TRDetectCnt = 0;
|
||||||
|
uint8_t LinkTaskPeriod = 50;
|
||||||
|
uint32_t RandVal = 0;
|
||||||
|
uint8_t volatile phyLinkReset;
|
||||||
|
uint32_t volatile phyLinkTime;
|
||||||
|
|
||||||
|
/* PHY receive processing */
|
||||||
|
uint8_t ReInitMACFlag = 0;
|
||||||
|
uint8_t PhyPolarityDetect = 0;
|
||||||
|
uint32_t LinkSuccTime = 0;
|
||||||
|
|
||||||
|
/*Parameters used when connecting to
|
||||||
|
* devices that do not support auto-negotiation.*/
|
||||||
|
uint8_t phyNegoStat = 0;
|
||||||
|
uint32_t phyNegoLinkTime = 0;
|
||||||
|
|
||||||
|
extern u8 MACAddr[6];
|
||||||
|
void ReInitMACReg(void);
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_GetMacAddr
|
||||||
|
*
|
||||||
|
* @brief Get the MAC address
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_GetMacAddr( uint8_t *p )
|
||||||
|
{
|
||||||
|
uint8_t i;
|
||||||
|
uint8_t *macaddr=(uint8_t *)(ROM_CFG_USERADR_ID+5);
|
||||||
|
|
||||||
|
for(i=0;i<6;i++)
|
||||||
|
{
|
||||||
|
*p = *macaddr;
|
||||||
|
p++;
|
||||||
|
macaddr--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_TimeIsr
|
||||||
|
*
|
||||||
|
* @brief
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_TimeIsr( uint16_t timperiod )
|
||||||
|
{
|
||||||
|
LocalTime += timperiod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_PhyPNProcess
|
||||||
|
*
|
||||||
|
* @brief Phy PN Polarity related processing
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_PhyPNProcess(void)
|
||||||
|
{
|
||||||
|
uint32_t PhyVal;
|
||||||
|
|
||||||
|
LinkSuccTime = LocalTime;
|
||||||
|
if((ETH->MMCRGUFCR == 0) && (ETH->MMCRFCECR >= 3))
|
||||||
|
{
|
||||||
|
PhyVal = ETH_ReadPHYRegister(gPHYAddress, PHY_MDIX);
|
||||||
|
if((PhyVal >> 2) & 0x01)
|
||||||
|
PhyVal &= ~(3 << 2); //change PHY PN Polarity to normal
|
||||||
|
else
|
||||||
|
PhyVal |= 1 << 2; //change PHY PN Polarity to reverse
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, PhyVal);
|
||||||
|
ETH->MMCCR |= ETH_MMCCR_CR; //Counters Reset
|
||||||
|
while(ETH->MMCCR & ETH_MMCCR_CR); //Wait for counters reset to complete
|
||||||
|
}
|
||||||
|
if(ETH->MMCRGUFCR != 0)
|
||||||
|
{
|
||||||
|
PhyPolarityDetect = 0;
|
||||||
|
/* enable Filter function */
|
||||||
|
ETH->MACFFR &= ~(ETH_ReceiveAll_Enable | ETH_PromiscuousMode_Enable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_RecProcess
|
||||||
|
*
|
||||||
|
* @brief Receiving related processing
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_RecProcess(void)
|
||||||
|
{
|
||||||
|
if(((ChipId & 0xf0) == 0x20) && \
|
||||||
|
((ETH->DMAMFBOCR & 0x1FFE0000) != 0))
|
||||||
|
{
|
||||||
|
ReInitMACReg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_LinkProcess
|
||||||
|
*
|
||||||
|
* @brief link process.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_LinkProcess( void )
|
||||||
|
{
|
||||||
|
uint16_t phy_anlpar, phy_bmsr, phy_mdix, RegVal;
|
||||||
|
|
||||||
|
phy_anlpar = ETH_ReadPHYRegister(gPHYAddress, PHY_ANLPAR);
|
||||||
|
phy_bmsr = ETH_ReadPHYRegister( gPHYAddress, PHY_BMSR);
|
||||||
|
|
||||||
|
if( (phy_anlpar&PHY_ANLPAR_SELECTOR_FIELD) )
|
||||||
|
{
|
||||||
|
if(TRDetectStep == 0)
|
||||||
|
{
|
||||||
|
TRDetectStep = 1;
|
||||||
|
TRDetectCnt = 1;
|
||||||
|
PHY_TR_SWITCH();
|
||||||
|
LinkTaskPeriod = RandVal%100 + 50;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if(TRDetectStep == 1)
|
||||||
|
{
|
||||||
|
TRDetectStep = 2;
|
||||||
|
TRDetectCnt = 0;
|
||||||
|
}
|
||||||
|
if( !(phyLinkStatus&PHY_LINK_WAIT_SUC) )
|
||||||
|
{
|
||||||
|
if( phyPN == PHY_PN_SWITCH_AUTO )
|
||||||
|
{
|
||||||
|
PHY_PN_SWITCH(PHY_PN_SWITCH_P);
|
||||||
|
}
|
||||||
|
else if( phyPN == PHY_PN_SWITCH_P )
|
||||||
|
{
|
||||||
|
phyLinkStatus = PHY_LINK_WAIT_SUC;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
phyLinkStatus = PHY_LINK_WAIT_SUC;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
if((phySucCnt++ == 5) && ((phy_bmsr&(1<<5)) == 0))
|
||||||
|
{
|
||||||
|
phySucCnt = 0;
|
||||||
|
if(phyPN == PHY_PN_SWITCH_N)
|
||||||
|
PHY_PN_SWITCH(PHY_PN_SWITCH_P);
|
||||||
|
else PHY_PN_SWITCH(PHY_PN_SWITCH_N);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
phyLinkCnt = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if(TRDetectStep == 1)
|
||||||
|
{
|
||||||
|
TRDetectCnt++;
|
||||||
|
if(TRDetectCnt == 8)
|
||||||
|
{
|
||||||
|
TRDetectCnt = 0;
|
||||||
|
TRDetectStep = 0;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, PHY_PN_SWITCH_AUTO);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
PHY_TR_SWITCH();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if( phyLinkStatus == PHY_LINK_WAIT_SUC )
|
||||||
|
{
|
||||||
|
if(phyLinkCnt++ == 15 )
|
||||||
|
{
|
||||||
|
phyLinkCnt = 0;
|
||||||
|
phySucCnt = 0;
|
||||||
|
TRDetectStep = 0;
|
||||||
|
phyLinkStatus = PHY_LINK_INIT;
|
||||||
|
PHY_PN_SWITCH(PHY_PN_SWITCH_AUTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if( phyPN == PHY_PN_SWITCH_P )
|
||||||
|
{
|
||||||
|
if(phyLinkCnt++ == 4 )
|
||||||
|
{
|
||||||
|
phyLinkCnt = 0;
|
||||||
|
PHY_PN_SWITCH(PHY_PN_SWITCH_N);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if( phyPN == PHY_PN_SWITCH_N )
|
||||||
|
{
|
||||||
|
if(phyLinkCnt++ == 15 )
|
||||||
|
{
|
||||||
|
phyLinkCnt = 0;
|
||||||
|
phySucCnt = 0;
|
||||||
|
TRDetectStep = 0;
|
||||||
|
phyLinkStatus = PHY_LINK_INIT;
|
||||||
|
PHY_PN_SWITCH(PHY_PN_SWITCH_AUTO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
if(phyLinkCnt++ == (5000 / PHY_LINK_TASK_PERIOD))
|
||||||
|
PHY_LINK_RESET( );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_HandlePhyNegotiation
|
||||||
|
*
|
||||||
|
* @brief Handle PHY Negotiation.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_HandlePhyNegotiation(void)
|
||||||
|
{
|
||||||
|
if(phyLinkReset) /* After the PHY link is disconnected, wait 500ms before turning on the PHY clock*/
|
||||||
|
{
|
||||||
|
if( LocalTime - phyLinkTime >= 500 )
|
||||||
|
{
|
||||||
|
phyLinkReset = 0;
|
||||||
|
EXTEN->EXTEN_CTR |= EXTEN_ETH_10M_EN;
|
||||||
|
PHY_LINK_RESET();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if( !phyStatus ) /* Handling PHY Negotiation Exceptions */
|
||||||
|
{
|
||||||
|
ACCELERATE_LINK_PROCESS();
|
||||||
|
if( LocalTime - phyLinkTime >= LinkTaskPeriod )
|
||||||
|
{
|
||||||
|
UPDATE_LINKTASKPERIOD();
|
||||||
|
phyLinkTime = LocalTime;
|
||||||
|
WCHNET_LinkProcess( );
|
||||||
|
}
|
||||||
|
if(ReInitMACFlag) ReInitMACFlag = 0;
|
||||||
|
}
|
||||||
|
else{ /* PHY link complete */
|
||||||
|
if(ReInitMACFlag)
|
||||||
|
{
|
||||||
|
if( LocalTime - phyLinkTime >= 5 * PHY_LINK_TASK_PERIOD ){
|
||||||
|
u32 phy_stat;
|
||||||
|
ReInitMACFlag = 0;
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, PHY_BMSR);
|
||||||
|
if((phy_stat&PHY_Linked_Status) == 0)
|
||||||
|
{
|
||||||
|
WCHNET_PhyStatus( phy_stat );
|
||||||
|
PHY_LINK_RESET();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(PhyPolarityDetect)
|
||||||
|
{
|
||||||
|
if( LocalTime - LinkSuccTime >= 2 * PHY_LINK_TASK_PERIOD )
|
||||||
|
{
|
||||||
|
WCHNET_PhyPNProcess();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_MainTask
|
||||||
|
*
|
||||||
|
* @brief library main task function
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_MainTask(void)
|
||||||
|
{
|
||||||
|
WCHNET_NetInput( ); /* Ethernet data input */
|
||||||
|
WCHNET_PeriodicHandle( ); /* Protocol stack time-related task processing */
|
||||||
|
WCHNET_HandlePhyNegotiation();
|
||||||
|
WCHNET_RecProcess();
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LedLinkSet
|
||||||
|
*
|
||||||
|
* @brief set eth link led,setbit 0 or 1,the link led turn on or turn off
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_LedLinkSet( uint8_t mode )
|
||||||
|
{
|
||||||
|
if( mode == LED_OFF )
|
||||||
|
{
|
||||||
|
GPIO_SetBits(GPIOC, GPIO_Pin_0);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
GPIO_ResetBits(GPIOC, GPIO_Pin_0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LedDataSet
|
||||||
|
*
|
||||||
|
* @brief set eth data led,setbit 0 or 1,the data led turn on or turn off
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_LedDataSet( uint8_t mode )
|
||||||
|
{
|
||||||
|
if( mode == LED_OFF )
|
||||||
|
{
|
||||||
|
GPIO_SetBits(GPIOC, GPIO_Pin_1);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
GPIO_ResetBits(GPIOC, GPIO_Pin_1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LedConfiguration
|
||||||
|
*
|
||||||
|
* @brief set eth data and link led pin
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LedConfiguration(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO={0};
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
|
||||||
|
GPIO.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1;
|
||||||
|
GPIO.GPIO_Mode = GPIO_Mode_Out_PP;
|
||||||
|
GPIO.GPIO_Speed = GPIO_Speed_50MHz;
|
||||||
|
GPIO_Init(GPIOC,&GPIO);
|
||||||
|
ETH_LedDataSet(LED_OFF);
|
||||||
|
ETH_LedLinkSet(LED_OFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_SetClock
|
||||||
|
*
|
||||||
|
* @brief Set ETH Clock(60MHZ).
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_SetClock(void)
|
||||||
|
{
|
||||||
|
RCC_PLL3Cmd(DISABLE);
|
||||||
|
RCC_PREDIV2Config(RCC_PREDIV2_Div2); /* HSE = 8M */
|
||||||
|
RCC_PLL3Config(RCC_PLL3Mul_15); /* 4M*15 = 60MHz */
|
||||||
|
RCC_PLL3Cmd(ENABLE);
|
||||||
|
while(RESET == RCC_GetFlagStatus(RCC_FLAG_PLL3RDY));
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LinkUpCfg
|
||||||
|
*
|
||||||
|
* @brief When the PHY is connected, configure the relevant functions.
|
||||||
|
*
|
||||||
|
* @param regval BMSR register value
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LinkUpCfg(uint16_t regval)
|
||||||
|
{
|
||||||
|
WCHNET_PhyStatus( regval );
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
phyStatus = PHY_Linked_Status;
|
||||||
|
|
||||||
|
/* disable Filter function */
|
||||||
|
ETH->MACFFR |= (ETH_ReceiveAll_Enable | ETH_PromiscuousMode_Enable);
|
||||||
|
|
||||||
|
ETH->MMCCR |= ETH_MMCCR_CR; //Counters Reset
|
||||||
|
while(ETH->MMCCR & ETH_MMCCR_CR); //Wait for counters reset to complete
|
||||||
|
PhyPolarityDetect = 1;
|
||||||
|
LinkSuccTime = LocalTime;
|
||||||
|
ETH_Start( );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_PHYLink
|
||||||
|
*
|
||||||
|
* @brief Configure MAC parameters after the PHY Link is successful.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_PHYLink( void )
|
||||||
|
{
|
||||||
|
u16 phy_bsr, phy_stat, phy_anlpar, phy_bcr;
|
||||||
|
|
||||||
|
phy_bsr = ETH_ReadPHYRegister( gPHYAddress, PHY_BSR);
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( gPHYAddress, PHY_BCR);
|
||||||
|
phy_anlpar = ETH_ReadPHYRegister( gPHYAddress, PHY_ANLPAR);
|
||||||
|
|
||||||
|
if(phy_bsr & PHY_Linked_Status) //LinkUp
|
||||||
|
{
|
||||||
|
if(phy_bcr & PHY_AutoNegotiation) //determine whether auto-negotiation is enable
|
||||||
|
{
|
||||||
|
if(phy_anlpar == 0)
|
||||||
|
{
|
||||||
|
if(phy_bsr & PHY_AutoNego_Complete)
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
ETH_LinkUpCfg(phy_bsr);
|
||||||
|
if((ChipId & 0xf0) == 0x20)
|
||||||
|
{
|
||||||
|
if(phyNegoStat & TURN_PN_POLARITY)
|
||||||
|
{
|
||||||
|
//select N polarity
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, PHY_PN_SWITCH_N);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//select P polarity
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_MDIX, PHY_PN_SWITCH_P);
|
||||||
|
phyNegoStat |= LAST_NEGO_STAT;
|
||||||
|
}
|
||||||
|
phyNegoLinkTime = LocalTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
PHY_LINK_RESET();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
phyNegoStat = 0;
|
||||||
|
if(phy_bsr & PHY_AutoNego_Complete)
|
||||||
|
{
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, PHY_STATUS );
|
||||||
|
if( phy_stat & (1<<2) )
|
||||||
|
{
|
||||||
|
ETH->MACCR |= ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if( (phy_anlpar&PHY_ANLPAR_SELECTOR_FIELD) != PHY_ANLPAR_SELECTOR_VALUE )
|
||||||
|
{
|
||||||
|
ETH->MACCR |= ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ETH_LinkUpCfg(phy_bsr);
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
EXTEN->EXTEN_CTR &= ~EXTEN_ETH_10M_EN;
|
||||||
|
phyLinkReset = 1;
|
||||||
|
phyLinkTime = LocalTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
ETH_LinkUpCfg(phy_bsr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { //LinkDown
|
||||||
|
WCHNET_PhyStatus( phy_bsr );
|
||||||
|
EXTEN->EXTEN_CTR &= ~EXTEN_ETH_10M_EN;
|
||||||
|
phyLinkReset = 1;
|
||||||
|
phyLinkTime = LocalTime;
|
||||||
|
if((ChipId & 0xf0) == 0x20)
|
||||||
|
{
|
||||||
|
if(phyNegoStat & LAST_NEGO_STAT)
|
||||||
|
{
|
||||||
|
if(LocalTime - phyNegoLinkTime < 100)
|
||||||
|
{
|
||||||
|
phyNegoLinkTime = 0;
|
||||||
|
//Clear any existing error count values.
|
||||||
|
ETH->DMAMFBOCR;
|
||||||
|
phyNegoStat ^= TURN_PN_POLARITY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ReInitMACReg
|
||||||
|
*
|
||||||
|
* @brief Reinitialize MAC register.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ReInitMACReg(void)
|
||||||
|
{
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
uint16_t RegVal;
|
||||||
|
uint32_t maccr, macmiiar, macffr, machthr, machtlr;
|
||||||
|
uint32_t macfcr, macvlantr, dmaomr;
|
||||||
|
|
||||||
|
/* Wait for sending data to complete */
|
||||||
|
while((ETH->DMASR & (7 << 20)) != ETH_DMA_TransmitProcess_Suspended);
|
||||||
|
|
||||||
|
PHY_TR_REVERSE();
|
||||||
|
|
||||||
|
/* Record the register value */
|
||||||
|
macmiiar = ETH->MACMIIAR;
|
||||||
|
maccr = ETH->MACCR;
|
||||||
|
macffr = ETH->MACFFR;
|
||||||
|
machthr = ETH->MACHTHR;
|
||||||
|
machtlr = ETH->MACHTLR;
|
||||||
|
macfcr = ETH->MACFCR;
|
||||||
|
macvlantr = ETH->MACVLANTR;
|
||||||
|
dmaomr = ETH->DMAOMR;
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((MACAddr[5]<<8) | MACAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(MACAddr[0] | (MACAddr[1]<<8) | (MACAddr[2]<<16) | (MACAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU |\
|
||||||
|
ETH_DMA_IT_PHYLINK,\
|
||||||
|
ENABLE);
|
||||||
|
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
|
||||||
|
ETH->MACMIIAR = macmiiar;
|
||||||
|
ETH->MACCR = maccr;
|
||||||
|
ETH->MACFFR = macffr;
|
||||||
|
ETH->MACHTHR = machthr;
|
||||||
|
ETH->MACHTLR = machtlr;
|
||||||
|
ETH->MACFCR = macfcr;
|
||||||
|
ETH->MACVLANTR = macvlantr;
|
||||||
|
ETH->DMAOMR = dmaomr;
|
||||||
|
|
||||||
|
ETH_Start( );
|
||||||
|
|
||||||
|
PHY_TR_REVERSE();
|
||||||
|
|
||||||
|
if(!phyStatus)
|
||||||
|
{
|
||||||
|
PHY_LINK_RESET();
|
||||||
|
}
|
||||||
|
|
||||||
|
ReInitMACFlag = 1;
|
||||||
|
phyLinkTime = LocalTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RegInit
|
||||||
|
*
|
||||||
|
* @brief ETH register initialization.
|
||||||
|
*
|
||||||
|
* @param ETH_InitStruct:initialization struct.
|
||||||
|
* PHYAddress:PHY address.
|
||||||
|
*
|
||||||
|
* @return Initialization status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_RegInit( ETH_InitTypeDef* ETH_InitStruct, uint16_t PHYAddress )
|
||||||
|
{
|
||||||
|
/* Set the SMI interface clock, set as the main frequency divided by 42 */
|
||||||
|
ETH->MACMIIAR = (uint32_t)ETH_MACMIIAR_CR_Div42;
|
||||||
|
|
||||||
|
/*------------------------ MAC register configuration -------------------------------------------*/
|
||||||
|
ETH->MACCR = (uint32_t)(ETH_InitStruct->ETH_Watchdog |
|
||||||
|
ETH_InitStruct->ETH_Jabber |
|
||||||
|
ETH_InitStruct->ETH_InterFrameGap |
|
||||||
|
ETH_InitStruct->ETH_ChecksumOffload |
|
||||||
|
ETH_InitStruct->ETH_AutomaticPadCRCStrip |
|
||||||
|
ETH_InitStruct->ETH_LoopbackMode |
|
||||||
|
ETH_Internal_Pull_Up_Res_Enable);
|
||||||
|
|
||||||
|
ETH->MACFFR = (uint32_t)(ETH_InitStruct->ETH_ReceiveAll |
|
||||||
|
ETH_InitStruct->ETH_SourceAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PassControlFrames |
|
||||||
|
ETH_InitStruct->ETH_BroadcastFramesReception |
|
||||||
|
ETH_InitStruct->ETH_DestinationAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PromiscuousMode |
|
||||||
|
ETH_InitStruct->ETH_MulticastFramesFilter |
|
||||||
|
ETH_InitStruct->ETH_UnicastFramesFilter);
|
||||||
|
|
||||||
|
ETH->MACHTHR = (uint32_t)ETH_InitStruct->ETH_HashTableHigh;
|
||||||
|
ETH->MACHTLR = (uint32_t)ETH_InitStruct->ETH_HashTableLow;
|
||||||
|
|
||||||
|
ETH->MACFCR = (uint32_t)((ETH_InitStruct->ETH_PauseTime << 16) |
|
||||||
|
ETH_InitStruct->ETH_UnicastPauseFrameDetect |
|
||||||
|
ETH_InitStruct->ETH_ReceiveFlowControl |
|
||||||
|
ETH_InitStruct->ETH_TransmitFlowControl);
|
||||||
|
|
||||||
|
ETH->MACVLANTR = (uint32_t)(ETH_InitStruct->ETH_VLANTagComparison |
|
||||||
|
ETH_InitStruct->ETH_VLANTagIdentifier);
|
||||||
|
|
||||||
|
ETH->DMAOMR = (uint32_t)(ETH_InitStruct->ETH_DropTCPIPChecksumErrorFrame |
|
||||||
|
ETH_InitStruct->ETH_TransmitStoreForward |
|
||||||
|
ETH_InitStruct->ETH_ForwardErrorFrames |
|
||||||
|
ETH_InitStruct->ETH_ForwardUndersizedGoodFrames);
|
||||||
|
|
||||||
|
/* Reset the physical layer */
|
||||||
|
ETH_WritePHYRegister(PHYAddress, PHY_BCR, PHY_Reset);
|
||||||
|
ETH_WritePHYRegister(PHYAddress, PHY_MDIX, PHY_PN_SWITCH_AUTO);
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Configuration
|
||||||
|
*
|
||||||
|
* @brief Ethernet configure.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Configuration( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ETH_InitTypeDef ETH_InitStructure;
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
|
||||||
|
/* Enable Ethernet MAC clock */
|
||||||
|
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ETH_MAC | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Tx | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Rx, ENABLE);
|
||||||
|
|
||||||
|
gPHYAddress = PHY_ADDRESS;
|
||||||
|
ETH_SetClock( );
|
||||||
|
|
||||||
|
/* Enable internal 10BASE-T PHY*/
|
||||||
|
EXTEN->EXTEN_CTR |= EXTEN_ETH_10M_EN; /* Enable 10M Ethernet physical layer */
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* ETHERNET Configuration */
|
||||||
|
/*------------------------ MAC -----------------------------------*/
|
||||||
|
ETH_InitStructure.ETH_Watchdog = ETH_Watchdog_Enable;
|
||||||
|
ETH_InitStructure.ETH_Jabber = ETH_Jabber_Enable;
|
||||||
|
ETH_InitStructure.ETH_InterFrameGap = ETH_InterFrameGap_96Bit;
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Enable;
|
||||||
|
#else
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Disable;
|
||||||
|
#endif
|
||||||
|
ETH_InitStructure.ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable;
|
||||||
|
ETH_InitStructure.ETH_LoopbackMode = ETH_LoopbackMode_Disable;
|
||||||
|
|
||||||
|
/* Filter function configuration */
|
||||||
|
ETH_InitStructure.ETH_ReceiveAll = ETH_ReceiveAll_Disable;
|
||||||
|
ETH_InitStructure.ETH_PromiscuousMode = ETH_PromiscuousMode_Disable;
|
||||||
|
ETH_InitStructure.ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Enable;
|
||||||
|
ETH_InitStructure.ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_PassControlFrames = ETH_PassControlFrames_BlockAll;
|
||||||
|
ETH_InitStructure.ETH_DestinationAddrFilter = ETH_DestinationAddrFilter_Normal;
|
||||||
|
ETH_InitStructure.ETH_SourceAddrFilter = ETH_SourceAddrFilter_Disable;
|
||||||
|
|
||||||
|
ETH_InitStructure.ETH_HashTableHigh = 0x0;
|
||||||
|
ETH_InitStructure.ETH_HashTableLow = 0x0;
|
||||||
|
|
||||||
|
/* VLan function configuration */
|
||||||
|
ETH_InitStructure.ETH_VLANTagComparison = ETH_VLANTagComparison_16Bit;
|
||||||
|
ETH_InitStructure.ETH_VLANTagIdentifier = 0x0;
|
||||||
|
|
||||||
|
/* Flow Control function configuration */
|
||||||
|
ETH_InitStructure.ETH_PauseTime = 0x0;
|
||||||
|
ETH_InitStructure.ETH_UnicastPauseFrameDetect = ETH_UnicastPauseFrameDetect_Disable;
|
||||||
|
ETH_InitStructure.ETH_ReceiveFlowControl = ETH_ReceiveFlowControl_Disable;
|
||||||
|
ETH_InitStructure.ETH_TransmitFlowControl = ETH_TransmitFlowControl_Disable;
|
||||||
|
|
||||||
|
/*------------------------ DMA -----------------------------------*/
|
||||||
|
/* When we use the Checksum offload feature, we need to enable the Store and Forward mode:
|
||||||
|
the store and forward guarantee that a whole frame is stored in the FIFO, so the MAC can insert/verify the checksum,
|
||||||
|
if the checksum is OK the DMA can handle the frame otherwise the frame is dropped */
|
||||||
|
ETH_InitStructure.ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Enable;
|
||||||
|
ETH_InitStructure.ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Enable;
|
||||||
|
|
||||||
|
/* Configure Ethernet */
|
||||||
|
ETH_RegInit( Ð_InitStructure, gPHYAddress );
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((macAddr[5]<<8) | macAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(macAddr[0] | (macAddr[1]<<8) | (macAddr[2]<<16) | (macAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU |\
|
||||||
|
ETH_DMA_IT_PHYLINK,\
|
||||||
|
ENABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_TxPktChainMode
|
||||||
|
*
|
||||||
|
* @brief Ethernet sends data frames in chain mode.
|
||||||
|
*
|
||||||
|
* @param len Send data length
|
||||||
|
* pBuff send buffer pointer
|
||||||
|
*
|
||||||
|
* @return Send status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_TxPktChainMode(uint16_t len, uint32_t *pBuff )
|
||||||
|
{
|
||||||
|
/* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */
|
||||||
|
if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (u32)RESET)
|
||||||
|
{
|
||||||
|
/* Return ERROR: OWN bit set */
|
||||||
|
return ETH_ERROR;
|
||||||
|
}
|
||||||
|
/* Setting the Frame Length: bits[12:0] */
|
||||||
|
DMATxDescToSet->ControlBufferSize = (len & ETH_DMATxDesc_TBS1);
|
||||||
|
DMATxDescToSet->Buffer1Addr = (uint32_t)pBuff;
|
||||||
|
|
||||||
|
/* Setting the last segment and first segment bits (in this case a frame is transmitted in one descriptor) */
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS | ETH_DMATxDesc_CIC_TCPUDPICMP_Full;
|
||||||
|
#else
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_OWN;
|
||||||
|
|
||||||
|
/* Clear TBUS ETHERNET DMA flag */
|
||||||
|
ETH->DMASR = ETH_DMASR_TBUS;
|
||||||
|
/* Resume DMA transmission*/
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
|
||||||
|
/* Update the ETHERNET DMA global Tx descriptor with next Tx descriptor */
|
||||||
|
/* Chained Mode */
|
||||||
|
/* Selects the next DMA Tx descriptor list for next buffer to send */
|
||||||
|
DMATxDescToSet = (ETH_DMADESCTypeDef*) (DMATxDescToSet->Buffer2NextDescAddr);
|
||||||
|
/* Return SUCCESS */
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_ETHIsr
|
||||||
|
*
|
||||||
|
* @brief Ethernet Interrupt Service Routine
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void WCHNET_ETHIsr(void)
|
||||||
|
{
|
||||||
|
uint32_t int_sta;
|
||||||
|
|
||||||
|
int_sta = ETH->DMASR;
|
||||||
|
if (int_sta & ETH_DMA_IT_AIS)
|
||||||
|
{
|
||||||
|
if (int_sta & ETH_DMA_IT_RBU)
|
||||||
|
{
|
||||||
|
if((ChipId & 0xf0) == 0x10)
|
||||||
|
{
|
||||||
|
((ETH_DMADESCTypeDef *)(((ETH_DMADESCTypeDef *)(ETH->DMACHRDR))->Buffer2NextDescAddr))->Status = ETH_DMARxDesc_OWN;
|
||||||
|
|
||||||
|
/* Resume DMA reception */
|
||||||
|
ETH->DMARPDR = 0;
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_RBU);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_AIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
if( int_sta & ETH_DMA_IT_NIS )
|
||||||
|
{
|
||||||
|
if( int_sta & ETH_DMA_IT_R )
|
||||||
|
{
|
||||||
|
/*If you don't use the Ethernet library,
|
||||||
|
* you can do some data processing operations here*/
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
|
||||||
|
}
|
||||||
|
if( int_sta & ETH_DMA_IT_T )
|
||||||
|
{
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_T);
|
||||||
|
}
|
||||||
|
if( int_sta & ETH_DMA_IT_PHYLINK)
|
||||||
|
{
|
||||||
|
ETH_PHYLink( );
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_PHYLINK);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Init
|
||||||
|
*
|
||||||
|
* @brief Ethernet initialization.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Init( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
Delay_Ms(100);
|
||||||
|
ChipId = DBGMCU_GetCHIPID();
|
||||||
|
ETH_LedConfiguration( );
|
||||||
|
RandVal = (macAddr[3]^macAddr[4]^macAddr[5]) * 214017 + 2531017;
|
||||||
|
ETH_Configuration( macAddr );
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
NVIC_EnableIRQ(ETH_IRQn);
|
||||||
|
NVIC_SetPriority(ETH_IRQn, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LibInit
|
||||||
|
*
|
||||||
|
* @brief Ethernet library initialization program
|
||||||
|
*
|
||||||
|
* @return command status
|
||||||
|
*/
|
||||||
|
uint8_t ETH_LibInit( uint8_t *ip, uint8_t *gwip, uint8_t *mask, uint8_t *macaddr )
|
||||||
|
{
|
||||||
|
uint8_t s;
|
||||||
|
struct _WCH_CFG cfg;
|
||||||
|
|
||||||
|
memset(&cfg,0,sizeof(cfg));
|
||||||
|
cfg.TxBufSize = ETH_TX_BUF_SZE;
|
||||||
|
cfg.TCPMss = WCHNET_TCP_MSS;
|
||||||
|
cfg.HeapSize = WCHNET_MEM_HEAP_SIZE;
|
||||||
|
cfg.ARPTableNum = WCHNET_NUM_ARP_TABLE;
|
||||||
|
cfg.MiscConfig0 = WCHNET_MISC_CONFIG0;
|
||||||
|
cfg.MiscConfig1 = WCHNET_MISC_CONFIG1;
|
||||||
|
cfg.led_link = ETH_LedLinkSet;
|
||||||
|
cfg.led_data = ETH_LedDataSet;
|
||||||
|
cfg.net_send = ETH_TxPktChainMode;
|
||||||
|
cfg.CheckValid = WCHNET_CFG_VALID;
|
||||||
|
s = WCHNET_ConfigLIB(&cfg);
|
||||||
|
if( s ){
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
s = WCHNET_Init(ip,gwip,mask,macaddr);
|
||||||
|
ETH_Init( macaddr );
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************** endfile @ eth_driver ******************************/
|
||||||
@@ -0,0 +1,794 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : eth_driver.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.3.0
|
||||||
|
* Date : 2022/06/02
|
||||||
|
* Description : eth program body.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB]; /* MAC receive descriptor, 4-byte aligned*/
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMATxDscrTab[ETH_TXBUFNB]; /* MAC send descriptor, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACRxBuf[ETH_RXBUFNB*ETH_RX_BUF_SZE]; /* MAC receive buffer, 4-byte aligned */
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACTxBuf[ETH_TXBUFNB*ETH_TX_BUF_SZE]; /* MAC send buffer, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) SOCK_INF SocketInf[WCHNET_MAX_SOCKET_NUM]; /* Socket information table, 4-byte alignment */
|
||||||
|
const uint16_t MemNum[8] = {WCHNET_NUM_IPRAW,
|
||||||
|
WCHNET_NUM_UDP,
|
||||||
|
WCHNET_NUM_TCP,
|
||||||
|
WCHNET_NUM_TCP_LISTEN,
|
||||||
|
WCHNET_NUM_TCP_SEG,
|
||||||
|
WCHNET_NUM_IP_REASSDATA,
|
||||||
|
WCHNET_NUM_PBUF,
|
||||||
|
WCHNET_NUM_POOL_BUF
|
||||||
|
};
|
||||||
|
const uint16_t MemSize[8] = {WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IPRAW_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_UDP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB_LISTEN),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_SEG),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IP_REASSDATA),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF) + WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_POOL_BUF)
|
||||||
|
};
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Memp_Memory[WCHNET_MEMP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_Heap_Memory[WCHNET_RAM_HEAP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_ArpTable[WCHNET_RAM_ARP_TABLE_SIZE];
|
||||||
|
|
||||||
|
uint16_t gPHYAddress;
|
||||||
|
uint32_t volatile LocalTime;
|
||||||
|
|
||||||
|
ETH_DMADESCTypeDef *pDMARxSet;
|
||||||
|
ETH_DMADESCTypeDef *pDMATxSet;
|
||||||
|
|
||||||
|
volatile uint8_t LinkSta = 0; //0:Link down 1:Link up
|
||||||
|
uint8_t LinkVaildFlag = 0; //0:invalid 1:valid
|
||||||
|
uint8_t AccelerateLinkStep = 0;
|
||||||
|
uint8_t AccelerateLinkTime = 0;
|
||||||
|
uint8_t LinkProcessingStep = 0;
|
||||||
|
uint32_t LinkProcessingTime = 0;
|
||||||
|
uint32_t TaskExecutionTime = 0;
|
||||||
|
u16 LastPhyStat = 0;
|
||||||
|
u32 LastQueryPhyTime = 0;
|
||||||
|
void ETH_LinkDownCfg(void);
|
||||||
|
void PHY_FuncInit(void);
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_GetMacAddr
|
||||||
|
*
|
||||||
|
* @brief Get the MAC address
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_GetMacAddr( uint8_t *p )
|
||||||
|
{
|
||||||
|
uint8_t i;
|
||||||
|
uint8_t *macaddr = (uint8_t *)(ROM_CFG_USERADR_ID+5);
|
||||||
|
|
||||||
|
for(i=0;i<6;i++)
|
||||||
|
{
|
||||||
|
*p = *macaddr;
|
||||||
|
p++;
|
||||||
|
macaddr--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_TimeIsr
|
||||||
|
*
|
||||||
|
* @brief
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_TimeIsr( uint16_t timperiod )
|
||||||
|
{
|
||||||
|
LocalTime += timperiod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_QueryPhySta
|
||||||
|
*
|
||||||
|
* @brief Query external PHY status
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_QueryPhySta(void)
|
||||||
|
{
|
||||||
|
u16 phy_stat;
|
||||||
|
if(QUERY_STAT_FLAG){ /* Query the PHY link status every 1s */
|
||||||
|
LastQueryPhyTime = LocalTime / 1000;
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
if((phy_stat != LastPhyStat) && (phy_stat != 0xffff)){
|
||||||
|
ETH_PHYLink();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_CheckPHYPN
|
||||||
|
*
|
||||||
|
* @brief check PHY PN polarity
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_CheckPHYPN(uint16_t time)
|
||||||
|
{
|
||||||
|
u16 phy_stat;
|
||||||
|
|
||||||
|
//check PHY PN
|
||||||
|
if((LinkProcessingStep == 0)||(LocalTime >= LinkProcessingTime))
|
||||||
|
{
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x10);
|
||||||
|
if(phy_stat & (1<<12))
|
||||||
|
{
|
||||||
|
if(LinkProcessingStep == 0)
|
||||||
|
{
|
||||||
|
LinkProcessingStep = 1;
|
||||||
|
LinkProcessingTime = LocalTime + time;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, PHY_ANER);
|
||||||
|
if((time == 200) || ((phy_stat & 1) == 0))
|
||||||
|
{
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x16);
|
||||||
|
phy_stat |= 1<<5;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x16, phy_stat );
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x16);
|
||||||
|
phy_stat &= ~(1<<5);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x16, phy_stat );
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x1E); /* Clear the Interrupt status */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_AccelerateLink
|
||||||
|
*
|
||||||
|
* @brief accelerate Link processing
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_AccelerateLink(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat;
|
||||||
|
|
||||||
|
switch(AccelerateLinkStep)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
AccelerateLinkTime = 0;
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x18);
|
||||||
|
phy_stat &= ~(1<<15);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x18, phy_stat );
|
||||||
|
|
||||||
|
//power down
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
phy_stat |= (1<<11);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_BCR, phy_stat );
|
||||||
|
|
||||||
|
//decrease Link Time
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x13, 0x4 );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
if(AccelerateLinkTime++ > 120) //unit:10ms,total time:1.2s~1.5s
|
||||||
|
{
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x18);
|
||||||
|
phy_stat |= 1<<15;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x18, phy_stat );
|
||||||
|
// power up
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
phy_stat &= ~(1<<11);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_BCR, phy_stat );
|
||||||
|
|
||||||
|
Delay_Us(300);
|
||||||
|
PHY_FuncInit();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 99 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x19);
|
||||||
|
if((phy_stat & 0xf) == 2)
|
||||||
|
{
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x13, 0x0 );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
/*do nothing*/
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_CheckLinkVaild
|
||||||
|
*
|
||||||
|
* @brief check whether Link is valid
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_CheckLinkVaild(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat, phy_bcr;
|
||||||
|
|
||||||
|
if(LinkVaildFlag == 0)
|
||||||
|
{
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
if((phy_bcr & (1<<13)) == 0) //Do nothing if Link mode is 10M.
|
||||||
|
{
|
||||||
|
LinkVaildFlag = 1;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x10);
|
||||||
|
if((phy_stat & (1<<9)) == 0)
|
||||||
|
{
|
||||||
|
LinkProcessingTime++;
|
||||||
|
if(LinkProcessingTime == 5)
|
||||||
|
{
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
phy_stat = ETH_ReadPHYRegister(gPHYAddress, PHY_BCR);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_BCR, PHY_Reset );
|
||||||
|
Delay_Us(100);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_BCR, phy_stat );
|
||||||
|
ETH_LinkDownCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkVaildFlag = 1;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_LinkProcessing
|
||||||
|
*
|
||||||
|
* @brief process Link stage task
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_LinkProcessing(void)
|
||||||
|
{
|
||||||
|
u16 phy_bcr;
|
||||||
|
|
||||||
|
if(LocalTime >= TaskExecutionTime)
|
||||||
|
{
|
||||||
|
TaskExecutionTime = LocalTime + 10; //execution cycle:10ms
|
||||||
|
if(LinkSta == 0) //Link down
|
||||||
|
{
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
if(phy_bcr & PHY_AutoNegotiation) //auto-negotiation is enabled
|
||||||
|
{
|
||||||
|
WCHNET_CheckPHYPN(300); //check PHY PN
|
||||||
|
WCHNET_AccelerateLink(); //accelerate Link processing
|
||||||
|
}
|
||||||
|
else { //auto-negotiation is disabled
|
||||||
|
if((phy_bcr & (1<<13)) == 0) // 10M
|
||||||
|
{
|
||||||
|
WCHNET_CheckPHYPN(200); //check PHY PN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { //Link up
|
||||||
|
WCHNET_CheckLinkVaild(); //check whether Link is valid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_MainTask
|
||||||
|
*
|
||||||
|
* @brief library main task function
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_MainTask(void)
|
||||||
|
{
|
||||||
|
WCHNET_NetInput( ); /* Ethernet data input */
|
||||||
|
WCHNET_PeriodicHandle( ); /* Protocol stack time-related task processing */
|
||||||
|
WCHNET_QueryPhySta(); /* Query external PHY status */
|
||||||
|
WCHNET_LinkProcessing(); /* process Link stage task */
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_SetClock
|
||||||
|
*
|
||||||
|
* @brief Set the Ethernet related clock
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_SetClock(void)
|
||||||
|
{
|
||||||
|
/* Only support HSE_VALUE: 8MHz.
|
||||||
|
* If you select other HSE value,you should
|
||||||
|
* change the configuration below*/
|
||||||
|
RCC_PLL3Cmd(DISABLE);
|
||||||
|
RCC_PREDIV2Config(RCC_PREDIV2_Div1); // HSE = 8M
|
||||||
|
RCC_PLL3Config(RCC_PLL3Mul_12_5); // 8M*12.5 = 100MHz
|
||||||
|
RCC_PLL3Cmd(ENABLE);
|
||||||
|
while(RESET == RCC_GetFlagStatus(RCC_FLAG_PLL3RDY));
|
||||||
|
Delay_Us(300);//Wait for the PHY clock to stabilize
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RMIIPinInit
|
||||||
|
*
|
||||||
|
* @brief PHY RMII interface GPIO initialization.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_RMIIPinInit(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure;
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD|RCC_APB2Periph_GPIOE|RCC_APB2Periph_AFIO, ENABLE);
|
||||||
|
GPIO_ETH_MediaInterfaceConfig(GPIO_ETH_MediaInterface_RMII);
|
||||||
|
GPIO_Output(GPIOD, GPIO_Pin_8); /* MDIO */
|
||||||
|
GPIO_Output(GPIOE, GPIO_Pin_15); /* MDC */
|
||||||
|
|
||||||
|
GPIO_Output(GPIOE, GPIO_Pin_8); /* TXEN */
|
||||||
|
GPIO_Output(GPIOE, GPIO_Pin_11); /* TXD0 */
|
||||||
|
GPIO_Output(GPIOE, GPIO_Pin_10); /* TXD1 */
|
||||||
|
|
||||||
|
GPIO_Output(GPIOE, GPIO_Pin_12); /* REFCLK */
|
||||||
|
GPIO_Input(GPIOE, GPIO_Pin_9); /* CRSDV */
|
||||||
|
GPIO_Input(GPIOE, GPIO_Pin_14); /* RXD0 */
|
||||||
|
GPIO_Input(GPIOE, GPIO_Pin_13); /* RXD1 */
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LinkUpCfg
|
||||||
|
*
|
||||||
|
* @brief When the PHY is connected, configure the relevant functions.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LinkUpCfg(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat;
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR );
|
||||||
|
/* PHY negotiation result */
|
||||||
|
if(phy_stat & (1<<13)) /* 100M */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
ETH->MACCR |= ETH_Speed_100M;
|
||||||
|
}
|
||||||
|
else /* 10M */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
}
|
||||||
|
if(phy_stat & (1<<8)) /* full duplex */
|
||||||
|
{
|
||||||
|
ETH->MACCR |= ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
else /* half duplex */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
|
||||||
|
LinkSta = 1;
|
||||||
|
AccelerateLinkStep = 0;
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
ETH_Start( );
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = 0x0;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x13, phy_stat );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LinkDownCfg
|
||||||
|
*
|
||||||
|
* @brief When the PHY is disconnected, configure the relevant functions.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LinkDownCfg(void)
|
||||||
|
{
|
||||||
|
LinkSta = 0;
|
||||||
|
LinkVaildFlag = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_PHYLink
|
||||||
|
*
|
||||||
|
* @brief Configure MAC parameters after the PHY Link is successful.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_PHYLink( void )
|
||||||
|
{
|
||||||
|
u32 phy_stat, phy_anlpar, phy_bcr;
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
phy_anlpar = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_ANLPAR);
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( gPHYAddress, PHY_BCR);
|
||||||
|
LastPhyStat = phy_stat;
|
||||||
|
|
||||||
|
WCHNET_PhyStatus( phy_stat );
|
||||||
|
if(phy_stat & PHY_Linked_Status) //LinkUp
|
||||||
|
{
|
||||||
|
if(phy_bcr & PHY_AutoNegotiation)
|
||||||
|
{
|
||||||
|
if(phy_anlpar == 0)
|
||||||
|
{
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if(phy_stat & PHY_AutoNego_Complete)
|
||||||
|
{
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { //LinkDown
|
||||||
|
/*Link down*/
|
||||||
|
ETH_LinkDownCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn PHY_FuncInit
|
||||||
|
*
|
||||||
|
* @brief PHY register initialization.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return None.
|
||||||
|
*/
|
||||||
|
void PHY_FuncInit(void)
|
||||||
|
{
|
||||||
|
uint16_t regval;
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x00 );
|
||||||
|
/* Configure Repeater mode */
|
||||||
|
regval = ETH_ReadPHYRegister(gPHYAddress, 28);
|
||||||
|
regval |= 1<<13;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 28, regval );
|
||||||
|
|
||||||
|
/*rmii rx&tx clock change */
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x07 );
|
||||||
|
regval = ETH_ReadPHYRegister( gPHYAddress, 16);
|
||||||
|
regval &= ~(0xff<<4);
|
||||||
|
regval |= 0x23<<4;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 16, regval );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RegInit
|
||||||
|
*
|
||||||
|
* @brief ETH register initialization.
|
||||||
|
*
|
||||||
|
* @param ETH_InitStruct:initialization struct.
|
||||||
|
* PHYAddress:PHY address.
|
||||||
|
*
|
||||||
|
* @return Initialization status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_RegInit( ETH_InitTypeDef* ETH_InitStruct, uint16_t PHYAddress )
|
||||||
|
{
|
||||||
|
/* Set the SMI interface clock, set as the main frequency divided by 42 */
|
||||||
|
ETH->MACMIIAR = (uint32_t)ETH_MACMIIAR_CR_Div42;
|
||||||
|
|
||||||
|
/*------------------------ MAC register configuration -------------------------------------------*/
|
||||||
|
ETH->MACCR = (uint32_t)(ETH_InitStruct->ETH_Watchdog |
|
||||||
|
ETH_InitStruct->ETH_Jabber |
|
||||||
|
ETH_InitStruct->ETH_InterFrameGap |
|
||||||
|
ETH_InitStruct->ETH_ChecksumOffload |
|
||||||
|
ETH_InitStruct->ETH_AutomaticPadCRCStrip |
|
||||||
|
ETH_InitStruct->ETH_LoopbackMode);
|
||||||
|
|
||||||
|
ETH->MACFFR = (uint32_t)(ETH_InitStruct->ETH_ReceiveAll |
|
||||||
|
ETH_InitStruct->ETH_SourceAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PassControlFrames |
|
||||||
|
ETH_InitStruct->ETH_BroadcastFramesReception |
|
||||||
|
ETH_InitStruct->ETH_DestinationAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PromiscuousMode |
|
||||||
|
ETH_InitStruct->ETH_MulticastFramesFilter |
|
||||||
|
ETH_InitStruct->ETH_UnicastFramesFilter);
|
||||||
|
|
||||||
|
ETH->MACHTHR = (uint32_t)ETH_InitStruct->ETH_HashTableHigh;
|
||||||
|
ETH->MACHTLR = (uint32_t)ETH_InitStruct->ETH_HashTableLow;
|
||||||
|
|
||||||
|
ETH->MACFCR = (uint32_t)((ETH_InitStruct->ETH_PauseTime << 16) |
|
||||||
|
ETH_InitStruct->ETH_UnicastPauseFrameDetect |
|
||||||
|
ETH_InitStruct->ETH_ReceiveFlowControl |
|
||||||
|
ETH_InitStruct->ETH_TransmitFlowControl);
|
||||||
|
|
||||||
|
ETH->MACVLANTR = (uint32_t)(ETH_InitStruct->ETH_VLANTagComparison |
|
||||||
|
ETH_InitStruct->ETH_VLANTagIdentifier);
|
||||||
|
|
||||||
|
ETH->DMAOMR = (uint32_t)(ETH_InitStruct->ETH_DropTCPIPChecksumErrorFrame |
|
||||||
|
ETH_InitStruct->ETH_TransmitStoreForward |
|
||||||
|
ETH_InitStruct->ETH_ForwardErrorFrames |
|
||||||
|
ETH_InitStruct->ETH_ForwardUndersizedGoodFrames);
|
||||||
|
|
||||||
|
/* Reset the physical layer */
|
||||||
|
ETH_WritePHYRegister(PHYAddress, PHY_BCR, PHY_Reset);
|
||||||
|
Delay_Ms(1);
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Configuration
|
||||||
|
*
|
||||||
|
* @brief Ethernet configure.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Configuration( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ETH_InitTypeDef ETH_InitStructure;
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
|
||||||
|
/* Enable Ethernet MAC clock */
|
||||||
|
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ETH_MAC | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Tx | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Rx, ENABLE);
|
||||||
|
|
||||||
|
gPHYAddress = PHY_ADDRESS;
|
||||||
|
|
||||||
|
/* Enable RMII GPIO */
|
||||||
|
ETH_RMIIPinInit();
|
||||||
|
|
||||||
|
/* Set the Ethernet related clock */
|
||||||
|
ETH_SetClock();
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* ETHERNET Configuration */
|
||||||
|
/*------------------------ MAC -----------------------------------*/
|
||||||
|
ETH_InitStructure.ETH_Watchdog = ETH_Watchdog_Enable;
|
||||||
|
ETH_InitStructure.ETH_Jabber = ETH_Jabber_Enable;
|
||||||
|
ETH_InitStructure.ETH_InterFrameGap = ETH_InterFrameGap_96Bit;
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Enable;
|
||||||
|
#else
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Disable;
|
||||||
|
#endif
|
||||||
|
ETH_InitStructure.ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable;
|
||||||
|
ETH_InitStructure.ETH_LoopbackMode = ETH_LoopbackMode_Disable;
|
||||||
|
|
||||||
|
/* Filter function configuration */
|
||||||
|
ETH_InitStructure.ETH_ReceiveAll = ETH_ReceiveAll_Disable;
|
||||||
|
ETH_InitStructure.ETH_PromiscuousMode = ETH_PromiscuousMode_Disable;
|
||||||
|
ETH_InitStructure.ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Enable;
|
||||||
|
ETH_InitStructure.ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_PassControlFrames = ETH_PassControlFrames_BlockAll;
|
||||||
|
ETH_InitStructure.ETH_DestinationAddrFilter = ETH_DestinationAddrFilter_Normal;
|
||||||
|
ETH_InitStructure.ETH_SourceAddrFilter = ETH_SourceAddrFilter_Disable;
|
||||||
|
|
||||||
|
ETH_InitStructure.ETH_HashTableHigh = 0x0;
|
||||||
|
ETH_InitStructure.ETH_HashTableLow = 0x0;
|
||||||
|
|
||||||
|
/* VLan function configuration */
|
||||||
|
ETH_InitStructure.ETH_VLANTagComparison = ETH_VLANTagComparison_16Bit;
|
||||||
|
ETH_InitStructure.ETH_VLANTagIdentifier = 0x0;
|
||||||
|
|
||||||
|
/* Flow Control function configuration */
|
||||||
|
ETH_InitStructure.ETH_PauseTime = 0x0;
|
||||||
|
ETH_InitStructure.ETH_UnicastPauseFrameDetect = ETH_UnicastPauseFrameDetect_Disable;
|
||||||
|
ETH_InitStructure.ETH_ReceiveFlowControl = ETH_ReceiveFlowControl_Disable;
|
||||||
|
ETH_InitStructure.ETH_TransmitFlowControl = ETH_TransmitFlowControl_Disable;
|
||||||
|
|
||||||
|
/*------------------------ DMA -----------------------------------*/
|
||||||
|
/* When we use the Checksum offload feature, we need to enable the Store and Forward mode:
|
||||||
|
the store and forward guarantee that a whole frame is stored in the FIFO, so the MAC can insert/verify the checksum,
|
||||||
|
if the checksum is OK the DMA can handle the frame otherwise the frame is dropped */
|
||||||
|
ETH_InitStructure.ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Enable;
|
||||||
|
ETH_InitStructure.ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Enable;
|
||||||
|
/* Configure Ethernet */
|
||||||
|
ETH_RegInit( Ð_InitStructure, gPHYAddress );
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((macAddr[5]<<8) | macAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(macAddr[0] | (macAddr[1]<<8) | (macAddr[2]<<16) | (macAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU,\
|
||||||
|
ENABLE);
|
||||||
|
|
||||||
|
PHY_FuncInit();
|
||||||
|
/*Reads the default value of the PHY_BSR register*/
|
||||||
|
LastPhyStat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_TxPktChainMode
|
||||||
|
*
|
||||||
|
* @brief Ethernet sends data frames in chain mode.
|
||||||
|
*
|
||||||
|
* @param len Send data length
|
||||||
|
* pBuff send buffer pointer
|
||||||
|
*
|
||||||
|
* @return Send status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_TxPktChainMode(uint16_t len, uint32_t *pBuff )
|
||||||
|
{
|
||||||
|
/* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */
|
||||||
|
if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (u32)RESET)
|
||||||
|
{
|
||||||
|
/* Return ERROR: OWN bit set */
|
||||||
|
return ETH_ERROR;
|
||||||
|
}
|
||||||
|
/* Setting the Frame Length: bits[12:0] */
|
||||||
|
DMATxDescToSet->ControlBufferSize = (len & ETH_DMATxDesc_TBS1);
|
||||||
|
DMATxDescToSet->Buffer1Addr = (uint32_t)pBuff;
|
||||||
|
|
||||||
|
/* Setting the last segment and first segment bits (in this case a frame is transmitted in one descriptor) */
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS | ETH_DMATxDesc_CIC_TCPUDPICMP_Full;
|
||||||
|
#else
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_OWN;
|
||||||
|
|
||||||
|
/* Clear TBUS ETHERNET DMA flag */
|
||||||
|
ETH->DMASR = ETH_DMASR_TBUS;
|
||||||
|
/* Resume DMA transmission*/
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
|
||||||
|
/* Update the ETHERNET DMA global Tx descriptor with next Tx descriptor */
|
||||||
|
/* Chained Mode */
|
||||||
|
/* Selects the next DMA Tx descriptor list for next buffer to send */
|
||||||
|
DMATxDescToSet = (ETH_DMADESCTypeDef*) (DMATxDescToSet->Buffer2NextDescAddr);
|
||||||
|
/* Return SUCCESS */
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_ETHIsr
|
||||||
|
*
|
||||||
|
* @brief Ethernet Interrupt Service Routine
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void WCHNET_ETHIsr(void)
|
||||||
|
{
|
||||||
|
uint32_t int_sta;
|
||||||
|
|
||||||
|
int_sta = ETH->DMASR;
|
||||||
|
if (int_sta & ETH_DMA_IT_AIS)
|
||||||
|
{
|
||||||
|
if (int_sta & ETH_DMA_IT_RBU)
|
||||||
|
{
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_RBU);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_AIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
if( int_sta & ETH_DMA_IT_NIS )
|
||||||
|
{
|
||||||
|
if( int_sta & ETH_DMA_IT_R )
|
||||||
|
{
|
||||||
|
/*If you don't use the Ethernet library,
|
||||||
|
* you can do some data processing operations here*/
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
|
||||||
|
}
|
||||||
|
if( int_sta & ETH_DMA_IT_T )
|
||||||
|
{
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_T);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Init
|
||||||
|
*
|
||||||
|
* @brief Ethernet initialization.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Init( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ETH_Configuration( macAddr );
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
NVIC_EnableIRQ(ETH_IRQn);
|
||||||
|
NVIC_SetPriority(ETH_IRQn, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LibInit
|
||||||
|
*
|
||||||
|
* @brief Ethernet library initialization program
|
||||||
|
*
|
||||||
|
* @return command status
|
||||||
|
*/
|
||||||
|
uint8_t ETH_LibInit( uint8_t *ip, uint8_t *gwip, uint8_t *mask, uint8_t *macaddr )
|
||||||
|
{
|
||||||
|
uint8_t s;
|
||||||
|
struct _WCH_CFG cfg;
|
||||||
|
|
||||||
|
memset(&cfg,0,sizeof(cfg));
|
||||||
|
cfg.TxBufSize = ETH_TX_BUF_SZE;
|
||||||
|
cfg.TCPMss = WCHNET_TCP_MSS;
|
||||||
|
cfg.HeapSize = WCHNET_MEM_HEAP_SIZE;
|
||||||
|
cfg.ARPTableNum = WCHNET_NUM_ARP_TABLE;
|
||||||
|
cfg.MiscConfig0 = WCHNET_MISC_CONFIG0;
|
||||||
|
cfg.MiscConfig1 = WCHNET_MISC_CONFIG1;
|
||||||
|
cfg.net_send = ETH_TxPktChainMode;
|
||||||
|
cfg.CheckValid = WCHNET_CFG_VALID;
|
||||||
|
s = WCHNET_ConfigLIB(&cfg);
|
||||||
|
if( s ){
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
s = WCHNET_Init(ip,gwip,mask,macaddr);
|
||||||
|
ETH_Init( macaddr );
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************** endfile @ eth_driver ******************************/
|
||||||
@@ -0,0 +1,876 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : eth_driver.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.3.0
|
||||||
|
* Date : 2022/06/02
|
||||||
|
* Description : eth program body.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB]; /* MAC receive descriptor, 4-byte aligned*/
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMATxDscrTab[ETH_TXBUFNB]; /* MAC send descriptor, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACRxBuf[ETH_RXBUFNB*ETH_RX_BUF_SZE]; /* MAC receive buffer, 4-byte aligned */
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACTxBuf[ETH_TXBUFNB*ETH_TX_BUF_SZE]; /* MAC send buffer, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) SOCK_INF SocketInf[WCHNET_MAX_SOCKET_NUM]; /* Socket information table, 4-byte alignment */
|
||||||
|
const uint16_t MemNum[8] = {WCHNET_NUM_IPRAW,
|
||||||
|
WCHNET_NUM_UDP,
|
||||||
|
WCHNET_NUM_TCP,
|
||||||
|
WCHNET_NUM_TCP_LISTEN,
|
||||||
|
WCHNET_NUM_TCP_SEG,
|
||||||
|
WCHNET_NUM_IP_REASSDATA,
|
||||||
|
WCHNET_NUM_PBUF,
|
||||||
|
WCHNET_NUM_POOL_BUF
|
||||||
|
};
|
||||||
|
const uint16_t MemSize[8] = {WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IPRAW_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_UDP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB_LISTEN),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_SEG),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IP_REASSDATA),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF) + WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_POOL_BUF)
|
||||||
|
};
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Memp_Memory[WCHNET_MEMP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_Heap_Memory[WCHNET_RAM_HEAP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_ArpTable[WCHNET_RAM_ARP_TABLE_SIZE];
|
||||||
|
|
||||||
|
uint16_t gPHYAddress;
|
||||||
|
uint32_t ChipId = 0;
|
||||||
|
uint32_t volatile LocalTime;
|
||||||
|
|
||||||
|
ETH_DMADESCTypeDef *pDMARxSet;
|
||||||
|
ETH_DMADESCTypeDef *pDMATxSet;
|
||||||
|
|
||||||
|
extern u8 MACAddr[6];
|
||||||
|
volatile uint8_t LinkSta = 0; //0:Link down 1:Link up
|
||||||
|
uint8_t LinkVaildFlag = 0; //0:invalid 1:valid
|
||||||
|
uint8_t AccelerateLinkStep = 0;
|
||||||
|
uint8_t AccelerateLinkTime = 0;
|
||||||
|
uint8_t LinkProcessingStep = 0;
|
||||||
|
uint32_t LinkProcessingTime = 0;
|
||||||
|
uint32_t TaskExecutionTime = 0;
|
||||||
|
u16 LastPhyStat = 0;
|
||||||
|
u32 LastQueryPhyTime = 0;
|
||||||
|
void ETH_LinkDownCfg(void);
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_GetMacAddr
|
||||||
|
*
|
||||||
|
* @brief Get the MAC address
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_GetMacAddr( uint8_t *p )
|
||||||
|
{
|
||||||
|
uint8_t i;
|
||||||
|
uint8_t *macaddr = (uint8_t *)(ROM_CFG_USERADR_ID+5);
|
||||||
|
|
||||||
|
for(i=0;i<6;i++)
|
||||||
|
{
|
||||||
|
*p = *macaddr;
|
||||||
|
p++;
|
||||||
|
macaddr--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_TimeIsr
|
||||||
|
*
|
||||||
|
* @brief
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_TimeIsr( uint16_t timperiod )
|
||||||
|
{
|
||||||
|
LocalTime += timperiod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_QueryPhySta
|
||||||
|
*
|
||||||
|
* @brief Query external PHY status
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_QueryPhySta(void)
|
||||||
|
{
|
||||||
|
u16 phy_stat;
|
||||||
|
if(QUERY_STAT_FLAG){ /* Query the PHY link status every 1s */
|
||||||
|
LastQueryPhyTime = LocalTime / 1000;
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
if((phy_stat != LastPhyStat) && (phy_stat != 0xffff)){
|
||||||
|
ETH_PHYLink();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_CheckPHYPN
|
||||||
|
*
|
||||||
|
* @brief check PHY PN polarity
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_CheckPHYPN(uint16_t time)
|
||||||
|
{
|
||||||
|
u16 phy_stat;
|
||||||
|
|
||||||
|
//check PHY PN
|
||||||
|
if((LinkProcessingStep == 0)||(LocalTime >= LinkProcessingTime))
|
||||||
|
{
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x10);
|
||||||
|
if(phy_stat & (1<<12))
|
||||||
|
{
|
||||||
|
if(LinkProcessingStep == 0)
|
||||||
|
{
|
||||||
|
LinkProcessingStep = 1;
|
||||||
|
LinkProcessingTime = LocalTime + time;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, PHY_ANER);
|
||||||
|
if((time == 200) || ((phy_stat & 1) == 0))
|
||||||
|
{
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x16);
|
||||||
|
phy_stat |= 1<<5;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x16, phy_stat );
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x16);
|
||||||
|
phy_stat &= ~(1<<5);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x16, phy_stat );
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x1E); /* Clear the Interrupt status */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_AccelerateLink
|
||||||
|
*
|
||||||
|
* @brief accelerate Link processing
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_AccelerateLink(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat;
|
||||||
|
|
||||||
|
switch(AccelerateLinkStep)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
AccelerateLinkTime = 0;
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x18);
|
||||||
|
phy_stat &= ~(1<<15);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x18, phy_stat );
|
||||||
|
|
||||||
|
//power down
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
phy_stat |= (1<<11);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_BCR, phy_stat );
|
||||||
|
|
||||||
|
//decrease Link Time
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x13, 0x4 );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
if(AccelerateLinkTime++ > 120) //unit:10ms,total time:1.2s~1.5s
|
||||||
|
{
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x18);
|
||||||
|
phy_stat |= 1<<15;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x18, phy_stat );
|
||||||
|
// power up
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
phy_stat &= ~(1<<11);
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_BCR, phy_stat );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 99 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x19);
|
||||||
|
if((phy_stat & 0xf) == 2)
|
||||||
|
{
|
||||||
|
AccelerateLinkStep++;
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, PHY_PAG_SEL, 0x00 );
|
||||||
|
ETH_WritePHYRegister(PHY_ADDRESS, 0x13, 0x0 );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
/*do nothing*/
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_CheckLinkVaild
|
||||||
|
*
|
||||||
|
* @brief check whether Link is valid
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_CheckLinkVaild(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat, phy_bcr;
|
||||||
|
|
||||||
|
if(LinkVaildFlag == 0)
|
||||||
|
{
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
if((phy_bcr & (1<<13)) == 0) //Do nothing if Link mode is 10M.
|
||||||
|
{
|
||||||
|
LinkVaildFlag = 1;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0 );
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x10);
|
||||||
|
if((phy_stat & (1<<9)) == 0)
|
||||||
|
{
|
||||||
|
LinkProcessingTime++;
|
||||||
|
if(LinkProcessingTime == 5)
|
||||||
|
{
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
phy_stat = ETH_ReadPHYRegister(gPHYAddress, PHY_BCR);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_BCR, PHY_Reset );
|
||||||
|
Delay_Us(100);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, PHY_BCR, phy_stat );
|
||||||
|
ETH_LinkDownCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
LinkVaildFlag = 1;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_LinkProcessing
|
||||||
|
*
|
||||||
|
* @brief process Link stage task
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_LinkProcessing(void)
|
||||||
|
{
|
||||||
|
u16 phy_bcr;
|
||||||
|
|
||||||
|
if(LocalTime >= TaskExecutionTime)
|
||||||
|
{
|
||||||
|
TaskExecutionTime = LocalTime + 10; //execution cycle:10ms
|
||||||
|
if(LinkSta == 0) //Link down
|
||||||
|
{
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR);
|
||||||
|
if(phy_bcr & PHY_AutoNegotiation) //auto-negotiation is enabled
|
||||||
|
{
|
||||||
|
WCHNET_CheckPHYPN(300); //check PHY PN
|
||||||
|
WCHNET_AccelerateLink(); //accelerate Link processing
|
||||||
|
}
|
||||||
|
else { //auto-negotiation is disabled
|
||||||
|
if((phy_bcr & (1<<13)) == 0) // 10M
|
||||||
|
{
|
||||||
|
WCHNET_CheckPHYPN(200); //check PHY PN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { //Link up
|
||||||
|
WCHNET_CheckLinkVaild(); //check whether Link is valid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_MainTask
|
||||||
|
*
|
||||||
|
* @brief library main task function
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_MainTask(void)
|
||||||
|
{
|
||||||
|
WCHNET_NetInput( ); /* Ethernet data input */
|
||||||
|
WCHNET_PeriodicHandle( ); /* Protocol stack time-related task processing */
|
||||||
|
|
||||||
|
WCHNET_QueryPhySta(); /* Query external PHY status */
|
||||||
|
WCHNET_LinkProcessing(); /* process Link stage task */
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_MIIPinInit
|
||||||
|
*
|
||||||
|
* @brief PHY MII interface GPIO initialization.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_MIIPinInit(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure;
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC, ENABLE);
|
||||||
|
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_2); /* MDIO */
|
||||||
|
GPIO_Output(GPIOC, GPIO_Pin_1); /* MDC */
|
||||||
|
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_3); /* TXCLK */
|
||||||
|
GPIO_Output(GPIOB, GPIO_Pin_11); /* TXEN */
|
||||||
|
GPIO_Output(GPIOB, GPIO_Pin_12); /* TXD0 */
|
||||||
|
GPIO_Output(GPIOB, GPIO_Pin_13); /* TXD1 */
|
||||||
|
GPIO_Output(GPIOC, GPIO_Pin_2); /* TXD2 */
|
||||||
|
GPIO_Output(GPIOB, GPIO_Pin_8); /* TXD3 */
|
||||||
|
GPIO_Input(GPIOA, GPIO_Pin_1); /* RXC */
|
||||||
|
GPIO_Input(GPIOA, GPIO_Pin_7); /* RXDV */
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_4); /* RXD0 */
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_5); /* RXD1 */
|
||||||
|
GPIO_Input(GPIOB, GPIO_Pin_0); /* RXD2 */
|
||||||
|
GPIO_Input(GPIOB, GPIO_Pin_1); /* RXD3 */
|
||||||
|
GPIO_Input(GPIOB, GPIO_Pin_10); /* RXER */
|
||||||
|
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_0); /* CRS */
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_3); /* COL */
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LinkUpCfg
|
||||||
|
*
|
||||||
|
* @brief When the PHY is connected, configure the relevant functions.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LinkUpCfg(void)
|
||||||
|
{
|
||||||
|
uint16_t phy_stat;
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BCR );
|
||||||
|
/* PHY negotiation result */
|
||||||
|
if(phy_stat & (1<<13)) /* 100M */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
ETH->MACCR |= ETH_Speed_100M;
|
||||||
|
}
|
||||||
|
else /* 10M */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
}
|
||||||
|
if(phy_stat & (1<<8)) /* full duplex */
|
||||||
|
{
|
||||||
|
ETH->MACCR |= ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
else /* half duplex */
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
|
||||||
|
LinkSta = 1;
|
||||||
|
AccelerateLinkStep = 0;
|
||||||
|
LinkProcessingStep = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
ETH_Start( );
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0 );
|
||||||
|
phy_stat = 0x0;
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x13, phy_stat );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LinkDownCfg
|
||||||
|
*
|
||||||
|
* @brief When the PHY is disconnected, configure the relevant functions.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_LinkDownCfg(void)
|
||||||
|
{
|
||||||
|
LinkSta = 0;
|
||||||
|
LinkVaildFlag = 0;
|
||||||
|
LinkProcessingTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_PHYLink
|
||||||
|
*
|
||||||
|
* @brief Configure MAC parameters after the PHY Link is successful.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_PHYLink( void )
|
||||||
|
{
|
||||||
|
u32 phy_stat, phy_anlpar, phy_bcr;
|
||||||
|
uint8_t timeout = 0;
|
||||||
|
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
phy_anlpar = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_ANLPAR);
|
||||||
|
phy_bcr = ETH_ReadPHYRegister( gPHYAddress, PHY_BCR);
|
||||||
|
|
||||||
|
if((ChipId & 0xf0) <= 0x20)
|
||||||
|
{
|
||||||
|
while(phy_stat == 0)
|
||||||
|
{
|
||||||
|
Delay_Us(100);
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, PHY_BSR);
|
||||||
|
if(timeout++ == 15) break;
|
||||||
|
}
|
||||||
|
if(LastPhyStat == phy_stat) return;
|
||||||
|
}
|
||||||
|
LastPhyStat = phy_stat;
|
||||||
|
|
||||||
|
WCHNET_PhyStatus( phy_stat );
|
||||||
|
if(phy_stat & PHY_Linked_Status) //LinkUp
|
||||||
|
{
|
||||||
|
if(phy_bcr & PHY_AutoNegotiation)
|
||||||
|
{
|
||||||
|
if(phy_anlpar == 0)
|
||||||
|
{
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if(phy_stat & PHY_AutoNego_Complete)
|
||||||
|
{
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ETH_LinkUpCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { //LinkDown
|
||||||
|
/*Link down*/
|
||||||
|
ETH_LinkDownCfg();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RegInit
|
||||||
|
*
|
||||||
|
* @brief ETH register initialization.
|
||||||
|
*
|
||||||
|
* @param ETH_InitStruct:initialization struct.
|
||||||
|
* PHYAddress:PHY address.
|
||||||
|
*
|
||||||
|
* @return Initialization status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_RegInit( ETH_InitTypeDef* ETH_InitStruct, uint16_t PHYAddress )
|
||||||
|
{
|
||||||
|
uint16_t tmpreg;
|
||||||
|
/* Set the SMI interface clock, set as the main frequency divided by 42 */
|
||||||
|
ETH->MACMIIAR = (uint32_t)ETH_MACMIIAR_CR_Div42;
|
||||||
|
|
||||||
|
/*------------------------ MAC register configuration -------------------------------------------*/
|
||||||
|
ETH->MACCR = (uint32_t)(ETH_InitStruct->ETH_Watchdog |
|
||||||
|
ETH_InitStruct->ETH_Jabber |
|
||||||
|
ETH_InitStruct->ETH_InterFrameGap |
|
||||||
|
ETH_InitStruct->ETH_ChecksumOffload |
|
||||||
|
ETH_InitStruct->ETH_AutomaticPadCRCStrip |
|
||||||
|
ETH_InitStruct->ETH_LoopbackMode);
|
||||||
|
|
||||||
|
ETH->MACFFR = (uint32_t)(ETH_InitStruct->ETH_ReceiveAll |
|
||||||
|
ETH_InitStruct->ETH_SourceAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PassControlFrames |
|
||||||
|
ETH_InitStruct->ETH_BroadcastFramesReception |
|
||||||
|
ETH_InitStruct->ETH_DestinationAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PromiscuousMode |
|
||||||
|
ETH_InitStruct->ETH_MulticastFramesFilter |
|
||||||
|
ETH_InitStruct->ETH_UnicastFramesFilter);
|
||||||
|
|
||||||
|
ETH->MACHTHR = (uint32_t)ETH_InitStruct->ETH_HashTableHigh;
|
||||||
|
ETH->MACHTLR = (uint32_t)ETH_InitStruct->ETH_HashTableLow;
|
||||||
|
|
||||||
|
ETH->MACFCR = (uint32_t)((ETH_InitStruct->ETH_PauseTime << 16) |
|
||||||
|
ETH_InitStruct->ETH_UnicastPauseFrameDetect |
|
||||||
|
ETH_InitStruct->ETH_ReceiveFlowControl |
|
||||||
|
ETH_InitStruct->ETH_TransmitFlowControl);
|
||||||
|
|
||||||
|
ETH->MACVLANTR = (uint32_t)(ETH_InitStruct->ETH_VLANTagComparison |
|
||||||
|
ETH_InitStruct->ETH_VLANTagIdentifier);
|
||||||
|
|
||||||
|
ETH->DMAOMR = (uint32_t)(ETH_InitStruct->ETH_DropTCPIPChecksumErrorFrame |
|
||||||
|
ETH_InitStruct->ETH_TransmitStoreForward |
|
||||||
|
ETH_InitStruct->ETH_ForwardErrorFrames |
|
||||||
|
ETH_InitStruct->ETH_ForwardUndersizedGoodFrames);
|
||||||
|
|
||||||
|
/* Reset the physical layer */
|
||||||
|
ETH_WritePHYRegister(PHYAddress, PHY_BCR, PHY_Reset);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x00 );
|
||||||
|
tmpreg = ETH_ReadPHYRegister(gPHYAddress, 24);
|
||||||
|
if(tmpreg & (1<<1)) ETH_WritePHYRegister(PHYAddress, PHY_BCR, 0x3100);
|
||||||
|
|
||||||
|
/*Reads the default value of the PHY_BSR register*/
|
||||||
|
LastPhyStat = ETH_ReadPHYRegister( PHY_ADDRESS, PHY_BSR );
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Configuration
|
||||||
|
*
|
||||||
|
* @brief Ethernet configure.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Configuration( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ETH_InitTypeDef ETH_InitStructure;
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
|
||||||
|
/* Enable Ethernet MAC clock */
|
||||||
|
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ETH_MAC | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Tx | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Rx, ENABLE);
|
||||||
|
|
||||||
|
gPHYAddress = PHY_ADDRESS;
|
||||||
|
|
||||||
|
/* Enable MII GPIO */
|
||||||
|
ETH_MIIPinInit( );
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* ETHERNET Configuration */
|
||||||
|
/*------------------------ MAC -----------------------------------*/
|
||||||
|
ETH_InitStructure.ETH_Watchdog = ETH_Watchdog_Enable;
|
||||||
|
ETH_InitStructure.ETH_Jabber = ETH_Jabber_Enable;
|
||||||
|
ETH_InitStructure.ETH_InterFrameGap = ETH_InterFrameGap_96Bit;
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Enable;
|
||||||
|
#else
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Disable;
|
||||||
|
#endif
|
||||||
|
ETH_InitStructure.ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable;
|
||||||
|
ETH_InitStructure.ETH_LoopbackMode = ETH_LoopbackMode_Disable;
|
||||||
|
|
||||||
|
/* Filter function configuration */
|
||||||
|
ETH_InitStructure.ETH_ReceiveAll = ETH_ReceiveAll_Disable;
|
||||||
|
ETH_InitStructure.ETH_PromiscuousMode = ETH_PromiscuousMode_Disable;
|
||||||
|
ETH_InitStructure.ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Enable;
|
||||||
|
ETH_InitStructure.ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_PassControlFrames = ETH_PassControlFrames_BlockAll;
|
||||||
|
ETH_InitStructure.ETH_DestinationAddrFilter = ETH_DestinationAddrFilter_Normal;
|
||||||
|
ETH_InitStructure.ETH_SourceAddrFilter = ETH_SourceAddrFilter_Disable;
|
||||||
|
|
||||||
|
ETH_InitStructure.ETH_HashTableHigh = 0x0;
|
||||||
|
ETH_InitStructure.ETH_HashTableLow = 0x0;
|
||||||
|
|
||||||
|
/* VLan function configuration */
|
||||||
|
ETH_InitStructure.ETH_VLANTagComparison = ETH_VLANTagComparison_16Bit;
|
||||||
|
ETH_InitStructure.ETH_VLANTagIdentifier = 0x0;
|
||||||
|
|
||||||
|
/* Flow Control function configuration */
|
||||||
|
ETH_InitStructure.ETH_PauseTime = 0x0;
|
||||||
|
ETH_InitStructure.ETH_UnicastPauseFrameDetect = ETH_UnicastPauseFrameDetect_Disable;
|
||||||
|
ETH_InitStructure.ETH_ReceiveFlowControl = ETH_ReceiveFlowControl_Disable;
|
||||||
|
ETH_InitStructure.ETH_TransmitFlowControl = ETH_TransmitFlowControl_Disable;
|
||||||
|
|
||||||
|
/*------------------------ DMA -----------------------------------*/
|
||||||
|
/* When we use the Checksum offload feature, we need to enable the Store and Forward mode:
|
||||||
|
the store and forward guarantee that a whole frame is stored in the FIFO, so the MAC can insert/verify the checksum,
|
||||||
|
if the checksum is OK the DMA can handle the frame otherwise the frame is dropped */
|
||||||
|
ETH_InitStructure.ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Enable;
|
||||||
|
ETH_InitStructure.ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Enable;
|
||||||
|
/* Configure Ethernet */
|
||||||
|
ETH_RegInit( Ð_InitStructure, gPHYAddress );
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((macAddr[5]<<8) | macAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(macAddr[0] | (macAddr[1]<<8) | (macAddr[2]<<16) | (macAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU,\
|
||||||
|
ENABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_TxPktChainMode
|
||||||
|
*
|
||||||
|
* @brief Ethernet sends data frames in chain mode.
|
||||||
|
*
|
||||||
|
* @param len Send data length
|
||||||
|
* pBuff send buffer pointer
|
||||||
|
*
|
||||||
|
* @return Send status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_TxPktChainMode(uint16_t len, uint32_t *pBuff )
|
||||||
|
{
|
||||||
|
/* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */
|
||||||
|
if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (u32)RESET)
|
||||||
|
{
|
||||||
|
/* Return ERROR: OWN bit set */
|
||||||
|
return ETH_ERROR;
|
||||||
|
}
|
||||||
|
/* Setting the Frame Length: bits[12:0] */
|
||||||
|
DMATxDescToSet->ControlBufferSize = (len & ETH_DMATxDesc_TBS1);
|
||||||
|
DMATxDescToSet->Buffer1Addr = (uint32_t)pBuff;
|
||||||
|
|
||||||
|
/* Setting the last segment and first segment bits (in this case a frame is transmitted in one descriptor) */
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS | ETH_DMATxDesc_CIC_TCPUDPICMP_Full;
|
||||||
|
#else
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_OWN;
|
||||||
|
|
||||||
|
/* Clear TBUS ETHERNET DMA flag */
|
||||||
|
ETH->DMASR = ETH_DMASR_TBUS;
|
||||||
|
/* Resume DMA transmission*/
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
|
||||||
|
/* Update the ETHERNET DMA global Tx descriptor with next Tx descriptor */
|
||||||
|
/* Chained Mode */
|
||||||
|
/* Selects the next DMA Tx descriptor list for next buffer to send */
|
||||||
|
DMATxDescToSet = (ETH_DMADESCTypeDef*) (DMATxDescToSet->Buffer2NextDescAddr);
|
||||||
|
/* Return SUCCESS */
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Stop
|
||||||
|
*
|
||||||
|
* @brief Disables ENET MAC and DMA reception/transmission.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Stop(void)
|
||||||
|
{
|
||||||
|
ETH_MACTransmissionCmd(DISABLE);
|
||||||
|
ETH_FlushTransmitFIFO();
|
||||||
|
ETH_MACReceptionCmd(DISABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ReInitMACReg
|
||||||
|
*
|
||||||
|
* @brief Reinitialize MAC register.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ReInitMACReg(void)
|
||||||
|
{
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
uint32_t maccr, macmiiar, macffr, machthr, machtlr;
|
||||||
|
uint32_t macfcr, macvlantr, dmaomr;
|
||||||
|
|
||||||
|
/* Wait for sending data to complete */
|
||||||
|
while((ETH->DMASR & (7 << 20)) != ETH_DMA_TransmitProcess_Suspended);
|
||||||
|
|
||||||
|
ETH_Stop();
|
||||||
|
|
||||||
|
/* Record the register value */
|
||||||
|
macmiiar = ETH->MACMIIAR;
|
||||||
|
maccr = ETH->MACCR;
|
||||||
|
macffr = ETH->MACFFR;
|
||||||
|
machthr = ETH->MACHTHR;
|
||||||
|
machtlr = ETH->MACHTLR;
|
||||||
|
macfcr = ETH->MACFCR;
|
||||||
|
macvlantr = ETH->MACVLANTR;
|
||||||
|
dmaomr = ETH->DMAOMR;
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((MACAddr[5]<<8) | MACAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(MACAddr[0] | (MACAddr[1]<<8) | (MACAddr[2]<<16) | (MACAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU,\
|
||||||
|
ENABLE);
|
||||||
|
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
|
||||||
|
ETH->MACMIIAR = macmiiar;
|
||||||
|
ETH->MACCR = maccr;
|
||||||
|
ETH->MACFFR = macffr;
|
||||||
|
ETH->MACHTHR = machthr;
|
||||||
|
ETH->MACHTLR = machtlr;
|
||||||
|
ETH->MACFCR = macfcr;
|
||||||
|
ETH->MACVLANTR = macvlantr;
|
||||||
|
ETH->DMAOMR = dmaomr;
|
||||||
|
|
||||||
|
ETH_Start( );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_RecProcess
|
||||||
|
*
|
||||||
|
* @brief Receiving related processing
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_RecProcess(void)
|
||||||
|
{
|
||||||
|
if(((ChipId & 0xf0) <= 0x20) && \
|
||||||
|
((ETH->DMAMFBOCR & 0x1FFE0000) != 0))
|
||||||
|
{
|
||||||
|
ReInitMACReg();
|
||||||
|
/* Resume DMA transport */
|
||||||
|
ETH->DMARPDR = 0;
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_ETHIsr
|
||||||
|
*
|
||||||
|
* @brief Ethernet Interrupt Service Routine
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void WCHNET_ETHIsr(void)
|
||||||
|
{
|
||||||
|
uint32_t int_sta;
|
||||||
|
|
||||||
|
int_sta = ETH->DMASR;
|
||||||
|
if (int_sta & ETH_DMA_IT_AIS)
|
||||||
|
{
|
||||||
|
if (int_sta & ETH_DMA_IT_RBU)
|
||||||
|
{
|
||||||
|
WCHNET_RecProcess();
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_RBU);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_AIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
if( int_sta & ETH_DMA_IT_NIS )
|
||||||
|
{
|
||||||
|
if( int_sta & ETH_DMA_IT_R )
|
||||||
|
{
|
||||||
|
/*If you don't use the Ethernet library,
|
||||||
|
* you can do some data processing operations here*/
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
|
||||||
|
}
|
||||||
|
if( int_sta & ETH_DMA_IT_T )
|
||||||
|
{
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_T);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Init
|
||||||
|
*
|
||||||
|
* @brief Ethernet initialization.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Init( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ChipId = DBGMCU_GetCHIPID();
|
||||||
|
ETH_Configuration( macAddr );
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
NVIC_EnableIRQ(ETH_IRQn);
|
||||||
|
NVIC_SetPriority(ETH_IRQn, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LibInit
|
||||||
|
*
|
||||||
|
* @brief Ethernet library initialization program
|
||||||
|
*
|
||||||
|
* @return command status
|
||||||
|
*/
|
||||||
|
uint8_t ETH_LibInit( uint8_t *ip, uint8_t *gwip, uint8_t *mask, uint8_t *macaddr )
|
||||||
|
{
|
||||||
|
uint8_t s;
|
||||||
|
struct _WCH_CFG cfg;
|
||||||
|
|
||||||
|
memset(&cfg,0,sizeof(cfg));
|
||||||
|
cfg.TxBufSize = ETH_TX_BUF_SZE;
|
||||||
|
cfg.TCPMss = WCHNET_TCP_MSS;
|
||||||
|
cfg.HeapSize = WCHNET_MEM_HEAP_SIZE;
|
||||||
|
cfg.ARPTableNum = WCHNET_NUM_ARP_TABLE;
|
||||||
|
cfg.MiscConfig0 = WCHNET_MISC_CONFIG0;
|
||||||
|
cfg.MiscConfig1 = WCHNET_MISC_CONFIG1;
|
||||||
|
cfg.net_send = ETH_TxPktChainMode;
|
||||||
|
cfg.CheckValid = WCHNET_CFG_VALID;
|
||||||
|
s = WCHNET_ConfigLIB(&cfg);
|
||||||
|
if( s ){
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
s = WCHNET_Init(ip,gwip,mask,macaddr);
|
||||||
|
ETH_Init( macaddr );
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************** endfile @ eth_driver ******************************/
|
||||||
@@ -0,0 +1,714 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : eth_driver.c
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.3.0
|
||||||
|
* Date : 2022/06/02
|
||||||
|
* Description : eth program body.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
|
||||||
|
#include "string.h"
|
||||||
|
#include "eth_driver.h"
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMARxDscrTab[ETH_RXBUFNB]; /* MAC receive descriptor, 4-byte aligned*/
|
||||||
|
__attribute__((__aligned__(4))) ETH_DMADESCTypeDef DMATxDscrTab[ETH_TXBUFNB]; /* MAC send descriptor, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACRxBuf[ETH_RXBUFNB*ETH_RX_BUF_SZE]; /* MAC receive buffer, 4-byte aligned */
|
||||||
|
__attribute__((__aligned__(4))) uint8_t MACTxBuf[ETH_TXBUFNB*ETH_TX_BUF_SZE]; /* MAC send buffer, 4-byte aligned */
|
||||||
|
|
||||||
|
__attribute__((__aligned__(4))) SOCK_INF SocketInf[WCHNET_MAX_SOCKET_NUM]; /* Socket information table, 4-byte alignment */
|
||||||
|
const uint16_t MemNum[8] = {WCHNET_NUM_IPRAW,
|
||||||
|
WCHNET_NUM_UDP,
|
||||||
|
WCHNET_NUM_TCP,
|
||||||
|
WCHNET_NUM_TCP_LISTEN,
|
||||||
|
WCHNET_NUM_TCP_SEG,
|
||||||
|
WCHNET_NUM_IP_REASSDATA,
|
||||||
|
WCHNET_NUM_PBUF,
|
||||||
|
WCHNET_NUM_POOL_BUF
|
||||||
|
};
|
||||||
|
const uint16_t MemSize[8] = {WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IPRAW_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_UDP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB_LISTEN),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_SEG),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IP_REASSDATA),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF),
|
||||||
|
WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF) + WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_POOL_BUF)
|
||||||
|
};
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Memp_Memory[WCHNET_MEMP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_Heap_Memory[WCHNET_RAM_HEAP_SIZE];
|
||||||
|
__attribute__((__aligned__(4)))uint8_t Mem_ArpTable[WCHNET_RAM_ARP_TABLE_SIZE];
|
||||||
|
|
||||||
|
uint16_t gPHYAddress;
|
||||||
|
uint32_t volatile LocalTime;
|
||||||
|
|
||||||
|
ETH_DMADESCTypeDef *pDMARxSet;
|
||||||
|
ETH_DMADESCTypeDef *pDMATxSet;
|
||||||
|
|
||||||
|
u32 ChipId = 0;
|
||||||
|
#if !LINK_STAT_ACQUISITION_METHOD
|
||||||
|
u16 LastPhyStat = 0;
|
||||||
|
u32 LastQueryPhyTime = 0;
|
||||||
|
#endif
|
||||||
|
extern u8 MACAddr[6];
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_GetMacAddr
|
||||||
|
*
|
||||||
|
* @brief Get the MAC address
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_GetMacAddr( uint8_t *p )
|
||||||
|
{
|
||||||
|
uint8_t i;
|
||||||
|
uint8_t *macaddr = (uint8_t *)(ROM_CFG_USERADR_ID+5);
|
||||||
|
|
||||||
|
for(i=0;i<6;i++)
|
||||||
|
{
|
||||||
|
*p = *macaddr;
|
||||||
|
p++;
|
||||||
|
macaddr--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_TimeIsr
|
||||||
|
*
|
||||||
|
* @brief
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_TimeIsr( uint16_t timperiod )
|
||||||
|
{
|
||||||
|
LocalTime += timperiod;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_QueryPhySta
|
||||||
|
*
|
||||||
|
* @brief Query external PHY status
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
#if !LINK_STAT_ACQUISITION_METHOD
|
||||||
|
void WCHNET_QueryPhySta(void)
|
||||||
|
{
|
||||||
|
u16 phy_stat;
|
||||||
|
if(QUERY_STAT_FLAG){ /* Query the PHY link status every 1s */
|
||||||
|
LastQueryPhyTime = LocalTime / 1000;
|
||||||
|
ETH_WritePHYRegister( PHY_ADDRESS, 0x1F, 0x0a43 );
|
||||||
|
/*In some cases the status is not updated in time,
|
||||||
|
* so read this register twice to get the correct status value.*/
|
||||||
|
ETH_ReadPHYRegister( PHY_ADDRESS, 0x1A);
|
||||||
|
phy_stat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x1A) & 0x04;
|
||||||
|
if((phy_stat != LastPhyStat) && (phy_stat != 0xffff)){
|
||||||
|
ETH_PHYLink();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_MainTask
|
||||||
|
*
|
||||||
|
* @brief library main task function
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_MainTask(void)
|
||||||
|
{
|
||||||
|
WCHNET_NetInput( ); /* Ethernet data input */
|
||||||
|
WCHNET_PeriodicHandle( ); /* Protocol stack time-related task processing */
|
||||||
|
|
||||||
|
#if !LINK_STAT_ACQUISITION_METHOD
|
||||||
|
WCHNET_QueryPhySta(); /* Query external PHY status */
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RGMIIPinInit
|
||||||
|
*
|
||||||
|
* @brief PHY RGMII interface GPIO initialization.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_RGMIIPinInit(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure;
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC, ENABLE);
|
||||||
|
GPIOB->CFGHR &= ~(0xff<<16);
|
||||||
|
GPIOB->CFGHR |= (0xbb<<16);
|
||||||
|
GPIOB->CFGLR &= ~(0xff<<4);
|
||||||
|
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_2);
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_3);
|
||||||
|
GPIO_Output(GPIOA, GPIO_Pin_7);
|
||||||
|
GPIO_Output(GPIOC, GPIO_Pin_4);
|
||||||
|
GPIO_Output(GPIOC, GPIO_Pin_5);
|
||||||
|
GPIO_Output(GPIOB, GPIO_Pin_0);
|
||||||
|
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_0);
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_1);
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_2);
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_3);
|
||||||
|
GPIO_Input(GPIOA, GPIO_Pin_0);
|
||||||
|
GPIO_Input(GPIOA, GPIO_Pin_1);
|
||||||
|
|
||||||
|
GPIO_Input(GPIOB, GPIO_Pin_1); /* 125m in */
|
||||||
|
GPIO_Input(GPIOC, GPIO_Pin_7); /* interrupt pin */
|
||||||
|
}
|
||||||
|
|
||||||
|
#if LINK_STAT_ACQUISITION_METHOD
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn EXTI_Line_Init
|
||||||
|
*
|
||||||
|
* @brief Configure EXTI Line7.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void EXTI_Line_Init(void)
|
||||||
|
{
|
||||||
|
GPIO_InitTypeDef GPIO_InitStructure = {0};
|
||||||
|
EXTI_InitTypeDef EXTI_InitStructure = {0};
|
||||||
|
NVIC_InitTypeDef NVIC_InitStructure = {0};
|
||||||
|
|
||||||
|
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOC, ENABLE);
|
||||||
|
|
||||||
|
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
|
||||||
|
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
|
||||||
|
GPIO_Init(GPIOC, &GPIO_InitStructure);
|
||||||
|
|
||||||
|
/* GPIOC 7 ----> EXTI_Line7 */
|
||||||
|
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource7);
|
||||||
|
EXTI_InitStructure.EXTI_Line = EXTI_Line7;
|
||||||
|
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
|
||||||
|
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
|
||||||
|
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
|
||||||
|
EXTI_Init(&EXTI_InitStructure);
|
||||||
|
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
|
||||||
|
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
|
||||||
|
NVIC_Init(&NVIC_InitStructure);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn PHY_InterruptInit
|
||||||
|
*
|
||||||
|
* @brief Configure PHY interrupt function,Supported chip is:RTL8211FS
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void PHY_InterruptInit(void)
|
||||||
|
{
|
||||||
|
uint16_t RegValue;
|
||||||
|
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x1F, 0x0a42 );
|
||||||
|
RegValue = ETH_ReadPHYRegister(gPHYAddress, 0x12);
|
||||||
|
/* enable Link Status Change Interrupt and
|
||||||
|
* Auto-Negotiation Completed Interrupt*/
|
||||||
|
RegValue |= (1<<4)|(1<<3);
|
||||||
|
ETH_WritePHYRegister(gPHYAddress, 0x12, RegValue );
|
||||||
|
/* Clear the Interrupt status */
|
||||||
|
ETH_WritePHYRegister( gPHYAddress, 0x1F, 0x0a43 );
|
||||||
|
ETH_ReadPHYRegister( gPHYAddress, 0x1D);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_PHYLink
|
||||||
|
*
|
||||||
|
* @brief Configure MAC parameters after the PHY Link is successful.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ETH_PHYLink( void )
|
||||||
|
{
|
||||||
|
u32 phy_stat;
|
||||||
|
#if !LINK_STAT_ACQUISITION_METHOD
|
||||||
|
uint8_t timeout = 0;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
ETH_WritePHYRegister( gPHYAddress, 0x1F, 0x0a43 );
|
||||||
|
/*In some cases the status is not updated in time,
|
||||||
|
* so read this register twice to get the correct status value.*/
|
||||||
|
ETH_ReadPHYRegister( gPHYAddress, 0x1A);
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x1A);
|
||||||
|
#if !LINK_STAT_ACQUISITION_METHOD
|
||||||
|
if((ChipId & 0xf0) <= 0x20)
|
||||||
|
{
|
||||||
|
while(phy_stat == 0)
|
||||||
|
{
|
||||||
|
Delay_Us(100);
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x1A);
|
||||||
|
if(timeout++ == 15) break;
|
||||||
|
}
|
||||||
|
if(LastPhyStat == (phy_stat & 0x04)) return;
|
||||||
|
}
|
||||||
|
LastPhyStat = phy_stat & 0x04;
|
||||||
|
#endif
|
||||||
|
WCHNET_PhyStatus( phy_stat );
|
||||||
|
|
||||||
|
if( phy_stat & 0x04 )
|
||||||
|
{
|
||||||
|
/* Configure the polarity and delay of TXC */
|
||||||
|
RGMII_TXC_Delay(0, 4);
|
||||||
|
if( phy_stat & 0x08 )
|
||||||
|
{
|
||||||
|
ETH->MACCR |= ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~ETH_Mode_FullDuplex;
|
||||||
|
}
|
||||||
|
if( (phy_stat & 0x30) == 0x00 )
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
}
|
||||||
|
else if( (phy_stat & 0x30) == 0x10 )
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
ETH->MACCR |= ETH_Speed_100M;
|
||||||
|
}
|
||||||
|
else if( (phy_stat & 0x30) == 0x20 )
|
||||||
|
{
|
||||||
|
ETH->MACCR &= ~(ETH_Speed_100M|ETH_Speed_1000M);
|
||||||
|
ETH->MACCR |= ETH_Speed_1000M;
|
||||||
|
/* Configure the polarity and delay of TXC */
|
||||||
|
if((ChipId & 0xf0) >= 0x60)
|
||||||
|
RGMII_TXC_Delay(1, 2);
|
||||||
|
}
|
||||||
|
ETH_Start( );
|
||||||
|
}
|
||||||
|
phy_stat = ETH_ReadPHYRegister( gPHYAddress, 0x1D); /* Clear the Interrupt status */
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_RegInit
|
||||||
|
*
|
||||||
|
* @brief ETH register initialization.
|
||||||
|
*
|
||||||
|
* @param ETH_InitStruct:initialization struct.
|
||||||
|
* PHYAddress:PHY address.
|
||||||
|
*
|
||||||
|
* @return Initialization status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_RegInit( ETH_InitTypeDef* ETH_InitStruct, uint16_t PHYAddress )
|
||||||
|
{
|
||||||
|
/* Set the SMI interface clock, set as the main frequency divided by 42 */
|
||||||
|
ETH->MACMIIAR = (uint32_t)ETH_MACMIIAR_CR_Div42;
|
||||||
|
|
||||||
|
/*------------------------ MAC register configuration -------------------------------------------*/
|
||||||
|
ETH->MACCR = (uint32_t)(ETH_InitStruct->ETH_Watchdog |
|
||||||
|
ETH_InitStruct->ETH_Jabber |
|
||||||
|
ETH_InitStruct->ETH_InterFrameGap |
|
||||||
|
ETH_InitStruct->ETH_ChecksumOffload |
|
||||||
|
ETH_InitStruct->ETH_AutomaticPadCRCStrip |
|
||||||
|
ETH_InitStruct->ETH_LoopbackMode);
|
||||||
|
|
||||||
|
ETH->MACFFR = (uint32_t)(ETH_InitStruct->ETH_ReceiveAll |
|
||||||
|
ETH_InitStruct->ETH_SourceAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PassControlFrames |
|
||||||
|
ETH_InitStruct->ETH_BroadcastFramesReception |
|
||||||
|
ETH_InitStruct->ETH_DestinationAddrFilter |
|
||||||
|
ETH_InitStruct->ETH_PromiscuousMode |
|
||||||
|
ETH_InitStruct->ETH_MulticastFramesFilter |
|
||||||
|
ETH_InitStruct->ETH_UnicastFramesFilter);
|
||||||
|
|
||||||
|
ETH->MACHTHR = (uint32_t)ETH_InitStruct->ETH_HashTableHigh;
|
||||||
|
ETH->MACHTLR = (uint32_t)ETH_InitStruct->ETH_HashTableLow;
|
||||||
|
|
||||||
|
ETH->MACFCR = (uint32_t)((ETH_InitStruct->ETH_PauseTime << 16) |
|
||||||
|
ETH_InitStruct->ETH_UnicastPauseFrameDetect |
|
||||||
|
ETH_InitStruct->ETH_ReceiveFlowControl |
|
||||||
|
ETH_InitStruct->ETH_TransmitFlowControl);
|
||||||
|
|
||||||
|
ETH->MACVLANTR = (uint32_t)(ETH_InitStruct->ETH_VLANTagComparison |
|
||||||
|
ETH_InitStruct->ETH_VLANTagIdentifier);
|
||||||
|
|
||||||
|
ETH->DMAOMR = (uint32_t)(ETH_InitStruct->ETH_DropTCPIPChecksumErrorFrame |
|
||||||
|
ETH_InitStruct->ETH_TransmitStoreForward |
|
||||||
|
ETH_InitStruct->ETH_ForwardErrorFrames |
|
||||||
|
ETH_InitStruct->ETH_ForwardUndersizedGoodFrames);
|
||||||
|
|
||||||
|
/* Reset the physical layer */
|
||||||
|
ETH_WritePHYRegister(PHYAddress, PHY_BCR, PHY_Reset);
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Configuration
|
||||||
|
*
|
||||||
|
* @brief Ethernet configure.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Configuration( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ETH_InitTypeDef ETH_InitStructure;
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
|
||||||
|
/* Enable Ethernet MAC clock */
|
||||||
|
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ETH_MAC | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Tx | \
|
||||||
|
RCC_AHBPeriph_ETH_MAC_Rx, ENABLE);
|
||||||
|
|
||||||
|
gPHYAddress = PHY_ADDRESS;
|
||||||
|
|
||||||
|
/* Enable 1G MAC*/
|
||||||
|
EXTEN->EXTEN_CTR |= EXTEN_ETH_RGMII_SEL;
|
||||||
|
RCC_ETH1GCLKConfig(RCC_ETH1GCLKSource_PB1_IN);
|
||||||
|
RCC_ETH1G_125Mcmd(ENABLE);
|
||||||
|
/* Enable RGMII GPIO */
|
||||||
|
ETH_RGMIIPinInit();
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* ETHERNET Configuration */
|
||||||
|
/*------------------------ MAC -----------------------------------*/
|
||||||
|
ETH_InitStructure.ETH_Watchdog = ETH_Watchdog_Enable;
|
||||||
|
ETH_InitStructure.ETH_Jabber = ETH_Jabber_Enable;
|
||||||
|
ETH_InitStructure.ETH_InterFrameGap = ETH_InterFrameGap_96Bit;
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Enable;
|
||||||
|
#else
|
||||||
|
ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Disable;
|
||||||
|
#endif
|
||||||
|
ETH_InitStructure.ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable;
|
||||||
|
ETH_InitStructure.ETH_LoopbackMode = ETH_LoopbackMode_Disable;
|
||||||
|
|
||||||
|
/* Filter function configuration */
|
||||||
|
ETH_InitStructure.ETH_ReceiveAll = ETH_ReceiveAll_Disable;
|
||||||
|
ETH_InitStructure.ETH_PromiscuousMode = ETH_PromiscuousMode_Disable;
|
||||||
|
ETH_InitStructure.ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Enable;
|
||||||
|
ETH_InitStructure.ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect;
|
||||||
|
ETH_InitStructure.ETH_PassControlFrames = ETH_PassControlFrames_BlockAll;
|
||||||
|
ETH_InitStructure.ETH_DestinationAddrFilter = ETH_DestinationAddrFilter_Normal;
|
||||||
|
ETH_InitStructure.ETH_SourceAddrFilter = ETH_SourceAddrFilter_Disable;
|
||||||
|
|
||||||
|
ETH_InitStructure.ETH_HashTableHigh = 0x0;
|
||||||
|
ETH_InitStructure.ETH_HashTableLow = 0x0;
|
||||||
|
|
||||||
|
/* VLan function configuration */
|
||||||
|
ETH_InitStructure.ETH_VLANTagComparison = ETH_VLANTagComparison_16Bit;
|
||||||
|
ETH_InitStructure.ETH_VLANTagIdentifier = 0x0;
|
||||||
|
|
||||||
|
/* Flow Control function configuration */
|
||||||
|
ETH_InitStructure.ETH_PauseTime = 0x0;
|
||||||
|
ETH_InitStructure.ETH_UnicastPauseFrameDetect = ETH_UnicastPauseFrameDetect_Disable;
|
||||||
|
ETH_InitStructure.ETH_ReceiveFlowControl = ETH_ReceiveFlowControl_Disable;
|
||||||
|
ETH_InitStructure.ETH_TransmitFlowControl = ETH_TransmitFlowControl_Disable;
|
||||||
|
|
||||||
|
/*------------------------ DMA -----------------------------------*/
|
||||||
|
/* When we use the Checksum offload feature, we need to enable the Store and Forward mode:
|
||||||
|
the store and forward guarantee that a whole frame is stored in the FIFO, so the MAC can insert/verify the checksum,
|
||||||
|
if the checksum is OK the DMA can handle the frame otherwise the frame is dropped */
|
||||||
|
ETH_InitStructure.ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Enable;
|
||||||
|
ETH_InitStructure.ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Enable;
|
||||||
|
ETH_InitStructure.ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Enable;
|
||||||
|
/* Configure Ethernet */
|
||||||
|
ETH_RegInit( Ð_InitStructure, gPHYAddress );
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((macAddr[5]<<8) | macAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(macAddr[0] | (macAddr[1]<<8) | (macAddr[2]<<16) | (macAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU,\
|
||||||
|
ENABLE);
|
||||||
|
|
||||||
|
#if LINK_STAT_ACQUISITION_METHOD
|
||||||
|
/* Configure the PHY interrupt function, the supported chip is: RTL8211FS */
|
||||||
|
PHY_InterruptInit( );
|
||||||
|
/* Configure EXTI Line7. */
|
||||||
|
EXTI_Line_Init( );
|
||||||
|
#else
|
||||||
|
ETH_WritePHYRegister( PHY_ADDRESS, 0x1F, 0x0a43 );
|
||||||
|
/*In some cases the status is not updated in time,
|
||||||
|
* so read this register twice to get the correct status value.*/
|
||||||
|
ETH_ReadPHYRegister( PHY_ADDRESS, 0x1A);
|
||||||
|
LastPhyStat = ETH_ReadPHYRegister( PHY_ADDRESS, 0x1A) & 0x04;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_TxPktChainMode
|
||||||
|
*
|
||||||
|
* @brief Ethernet sends data frames in chain mode.
|
||||||
|
*
|
||||||
|
* @param len Send data length
|
||||||
|
* pBuff send buffer pointer
|
||||||
|
*
|
||||||
|
* @return Send status.
|
||||||
|
*/
|
||||||
|
uint32_t ETH_TxPktChainMode(uint16_t len, uint32_t *pBuff )
|
||||||
|
{
|
||||||
|
/* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */
|
||||||
|
if((DMATxDescToSet->Status & ETH_DMATxDesc_OWN) != (u32)RESET)
|
||||||
|
{
|
||||||
|
/* Return ERROR: OWN bit set */
|
||||||
|
return ETH_ERROR;
|
||||||
|
}
|
||||||
|
/* Setting the Frame Length: bits[12:0] */
|
||||||
|
DMATxDescToSet->ControlBufferSize = (len & ETH_DMATxDesc_TBS1);
|
||||||
|
DMATxDescToSet->Buffer1Addr = (uint32_t)pBuff;
|
||||||
|
|
||||||
|
/* Setting the last segment and first segment bits (in this case a frame is transmitted in one descriptor) */
|
||||||
|
#if HARDWARE_CHECKSUM_CONFIG
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS | ETH_DMATxDesc_CIC_TCPUDPICMP_Full;
|
||||||
|
#else
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_LS | ETH_DMATxDesc_FS;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */
|
||||||
|
DMATxDescToSet->Status |= ETH_DMATxDesc_OWN;
|
||||||
|
|
||||||
|
/* Clear TBUS ETHERNET DMA flag */
|
||||||
|
ETH->DMASR = ETH_DMASR_TBUS;
|
||||||
|
/* Resume DMA transmission*/
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
|
||||||
|
/* Update the ETHERNET DMA global Tx descriptor with next Tx descriptor */
|
||||||
|
/* Chained Mode */
|
||||||
|
/* Selects the next DMA Tx descriptor list for next buffer to send */
|
||||||
|
DMATxDescToSet = (ETH_DMADESCTypeDef*) (DMATxDescToSet->Buffer2NextDescAddr);
|
||||||
|
/* Return SUCCESS */
|
||||||
|
return ETH_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Stop
|
||||||
|
*
|
||||||
|
* @brief Disables ENET MAC and DMA reception/transmission.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Stop(void)
|
||||||
|
{
|
||||||
|
ETH_MACTransmissionCmd(DISABLE);
|
||||||
|
ETH_FlushTransmitFIFO();
|
||||||
|
ETH_MACReceptionCmd(DISABLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ReInitMACReg
|
||||||
|
*
|
||||||
|
* @brief Reinitialize MAC register.
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void ReInitMACReg(void)
|
||||||
|
{
|
||||||
|
uint16_t timeout = 10000;
|
||||||
|
uint32_t maccr, macmiiar, macffr, machthr, machtlr;
|
||||||
|
uint32_t macfcr, macvlantr, dmaomr;
|
||||||
|
|
||||||
|
/* Wait for sending data to complete */
|
||||||
|
while((ETH->DMASR & (7 << 20)) != ETH_DMA_TransmitProcess_Suspended);
|
||||||
|
|
||||||
|
ETH_Stop();
|
||||||
|
|
||||||
|
/* Record the register value */
|
||||||
|
macmiiar = ETH->MACMIIAR;
|
||||||
|
maccr = ETH->MACCR;
|
||||||
|
macffr = ETH->MACFFR;
|
||||||
|
machthr = ETH->MACHTHR;
|
||||||
|
machtlr = ETH->MACHTLR;
|
||||||
|
macfcr = ETH->MACFCR;
|
||||||
|
macvlantr = ETH->MACVLANTR;
|
||||||
|
dmaomr = ETH->DMAOMR;
|
||||||
|
|
||||||
|
/* Reset ETHERNET on AHB Bus */
|
||||||
|
ETH_DeInit();
|
||||||
|
|
||||||
|
/* Software reset */
|
||||||
|
ETH_SoftwareReset();
|
||||||
|
|
||||||
|
/* Wait for software reset */
|
||||||
|
do{
|
||||||
|
Delay_Us(10);
|
||||||
|
if( !--timeout ) break;
|
||||||
|
}while(ETH->DMABMR & ETH_DMABMR_SR);
|
||||||
|
|
||||||
|
/* Configure MAC address */
|
||||||
|
ETH->MACA0HR = (uint32_t)((MACAddr[5]<<8) | MACAddr[4]);
|
||||||
|
ETH->MACA0LR = (uint32_t)(MACAddr[0] | (MACAddr[1]<<8) | (MACAddr[2]<<16) | (MACAddr[3]<<24));
|
||||||
|
|
||||||
|
/* Mask the interrupt that Tx good frame count counter reaches half the maximum value */
|
||||||
|
ETH->MMCTIMR = ETH_MMCTIMR_TGFM;
|
||||||
|
/* Mask the interrupt that Rx good unicast frames counter reaches half the maximum value */
|
||||||
|
/* Mask the interrupt that Rx crc error counter reaches half the maximum value */
|
||||||
|
ETH->MMCRIMR = ETH_MMCRIMR_RGUFM | ETH_MMCRIMR_RFCEM;
|
||||||
|
|
||||||
|
ETH_DMAITConfig(ETH_DMA_IT_NIS |\
|
||||||
|
ETH_DMA_IT_R |\
|
||||||
|
ETH_DMA_IT_T |\
|
||||||
|
ETH_DMA_IT_AIS |\
|
||||||
|
ETH_DMA_IT_RBU,\
|
||||||
|
ENABLE);
|
||||||
|
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
|
||||||
|
ETH->MACMIIAR = macmiiar;
|
||||||
|
ETH->MACCR = maccr;
|
||||||
|
ETH->MACFFR = macffr;
|
||||||
|
ETH->MACHTHR = machthr;
|
||||||
|
ETH->MACHTLR = machtlr;
|
||||||
|
ETH->MACFCR = macfcr;
|
||||||
|
ETH->MACVLANTR = macvlantr;
|
||||||
|
ETH->DMAOMR = dmaomr;
|
||||||
|
|
||||||
|
ETH_Start( );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_RecProcess
|
||||||
|
*
|
||||||
|
* @brief Receiving related processing
|
||||||
|
*
|
||||||
|
* @param none.
|
||||||
|
*
|
||||||
|
* @return none.
|
||||||
|
*/
|
||||||
|
void WCHNET_RecProcess(void)
|
||||||
|
{
|
||||||
|
if(((ChipId & 0xf0) <= 0x20) && \
|
||||||
|
((ETH->DMAMFBOCR & 0x1FFE0000) != 0))
|
||||||
|
{
|
||||||
|
ReInitMACReg();
|
||||||
|
/* Resume DMA transport */
|
||||||
|
ETH->DMARPDR = 0;
|
||||||
|
ETH->DMATPDR = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn WCHNET_ETHIsr
|
||||||
|
*
|
||||||
|
* @brief Ethernet Interrupt Service Routine
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void WCHNET_ETHIsr(void)
|
||||||
|
{
|
||||||
|
uint32_t int_sta;
|
||||||
|
|
||||||
|
int_sta = ETH->DMASR;
|
||||||
|
if (int_sta & ETH_DMA_IT_AIS)
|
||||||
|
{
|
||||||
|
if (int_sta & ETH_DMA_IT_RBU)
|
||||||
|
{
|
||||||
|
WCHNET_RecProcess();
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_RBU);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_AIS);
|
||||||
|
}
|
||||||
|
|
||||||
|
if( int_sta & ETH_DMA_IT_NIS )
|
||||||
|
{
|
||||||
|
if( int_sta & ETH_DMA_IT_R )
|
||||||
|
{
|
||||||
|
/*If you don't use the Ethernet library,
|
||||||
|
* you can do some data processing operations here*/
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_R);
|
||||||
|
}
|
||||||
|
if( int_sta & ETH_DMA_IT_T )
|
||||||
|
{
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_T);
|
||||||
|
}
|
||||||
|
ETH_DMAClearITPendingBit(ETH_DMA_IT_NIS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_Init
|
||||||
|
*
|
||||||
|
* @brief Ethernet initialization.
|
||||||
|
*
|
||||||
|
* @return none
|
||||||
|
*/
|
||||||
|
void ETH_Init( uint8_t *macAddr )
|
||||||
|
{
|
||||||
|
ChipId = DBGMCU_GetCHIPID();
|
||||||
|
ETH_Configuration( macAddr );
|
||||||
|
ETH_DMATxDescChainInit(DMATxDscrTab, MACTxBuf, ETH_TXBUFNB);
|
||||||
|
ETH_DMARxDescChainInit(DMARxDscrTab, MACRxBuf, ETH_RXBUFNB);
|
||||||
|
pDMARxSet = DMARxDscrTab;
|
||||||
|
pDMATxSet = DMATxDscrTab;
|
||||||
|
NVIC_EnableIRQ(ETH_IRQn);
|
||||||
|
NVIC_SetPriority(ETH_IRQn, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*********************************************************************
|
||||||
|
* @fn ETH_LibInit
|
||||||
|
*
|
||||||
|
* @brief Ethernet library initialization program
|
||||||
|
*
|
||||||
|
* @return command status
|
||||||
|
*/
|
||||||
|
uint8_t ETH_LibInit( uint8_t *ip, uint8_t *gwip, uint8_t *mask, uint8_t *macaddr )
|
||||||
|
{
|
||||||
|
uint8_t s;
|
||||||
|
struct _WCH_CFG cfg;
|
||||||
|
|
||||||
|
memset(&cfg,0,sizeof(cfg));
|
||||||
|
cfg.TxBufSize = ETH_TX_BUF_SZE;
|
||||||
|
cfg.TCPMss = WCHNET_TCP_MSS;
|
||||||
|
cfg.HeapSize = WCHNET_MEM_HEAP_SIZE;
|
||||||
|
cfg.ARPTableNum = WCHNET_NUM_ARP_TABLE;
|
||||||
|
cfg.MiscConfig0 = WCHNET_MISC_CONFIG0;
|
||||||
|
cfg.MiscConfig1 = WCHNET_MISC_CONFIG1;
|
||||||
|
cfg.net_send = ETH_TxPktChainMode;
|
||||||
|
cfg.CheckValid = WCHNET_CFG_VALID;
|
||||||
|
s = WCHNET_ConfigLIB(&cfg);
|
||||||
|
if( s ){
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
s = WCHNET_Init(ip,gwip,mask,macaddr);
|
||||||
|
ETH_Init( macaddr );
|
||||||
|
return (s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/******************************** endfile @ eth_driver ******************************/
|
||||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
+630
@@ -0,0 +1,630 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : wchnet.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.90
|
||||||
|
* Date : 2023/05/12
|
||||||
|
* Description : This file contains the headers of
|
||||||
|
* the Ethernet protocol stack library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __WCHNET_H__
|
||||||
|
#define __WCHNET_H__
|
||||||
|
|
||||||
|
#include "stdint.h"
|
||||||
|
#ifndef NET_LIB
|
||||||
|
#include "net_config.h"
|
||||||
|
#endif
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define WCHNET_LIB_VER 0x1B //the library version number
|
||||||
|
#define WCHNET_CFG_VALID 0x12345678 //Configuration value valid flag
|
||||||
|
|
||||||
|
/* LED state @LED_STAT */
|
||||||
|
#define LED_ON 0
|
||||||
|
#define LED_OFF 1
|
||||||
|
|
||||||
|
/* PHY state @PHY_STAT */
|
||||||
|
#define PHY_LINK_SUCCESS (1 << 2) //PHY connection success
|
||||||
|
#define PHY_AUTO_SUCCESS (1 << 5) //PHY auto negotiation completed
|
||||||
|
|
||||||
|
/* Library initialization state @CFG_INIT_STAT */
|
||||||
|
#define INIT_OK 0x00
|
||||||
|
#define INIT_ERR_RX_BUF_SIZE 0x01
|
||||||
|
#define INIT_ERR_TCP_MSS 0x02
|
||||||
|
#define INIT_ERR_HEAP_SIZE 0x03
|
||||||
|
#define INIT_ERR_ARP_TABLE_NEM 0x04
|
||||||
|
#define INIT_ERR_MISC_CONFIG0 0x05
|
||||||
|
#define INIT_ERR_MISC_CONFIG1 0x06
|
||||||
|
#define INIT_ERR_FUNC_SEND 0x09
|
||||||
|
#define INIT_ERR_CHECK_VALID 0xFF
|
||||||
|
|
||||||
|
/* Socket protocol type */
|
||||||
|
#define PROTO_TYPE_IP_RAW 0 //IP layer raw data
|
||||||
|
#define PROTO_TYPE_UDP 2 //UDP protocol
|
||||||
|
#define PROTO_TYPE_TCP 3 //TCP protocol
|
||||||
|
|
||||||
|
/* interrupt status */
|
||||||
|
/* The following are the states
|
||||||
|
* that GLOB_INT will generate */
|
||||||
|
#define GINT_STAT_UNREACH (1 << 0) //unreachable interrupt
|
||||||
|
#define GINT_STAT_IP_CONFLI (1 << 1) //IP conflict interrupt
|
||||||
|
#define GINT_STAT_PHY_CHANGE (1 << 2) //PHY state change interrupt
|
||||||
|
#define GINT_STAT_SOCKET (1 << 4) //socket related interrupt
|
||||||
|
|
||||||
|
/* The following are the states
|
||||||
|
* that Sn_INT will generate*/
|
||||||
|
#define SINT_STAT_RECV (1 << 2) //the socket receives data or the receive buffer is not empty
|
||||||
|
#define SINT_STAT_CONNECT (1 << 3) //connect successfully,generated in TCP mode
|
||||||
|
#define SINT_STAT_DISCONNECT (1 << 4) //disconnect,generated in TCP mode
|
||||||
|
#define SINT_STAT_TIM_OUT (1 << 6) //timeout disconnect,generated in TCP mode
|
||||||
|
|
||||||
|
|
||||||
|
/* Definitions for error constants. @ERR_T */
|
||||||
|
#define ERR_T
|
||||||
|
#define WCHNET_ERR_SUCCESS 0x00 //No error, everything OK
|
||||||
|
#define WCHNET_ERR_BUSY 0x10 //busy
|
||||||
|
#define WCHNET_ERR_MEM 0x11 //Out of memory error
|
||||||
|
#define WCHNET_ERR_BUF 0x12 //Buffer error
|
||||||
|
#define WCHNET_ERR_TIMEOUT 0x13 //Timeout
|
||||||
|
#define WCHNET_ERR_RTE 0x14 //Routing problem
|
||||||
|
#define WCHNET_ERR_ABRT 0x15 //Connection aborted
|
||||||
|
#define WCHNET_ERR_RST 0x16 //Connection reset
|
||||||
|
#define WCHNET_ERR_CLSD 0x17 //Connection closed
|
||||||
|
#define WCHNET_ERR_CONN 0x18 //Not connected
|
||||||
|
#define WCHNET_ERR_VAL 0x19 //Illegal value
|
||||||
|
#define WCHNET_ERR_ARG 0x1a //Illegal argument
|
||||||
|
#define WCHNET_ERR_USE 0x1b //Address in use
|
||||||
|
#define WCHNET_ERR_IF 0x1c //Low-level netif error
|
||||||
|
#define WCHNET_ERR_ISCONN 0x1d //Already connected
|
||||||
|
#define WCHNET_ERR_INPROGRESS 0x1e //Operation in progress
|
||||||
|
#define WCHNET_ERR_SOCKET_MEM 0X20 //Socket information error
|
||||||
|
#define WCHNET_ERR_UNSUPPORT_PROTO 0X21 //unsupported protocol type
|
||||||
|
#define WCHNET_RET_ABORT 0x5F //command process fail
|
||||||
|
#define WCHNET_ERR_UNKNOW 0xFA //unknow
|
||||||
|
|
||||||
|
/* unreachable condition related codes */
|
||||||
|
#define UNREACH_CODE_HOST 0 //host unreachable
|
||||||
|
#define UNREACH_CODE_NET 1 //network unreachable
|
||||||
|
#define UNREACH_CODE_PROTOCOL 2 //protocol unreachable
|
||||||
|
#define UNREACH_CODE_PROT 3 //port unreachable
|
||||||
|
/*For other values, please refer to the RFC792 document*/
|
||||||
|
|
||||||
|
/* TCP disconnect related codes */
|
||||||
|
#define TCP_CLOSE_NORMAL 0 //normal disconnect,a four-way handshake
|
||||||
|
#define TCP_CLOSE_RST 1 //reset the connection and close
|
||||||
|
#define TCP_CLOSE_ABANDON 2 //drop connection, and no termination message is sent
|
||||||
|
|
||||||
|
/* socket state code */
|
||||||
|
#define SOCK_STAT_CLOSED 0X00 //socket close
|
||||||
|
#define SOCK_STAT_OPEN 0X05 //socket open
|
||||||
|
|
||||||
|
/* TCP state code */
|
||||||
|
#define TCP_CLOSED 0 //TCP close
|
||||||
|
#define TCP_LISTEN 1 //TCP listening
|
||||||
|
#define TCP_SYN_SENT 2 //SYN send, connect request
|
||||||
|
#define TCP_SYN_RCVD 3 //SYN received, connection request received
|
||||||
|
#define TCP_ESTABLISHED 4 //TCP connection establishment
|
||||||
|
#define TCP_FIN_WAIT_1 5 //WAIT_1 state
|
||||||
|
#define TCP_FIN_WAIT_2 6 //WAIT_2 state
|
||||||
|
#define TCP_CLOSE_WAIT 7 //wait to close
|
||||||
|
#define TCP_CLOSING 8 //closing
|
||||||
|
#define TCP_LAST_ACK 9 //LAST_ACK
|
||||||
|
#define TCP_TIME_WAIT 10 //2MSL wait
|
||||||
|
|
||||||
|
/* The following values are fixed and cannot be changed */
|
||||||
|
#define WCHNET_MEM_ALIGN_SIZE(size) (((size) + WCHNET_MEM_ALIGNMENT - 1) & ~(WCHNET_MEM_ALIGNMENT - 1))
|
||||||
|
#define WCHNET_SIZE_IPRAW_PCB 0x1C //IPRAW PCB size
|
||||||
|
#define WCHNET_SIZE_UDP_PCB 0x20 //UDP PCB size
|
||||||
|
#define WCHNET_SIZE_TCP_PCB 0xB4 //TCP PCB size
|
||||||
|
#define WCHNET_SIZE_TCP_PCB_LISTEN 0x24 //TCP LISTEN PCB size
|
||||||
|
#define WCHNET_SIZE_IP_REASSDATA 0x20 //IP reassembled Management
|
||||||
|
#define WCHNET_SIZE_PBUF 0x10 //Packet Buf
|
||||||
|
#define WCHNET_SIZE_TCP_SEG 0x14 //TCP SEG structure
|
||||||
|
#define WCHNET_SIZE_MEM 0x08 //sizeof(struct mem)
|
||||||
|
#define WCHNET_SIZE_ARP_TABLE 0x18 //sizeof ARP table
|
||||||
|
|
||||||
|
#define WCHNET_MEMP_SIZE ((WCHNET_MEM_ALIGNMENT - 1) + \
|
||||||
|
(WCHNET_NUM_IPRAW * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IPRAW_PCB)) + \
|
||||||
|
(WCHNET_NUM_UDP * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_UDP_PCB)) + \
|
||||||
|
(WCHNET_NUM_TCP * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB)) + \
|
||||||
|
(WCHNET_NUM_TCP_LISTEN * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_PCB_LISTEN)) + \
|
||||||
|
(WCHNET_NUM_TCP_SEG * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_TCP_SEG)) + \
|
||||||
|
(WCHNET_NUM_IP_REASSDATA * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_IP_REASSDATA)) + \
|
||||||
|
(WCHNET_NUM_PBUF * WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF)) + \
|
||||||
|
(WCHNET_NUM_POOL_BUF * (WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_PBUF) + WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_POOL_BUF))))
|
||||||
|
|
||||||
|
#define HEAP_MEM_ALIGN_SIZE (WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_MEM))
|
||||||
|
#define WCHNET_RAM_HEAP_SIZE (WCHNET_MEM_ALIGN_SIZE(WCHNET_MEM_HEAP_SIZE) + HEAP_MEM_ALIGN_SIZE )
|
||||||
|
#define WCHNET_RAM_ARP_TABLE_SIZE (WCHNET_MEM_ALIGN_SIZE(WCHNET_SIZE_ARP_TABLE) * WCHNET_NUM_ARP_TABLE)
|
||||||
|
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t length;
|
||||||
|
uint32_t buffer;
|
||||||
|
}ETHFrameType;
|
||||||
|
|
||||||
|
/* LED callback type */
|
||||||
|
typedef void (*led_callback)( uint8_t setbit );
|
||||||
|
|
||||||
|
/* net send callback type */
|
||||||
|
typedef uint32_t (*eth_tx_set )( uint16_t len, uint32_t *pBuff );
|
||||||
|
|
||||||
|
/* net receive callback type */
|
||||||
|
typedef uint32_t (*eth_rx_set )( ETHFrameType *pkt );
|
||||||
|
|
||||||
|
/* DNS callback type */
|
||||||
|
typedef void (*dns_callback)( const char *name, uint8_t *ipaddr, void *callback_arg );
|
||||||
|
|
||||||
|
/* DHCP callback type */
|
||||||
|
typedef uint8_t (*dhcp_callback)( uint8_t status, void * );
|
||||||
|
|
||||||
|
/* socket receive callback type */
|
||||||
|
struct _SOCK_INF;
|
||||||
|
typedef void (*pSockRecv)( struct _SOCK_INF *, uint32_t, uint16_t, uint8_t *, uint32_t);
|
||||||
|
|
||||||
|
typedef uint8_t (*pTcpVerifyConnection)(uint32_t src_ip, uint16_t src_port, uint16_t dest_port);
|
||||||
|
|
||||||
|
/* Socket information struct */
|
||||||
|
typedef struct _SOCK_INF
|
||||||
|
{
|
||||||
|
uint32_t IntStatus; //interrupt state
|
||||||
|
uint32_t SockIndex; //Socket index value
|
||||||
|
uint32_t RecvStartPoint; //Start pointer of the receive buffer
|
||||||
|
uint32_t RecvBufLen; //Receive buffer length
|
||||||
|
uint32_t RecvCurPoint; //current pointer to receive buffer
|
||||||
|
uint32_t RecvReadPoint; //The read pointer of the receive buffer
|
||||||
|
uint32_t RecvRemLen; //The length of the remaining data in the receive buffer
|
||||||
|
uint32_t ProtoType; //protocol type
|
||||||
|
uint32_t SockStatus; //Low byte Socket state, the next low byte is TCP state, only meaningful in TCP mode
|
||||||
|
uint32_t DesPort; //destination port
|
||||||
|
uint32_t SourPort; //Source port, protocol type in IPRAW mode
|
||||||
|
uint8_t IPAddr[4]; //Socket destination IP address
|
||||||
|
void *Resv1; //Reserved, for internal use, for saving individual PCBs
|
||||||
|
void *Resv2; //Reserved, used internally, used by TCP Server
|
||||||
|
pSockRecv AppCallBack; //receive callback function
|
||||||
|
} SOCK_INF;
|
||||||
|
|
||||||
|
struct _WCH_CFG
|
||||||
|
{
|
||||||
|
uint32_t TxBufSize; //MAC send buffer size, reserved for use
|
||||||
|
uint32_t TCPMss; //TCP MSS size
|
||||||
|
uint32_t HeapSize; //heap memory size
|
||||||
|
uint32_t ARPTableNum; //Number of ARP lists
|
||||||
|
uint32_t MiscConfig0; //Miscellaneous Configuration 0
|
||||||
|
/* Bit 0 TCP send buffer copy 1: copy, 0: not copy */
|
||||||
|
/* Bit 1 TCP receive replication optimization, used for internal debugging */
|
||||||
|
/* bit 2 delete oldest TCP connection 1: enable, 0: disable */
|
||||||
|
/* Bits 3-7 Number of PBUFs of IP segments */
|
||||||
|
/* Bit 8 TCP Delay ACK disable */
|
||||||
|
uint32_t MiscConfig1; //Miscellaneous Configuration 1
|
||||||
|
/* Bits 0-7 Number of Sockets*/
|
||||||
|
/* Bits 8-12 Reserved */
|
||||||
|
/* Bit 13 PING enable, 1: On 0: Off */
|
||||||
|
/* Bits 14-18 TCP retransmission times */
|
||||||
|
/* Bits 19-23 TCP retransmission period, in 50 milliseconds */
|
||||||
|
/* bit 25 send failed retry, 1: enable, 0: disable */
|
||||||
|
/* bit 26 Select whether to perform IPv4 checksum check on
|
||||||
|
* the TCP/UDP/ICMP header of the received frame payload by hardware,
|
||||||
|
* and calculate and insert the checksum of the IP header and payload of the sent frame by hardware.*/
|
||||||
|
/* Bits 27-31 period (in 250 milliseconds) of Fine DHCP periodic process */
|
||||||
|
led_callback led_link; //PHY Link Status Indicator
|
||||||
|
led_callback led_data; //Ethernet communication indicator
|
||||||
|
eth_tx_set net_send; //Ethernet send
|
||||||
|
eth_rx_set net_recv; //Ethernet receive
|
||||||
|
uint32_t CheckValid; //Configuration value valid flag, fixed value @WCHNET_CFG_VALID
|
||||||
|
};
|
||||||
|
|
||||||
|
struct _NET_SYS
|
||||||
|
{
|
||||||
|
uint8_t IPAddr[4]; //IP address
|
||||||
|
uint8_t GWIPAddr[4]; //Gateway IP address
|
||||||
|
uint8_t MASKAddr[4]; //subnet mask
|
||||||
|
uint8_t MacAddr[8]; //MAC address
|
||||||
|
uint8_t UnreachIPAddr[4]; //Unreachable IP address
|
||||||
|
uint32_t RetranCount; //number of retries,default is 10 times
|
||||||
|
uint32_t RetranPeriod; //Retry period, unit MS, default 500MS
|
||||||
|
uint32_t PHYStat; //PHY state code
|
||||||
|
uint32_t NetStat; //The status of the Ethernet, including whether it is open, etc.
|
||||||
|
uint32_t MackFilt; //MAC filtering, the default is to receive broadcasts, receive local MAC
|
||||||
|
uint32_t GlobIntStatus; //global interrupt
|
||||||
|
uint32_t UnreachCode; //unreachable code
|
||||||
|
uint32_t UnreachProto; //unreachable protocol
|
||||||
|
uint32_t UnreachPort; //unreachable port
|
||||||
|
uint32_t SendFlag;
|
||||||
|
uint32_t Flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* KEEP LIVE configuration structure */
|
||||||
|
struct _KEEP_CFG
|
||||||
|
{
|
||||||
|
uint32_t KLIdle; //KEEPLIVE idle time, in ms
|
||||||
|
uint32_t KLIntvl; //KEEPLIVE period, in ms
|
||||||
|
uint32_t KLCount; //KEEPLIVE times
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Library initialization .
|
||||||
|
*
|
||||||
|
* @param ip - IP address pointer
|
||||||
|
* @param gwip - Gateway address pointer
|
||||||
|
* @param mask - Subnet mask pointer
|
||||||
|
* @param macaddr - MAC address pointer
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_Init(const uint8_t *ip, const uint8_t *gwip, const uint8_t *mask, const uint8_t *macaddr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief get library version
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return library version
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_GetVer(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get MAC address.
|
||||||
|
*
|
||||||
|
* @param(in) macaddr - MAC address
|
||||||
|
*
|
||||||
|
* @param(out) MAC address
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_GetMacAddr(uint8_t *macaddr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Library parameter configuration.
|
||||||
|
*
|
||||||
|
* @param cfg - Configuration parameter @_WCH_CFG
|
||||||
|
*
|
||||||
|
* @return Library configuration initialization state @CFG_INIT_STAT
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_ConfigLIB(struct _WCH_CFG *cfg);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Handle periodic tasks in the protocol stack
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_PeriodicHandle(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Ethernet data input. Always called in the main program,
|
||||||
|
* or called after the reception interrupt is detected.
|
||||||
|
*
|
||||||
|
* @param
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_NetInput( void );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Ethernet interrupt service function. Called after
|
||||||
|
* Ethernet interrupt is generated.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_ETHIsr(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get PHY status
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return PHY status @PHY_STAT
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_GetPHYStatus(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Query global interrupt status.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return GLOB_INT
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_QueryGlobalInt(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Read global interrupt and clear it.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return GLOB_INT
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_GetGlobalInt(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief create socket
|
||||||
|
*
|
||||||
|
* @param(in) *socketid - socket variable pointer
|
||||||
|
* @param socinf - Configuration parameters for creating sockets @SOCK_INF
|
||||||
|
*
|
||||||
|
* @param(out) *socketid - socket value
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketCreat( uint8_t *socketid, SOCK_INF *socinf);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Socket sends data.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param *buf - the first address of send buffer
|
||||||
|
* @param(in) *len - pointer to the length of the data expected to be sent
|
||||||
|
*
|
||||||
|
* @param(out) *len - pointer to the length of the data sent actually
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketSend( uint8_t socketid, uint8_t *buf, uint32_t *len);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Socket receives data.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param *buf - the first address of receive buffer
|
||||||
|
* @param(in) *len - pointer to the length of the data expected to be read
|
||||||
|
*
|
||||||
|
* @param(out) *buf - the first address of data buffer
|
||||||
|
* @param(out) *len - pointer to the length of the data read actually
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketRecv( uint8_t socketid, uint8_t *buf, uint32_t *len);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get socket interrupt, and clear socket interrupt.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
*
|
||||||
|
* @return Sn_INT
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_GetSocketInt( uint8_t socketid );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Get the length of the data received by socket.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param(in) *bufaddr - the first address of receive buffer
|
||||||
|
*
|
||||||
|
* @param(out) *bufaddr - the first address of data buffer
|
||||||
|
*
|
||||||
|
* @return the length of the data
|
||||||
|
*/
|
||||||
|
uint32_t WCHNET_SocketRecvLen( uint8_t socketid, uint32_t *bufaddr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief TCP connect. Used in TCP Client mode.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketConnect( uint8_t socketid);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief TCP listen. Used in TCP SERVER mode.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketListen( uint8_t socketid);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Close socket.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param mode - the way of disconnection.Used in TCP connection.
|
||||||
|
* @TCP disconnect related codes
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketClose( uint8_t socketid, uint8_t mode );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Modify socket receive buffer.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param bufaddr - Address of the receive buffer
|
||||||
|
* @param bufsize - Size of the receive buffer
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_ModifyRecvBuf( uint8_t socketid, uint32_t bufaddr, uint32_t bufsize);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief UDP send, specify the target IP and target port
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param *buf - Address of the sent data
|
||||||
|
* @param(in) *slen - Address of the sent length
|
||||||
|
* @param *sip - destination IP address
|
||||||
|
* @param port - destination port
|
||||||
|
*
|
||||||
|
* @param(out) *slen - actual length sent
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketUdpSendTo( uint8_t socketid, uint8_t *buf, uint32_t *slen, uint8_t *sip, uint16_t port);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Convert ASCII address to network address.
|
||||||
|
*
|
||||||
|
* @param *cp - ASCII address to be converted, such as "192.168.1.2"
|
||||||
|
* @param(in) *addr - First address of the memory stored in the converted network address
|
||||||
|
* @param(out) *addr - Converted network address, such as 0xC0A80102
|
||||||
|
* @return 0 - Success. Others - Failure.
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_Aton(const char *cp, uint8_t *addr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Convert network address to ASCII address.
|
||||||
|
*
|
||||||
|
* @param *ipaddr - socket id value
|
||||||
|
*
|
||||||
|
* @return Converted ASCII address
|
||||||
|
*/
|
||||||
|
uint8_t *WCHNET_Ntoa( uint8_t *ipaddr);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Set socket TTL.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param ttl - TTL value
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SetSocketTTL( uint8_t socketid, uint8_t ttl);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Start TCP retry sending immediately.
|
||||||
|
*
|
||||||
|
* @param socketid - TTL value
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_RetrySendUnack( uint8_t socketid);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Query the packets that are not sent successfully.
|
||||||
|
*
|
||||||
|
* @param socketid - TTL value
|
||||||
|
* @param(in) *addrlist - pointer to the address of the address list
|
||||||
|
* @param lislen - Length of the list
|
||||||
|
*
|
||||||
|
* @param(out) *addrlist - Address list of the data packets that are not sent successfully
|
||||||
|
*
|
||||||
|
* @return Number of unsent and unacknowledged segments
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_QueryUnack( uint8_t socketid, uint32_t *addrlist, uint16_t lislen );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Start DHCP.
|
||||||
|
*
|
||||||
|
* @param dhcp - Application layer callback function
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_DHCPStart( dhcp_callback dhcp );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Stop DHCP.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_DHCPStop( void );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure DHCP host name.
|
||||||
|
*
|
||||||
|
* @param *name - First address of DHCP host name
|
||||||
|
*
|
||||||
|
* @return 0 - Success. Others - Failure.
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_DHCPSetHostname(char *name);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialize the resolver: set up the UDP pcb and configure the default server
|
||||||
|
*
|
||||||
|
* @param *dnsip - the IP address of dns server
|
||||||
|
* @param port - the port number of dns server
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_InitDNS( uint8_t *dnsip, uint16_t port);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Stop DNS.
|
||||||
|
*
|
||||||
|
* @param None
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_DNSStop(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a hostname (string) into an IP address.
|
||||||
|
*
|
||||||
|
* @param hostname - the hostname that is to be queried
|
||||||
|
* @param addr - pointer to a struct ip_addr where to store the address if it is already
|
||||||
|
* cached in the dns_table (only valid if ERR_OK is returned!)
|
||||||
|
* @param found - a callback function to be called on success, failure or timeout (only if
|
||||||
|
* ERR_INPROGRESS is returned!)
|
||||||
|
* @param arg - argument to pass to the callback function
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
* WCHNET_ERR_SUCCESS if hostname is a valid IP address string or the host name is already in the local names table.
|
||||||
|
* ERR_INPROGRESS enqueue a request to be sent to the DNS server for resolution if no errors are present.
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_HostNameGetIp( const char *hostname, uint8_t *addr, dns_callback found, void *arg );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure KEEP LIVE parameter.
|
||||||
|
*
|
||||||
|
* @param *cfg - KEEPLIVE configuration parameter
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_ConfigKeepLive( struct _KEEP_CFG *cfg );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure ARP retransmission parameters.
|
||||||
|
*
|
||||||
|
* @param retry_period - ARP retransmission period, the default value is 10, the unit is 100ms
|
||||||
|
* retry_cnt - The number of ARP retransmissions, the default value is 3.
|
||||||
|
* When the value of the retry_cnt is 0xff, it will be retried
|
||||||
|
* until the MAC address of the device is obtained.
|
||||||
|
* Arp_Entry_timeout_s - the time an ARP entry stays valid after its last update.
|
||||||
|
* the default value is 300, the unit is 1s
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_ARPRetryCfg(uint8_t retry_period, uint8_t retry_cnt, uint16_t Arp_Entry_timeout_s);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure socket KEEP LIVE enable.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param enable - 1: Enabled. 0: Disabled.
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketSetKeepLive( uint8_t socketid, uint8_t enable );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure PHY state
|
||||||
|
*
|
||||||
|
* @param phy_stat - PHY state
|
||||||
|
*
|
||||||
|
* @return None
|
||||||
|
*/
|
||||||
|
void WCHNET_PhyStatus( uint32_t phy_stat );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Configure socket Nagle Func.
|
||||||
|
*
|
||||||
|
* @param socketid - socket id value
|
||||||
|
* @param enable - 1: Enabled. 0: Disabled.
|
||||||
|
*
|
||||||
|
* @return @ERR_T
|
||||||
|
*/
|
||||||
|
uint8_t WCHNET_SocketSetNagle( uint8_t socketid, uint8_t enable );
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,230 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_adc.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* ADC firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_ADC_H
|
||||||
|
#define __CH32V30x_ADC_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* ADC Init structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t ADC_Mode; /* Configures the ADC to operate in independent or
|
||||||
|
dual mode.
|
||||||
|
This parameter can be a value of @ref ADC_mode */
|
||||||
|
|
||||||
|
FunctionalState ADC_ScanConvMode; /* Specifies whether the conversion is performed in
|
||||||
|
Scan (multichannels) or Single (one channel) mode.
|
||||||
|
This parameter can be set to ENABLE or DISABLE */
|
||||||
|
|
||||||
|
FunctionalState ADC_ContinuousConvMode; /* Specifies whether the conversion is performed in
|
||||||
|
Continuous or Single mode.
|
||||||
|
This parameter can be set to ENABLE or DISABLE. */
|
||||||
|
|
||||||
|
uint32_t ADC_ExternalTrigConv; /* Defines the external trigger used to start the analog
|
||||||
|
to digital conversion of regular channels. This parameter
|
||||||
|
can be a value of @ref ADC_external_trigger_sources_for_regular_channels_conversion */
|
||||||
|
|
||||||
|
uint32_t ADC_DataAlign; /* Specifies whether the ADC data alignment is left or right.
|
||||||
|
This parameter can be a value of @ref ADC_data_align */
|
||||||
|
|
||||||
|
uint8_t ADC_NbrOfChannel; /* Specifies the number of ADC channels that will be converted
|
||||||
|
using the sequencer for regular channel group.
|
||||||
|
This parameter must range from 1 to 16. */
|
||||||
|
|
||||||
|
uint32_t ADC_OutputBuffer; /* Specifies whether the ADC channel output buffer is enabled or disabled.
|
||||||
|
This parameter can be a value of @ref ADC_OutputBuffer */
|
||||||
|
|
||||||
|
uint32_t ADC_Pga; /* Specifies the PGA gain multiple.
|
||||||
|
This parameter can be a value of @ref ADC_Pga */
|
||||||
|
}ADC_InitTypeDef;
|
||||||
|
|
||||||
|
/* ADC_mode */
|
||||||
|
#define ADC_Mode_Independent ((uint32_t)0x00000000)
|
||||||
|
#define ADC_Mode_RegInjecSimult ((uint32_t)0x00010000)
|
||||||
|
#define ADC_Mode_RegSimult_AlterTrig ((uint32_t)0x00020000)
|
||||||
|
#define ADC_Mode_InjecSimult_FastInterl ((uint32_t)0x00030000)
|
||||||
|
#define ADC_Mode_InjecSimult_SlowInterl ((uint32_t)0x00040000)
|
||||||
|
#define ADC_Mode_InjecSimult ((uint32_t)0x00050000)
|
||||||
|
#define ADC_Mode_RegSimult ((uint32_t)0x00060000)
|
||||||
|
#define ADC_Mode_FastInterl ((uint32_t)0x00070000)
|
||||||
|
#define ADC_Mode_SlowInterl ((uint32_t)0x00080000)
|
||||||
|
#define ADC_Mode_AlterTrig ((uint32_t)0x00090000)
|
||||||
|
|
||||||
|
/* ADC_external_trigger_sources_for_regular_channels_conversion */
|
||||||
|
#define ADC_ExternalTrigConv_T1_CC1 ((uint32_t)0x00000000)
|
||||||
|
#define ADC_ExternalTrigConv_T1_CC2 ((uint32_t)0x00020000)
|
||||||
|
#define ADC_ExternalTrigConv_T2_CC2 ((uint32_t)0x00060000)
|
||||||
|
#define ADC_ExternalTrigConv_T3_TRGO ((uint32_t)0x00080000)
|
||||||
|
#define ADC_ExternalTrigConv_T4_CC4 ((uint32_t)0x000A0000)
|
||||||
|
#define ADC_ExternalTrigConv_Ext_IT11_TIM8_TRGO ((uint32_t)0x000C0000)
|
||||||
|
|
||||||
|
#define ADC_ExternalTrigConv_T1_CC3 ((uint32_t)0x00040000)
|
||||||
|
#define ADC_ExternalTrigConv_None ((uint32_t)0x000E0000)
|
||||||
|
|
||||||
|
#define ADC_ExternalTrigConv_T3_CC1 ((uint32_t)0x00000000)
|
||||||
|
#define ADC_ExternalTrigConv_T2_CC3 ((uint32_t)0x00020000)
|
||||||
|
#define ADC_ExternalTrigConv_T8_CC1 ((uint32_t)0x00060000)
|
||||||
|
#define ADC_ExternalTrigConv_T8_TRGO ((uint32_t)0x00080000)
|
||||||
|
#define ADC_ExternalTrigConv_T5_CC1 ((uint32_t)0x000A0000)
|
||||||
|
#define ADC_ExternalTrigConv_T5_CC3 ((uint32_t)0x000C0000)
|
||||||
|
|
||||||
|
|
||||||
|
/* ADC_data_align */
|
||||||
|
#define ADC_DataAlign_Right ((uint32_t)0x00000000)
|
||||||
|
#define ADC_DataAlign_Left ((uint32_t)0x00000800)
|
||||||
|
|
||||||
|
/* ADC_channels */
|
||||||
|
#define ADC_Channel_0 ((uint8_t)0x00)
|
||||||
|
#define ADC_Channel_1 ((uint8_t)0x01)
|
||||||
|
#define ADC_Channel_2 ((uint8_t)0x02)
|
||||||
|
#define ADC_Channel_3 ((uint8_t)0x03)
|
||||||
|
#define ADC_Channel_4 ((uint8_t)0x04)
|
||||||
|
#define ADC_Channel_5 ((uint8_t)0x05)
|
||||||
|
#define ADC_Channel_6 ((uint8_t)0x06)
|
||||||
|
#define ADC_Channel_7 ((uint8_t)0x07)
|
||||||
|
#define ADC_Channel_8 ((uint8_t)0x08)
|
||||||
|
#define ADC_Channel_9 ((uint8_t)0x09)
|
||||||
|
#define ADC_Channel_10 ((uint8_t)0x0A)
|
||||||
|
#define ADC_Channel_11 ((uint8_t)0x0B)
|
||||||
|
#define ADC_Channel_12 ((uint8_t)0x0C)
|
||||||
|
#define ADC_Channel_13 ((uint8_t)0x0D)
|
||||||
|
#define ADC_Channel_14 ((uint8_t)0x0E)
|
||||||
|
#define ADC_Channel_15 ((uint8_t)0x0F)
|
||||||
|
#define ADC_Channel_16 ((uint8_t)0x10)
|
||||||
|
#define ADC_Channel_17 ((uint8_t)0x11)
|
||||||
|
|
||||||
|
#define ADC_Channel_TempSensor ((uint8_t)ADC_Channel_16)
|
||||||
|
#define ADC_Channel_Vrefint ((uint8_t)ADC_Channel_17)
|
||||||
|
|
||||||
|
/*ADC_output_buffer*/
|
||||||
|
#define ADC_OutputBuffer_Enable ((uint32_t)0x04000000)
|
||||||
|
#define ADC_OutputBuffer_Disable ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/*ADC_pga*/
|
||||||
|
#define ADC_Pga_1 ((uint32_t)0x00000000)
|
||||||
|
#define ADC_Pga_4 ((uint32_t)0x08000000)
|
||||||
|
#define ADC_Pga_16 ((uint32_t)0x10000000)
|
||||||
|
#define ADC_Pga_64 ((uint32_t)0x18000000)
|
||||||
|
|
||||||
|
/* ADC_sampling_time */
|
||||||
|
#define ADC_SampleTime_1Cycles5 ((uint8_t)0x00)
|
||||||
|
#define ADC_SampleTime_7Cycles5 ((uint8_t)0x01)
|
||||||
|
#define ADC_SampleTime_13Cycles5 ((uint8_t)0x02)
|
||||||
|
#define ADC_SampleTime_28Cycles5 ((uint8_t)0x03)
|
||||||
|
#define ADC_SampleTime_41Cycles5 ((uint8_t)0x04)
|
||||||
|
#define ADC_SampleTime_55Cycles5 ((uint8_t)0x05)
|
||||||
|
#define ADC_SampleTime_71Cycles5 ((uint8_t)0x06)
|
||||||
|
#define ADC_SampleTime_239Cycles5 ((uint8_t)0x07)
|
||||||
|
|
||||||
|
/* ADC_external_trigger_sources_for_injected_channels_conversion */
|
||||||
|
#define ADC_ExternalTrigInjecConv_T2_TRGO ((uint32_t)0x00002000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T2_CC1 ((uint32_t)0x00003000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T3_CC4 ((uint32_t)0x00004000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T4_TRGO ((uint32_t)0x00005000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_Ext_IT15_TIM8_CC4 ((uint32_t)0x00006000)
|
||||||
|
|
||||||
|
#define ADC_ExternalTrigInjecConv_T1_TRGO ((uint32_t)0x00000000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T1_CC4 ((uint32_t)0x00001000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_None ((uint32_t)0x00007000)
|
||||||
|
|
||||||
|
#define ADC_ExternalTrigInjecConv_T4_CC3 ((uint32_t)0x00002000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T8_CC2 ((uint32_t)0x00003000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T8_CC4 ((uint32_t)0x00004000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T5_TRGO ((uint32_t)0x00005000)
|
||||||
|
#define ADC_ExternalTrigInjecConv_T5_CC4 ((uint32_t)0x00006000)
|
||||||
|
|
||||||
|
|
||||||
|
/* ADC_injected_channel_selection */
|
||||||
|
#define ADC_InjectedChannel_1 ((uint8_t)0x14)
|
||||||
|
#define ADC_InjectedChannel_2 ((uint8_t)0x18)
|
||||||
|
#define ADC_InjectedChannel_3 ((uint8_t)0x1C)
|
||||||
|
#define ADC_InjectedChannel_4 ((uint8_t)0x20)
|
||||||
|
|
||||||
|
/* ADC_analog_watchdog_selection */
|
||||||
|
#define ADC_AnalogWatchdog_SingleRegEnable ((uint32_t)0x00800200)
|
||||||
|
#define ADC_AnalogWatchdog_SingleInjecEnable ((uint32_t)0x00400200)
|
||||||
|
#define ADC_AnalogWatchdog_SingleRegOrInjecEnable ((uint32_t)0x00C00200)
|
||||||
|
#define ADC_AnalogWatchdog_AllRegEnable ((uint32_t)0x00800000)
|
||||||
|
#define ADC_AnalogWatchdog_AllInjecEnable ((uint32_t)0x00400000)
|
||||||
|
#define ADC_AnalogWatchdog_AllRegAllInjecEnable ((uint32_t)0x00C00000)
|
||||||
|
#define ADC_AnalogWatchdog_None ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* ADC_interrupts_definition */
|
||||||
|
#define ADC_IT_EOC ((uint16_t)0x0220)
|
||||||
|
#define ADC_IT_AWD ((uint16_t)0x0140)
|
||||||
|
#define ADC_IT_JEOC ((uint16_t)0x0480)
|
||||||
|
|
||||||
|
/* ADC_flags_definition */
|
||||||
|
#define ADC_FLAG_AWD ((uint8_t)0x01)
|
||||||
|
#define ADC_FLAG_EOC ((uint8_t)0x02)
|
||||||
|
#define ADC_FLAG_JEOC ((uint8_t)0x04)
|
||||||
|
#define ADC_FLAG_JSTRT ((uint8_t)0x08)
|
||||||
|
#define ADC_FLAG_STRT ((uint8_t)0x10)
|
||||||
|
|
||||||
|
|
||||||
|
void ADC_DeInit(ADC_TypeDef* ADCx);
|
||||||
|
void ADC_Init(ADC_TypeDef* ADCx, ADC_InitTypeDef* ADC_InitStruct);
|
||||||
|
void ADC_StructInit(ADC_InitTypeDef* ADC_InitStruct);
|
||||||
|
void ADC_Cmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_DMACmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_ITConfig(ADC_TypeDef* ADCx, uint16_t ADC_IT, FunctionalState NewState);
|
||||||
|
void ADC_ResetCalibration(ADC_TypeDef* ADCx);
|
||||||
|
FlagStatus ADC_GetResetCalibrationStatus(ADC_TypeDef* ADCx);
|
||||||
|
void ADC_StartCalibration(ADC_TypeDef* ADCx);
|
||||||
|
FlagStatus ADC_GetCalibrationStatus(ADC_TypeDef* ADCx);
|
||||||
|
void ADC_SoftwareStartConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
FlagStatus ADC_GetSoftwareStartConvStatus(ADC_TypeDef* ADCx);
|
||||||
|
void ADC_DiscModeChannelCountConfig(ADC_TypeDef* ADCx, uint8_t Number);
|
||||||
|
void ADC_DiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_RegularChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
|
||||||
|
void ADC_ExternalTrigConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
uint16_t ADC_GetConversionValue(ADC_TypeDef* ADCx);
|
||||||
|
uint32_t ADC_GetDualModeConversionValue(void);
|
||||||
|
void ADC_AutoInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_InjectedDiscModeCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_ExternalTrigInjectedConvConfig(ADC_TypeDef* ADCx, uint32_t ADC_ExternalTrigInjecConv);
|
||||||
|
void ADC_ExternalTrigInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
void ADC_SoftwareStartInjectedConvCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
FlagStatus ADC_GetSoftwareStartInjectedConvCmdStatus(ADC_TypeDef* ADCx);
|
||||||
|
void ADC_InjectedChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel, uint8_t Rank, uint8_t ADC_SampleTime);
|
||||||
|
void ADC_InjectedSequencerLengthConfig(ADC_TypeDef* ADCx, uint8_t Length);
|
||||||
|
void ADC_SetInjectedOffset(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel, uint16_t Offset);
|
||||||
|
uint16_t ADC_GetInjectedConversionValue(ADC_TypeDef* ADCx, uint8_t ADC_InjectedChannel);
|
||||||
|
void ADC_AnalogWatchdogCmd(ADC_TypeDef* ADCx, uint32_t ADC_AnalogWatchdog);
|
||||||
|
void ADC_AnalogWatchdogThresholdsConfig(ADC_TypeDef* ADCx, uint16_t HighThreshold, uint16_t LowThreshold);
|
||||||
|
void ADC_AnalogWatchdogSingleChannelConfig(ADC_TypeDef* ADCx, uint8_t ADC_Channel);
|
||||||
|
void ADC_TempSensorVrefintCmd(FunctionalState NewState);
|
||||||
|
FlagStatus ADC_GetFlagStatus(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
|
||||||
|
void ADC_ClearFlag(ADC_TypeDef* ADCx, uint8_t ADC_FLAG);
|
||||||
|
ITStatus ADC_GetITStatus(ADC_TypeDef* ADCx, uint16_t ADC_IT);
|
||||||
|
void ADC_ClearITPendingBit(ADC_TypeDef* ADCx, uint16_t ADC_IT);
|
||||||
|
s32 TempSensor_Volt_To_Temper(s32 Value);
|
||||||
|
void ADC_BufferCmd(ADC_TypeDef* ADCx, FunctionalState NewState);
|
||||||
|
int16_t Get_CalibrationValue(ADC_TypeDef* ADCx);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_bkp.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* BKP firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_BKP_H
|
||||||
|
#define __CH32V30x_BKP_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* Tamper_Pin_active_level */
|
||||||
|
#define BKP_TamperPinLevel_High ((uint16_t)0x0000)
|
||||||
|
#define BKP_TamperPinLevel_Low ((uint16_t)0x0001)
|
||||||
|
|
||||||
|
/* RTC_output_source_to_output_on_the_Tamper_pin */
|
||||||
|
#define BKP_RTCOutputSource_None ((uint16_t)0x0000)
|
||||||
|
#define BKP_RTCOutputSource_CalibClock ((uint16_t)0x0080)
|
||||||
|
#define BKP_RTCOutputSource_Alarm ((uint16_t)0x0100)
|
||||||
|
#define BKP_RTCOutputSource_Second ((uint16_t)0x0300)
|
||||||
|
|
||||||
|
/* Data_Backup_Register */
|
||||||
|
#define BKP_DR1 ((uint16_t)0x0004)
|
||||||
|
#define BKP_DR2 ((uint16_t)0x0008)
|
||||||
|
#define BKP_DR3 ((uint16_t)0x000C)
|
||||||
|
#define BKP_DR4 ((uint16_t)0x0010)
|
||||||
|
#define BKP_DR5 ((uint16_t)0x0014)
|
||||||
|
#define BKP_DR6 ((uint16_t)0x0018)
|
||||||
|
#define BKP_DR7 ((uint16_t)0x001C)
|
||||||
|
#define BKP_DR8 ((uint16_t)0x0020)
|
||||||
|
#define BKP_DR9 ((uint16_t)0x0024)
|
||||||
|
#define BKP_DR10 ((uint16_t)0x0028)
|
||||||
|
#define BKP_DR11 ((uint16_t)0x0040)
|
||||||
|
#define BKP_DR12 ((uint16_t)0x0044)
|
||||||
|
#define BKP_DR13 ((uint16_t)0x0048)
|
||||||
|
#define BKP_DR14 ((uint16_t)0x004C)
|
||||||
|
#define BKP_DR15 ((uint16_t)0x0050)
|
||||||
|
#define BKP_DR16 ((uint16_t)0x0054)
|
||||||
|
#define BKP_DR17 ((uint16_t)0x0058)
|
||||||
|
#define BKP_DR18 ((uint16_t)0x005C)
|
||||||
|
#define BKP_DR19 ((uint16_t)0x0060)
|
||||||
|
#define BKP_DR20 ((uint16_t)0x0064)
|
||||||
|
#define BKP_DR21 ((uint16_t)0x0068)
|
||||||
|
#define BKP_DR22 ((uint16_t)0x006C)
|
||||||
|
#define BKP_DR23 ((uint16_t)0x0070)
|
||||||
|
#define BKP_DR24 ((uint16_t)0x0074)
|
||||||
|
#define BKP_DR25 ((uint16_t)0x0078)
|
||||||
|
#define BKP_DR26 ((uint16_t)0x007C)
|
||||||
|
#define BKP_DR27 ((uint16_t)0x0080)
|
||||||
|
#define BKP_DR28 ((uint16_t)0x0084)
|
||||||
|
#define BKP_DR29 ((uint16_t)0x0088)
|
||||||
|
#define BKP_DR30 ((uint16_t)0x008C)
|
||||||
|
#define BKP_DR31 ((uint16_t)0x0090)
|
||||||
|
#define BKP_DR32 ((uint16_t)0x0094)
|
||||||
|
#define BKP_DR33 ((uint16_t)0x0098)
|
||||||
|
#define BKP_DR34 ((uint16_t)0x009C)
|
||||||
|
#define BKP_DR35 ((uint16_t)0x00A0)
|
||||||
|
#define BKP_DR36 ((uint16_t)0x00A4)
|
||||||
|
#define BKP_DR37 ((uint16_t)0x00A8)
|
||||||
|
#define BKP_DR38 ((uint16_t)0x00AC)
|
||||||
|
#define BKP_DR39 ((uint16_t)0x00B0)
|
||||||
|
#define BKP_DR40 ((uint16_t)0x00B4)
|
||||||
|
#define BKP_DR41 ((uint16_t)0x00B8)
|
||||||
|
#define BKP_DR42 ((uint16_t)0x00BC)
|
||||||
|
|
||||||
|
|
||||||
|
void BKP_DeInit(void);
|
||||||
|
void BKP_TamperPinLevelConfig(uint16_t BKP_TamperPinLevel);
|
||||||
|
void BKP_TamperPinCmd(FunctionalState NewState);
|
||||||
|
void BKP_ITConfig(FunctionalState NewState);
|
||||||
|
void BKP_RTCOutputConfig(uint16_t BKP_RTCOutputSource);
|
||||||
|
void BKP_SetRTCCalibrationValue(uint8_t CalibrationValue);
|
||||||
|
void BKP_WriteBackupRegister(uint16_t BKP_DR, uint16_t Data);
|
||||||
|
uint16_t BKP_ReadBackupRegister(uint16_t BKP_DR);
|
||||||
|
FlagStatus BKP_GetFlagStatus(void);
|
||||||
|
void BKP_ClearFlag(void);
|
||||||
|
ITStatus BKP_GetITStatus(void);
|
||||||
|
void BKP_ClearITPendingBit(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_can.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* CAN firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_CAN_H
|
||||||
|
#define __CH32V30x_CAN_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* CAN init structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint16_t CAN_Prescaler; /* Specifies the length of a time quantum.
|
||||||
|
It ranges from 1 to 1024. */
|
||||||
|
|
||||||
|
uint8_t CAN_Mode; /* Specifies the CAN operating mode.
|
||||||
|
This parameter can be a value of
|
||||||
|
@ref CAN_operating_mode */
|
||||||
|
|
||||||
|
uint8_t CAN_SJW; /* Specifies the maximum number of time quanta
|
||||||
|
the CAN hardware is allowed to lengthen or
|
||||||
|
shorten a bit to perform resynchronization.
|
||||||
|
This parameter can be a value of
|
||||||
|
@ref CAN_synchronisation_jump_width */
|
||||||
|
|
||||||
|
uint8_t CAN_BS1; /* Specifies the number of time quanta in Bit
|
||||||
|
Segment 1. This parameter can be a value of
|
||||||
|
@ref CAN_time_quantum_in_bit_segment_1 */
|
||||||
|
|
||||||
|
uint8_t CAN_BS2; /* Specifies the number of time quanta in Bit
|
||||||
|
Segment 2.
|
||||||
|
This parameter can be a value of
|
||||||
|
@ref CAN_time_quantum_in_bit_segment_2 */
|
||||||
|
|
||||||
|
FunctionalState CAN_TTCM; /* Enable or disable the time triggered
|
||||||
|
communication mode. This parameter can be set
|
||||||
|
either to ENABLE or DISABLE. */
|
||||||
|
|
||||||
|
FunctionalState CAN_ABOM; /* Enable or disable the automatic bus-off
|
||||||
|
management. This parameter can be set either
|
||||||
|
to ENABLE or DISABLE. */
|
||||||
|
|
||||||
|
FunctionalState CAN_AWUM; /* Enable or disable the automatic wake-up mode.
|
||||||
|
This parameter can be set either to ENABLE or
|
||||||
|
DISABLE. */
|
||||||
|
|
||||||
|
FunctionalState CAN_NART; /* Enable or disable the no-automatic
|
||||||
|
retransmission mode. This parameter can be
|
||||||
|
set either to ENABLE or DISABLE. */
|
||||||
|
|
||||||
|
FunctionalState CAN_RFLM; /* Enable or disable the Receive FIFO Locked mode.
|
||||||
|
This parameter can be set either to ENABLE
|
||||||
|
or DISABLE. */
|
||||||
|
|
||||||
|
FunctionalState CAN_TXFP; /* Enable or disable the transmit FIFO priority.
|
||||||
|
This parameter can be set either to ENABLE
|
||||||
|
or DISABLE. */
|
||||||
|
} CAN_InitTypeDef;
|
||||||
|
|
||||||
|
/* CAN filter init structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint16_t CAN_FilterIdHigh; /* Specifies the filter identification number (MSBs for a 32-bit
|
||||||
|
configuration, first one for a 16-bit configuration).
|
||||||
|
This parameter can be a value between 0x0000 and 0xFFFF */
|
||||||
|
|
||||||
|
uint16_t CAN_FilterIdLow; /* Specifies the filter identification number (LSBs for a 32-bit
|
||||||
|
configuration, second one for a 16-bit configuration).
|
||||||
|
This parameter can be a value between 0x0000 and 0xFFFF */
|
||||||
|
|
||||||
|
uint16_t CAN_FilterMaskIdHigh; /* Specifies the filter mask number or identification number,
|
||||||
|
according to the mode (MSBs for a 32-bit configuration,
|
||||||
|
first one for a 16-bit configuration).
|
||||||
|
This parameter can be a value between 0x0000 and 0xFFFF */
|
||||||
|
|
||||||
|
uint16_t CAN_FilterMaskIdLow; /* Specifies the filter mask number or identification number,
|
||||||
|
according to the mode (LSBs for a 32-bit configuration,
|
||||||
|
second one for a 16-bit configuration).
|
||||||
|
This parameter can be a value between 0x0000 and 0xFFFF */
|
||||||
|
|
||||||
|
uint16_t CAN_FilterFIFOAssignment; /* Specifies the FIFO (0 or 1) which will be assigned to the filter.
|
||||||
|
This parameter can be a value of @ref CAN_filter_FIFO */
|
||||||
|
|
||||||
|
uint8_t CAN_FilterNumber; /* Specifies the filter which will be initialized. It ranges from 0 to 13. */
|
||||||
|
|
||||||
|
uint8_t CAN_FilterMode; /* Specifies the filter mode to be initialized.
|
||||||
|
This parameter can be a value of @ref CAN_filter_mode */
|
||||||
|
|
||||||
|
uint8_t CAN_FilterScale; /* Specifies the filter scale.
|
||||||
|
This parameter can be a value of @ref CAN_filter_scale */
|
||||||
|
|
||||||
|
FunctionalState CAN_FilterActivation; /* Enable or disable the filter.
|
||||||
|
This parameter can be set either to ENABLE or DISABLE. */
|
||||||
|
} CAN_FilterInitTypeDef;
|
||||||
|
|
||||||
|
/* CAN Tx message structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t StdId; /* Specifies the standard identifier.
|
||||||
|
This parameter can be a value between 0 to 0x7FF. */
|
||||||
|
|
||||||
|
uint32_t ExtId; /* Specifies the extended identifier.
|
||||||
|
This parameter can be a value between 0 to 0x1FFFFFFF. */
|
||||||
|
|
||||||
|
uint8_t IDE; /* Specifies the type of identifier for the message that
|
||||||
|
will be transmitted. This parameter can be a value
|
||||||
|
of @ref CAN_identifier_type */
|
||||||
|
|
||||||
|
uint8_t RTR; /* Specifies the type of frame for the message that will
|
||||||
|
be transmitted. This parameter can be a value of
|
||||||
|
@ref CAN_remote_transmission_request */
|
||||||
|
|
||||||
|
uint8_t DLC; /* Specifies the length of the frame that will be
|
||||||
|
transmitted. This parameter can be a value between
|
||||||
|
0 to 8 */
|
||||||
|
|
||||||
|
uint8_t Data[8]; /* Contains the data to be transmitted. It ranges from 0
|
||||||
|
to 0xFF. */
|
||||||
|
} CanTxMsg;
|
||||||
|
|
||||||
|
/* CAN Rx message structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t StdId; /* Specifies the standard identifier.
|
||||||
|
This parameter can be a value between 0 to 0x7FF. */
|
||||||
|
|
||||||
|
uint32_t ExtId; /* Specifies the extended identifier.
|
||||||
|
This parameter can be a value between 0 to 0x1FFFFFFF. */
|
||||||
|
|
||||||
|
uint8_t IDE; /* Specifies the type of identifier for the message that
|
||||||
|
will be received. This parameter can be a value of
|
||||||
|
@ref CAN_identifier_type */
|
||||||
|
|
||||||
|
uint8_t RTR; /* Specifies the type of frame for the received message.
|
||||||
|
This parameter can be a value of
|
||||||
|
@ref CAN_remote_transmission_request */
|
||||||
|
|
||||||
|
uint8_t DLC; /* Specifies the length of the frame that will be received.
|
||||||
|
This parameter can be a value between 0 to 8 */
|
||||||
|
|
||||||
|
uint8_t Data[8]; /* Contains the data to be received. It ranges from 0 to
|
||||||
|
0xFF. */
|
||||||
|
|
||||||
|
uint8_t FMI; /* Specifies the index of the filter the message stored in
|
||||||
|
the mailbox passes through. This parameter can be a
|
||||||
|
value between 0 to 0xFF */
|
||||||
|
} CanRxMsg;
|
||||||
|
|
||||||
|
/* CAN_sleep_constants */
|
||||||
|
#define CAN_InitStatus_Failed ((uint8_t)0x00) /* CAN initialization failed */
|
||||||
|
#define CAN_InitStatus_Success ((uint8_t)0x01) /* CAN initialization OK */
|
||||||
|
|
||||||
|
/* CAN_Mode */
|
||||||
|
#define CAN_Mode_Normal ((uint8_t)0x00) /* normal mode */
|
||||||
|
#define CAN_Mode_LoopBack ((uint8_t)0x01) /* loopback mode */
|
||||||
|
#define CAN_Mode_Silent ((uint8_t)0x02) /* silent mode */
|
||||||
|
#define CAN_Mode_Silent_LoopBack ((uint8_t)0x03) /* loopback combined with silent mode */
|
||||||
|
|
||||||
|
/* CAN_Operating_Mode */
|
||||||
|
#define CAN_OperatingMode_Initialization ((uint8_t)0x00) /* Initialization mode */
|
||||||
|
#define CAN_OperatingMode_Normal ((uint8_t)0x01) /* Normal mode */
|
||||||
|
#define CAN_OperatingMode_Sleep ((uint8_t)0x02) /* sleep mode */
|
||||||
|
|
||||||
|
/* CAN_Mode_Status */
|
||||||
|
#define CAN_ModeStatus_Failed ((uint8_t)0x00) /* CAN entering the specific mode failed */
|
||||||
|
#define CAN_ModeStatus_Success ((uint8_t)!CAN_ModeStatus_Failed) /* CAN entering the specific mode Succeed */
|
||||||
|
|
||||||
|
/* CAN_synchronisation_jump_width */
|
||||||
|
#define CAN_SJW_1tq ((uint8_t)0x00) /* 1 time quantum */
|
||||||
|
#define CAN_SJW_2tq ((uint8_t)0x01) /* 2 time quantum */
|
||||||
|
#define CAN_SJW_3tq ((uint8_t)0x02) /* 3 time quantum */
|
||||||
|
#define CAN_SJW_4tq ((uint8_t)0x03) /* 4 time quantum */
|
||||||
|
|
||||||
|
/* CAN_time_quantum_in_bit_segment_1 */
|
||||||
|
#define CAN_BS1_1tq ((uint8_t)0x00) /* 1 time quantum */
|
||||||
|
#define CAN_BS1_2tq ((uint8_t)0x01) /* 2 time quantum */
|
||||||
|
#define CAN_BS1_3tq ((uint8_t)0x02) /* 3 time quantum */
|
||||||
|
#define CAN_BS1_4tq ((uint8_t)0x03) /* 4 time quantum */
|
||||||
|
#define CAN_BS1_5tq ((uint8_t)0x04) /* 5 time quantum */
|
||||||
|
#define CAN_BS1_6tq ((uint8_t)0x05) /* 6 time quantum */
|
||||||
|
#define CAN_BS1_7tq ((uint8_t)0x06) /* 7 time quantum */
|
||||||
|
#define CAN_BS1_8tq ((uint8_t)0x07) /* 8 time quantum */
|
||||||
|
#define CAN_BS1_9tq ((uint8_t)0x08) /* 9 time quantum */
|
||||||
|
#define CAN_BS1_10tq ((uint8_t)0x09) /* 10 time quantum */
|
||||||
|
#define CAN_BS1_11tq ((uint8_t)0x0A) /* 11 time quantum */
|
||||||
|
#define CAN_BS1_12tq ((uint8_t)0x0B) /* 12 time quantum */
|
||||||
|
#define CAN_BS1_13tq ((uint8_t)0x0C) /* 13 time quantum */
|
||||||
|
#define CAN_BS1_14tq ((uint8_t)0x0D) /* 14 time quantum */
|
||||||
|
#define CAN_BS1_15tq ((uint8_t)0x0E) /* 15 time quantum */
|
||||||
|
#define CAN_BS1_16tq ((uint8_t)0x0F) /* 16 time quantum */
|
||||||
|
|
||||||
|
/* CAN_time_quantum_in_bit_segment_2 */
|
||||||
|
#define CAN_BS2_1tq ((uint8_t)0x00) /* 1 time quantum */
|
||||||
|
#define CAN_BS2_2tq ((uint8_t)0x01) /* 2 time quantum */
|
||||||
|
#define CAN_BS2_3tq ((uint8_t)0x02) /* 3 time quantum */
|
||||||
|
#define CAN_BS2_4tq ((uint8_t)0x03) /* 4 time quantum */
|
||||||
|
#define CAN_BS2_5tq ((uint8_t)0x04) /* 5 time quantum */
|
||||||
|
#define CAN_BS2_6tq ((uint8_t)0x05) /* 6 time quantum */
|
||||||
|
#define CAN_BS2_7tq ((uint8_t)0x06) /* 7 time quantum */
|
||||||
|
#define CAN_BS2_8tq ((uint8_t)0x07) /* 8 time quantum */
|
||||||
|
|
||||||
|
/* CAN_filter_mode */
|
||||||
|
#define CAN_FilterMode_IdMask ((uint8_t)0x00) /* identifier/mask mode */
|
||||||
|
#define CAN_FilterMode_IdList ((uint8_t)0x01) /* identifier list mode */
|
||||||
|
|
||||||
|
/* CAN_filter_scale */
|
||||||
|
#define CAN_FilterScale_16bit ((uint8_t)0x00) /* Two 16-bit filters */
|
||||||
|
#define CAN_FilterScale_32bit ((uint8_t)0x01) /* One 32-bit filter */
|
||||||
|
|
||||||
|
/* CAN_filter_FIFO */
|
||||||
|
#define CAN_Filter_FIFO0 ((uint8_t)0x00) /* Filter FIFO 0 assignment for filter x */
|
||||||
|
#define CAN_Filter_FIFO1 ((uint8_t)0x01) /* Filter FIFO 1 assignment for filter x */
|
||||||
|
|
||||||
|
/* CAN_identifier_type */
|
||||||
|
#define CAN_Id_Standard ((uint32_t)0x00000000) /* Standard Id */
|
||||||
|
#define CAN_Id_Extended ((uint32_t)0x00000004) /* Extended Id */
|
||||||
|
|
||||||
|
/* CAN_remote_transmission_request */
|
||||||
|
#define CAN_RTR_Data ((uint32_t)0x00000000) /* Data frame */
|
||||||
|
#define CAN_RTR_Remote ((uint32_t)0x00000002) /* Remote frame */
|
||||||
|
|
||||||
|
/* CAN_transmit_constants */
|
||||||
|
#define CAN_TxStatus_Failed ((uint8_t)0x00)/* CAN transmission failed */
|
||||||
|
#define CAN_TxStatus_Ok ((uint8_t)0x01) /* CAN transmission succeeded */
|
||||||
|
#define CAN_TxStatus_Pending ((uint8_t)0x02) /* CAN transmission pending */
|
||||||
|
#define CAN_TxStatus_NoMailBox ((uint8_t)0x04) /* CAN cell did not provide an empty mailbox */
|
||||||
|
|
||||||
|
/* CAN_receive_FIFO_number_constants */
|
||||||
|
#define CAN_FIFO0 ((uint8_t)0x00) /* CAN FIFO 0 used to receive */
|
||||||
|
#define CAN_FIFO1 ((uint8_t)0x01) /* CAN FIFO 1 used to receive */
|
||||||
|
|
||||||
|
/* CAN_sleep_constants */
|
||||||
|
#define CAN_Sleep_Failed ((uint8_t)0x00) /* CAN did not enter the sleep mode */
|
||||||
|
#define CAN_Sleep_Ok ((uint8_t)0x01) /* CAN entered the sleep mode */
|
||||||
|
|
||||||
|
/* CAN_wake_up_constants */
|
||||||
|
#define CAN_WakeUp_Failed ((uint8_t)0x00) /* CAN did not leave the sleep mode */
|
||||||
|
#define CAN_WakeUp_Ok ((uint8_t)0x01) /* CAN leaved the sleep mode */
|
||||||
|
|
||||||
|
/* CAN_Error_Code_constants */
|
||||||
|
#define CAN_ErrorCode_NoErr ((uint8_t)0x00) /* No Error */
|
||||||
|
#define CAN_ErrorCode_StuffErr ((uint8_t)0x10) /* Stuff Error */
|
||||||
|
#define CAN_ErrorCode_FormErr ((uint8_t)0x20) /* Form Error */
|
||||||
|
#define CAN_ErrorCode_ACKErr ((uint8_t)0x30) /* Acknowledgment Error */
|
||||||
|
#define CAN_ErrorCode_BitRecessiveErr ((uint8_t)0x40) /* Bit Recessive Error */
|
||||||
|
#define CAN_ErrorCode_BitDominantErr ((uint8_t)0x50) /* Bit Dominant Error */
|
||||||
|
#define CAN_ErrorCode_CRCErr ((uint8_t)0x60) /* CRC Error */
|
||||||
|
#define CAN_ErrorCode_SoftwareSetErr ((uint8_t)0x70) /* Software Set Error */
|
||||||
|
|
||||||
|
|
||||||
|
/* CAN_flags */
|
||||||
|
/* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus()
|
||||||
|
* and CAN_ClearFlag() functions.
|
||||||
|
* If the flag is 0x1XXXXXXX, it means that it can only be used with CAN_GetFlagStatus() function.
|
||||||
|
*/
|
||||||
|
/* Transmit Flags */
|
||||||
|
#define CAN_FLAG_RQCP0 ((uint32_t)0x38000001) /* Request MailBox0 Flag */
|
||||||
|
#define CAN_FLAG_RQCP1 ((uint32_t)0x38000100) /* Request MailBox1 Flag */
|
||||||
|
#define CAN_FLAG_RQCP2 ((uint32_t)0x38010000) /* Request MailBox2 Flag */
|
||||||
|
|
||||||
|
/* Receive Flags */
|
||||||
|
#define CAN_FLAG_FMP0 ((uint32_t)0x12000003) /* FIFO 0 Message Pending Flag */
|
||||||
|
#define CAN_FLAG_FF0 ((uint32_t)0x32000008) /* FIFO 0 Full Flag */
|
||||||
|
#define CAN_FLAG_FOV0 ((uint32_t)0x32000010) /* FIFO 0 Overrun Flag */
|
||||||
|
#define CAN_FLAG_FMP1 ((uint32_t)0x14000003) /* FIFO 1 Message Pending Flag */
|
||||||
|
#define CAN_FLAG_FF1 ((uint32_t)0x34000008) /* FIFO 1 Full Flag */
|
||||||
|
#define CAN_FLAG_FOV1 ((uint32_t)0x34000010) /* FIFO 1 Overrun Flag */
|
||||||
|
|
||||||
|
/* Operating Mode Flags */
|
||||||
|
#define CAN_FLAG_WKU ((uint32_t)0x31000008) /* Wake up Flag */
|
||||||
|
#define CAN_FLAG_SLAK ((uint32_t)0x31000012) /* Sleep acknowledge Flag */
|
||||||
|
/* Note:
|
||||||
|
*When SLAK intterupt is disabled (SLKIE=0), no polling on SLAKI is possible.
|
||||||
|
*In this case the SLAK bit can be polled.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Error Flags */
|
||||||
|
#define CAN_FLAG_EWG ((uint32_t)0x10F00001) /* Error Warning Flag */
|
||||||
|
#define CAN_FLAG_EPV ((uint32_t)0x10F00002) /* Error Passive Flag */
|
||||||
|
#define CAN_FLAG_BOF ((uint32_t)0x10F00004) /* Bus-Off Flag */
|
||||||
|
#define CAN_FLAG_LEC ((uint32_t)0x30F00070) /* Last error code Flag */
|
||||||
|
|
||||||
|
|
||||||
|
/* CAN_interrupts */
|
||||||
|
#define CAN_IT_TME ((uint32_t)0x00000001) /* Transmit mailbox empty Interrupt*/
|
||||||
|
|
||||||
|
/* Receive Interrupts */
|
||||||
|
#define CAN_IT_FMP0 ((uint32_t)0x00000002) /* FIFO 0 message pending Interrupt*/
|
||||||
|
#define CAN_IT_FF0 ((uint32_t)0x00000004) /* FIFO 0 full Interrupt*/
|
||||||
|
#define CAN_IT_FOV0 ((uint32_t)0x00000008) /* FIFO 0 overrun Interrupt*/
|
||||||
|
#define CAN_IT_FMP1 ((uint32_t)0x00000010) /* FIFO 1 message pending Interrupt*/
|
||||||
|
#define CAN_IT_FF1 ((uint32_t)0x00000020) /* FIFO 1 full Interrupt*/
|
||||||
|
#define CAN_IT_FOV1 ((uint32_t)0x00000040) /* FIFO 1 overrun Interrupt*/
|
||||||
|
|
||||||
|
/* Operating Mode Interrupts */
|
||||||
|
#define CAN_IT_WKU ((uint32_t)0x00010000) /* Wake-up Interrupt*/
|
||||||
|
#define CAN_IT_SLK ((uint32_t)0x00020000) /* Sleep acknowledge Interrupt*/
|
||||||
|
|
||||||
|
/* Error Interrupts */
|
||||||
|
#define CAN_IT_EWG ((uint32_t)0x00000100) /* Error warning Interrupt*/
|
||||||
|
#define CAN_IT_EPV ((uint32_t)0x00000200) /* Error passive Interrupt*/
|
||||||
|
#define CAN_IT_BOF ((uint32_t)0x00000400) /* Bus-off Interrupt*/
|
||||||
|
#define CAN_IT_LEC ((uint32_t)0x00000800) /* Last error code Interrupt*/
|
||||||
|
#define CAN_IT_ERR ((uint32_t)0x00008000) /* Error Interrupt*/
|
||||||
|
|
||||||
|
/* Flags named as Interrupts : kept only for FW compatibility */
|
||||||
|
#define CAN_IT_RQCP0 CAN_IT_TME
|
||||||
|
#define CAN_IT_RQCP1 CAN_IT_TME
|
||||||
|
#define CAN_IT_RQCP2 CAN_IT_TME
|
||||||
|
|
||||||
|
/* CAN_Legacy */
|
||||||
|
#define CANINITFAILED CAN_InitStatus_Failed
|
||||||
|
#define CANINITOK CAN_InitStatus_Success
|
||||||
|
#define CAN_FilterFIFO0 CAN_Filter_FIFO0
|
||||||
|
#define CAN_FilterFIFO1 CAN_Filter_FIFO1
|
||||||
|
#define CAN_ID_STD CAN_Id_Standard
|
||||||
|
#define CAN_ID_EXT CAN_Id_Extended
|
||||||
|
#define CAN_RTR_DATA CAN_RTR_Data
|
||||||
|
#define CAN_RTR_REMOTE CAN_RTR_Remote
|
||||||
|
#define CANTXFAILE CAN_TxStatus_Failed
|
||||||
|
#define CANTXOK CAN_TxStatus_Ok
|
||||||
|
#define CANTXPENDING CAN_TxStatus_Pending
|
||||||
|
#define CAN_NO_MB CAN_TxStatus_NoMailBox
|
||||||
|
#define CANSLEEPFAILED CAN_Sleep_Failed
|
||||||
|
#define CANSLEEPOK CAN_Sleep_Ok
|
||||||
|
#define CANWAKEUPFAILED CAN_WakeUp_Failed
|
||||||
|
#define CANWAKEUPOK CAN_WakeUp_Ok
|
||||||
|
|
||||||
|
|
||||||
|
void CAN_DeInit(CAN_TypeDef* CANx);
|
||||||
|
uint8_t CAN_Init(CAN_TypeDef* CANx, CAN_InitTypeDef* CAN_InitStruct);
|
||||||
|
void CAN_FilterInit(CAN_FilterInitTypeDef* CAN_FilterInitStruct);
|
||||||
|
void CAN_StructInit(CAN_InitTypeDef* CAN_InitStruct);
|
||||||
|
void CAN_SlaveStartBank(uint8_t CAN_BankNumber);
|
||||||
|
void CAN_DBGFreeze(CAN_TypeDef* CANx, FunctionalState NewState);
|
||||||
|
void CAN_TTComModeCmd(CAN_TypeDef* CANx, FunctionalState NewState);
|
||||||
|
uint8_t CAN_Transmit(CAN_TypeDef* CANx, CanTxMsg* TxMessage);
|
||||||
|
uint8_t CAN_TransmitStatus(CAN_TypeDef* CANx, uint8_t TransmitMailbox);
|
||||||
|
void CAN_CancelTransmit(CAN_TypeDef* CANx, uint8_t Mailbox);
|
||||||
|
void CAN_Receive(CAN_TypeDef* CANx, uint8_t FIFONumber, CanRxMsg* RxMessage);
|
||||||
|
void CAN_FIFORelease(CAN_TypeDef* CANx, uint8_t FIFONumber);
|
||||||
|
uint8_t CAN_MessagePending(CAN_TypeDef* CANx, uint8_t FIFONumber);
|
||||||
|
uint8_t CAN_OperatingModeRequest(CAN_TypeDef* CANx, uint8_t CAN_OperatingMode);
|
||||||
|
uint8_t CAN_Sleep(CAN_TypeDef* CANx);
|
||||||
|
uint8_t CAN_WakeUp(CAN_TypeDef* CANx);
|
||||||
|
uint8_t CAN_GetLastErrorCode(CAN_TypeDef* CANx);
|
||||||
|
uint8_t CAN_GetReceiveErrorCounter(CAN_TypeDef* CANx);
|
||||||
|
uint8_t CAN_GetLSBTransmitErrorCounter(CAN_TypeDef* CANx);
|
||||||
|
void CAN_ITConfig(CAN_TypeDef* CANx, uint32_t CAN_IT, FunctionalState NewState);
|
||||||
|
FlagStatus CAN_GetFlagStatus(CAN_TypeDef* CANx, uint32_t CAN_FLAG);
|
||||||
|
void CAN_ClearFlag(CAN_TypeDef* CANx, uint32_t CAN_FLAG);
|
||||||
|
ITStatus CAN_GetITStatus(CAN_TypeDef* CANx, uint32_t CAN_IT);
|
||||||
|
void CAN_ClearITPendingBit(CAN_TypeDef* CANx, uint32_t CAN_IT);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_crc.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* CRC firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_CRC_H
|
||||||
|
#define __CH32V30x_CRC_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
|
||||||
|
void CRC_ResetDR(void);
|
||||||
|
uint32_t CRC_CalcCRC(uint32_t Data);
|
||||||
|
uint32_t CRC_CalcBlockCRC(uint32_t pBuffer[], uint32_t BufferLength);
|
||||||
|
uint32_t CRC_GetCRC(void);
|
||||||
|
void CRC_SetIDRegister(uint8_t IDValue);
|
||||||
|
uint8_t CRC_GetIDRegister(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_dac.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* DAC firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_DAC_H
|
||||||
|
#define __CH32V30x_DAC_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* DAC Init structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t DAC_Trigger; /* Specifies the external trigger for the selected DAC channel.
|
||||||
|
This parameter can be a value of @ref DAC_trigger_selection */
|
||||||
|
|
||||||
|
uint32_t DAC_WaveGeneration; /* Specifies whether DAC channel noise waves or triangle waves
|
||||||
|
are generated, or whether no wave is generated.
|
||||||
|
This parameter can be a value of @ref DAC_wave_generation */
|
||||||
|
|
||||||
|
uint32_t DAC_LFSRUnmask_TriangleAmplitude; /* Specifies the LFSR mask for noise wave generation or
|
||||||
|
the maximum amplitude triangle generation for the DAC channel.
|
||||||
|
This parameter can be a value of @ref DAC_lfsrunmask_triangleamplitude */
|
||||||
|
|
||||||
|
uint32_t DAC_OutputBuffer; /* Specifies whether the DAC channel output buffer is enabled or disabled.
|
||||||
|
This parameter can be a value of @ref DAC_output_buffer */
|
||||||
|
}DAC_InitTypeDef;
|
||||||
|
|
||||||
|
|
||||||
|
/* DAC_trigger_selection */
|
||||||
|
#define DAC_Trigger_None ((uint32_t)0x00000000) /* Conversion is automatic once the DAC1_DHRxxxx register
|
||||||
|
has been loaded, and not by external trigger */
|
||||||
|
#define DAC_Trigger_T6_TRGO ((uint32_t)0x00000004) /* TIM6 TRGO selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_T8_TRGO ((uint32_t)0x0000000C) /* TIM8 TRGO selected as external conversion trigger for DAC channel
|
||||||
|
only in High-density devices*/
|
||||||
|
#define DAC_Trigger_T7_TRGO ((uint32_t)0x00000014) /* TIM7 TRGO selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_T5_TRGO ((uint32_t)0x0000001C) /* TIM5 TRGO selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_T2_TRGO ((uint32_t)0x00000024) /* TIM2 TRGO selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_T4_TRGO ((uint32_t)0x0000002C) /* TIM4 TRGO selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_Ext_IT9 ((uint32_t)0x00000034) /* EXTI Line9 event selected as external conversion trigger for DAC channel */
|
||||||
|
#define DAC_Trigger_Software ((uint32_t)0x0000003C) /* Conversion started by software trigger for DAC channel */
|
||||||
|
|
||||||
|
/* DAC_wave_generation */
|
||||||
|
#define DAC_WaveGeneration_None ((uint32_t)0x00000000)
|
||||||
|
#define DAC_WaveGeneration_Noise ((uint32_t)0x00000040)
|
||||||
|
#define DAC_WaveGeneration_Triangle ((uint32_t)0x00000080)
|
||||||
|
|
||||||
|
|
||||||
|
/* DAC_lfsrunmask_triangleamplitude */
|
||||||
|
#define DAC_LFSRUnmask_Bit0 ((uint32_t)0x00000000) /* Unmask DAC channel LFSR bit0 for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits1_0 ((uint32_t)0x00000100) /* Unmask DAC channel LFSR bit[1:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits2_0 ((uint32_t)0x00000200) /* Unmask DAC channel LFSR bit[2:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits3_0 ((uint32_t)0x00000300) /* Unmask DAC channel LFSR bit[3:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits4_0 ((uint32_t)0x00000400) /* Unmask DAC channel LFSR bit[4:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits5_0 ((uint32_t)0x00000500) /* Unmask DAC channel LFSR bit[5:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits6_0 ((uint32_t)0x00000600) /* Unmask DAC channel LFSR bit[6:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits7_0 ((uint32_t)0x00000700) /* Unmask DAC channel LFSR bit[7:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits8_0 ((uint32_t)0x00000800) /* Unmask DAC channel LFSR bit[8:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits9_0 ((uint32_t)0x00000900) /* Unmask DAC channel LFSR bit[9:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits10_0 ((uint32_t)0x00000A00) /* Unmask DAC channel LFSR bit[10:0] for noise wave generation */
|
||||||
|
#define DAC_LFSRUnmask_Bits11_0 ((uint32_t)0x00000B00) /* Unmask DAC channel LFSR bit[11:0] for noise wave generation */
|
||||||
|
#define DAC_TriangleAmplitude_1 ((uint32_t)0x00000000) /* Select max triangle amplitude of 1 */
|
||||||
|
#define DAC_TriangleAmplitude_3 ((uint32_t)0x00000100) /* Select max triangle amplitude of 3 */
|
||||||
|
#define DAC_TriangleAmplitude_7 ((uint32_t)0x00000200) /* Select max triangle amplitude of 7 */
|
||||||
|
#define DAC_TriangleAmplitude_15 ((uint32_t)0x00000300) /* Select max triangle amplitude of 15 */
|
||||||
|
#define DAC_TriangleAmplitude_31 ((uint32_t)0x00000400) /* Select max triangle amplitude of 31 */
|
||||||
|
#define DAC_TriangleAmplitude_63 ((uint32_t)0x00000500) /* Select max triangle amplitude of 63 */
|
||||||
|
#define DAC_TriangleAmplitude_127 ((uint32_t)0x00000600) /* Select max triangle amplitude of 127 */
|
||||||
|
#define DAC_TriangleAmplitude_255 ((uint32_t)0x00000700) /* Select max triangle amplitude of 255 */
|
||||||
|
#define DAC_TriangleAmplitude_511 ((uint32_t)0x00000800) /* Select max triangle amplitude of 511 */
|
||||||
|
#define DAC_TriangleAmplitude_1023 ((uint32_t)0x00000900) /* Select max triangle amplitude of 1023 */
|
||||||
|
#define DAC_TriangleAmplitude_2047 ((uint32_t)0x00000A00) /* Select max triangle amplitude of 2047 */
|
||||||
|
#define DAC_TriangleAmplitude_4095 ((uint32_t)0x00000B00) /* Select max triangle amplitude of 4095 */
|
||||||
|
|
||||||
|
/* DAC_output_buffer */
|
||||||
|
#define DAC_OutputBuffer_Enable ((uint32_t)0x00000000)
|
||||||
|
#define DAC_OutputBuffer_Disable ((uint32_t)0x00000002)
|
||||||
|
|
||||||
|
/* DAC_Channel_selection */
|
||||||
|
#define DAC_Channel_1 ((uint32_t)0x00000000)
|
||||||
|
#define DAC_Channel_2 ((uint32_t)0x00000010)
|
||||||
|
|
||||||
|
/* DAC_data_alignment */
|
||||||
|
#define DAC_Align_12b_R ((uint32_t)0x00000000)
|
||||||
|
#define DAC_Align_12b_L ((uint32_t)0x00000004)
|
||||||
|
#define DAC_Align_8b_R ((uint32_t)0x00000008)
|
||||||
|
|
||||||
|
/* DAC_wave_generation */
|
||||||
|
#define DAC_Wave_Noise ((uint32_t)0x00000040)
|
||||||
|
#define DAC_Wave_Triangle ((uint32_t)0x00000080)
|
||||||
|
|
||||||
|
|
||||||
|
void DAC_DeInit(void);
|
||||||
|
void DAC_Init(uint32_t DAC_Channel, DAC_InitTypeDef* DAC_InitStruct);
|
||||||
|
void DAC_StructInit(DAC_InitTypeDef* DAC_InitStruct);
|
||||||
|
void DAC_Cmd(uint32_t DAC_Channel, FunctionalState NewState);
|
||||||
|
void DAC_DMACmd(uint32_t DAC_Channel, FunctionalState NewState);
|
||||||
|
void DAC_SoftwareTriggerCmd(uint32_t DAC_Channel, FunctionalState NewState);
|
||||||
|
void DAC_DualSoftwareTriggerCmd(FunctionalState NewState);
|
||||||
|
void DAC_WaveGenerationCmd(uint32_t DAC_Channel, uint32_t DAC_Wave, FunctionalState NewState);
|
||||||
|
void DAC_SetChannel1Data(uint32_t DAC_Align, uint16_t Data);
|
||||||
|
void DAC_SetChannel2Data(uint32_t DAC_Align, uint16_t Data);
|
||||||
|
void DAC_SetDualChannelData(uint32_t DAC_Align, uint16_t Data2, uint16_t Data1);
|
||||||
|
uint16_t DAC_GetDataOutputValue(uint32_t DAC_Channel);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_dbgmcu.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* DBGMCU firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_DBGMCU_H
|
||||||
|
#define __CH32V30x_DBGMCU_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
#define DBGMCU_SLEEP ((uint32_t)0x00000001)
|
||||||
|
#define DBGMCU_STOP ((uint32_t)0x00000002)
|
||||||
|
#define DBGMCU_STANDBY ((uint32_t)0x00000004)
|
||||||
|
#define DBGMCU_IWDG_STOP ((uint32_t)0x00000100)
|
||||||
|
#define DBGMCU_WWDG_STOP ((uint32_t)0x00000200)
|
||||||
|
#define DBGMCU_I2C1_SMBUS_TIMEOUT ((uint32_t)0x00000400)
|
||||||
|
#define DBGMCU_I2C2_SMBUS_TIMEOUT ((uint32_t)0x00000800)
|
||||||
|
#define DBGMCU_TIM1_STOP ((uint32_t)0x00001000)
|
||||||
|
#define DBGMCU_TIM2_STOP ((uint32_t)0x00002000)
|
||||||
|
#define DBGMCU_TIM3_STOP ((uint32_t)0x00004000)
|
||||||
|
#define DBGMCU_TIM4_STOP ((uint32_t)0x00008000)
|
||||||
|
#define DBGMCU_TIM5_STOP ((uint32_t)0x00010000)
|
||||||
|
#define DBGMCU_TIM6_STOP ((uint32_t)0x00020000)
|
||||||
|
#define DBGMCU_TIM7_STOP ((uint32_t)0x00040000)
|
||||||
|
#define DBGMCU_TIM8_STOP ((uint32_t)0x00080000)
|
||||||
|
#define DBGMCU_CAN1_STOP ((uint32_t)0x00100000)
|
||||||
|
#define DBGMCU_CAN2_STOP ((uint32_t)0x00200000)
|
||||||
|
#define DBGMCU_TIM9_STOP ((uint32_t)0x00400000)
|
||||||
|
#define DBGMCU_TIM10_STOP ((uint32_t)0x00800000)
|
||||||
|
|
||||||
|
uint32_t DBGMCU_GetREVID(void);
|
||||||
|
uint32_t DBGMCU_GetDEVID(void);
|
||||||
|
uint32_t __get_DEBUG_CR(void);
|
||||||
|
void __set_DEBUG_CR(uint32_t value);
|
||||||
|
void DBGMCU_Config(uint32_t DBGMCU_Periph, FunctionalState NewState);
|
||||||
|
uint32_t DBGMCU_GetCHIPID( void );
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_dma.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* DMA firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_DMA_H
|
||||||
|
#define __CH32V30x_DMA_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* DMA Init structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t DMA_PeripheralBaseAddr; /* Specifies the peripheral base address for DMAy Channelx. */
|
||||||
|
|
||||||
|
uint32_t DMA_MemoryBaseAddr; /* Specifies the memory base address for DMAy Channelx. */
|
||||||
|
|
||||||
|
uint32_t DMA_DIR; /* Specifies if the peripheral is the source or destination.
|
||||||
|
This parameter can be a value of @ref DMA_data_transfer_direction */
|
||||||
|
|
||||||
|
uint32_t DMA_BufferSize; /* Specifies the buffer size, in data unit, of the specified Channel.
|
||||||
|
The data unit is equal to the configuration set in DMA_PeripheralDataSize
|
||||||
|
or DMA_MemoryDataSize members depending in the transfer direction. */
|
||||||
|
|
||||||
|
uint32_t DMA_PeripheralInc; /* Specifies whether the Peripheral address register is incremented or not.
|
||||||
|
This parameter can be a value of @ref DMA_peripheral_incremented_mode */
|
||||||
|
|
||||||
|
uint32_t DMA_MemoryInc; /* Specifies whether the memory address register is incremented or not.
|
||||||
|
This parameter can be a value of @ref DMA_memory_incremented_mode */
|
||||||
|
|
||||||
|
uint32_t DMA_PeripheralDataSize; /* Specifies the Peripheral data width.
|
||||||
|
This parameter can be a value of @ref DMA_peripheral_data_size */
|
||||||
|
|
||||||
|
uint32_t DMA_MemoryDataSize; /* Specifies the Memory data width.
|
||||||
|
This parameter can be a value of @ref DMA_memory_data_size */
|
||||||
|
|
||||||
|
uint32_t DMA_Mode; /* Specifies the operation mode of the DMAy Channelx.
|
||||||
|
This parameter can be a value of @ref DMA_circular_normal_mode.
|
||||||
|
@note: The circular buffer mode cannot be used if the memory-to-memory
|
||||||
|
data transfer is configured on the selected Channel */
|
||||||
|
|
||||||
|
uint32_t DMA_Priority; /* Specifies the software priority for the DMAy Channelx.
|
||||||
|
This parameter can be a value of @ref DMA_priority_level */
|
||||||
|
|
||||||
|
uint32_t DMA_M2M; /* Specifies if the DMAy Channelx will be used in memory-to-memory transfer.
|
||||||
|
This parameter can be a value of @ref DMA_memory_to_memory */
|
||||||
|
}DMA_InitTypeDef;
|
||||||
|
|
||||||
|
/* DMA_data_transfer_direction */
|
||||||
|
#define DMA_DIR_PeripheralDST ((uint32_t)0x00000010)
|
||||||
|
#define DMA_DIR_PeripheralSRC ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_peripheral_incremented_mode */
|
||||||
|
#define DMA_PeripheralInc_Enable ((uint32_t)0x00000040)
|
||||||
|
#define DMA_PeripheralInc_Disable ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_memory_incremented_mode */
|
||||||
|
#define DMA_MemoryInc_Enable ((uint32_t)0x00000080)
|
||||||
|
#define DMA_MemoryInc_Disable ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_peripheral_data_size */
|
||||||
|
#define DMA_PeripheralDataSize_Byte ((uint32_t)0x00000000)
|
||||||
|
#define DMA_PeripheralDataSize_HalfWord ((uint32_t)0x00000100)
|
||||||
|
#define DMA_PeripheralDataSize_Word ((uint32_t)0x00000200)
|
||||||
|
|
||||||
|
/* DMA_memory_data_size */
|
||||||
|
#define DMA_MemoryDataSize_Byte ((uint32_t)0x00000000)
|
||||||
|
#define DMA_MemoryDataSize_HalfWord ((uint32_t)0x00000400)
|
||||||
|
#define DMA_MemoryDataSize_Word ((uint32_t)0x00000800)
|
||||||
|
|
||||||
|
/* DMA_circular_normal_mode */
|
||||||
|
#define DMA_Mode_Circular ((uint32_t)0x00000020)
|
||||||
|
#define DMA_Mode_Normal ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_priority_level */
|
||||||
|
#define DMA_Priority_VeryHigh ((uint32_t)0x00003000)
|
||||||
|
#define DMA_Priority_High ((uint32_t)0x00002000)
|
||||||
|
#define DMA_Priority_Medium ((uint32_t)0x00001000)
|
||||||
|
#define DMA_Priority_Low ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_memory_to_memory */
|
||||||
|
#define DMA_M2M_Enable ((uint32_t)0x00004000)
|
||||||
|
#define DMA_M2M_Disable ((uint32_t)0x00000000)
|
||||||
|
|
||||||
|
/* DMA_interrupts_definition */
|
||||||
|
#define DMA_IT_TC ((uint32_t)0x00000002)
|
||||||
|
#define DMA_IT_HT ((uint32_t)0x00000004)
|
||||||
|
#define DMA_IT_TE ((uint32_t)0x00000008)
|
||||||
|
|
||||||
|
#define DMA1_IT_GL1 ((uint32_t)0x00000001)
|
||||||
|
#define DMA1_IT_TC1 ((uint32_t)0x00000002)
|
||||||
|
#define DMA1_IT_HT1 ((uint32_t)0x00000004)
|
||||||
|
#define DMA1_IT_TE1 ((uint32_t)0x00000008)
|
||||||
|
#define DMA1_IT_GL2 ((uint32_t)0x00000010)
|
||||||
|
#define DMA1_IT_TC2 ((uint32_t)0x00000020)
|
||||||
|
#define DMA1_IT_HT2 ((uint32_t)0x00000040)
|
||||||
|
#define DMA1_IT_TE2 ((uint32_t)0x00000080)
|
||||||
|
#define DMA1_IT_GL3 ((uint32_t)0x00000100)
|
||||||
|
#define DMA1_IT_TC3 ((uint32_t)0x00000200)
|
||||||
|
#define DMA1_IT_HT3 ((uint32_t)0x00000400)
|
||||||
|
#define DMA1_IT_TE3 ((uint32_t)0x00000800)
|
||||||
|
#define DMA1_IT_GL4 ((uint32_t)0x00001000)
|
||||||
|
#define DMA1_IT_TC4 ((uint32_t)0x00002000)
|
||||||
|
#define DMA1_IT_HT4 ((uint32_t)0x00004000)
|
||||||
|
#define DMA1_IT_TE4 ((uint32_t)0x00008000)
|
||||||
|
#define DMA1_IT_GL5 ((uint32_t)0x00010000)
|
||||||
|
#define DMA1_IT_TC5 ((uint32_t)0x00020000)
|
||||||
|
#define DMA1_IT_HT5 ((uint32_t)0x00040000)
|
||||||
|
#define DMA1_IT_TE5 ((uint32_t)0x00080000)
|
||||||
|
#define DMA1_IT_GL6 ((uint32_t)0x00100000)
|
||||||
|
#define DMA1_IT_TC6 ((uint32_t)0x00200000)
|
||||||
|
#define DMA1_IT_HT6 ((uint32_t)0x00400000)
|
||||||
|
#define DMA1_IT_TE6 ((uint32_t)0x00800000)
|
||||||
|
#define DMA1_IT_GL7 ((uint32_t)0x01000000)
|
||||||
|
#define DMA1_IT_TC7 ((uint32_t)0x02000000)
|
||||||
|
#define DMA1_IT_HT7 ((uint32_t)0x04000000)
|
||||||
|
#define DMA1_IT_TE7 ((uint32_t)0x08000000)
|
||||||
|
|
||||||
|
#define DMA2_IT_GL1 ((uint32_t)0x10000001)
|
||||||
|
#define DMA2_IT_TC1 ((uint32_t)0x10000002)
|
||||||
|
#define DMA2_IT_HT1 ((uint32_t)0x10000004)
|
||||||
|
#define DMA2_IT_TE1 ((uint32_t)0x10000008)
|
||||||
|
#define DMA2_IT_GL2 ((uint32_t)0x10000010)
|
||||||
|
#define DMA2_IT_TC2 ((uint32_t)0x10000020)
|
||||||
|
#define DMA2_IT_HT2 ((uint32_t)0x10000040)
|
||||||
|
#define DMA2_IT_TE2 ((uint32_t)0x10000080)
|
||||||
|
#define DMA2_IT_GL3 ((uint32_t)0x10000100)
|
||||||
|
#define DMA2_IT_TC3 ((uint32_t)0x10000200)
|
||||||
|
#define DMA2_IT_HT3 ((uint32_t)0x10000400)
|
||||||
|
#define DMA2_IT_TE3 ((uint32_t)0x10000800)
|
||||||
|
#define DMA2_IT_GL4 ((uint32_t)0x10001000)
|
||||||
|
#define DMA2_IT_TC4 ((uint32_t)0x10002000)
|
||||||
|
#define DMA2_IT_HT4 ((uint32_t)0x10004000)
|
||||||
|
#define DMA2_IT_TE4 ((uint32_t)0x10008000)
|
||||||
|
#define DMA2_IT_GL5 ((uint32_t)0x10010000)
|
||||||
|
#define DMA2_IT_TC5 ((uint32_t)0x10020000)
|
||||||
|
#define DMA2_IT_HT5 ((uint32_t)0x10040000)
|
||||||
|
#define DMA2_IT_TE5 ((uint32_t)0x10080000)
|
||||||
|
#define DMA2_IT_GL6 ((uint32_t)0x10100000)
|
||||||
|
#define DMA2_IT_TC6 ((uint32_t)0x10200000)
|
||||||
|
#define DMA2_IT_HT6 ((uint32_t)0x10400000)
|
||||||
|
#define DMA2_IT_TE6 ((uint32_t)0x10800000)
|
||||||
|
#define DMA2_IT_GL7 ((uint32_t)0x11000000)
|
||||||
|
#define DMA2_IT_TC7 ((uint32_t)0x12000000)
|
||||||
|
#define DMA2_IT_HT7 ((uint32_t)0x14000000)
|
||||||
|
#define DMA2_IT_TE7 ((uint32_t)0x18000000)
|
||||||
|
|
||||||
|
#define DMA2_IT_GL8 ((uint32_t)0x20000001)
|
||||||
|
#define DMA2_IT_TC8 ((uint32_t)0x20000002)
|
||||||
|
#define DMA2_IT_HT8 ((uint32_t)0x20000004)
|
||||||
|
#define DMA2_IT_TE8 ((uint32_t)0x20000008)
|
||||||
|
#define DMA2_IT_GL9 ((uint32_t)0x20000010)
|
||||||
|
#define DMA2_IT_TC9 ((uint32_t)0x20000020)
|
||||||
|
#define DMA2_IT_HT9 ((uint32_t)0x20000040)
|
||||||
|
#define DMA2_IT_TE9 ((uint32_t)0x20000080)
|
||||||
|
#define DMA2_IT_GL10 ((uint32_t)0x20000100)
|
||||||
|
#define DMA2_IT_TC10 ((uint32_t)0x20000200)
|
||||||
|
#define DMA2_IT_HT10 ((uint32_t)0x20000400)
|
||||||
|
#define DMA2_IT_TE10 ((uint32_t)0x20000800)
|
||||||
|
#define DMA2_IT_GL11 ((uint32_t)0x20001000)
|
||||||
|
#define DMA2_IT_TC11 ((uint32_t)0x20002000)
|
||||||
|
#define DMA2_IT_HT11 ((uint32_t)0x20004000)
|
||||||
|
#define DMA2_IT_TE11 ((uint32_t)0x20008000)
|
||||||
|
|
||||||
|
/* DMA_flags_definition */
|
||||||
|
#define DMA1_FLAG_GL1 ((uint32_t)0x00000001)
|
||||||
|
#define DMA1_FLAG_TC1 ((uint32_t)0x00000002)
|
||||||
|
#define DMA1_FLAG_HT1 ((uint32_t)0x00000004)
|
||||||
|
#define DMA1_FLAG_TE1 ((uint32_t)0x00000008)
|
||||||
|
#define DMA1_FLAG_GL2 ((uint32_t)0x00000010)
|
||||||
|
#define DMA1_FLAG_TC2 ((uint32_t)0x00000020)
|
||||||
|
#define DMA1_FLAG_HT2 ((uint32_t)0x00000040)
|
||||||
|
#define DMA1_FLAG_TE2 ((uint32_t)0x00000080)
|
||||||
|
#define DMA1_FLAG_GL3 ((uint32_t)0x00000100)
|
||||||
|
#define DMA1_FLAG_TC3 ((uint32_t)0x00000200)
|
||||||
|
#define DMA1_FLAG_HT3 ((uint32_t)0x00000400)
|
||||||
|
#define DMA1_FLAG_TE3 ((uint32_t)0x00000800)
|
||||||
|
#define DMA1_FLAG_GL4 ((uint32_t)0x00001000)
|
||||||
|
#define DMA1_FLAG_TC4 ((uint32_t)0x00002000)
|
||||||
|
#define DMA1_FLAG_HT4 ((uint32_t)0x00004000)
|
||||||
|
#define DMA1_FLAG_TE4 ((uint32_t)0x00008000)
|
||||||
|
#define DMA1_FLAG_GL5 ((uint32_t)0x00010000)
|
||||||
|
#define DMA1_FLAG_TC5 ((uint32_t)0x00020000)
|
||||||
|
#define DMA1_FLAG_HT5 ((uint32_t)0x00040000)
|
||||||
|
#define DMA1_FLAG_TE5 ((uint32_t)0x00080000)
|
||||||
|
#define DMA1_FLAG_GL6 ((uint32_t)0x00100000)
|
||||||
|
#define DMA1_FLAG_TC6 ((uint32_t)0x00200000)
|
||||||
|
#define DMA1_FLAG_HT6 ((uint32_t)0x00400000)
|
||||||
|
#define DMA1_FLAG_TE6 ((uint32_t)0x00800000)
|
||||||
|
#define DMA1_FLAG_GL7 ((uint32_t)0x01000000)
|
||||||
|
#define DMA1_FLAG_TC7 ((uint32_t)0x02000000)
|
||||||
|
#define DMA1_FLAG_HT7 ((uint32_t)0x04000000)
|
||||||
|
#define DMA1_FLAG_TE7 ((uint32_t)0x08000000)
|
||||||
|
|
||||||
|
#define DMA2_FLAG_GL1 ((uint32_t)0x10000001)
|
||||||
|
#define DMA2_FLAG_TC1 ((uint32_t)0x10000002)
|
||||||
|
#define DMA2_FLAG_HT1 ((uint32_t)0x10000004)
|
||||||
|
#define DMA2_FLAG_TE1 ((uint32_t)0x10000008)
|
||||||
|
#define DMA2_FLAG_GL2 ((uint32_t)0x10000010)
|
||||||
|
#define DMA2_FLAG_TC2 ((uint32_t)0x10000020)
|
||||||
|
#define DMA2_FLAG_HT2 ((uint32_t)0x10000040)
|
||||||
|
#define DMA2_FLAG_TE2 ((uint32_t)0x10000080)
|
||||||
|
#define DMA2_FLAG_GL3 ((uint32_t)0x10000100)
|
||||||
|
#define DMA2_FLAG_TC3 ((uint32_t)0x10000200)
|
||||||
|
#define DMA2_FLAG_HT3 ((uint32_t)0x10000400)
|
||||||
|
#define DMA2_FLAG_TE3 ((uint32_t)0x10000800)
|
||||||
|
#define DMA2_FLAG_GL4 ((uint32_t)0x10001000)
|
||||||
|
#define DMA2_FLAG_TC4 ((uint32_t)0x10002000)
|
||||||
|
#define DMA2_FLAG_HT4 ((uint32_t)0x10004000)
|
||||||
|
#define DMA2_FLAG_TE4 ((uint32_t)0x10008000)
|
||||||
|
#define DMA2_FLAG_GL5 ((uint32_t)0x10010000)
|
||||||
|
#define DMA2_FLAG_TC5 ((uint32_t)0x10020000)
|
||||||
|
#define DMA2_FLAG_HT5 ((uint32_t)0x10040000)
|
||||||
|
#define DMA2_FLAG_TE5 ((uint32_t)0x10080000)
|
||||||
|
#define DMA2_FLAG_GL6 ((uint32_t)0x10100000)
|
||||||
|
#define DMA2_FLAG_TC6 ((uint32_t)0x10200000)
|
||||||
|
#define DMA2_FLAG_HT6 ((uint32_t)0x10400000)
|
||||||
|
#define DMA2_FLAG_TE6 ((uint32_t)0x10800000)
|
||||||
|
#define DMA2_FLAG_GL7 ((uint32_t)0x11000000)
|
||||||
|
#define DMA2_FLAG_TC7 ((uint32_t)0x12000000)
|
||||||
|
#define DMA2_FLAG_HT7 ((uint32_t)0x14000000)
|
||||||
|
#define DMA2_FLAG_TE7 ((uint32_t)0x18000000)
|
||||||
|
|
||||||
|
#define DMA2_FLAG_GL8 ((uint32_t)0x20000001)
|
||||||
|
#define DMA2_FLAG_TC8 ((uint32_t)0x20000002)
|
||||||
|
#define DMA2_FLAG_HT8 ((uint32_t)0x20000004)
|
||||||
|
#define DMA2_FLAG_TE8 ((uint32_t)0x20000008)
|
||||||
|
#define DMA2_FLAG_GL9 ((uint32_t)0x20000010)
|
||||||
|
#define DMA2_FLAG_TC9 ((uint32_t)0x20000020)
|
||||||
|
#define DMA2_FLAG_HT9 ((uint32_t)0x20000040)
|
||||||
|
#define DMA2_FLAG_TE9 ((uint32_t)0x20000080)
|
||||||
|
#define DMA2_FLAG_GL10 ((uint32_t)0x20000100)
|
||||||
|
#define DMA2_FLAG_TC10 ((uint32_t)0x20000200)
|
||||||
|
#define DMA2_FLAG_HT10 ((uint32_t)0x20000400)
|
||||||
|
#define DMA2_FLAG_TE10 ((uint32_t)0x20000800)
|
||||||
|
#define DMA2_FLAG_GL11 ((uint32_t)0x20001000)
|
||||||
|
#define DMA2_FLAG_TC11 ((uint32_t)0x20002000)
|
||||||
|
#define DMA2_FLAG_HT11 ((uint32_t)0x20004000)
|
||||||
|
#define DMA2_FLAG_TE11 ((uint32_t)0x20008000)
|
||||||
|
|
||||||
|
|
||||||
|
void DMA_DeInit(DMA_Channel_TypeDef* DMAy_Channelx);
|
||||||
|
void DMA_Init(DMA_Channel_TypeDef* DMAy_Channelx, DMA_InitTypeDef* DMA_InitStruct);
|
||||||
|
void DMA_StructInit(DMA_InitTypeDef* DMA_InitStruct);
|
||||||
|
void DMA_Cmd(DMA_Channel_TypeDef* DMAy_Channelx, FunctionalState NewState);
|
||||||
|
void DMA_ITConfig(DMA_Channel_TypeDef* DMAy_Channelx, uint32_t DMA_IT, FunctionalState NewState);
|
||||||
|
void DMA_SetCurrDataCounter(DMA_Channel_TypeDef* DMAy_Channelx, uint16_t DataNumber);
|
||||||
|
uint16_t DMA_GetCurrDataCounter(DMA_Channel_TypeDef* DMAy_Channelx);
|
||||||
|
FlagStatus DMA_GetFlagStatus(uint32_t DMAy_FLAG);
|
||||||
|
void DMA_ClearFlag(uint32_t DMAy_FLAG);
|
||||||
|
ITStatus DMA_GetITStatus(uint32_t DMAy_IT);
|
||||||
|
void DMA_ClearITPendingBit(uint32_t DMAy_IT);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_dvp.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* DVP firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_DVP_H
|
||||||
|
#define __CH32V30x_DVP_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* DVP Data Mode */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
Video_Mode = 0,
|
||||||
|
JPEG_Mode,
|
||||||
|
}DVP_Data_ModeTypeDef;
|
||||||
|
|
||||||
|
|
||||||
|
/* DVP DMA */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
DVP_DMA_Disable = 0,
|
||||||
|
DVP_DMA_Enable,
|
||||||
|
}DVP_DMATypeDef;
|
||||||
|
|
||||||
|
/* DVP FLAG and FIFO Reset */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
DVP_FLAG_FIFO_RESET_Disable = 0,
|
||||||
|
DVP_FLAG_FIFO_RESET_Enable,
|
||||||
|
}DVP_FLAG_FIFO_RESETTypeDef;
|
||||||
|
|
||||||
|
/* DVP RX Reset */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
DVP_RX_RESET_Disable = 0,
|
||||||
|
DVP_RX_RESET_Enable,
|
||||||
|
}DVP_RX_RESETTypeDef;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
void DVP_INTCfg( uint8_t s, uint8_t i );
|
||||||
|
void DVP_Mode( uint8_t s, DVP_Data_ModeTypeDef i);
|
||||||
|
void DVP_Cfg( DVP_DMATypeDef s, DVP_FLAG_FIFO_RESETTypeDef i, DVP_RX_RESETTypeDef j);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,92 @@
|
|||||||
|
/********************************** (C) COPYRIGHT *******************************
|
||||||
|
* File Name : ch32v30x_exti.h
|
||||||
|
* Author : WCH
|
||||||
|
* Version : V1.0.0
|
||||||
|
* Date : 2021/06/06
|
||||||
|
* Description : This file contains all the functions prototypes for the
|
||||||
|
* EXTI firmware library.
|
||||||
|
*********************************************************************************
|
||||||
|
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
|
||||||
|
* Attention: This software (modified or not) and binary are used for
|
||||||
|
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
|
||||||
|
*******************************************************************************/
|
||||||
|
#ifndef __CH32V30x_EXTI_H
|
||||||
|
#define __CH32V30x_EXTI_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "ch32v30x.h"
|
||||||
|
|
||||||
|
/* EXTI mode enumeration */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
EXTI_Mode_Interrupt = 0x00,
|
||||||
|
EXTI_Mode_Event = 0x04
|
||||||
|
}EXTIMode_TypeDef;
|
||||||
|
|
||||||
|
/* EXTI Trigger enumeration */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
EXTI_Trigger_Rising = 0x08,
|
||||||
|
EXTI_Trigger_Falling = 0x0C,
|
||||||
|
EXTI_Trigger_Rising_Falling = 0x10
|
||||||
|
}EXTITrigger_TypeDef;
|
||||||
|
|
||||||
|
/* EXTI Init Structure definition */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
uint32_t EXTI_Line; /* Specifies the EXTI lines to be enabled or disabled.
|
||||||
|
This parameter can be any combination of @ref EXTI_Lines */
|
||||||
|
|
||||||
|
EXTIMode_TypeDef EXTI_Mode; /* Specifies the mode for the EXTI lines.
|
||||||
|
This parameter can be a value of @ref EXTIMode_TypeDef */
|
||||||
|
|
||||||
|
EXTITrigger_TypeDef EXTI_Trigger; /* Specifies the trigger signal active edge for the EXTI lines.
|
||||||
|
This parameter can be a value of @ref EXTIMode_TypeDef */
|
||||||
|
|
||||||
|
FunctionalState EXTI_LineCmd; /* Specifies the new state of the selected EXTI lines.
|
||||||
|
This parameter can be set either to ENABLE or DISABLE */
|
||||||
|
}EXTI_InitTypeDef;
|
||||||
|
|
||||||
|
|
||||||
|
/* EXTI_Lines */
|
||||||
|
#define EXTI_Line0 ((uint32_t)0x00001) /* External interrupt line 0 */
|
||||||
|
#define EXTI_Line1 ((uint32_t)0x00002) /* External interrupt line 1 */
|
||||||
|
#define EXTI_Line2 ((uint32_t)0x00004) /* External interrupt line 2 */
|
||||||
|
#define EXTI_Line3 ((uint32_t)0x00008) /* External interrupt line 3 */
|
||||||
|
#define EXTI_Line4 ((uint32_t)0x00010) /* External interrupt line 4 */
|
||||||
|
#define EXTI_Line5 ((uint32_t)0x00020) /* External interrupt line 5 */
|
||||||
|
#define EXTI_Line6 ((uint32_t)0x00040) /* External interrupt line 6 */
|
||||||
|
#define EXTI_Line7 ((uint32_t)0x00080) /* External interrupt line 7 */
|
||||||
|
#define EXTI_Line8 ((uint32_t)0x00100) /* External interrupt line 8 */
|
||||||
|
#define EXTI_Line9 ((uint32_t)0x00200) /* External interrupt line 9 */
|
||||||
|
#define EXTI_Line10 ((uint32_t)0x00400) /* External interrupt line 10 */
|
||||||
|
#define EXTI_Line11 ((uint32_t)0x00800) /* External interrupt line 11 */
|
||||||
|
#define EXTI_Line12 ((uint32_t)0x01000) /* External interrupt line 12 */
|
||||||
|
#define EXTI_Line13 ((uint32_t)0x02000) /* External interrupt line 13 */
|
||||||
|
#define EXTI_Line14 ((uint32_t)0x04000) /* External interrupt line 14 */
|
||||||
|
#define EXTI_Line15 ((uint32_t)0x08000) /* External interrupt line 15 */
|
||||||
|
#define EXTI_Line16 ((uint32_t)0x10000) /* External interrupt line 16 Connected to the PVD Output */
|
||||||
|
#define EXTI_Line17 ((uint32_t)0x20000) /* External interrupt line 17 Connected to the RTC Alarm event */
|
||||||
|
#define EXTI_Line18 ((uint32_t)0x40000) /* External interrupt line 18 Connected to the USBD/USBFS OTG
|
||||||
|
Wakeup from suspend event */
|
||||||
|
#define EXTI_Line19 ((uint32_t)0x80000) /* External interrupt line 19 Connected to the Ethernet Wakeup event */
|
||||||
|
#define EXTI_Line20 ((uint32_t)0x100000) /* External interrupt line 20 Connected to the USBHS Wakeup event */
|
||||||
|
|
||||||
|
void EXTI_DeInit(void);
|
||||||
|
void EXTI_Init(EXTI_InitTypeDef* EXTI_InitStruct);
|
||||||
|
void EXTI_StructInit(EXTI_InitTypeDef* EXTI_InitStruct);
|
||||||
|
void EXTI_GenerateSWInterrupt(uint32_t EXTI_Line);
|
||||||
|
FlagStatus EXTI_GetFlagStatus(uint32_t EXTI_Line);
|
||||||
|
void EXTI_ClearFlag(uint32_t EXTI_Line);
|
||||||
|
ITStatus EXTI_GetITStatus(uint32_t EXTI_Line);
|
||||||
|
void EXTI_ClearITPendingBit(uint32_t EXTI_Line);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user