diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 0df12e54..00000000 --- a/.gitignore +++ /dev/null @@ -1,81 +0,0 @@ -bin -src/github.com -src/golang.org -./arduino-builder - -# Created by .ignore support plugin (hsz.mobi) -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - - - -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -# User-specific stuff: -# .idea/workspace.xml -# .idea/tasks.xml -# .idea/dictionaries - -# Sensitive or high-churn files: -# .idea/dataSources.ids -# .idea/dataSources.xml -# .idea/sqlDataSources.xml -# .idea/dynamic.xml -# .idea/uiDesigner.xml - -# Gradle: -# .idea/gradle.xml -# .idea/libraries - -# Mongo Explorer plugin: -# .idea/mongoSettings.xml - -## File-based project format: -*.ipr -*.iws - -## Plugin-specific files: - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties diff --git a/.travis.yml b/.travis.yml index 910c086e..d19ffca0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,28 +1,17 @@ language: go +os: + - linux + - osx + go: - - 1.9.2 + - 1.12.x -install: - - go get github.com/go-errors/errors - - go get github.com/stretchr/testify - - go get github.com/jstemmer/go-junit-report - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - go get github.com/wadey/gocovmerge - - go get github.com/arduino/go-properties-map - - go get github.com/arduino/go-timeutils +env: + - GO111MODULE=on -script: - - go get github.com/arduino/arduino-builder/arduino-builder - - go build -o $HOME/arduino-builder -v github.com/arduino/arduino-builder/arduino-builder - - export TEST_PACKAGES=`go list github.com/arduino/arduino-builder/...` - - RES=0; I=0; for PKG in $TEST_PACKAGES; do go test -v -timeout 30m -covermode=count -coverprofile=coverage.$I.out $PKG; ((RES=RES+$?)); ((I++)); done; ( exit $RES ) +install: true -after_success: - - bin/gocovmerge coverage.*.out > coverage.out - - bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN +script: + - go build -env: - global: - secure: mm7X+dFQD4tUYwXxeVOJzereC04KdpTe6vrho1g6zmWgnMEqBe/gnX16Hv1LeQRzTnMVUxpcTXMkh4Nj16WL2IFAnizWiiMfFb6wUBBOM0dFhYJR7EzSzKMu7/CuhxIqT5ps/Ls3UUnpzUoI9ImygiLJCaNJCSjJxQ+hwnxyyEZD0FHvlQQcv3kiKAd8sg9oWKqTSBGIwBnn9ZGT9G2uykv+XU2B5B+dW9IoXaDR3SfUGlANldorD4T6S9QNs+JdwhX1NDDd7rOqF92qu2RA0TFf2Ljy1STimLXvVhGgcfetsUhVgkmDGKxp1/iax4jlJ8wRU7faqeFAt1WvJpBaOnsK8OcsNqf7iqmYxWxHKavFHfGKgc7L+dMP9gWIqgtzmfqG94/49IN8lPMpB29J8sfZfrb4nKNu66S9GqQCr/jgGD1uTXzC6SggoL6ro2di0bAvAlb6zgpv5zChqKkTzhHE/6rVA6EZG/JIIx5lXaDvkD+yp3o2LNKNknpwRPEY0KpReRivvajucDwiPqQD79gkKWOGtoo5034SGSGCUmXvAydJNVPJt6c5ADKpVgyiT065Gja4/n+n4GhjT6QKc2WRGQRQZGtkYkNh95tKUvgZiZ1G7+EAuRCotoKiqLPkLgUpzCoD7kZpo/Ai5xU2aRcKpMsAHEHSRP9F06F+zp4= diff --git a/README.md b/README.md index 013edb12..ed993a4d 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,8 @@ To build, run the following commands: go get github.com/go-errors/errors go get github.com/stretchr/testify go get github.com/jstemmer/go-junit-report -go get -u github.com/arduino/go-properties-map +go get -u github.com/arduino/go-paths-helper +go get -u github.com/arduino/go-properties-orderedmap go get -u github.com/arduino/go-timeutils go get google.golang.org/grpc go get github.com/golang/protobuf/proto diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go deleted file mode 100644 index 3d6f1fa1..00000000 --- a/add_additional_entries_to_context.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "path/filepath" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type AddAdditionalEntriesToContext struct{} - -func (s *AddAdditionalEntriesToContext) Run(ctx *types.Context) error { - if ctx.BuildPath != "" { - buildPath := ctx.BuildPath - preprocPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_PREPROC)) - if err != nil { - return i18n.WrapError(err) - } - sketchBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_SKETCH)) - if err != nil { - return i18n.WrapError(err) - } - librariesBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_LIBRARIES)) - if err != nil { - return i18n.WrapError(err) - } - coreBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_CORE)) - if err != nil { - return i18n.WrapError(err) - } - - ctx.PreprocPath = preprocPath - ctx.SketchBuildPath = sketchBuildPath - ctx.LibrariesBuildPath = librariesBuildPath - ctx.CoreBuildPath = coreBuildPath - } - - if ctx.BuildCachePath != "" { - coreBuildCachePath, err := filepath.Abs(filepath.Join(ctx.BuildCachePath, constants.FOLDER_CORE)) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CoreBuildCachePath = coreBuildCachePath - } - - if ctx.WarningsLevel == "" { - ctx.WarningsLevel = DEFAULT_WARNINGS_LEVEL - } - - ctx.CollectedSourceFiles = &types.UniqueSourceFileQueue{} - - ctx.LibrariesResolutionResults = make(map[string]types.LibraryResolutionResult) - ctx.HardwareRewriteResults = make(map[*types.Platform][]types.PlatforKeyRewrite) - - return nil -} diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go deleted file mode 100644 index 93c06c85..00000000 --- a/add_build_board_property_if_missing.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "os" - "strings" -) - -type AddBuildBoardPropertyIfMissing struct{} - -func (s *AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { - packages := ctx.Hardware - logger := ctx.GetLogger() - - for _, aPackage := range packages.Packages { - for _, platform := range aPackage.Platforms { - for _, board := range platform.Boards { - if board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] == constants.EMPTY_STRING { - board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] = strings.ToUpper(platform.PlatformId + "_" + board.BoardId) - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_MISSING_BUILD_BOARD, aPackage.PackageId, platform.PlatformId, board.BoardId, board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) - } - } - } - } - - return nil -} diff --git a/add_missing_build_properties_from_parent_platform_txt_files.go b/add_missing_build_properties_from_parent_platform_txt_files.go deleted file mode 100644 index 558aa820..00000000 --- a/add_missing_build_properties_from_parent_platform_txt_files.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/types" -) - -type AddMissingBuildPropertiesFromParentPlatformTxtFiles struct{} - -func (s *AddMissingBuildPropertiesFromParentPlatformTxtFiles) Run(ctx *types.Context) error { - packages := ctx.Hardware - targetPackage := ctx.TargetPackage - buildProperties := ctx.BuildProperties - - newBuildProperties := packages.Properties.Clone() - newBuildProperties.Merge(targetPackage.Properties) - newBuildProperties.Merge(buildProperties) - - ctx.BuildProperties = newBuildProperties - - return nil -} diff --git a/additional_sketch_files_copier.go b/additional_sketch_files_copier.go deleted file mode 100644 index c992e820..00000000 --- a/additional_sketch_files_copier.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "bytes" - "io/ioutil" - "path/filepath" -) - -type AdditionalSketchFilesCopier struct{} - -func (s *AdditionalSketchFilesCopier) Run(ctx *types.Context) error { - sketch := ctx.Sketch - sketchBuildPath := ctx.SketchBuildPath - - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { - return i18n.WrapError(err) - } - - sketchBasePath := filepath.Dir(sketch.MainFile.Name) - - for _, file := range sketch.AdditionalFiles { - relativePath, err := filepath.Rel(sketchBasePath, file.Name) - if err != nil { - return i18n.WrapError(err) - } - - targetFilePath := filepath.Join(sketchBuildPath, relativePath) - err = utils.EnsureFolderExists(filepath.Dir(targetFilePath)) - if err != nil { - return i18n.WrapError(err) - } - - bytes, err := ioutil.ReadFile(file.Name) - if err != nil { - return i18n.WrapError(err) - } - - if targetFileChanged(bytes, targetFilePath) { - err := utils.WriteFileBytes(targetFilePath, bytes) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func targetFileChanged(currentBytes []byte, targetFilePath string) bool { - oldBytes, err := ioutil.ReadFile(targetFilePath) - if err != nil { - return true - } - - return bytes.Compare(currentBytes, oldBytes) != 0 -} diff --git a/builder.go b/builder.go deleted file mode 100644 index 6c143996..00000000 --- a/builder.go +++ /dev/null @@ -1,234 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "reflect" - "strconv" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/phases" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -var MAIN_FILE_VALID_EXTENSIONS = map[string]bool{".ino": true, ".pde": true} -var ADDITIONAL_FILE_VALID_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true} -var ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS = map[string]bool{".c": true, ".cpp": true, ".s": true} - -var LIBRARY_MANDATORY_PROPERTIES = []string{constants.LIBRARY_NAME, constants.LIBRARY_VERSION, constants.LIBRARY_AUTHOR, constants.LIBRARY_MAINTAINER} -var LIBRARY_NOT_SO_MANDATORY_PROPERTIES = []string{constants.LIBRARY_SENTENCE, constants.LIBRARY_PARAGRAPH, constants.LIBRARY_URL} -var LIBRARY_CATEGORIES = map[string]bool{ - "Display": true, - "Communication": true, - "Signal Input/Output": true, - "Sensors": true, - "Device Control": true, - "Timing": true, - "Data Storage": true, - "Data Processing": true, - "Other": true, - "Uncategorized": true, -} - -const DEFAULT_DEBUG_LEVEL = 5 -const DEFAULT_WARNINGS_LEVEL = "none" -const DEFAULT_SOFTWARE = "ARDUINO" -const DEFAULT_BUILD_CORE = "arduino" - -type Builder struct{} - -func (s *Builder) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - &EnsureBuildPathExists{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &ContainerBuildOptions{}, - - &WarnAboutPlatformRewrites{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &ContainerMergeCopySketchFiles{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Detecting libraries used..."), - &ContainerFindIncludes{}, - - &WarnAboutArchIncompatibleLibraries{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Generating function prototypes..."), - &PreprocessSketch{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling sketch..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_SKETCH_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.SketchBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_SKETCH_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling libraries..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LIBRARIES_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &UnusedCompiledLibrariesRemover{}, - &phases.LibrariesBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LIBRARIES_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling core..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_CORE_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.CoreBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_CORE_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Linking everything together..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LINKING_PRELINK, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.Linker{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LINKING_POSTLINK, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_OBJCOPY_PREOBJCOPY, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &RecipeByPrefixSuffixRunner{Prefix: "recipe.objcopy.", Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_OBJCOPY_POSTOBJCOPY, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &MergeSketchWithBootloader{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - } - - mainErr := runCommands(ctx, commands, true) - - commands = []types.Command{ - &PrintUsedAndNotUsedLibraries{SketchError: mainErr != nil}, - - &PrintUsedLibrariesIfVerbose{}, - - &ExportProjectCMake{SketchError: mainErr != nil}, - - &phases.Sizer{SketchError: mainErr != nil}, - } - otherErr := runCommands(ctx, commands, false) - - if mainErr != nil { - return mainErr - } - - return otherErr -} - -type PreprocessSketch struct{} - -func (s *PreprocessSketch) Run(ctx *types.Context) error { - var commands []types.Command - if ctx.UseArduinoPreprocessor { - commands = append(commands, &PreprocessSketchArduino{}) - } else { - commands = append(commands, &ContainerAddPrototypes{}) - } - return runCommands(ctx, commands, true) -} - -type Preprocess struct{} - -func (s *Preprocess) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - &EnsureBuildPathExists{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &ContainerBuildOptions{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &ContainerMergeCopySketchFiles{}, - - &ContainerFindIncludes{}, - - &WarnAboutArchIncompatibleLibraries{}, - - &PreprocessSketch{}, - - &PrintPreprocessedSource{}, - } - - return runCommands(ctx, commands, true) -} - -type ParseHardwareAndDumpBuildProperties struct{} - -func (s *ParseHardwareAndDumpBuildProperties) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &DumpBuildProperties{}, - } - - return runCommands(ctx, commands, true) -} - -func runCommands(ctx *types.Context, commands []types.Command, progressEnabled bool) error { - - ctx.Progress.PrintEnabled = progressEnabled - ctx.Progress.Progress = 0 - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - ctx.Progress.Steps = 100.0 / float64(len(commands)) - builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func PrintRingNameIfDebug(ctx *types.Context, command types.Command) { - if ctx.DebugLevel >= 10 { - ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_RUNNING_COMMAND, strconv.FormatInt(time.Now().Unix(), 10), reflect.Indirect(reflect.ValueOf(command)).Type().Name()) - } -} - -func RunBuilder(ctx *types.Context) error { - command := Builder{} - return command.Run(ctx) -} - -func RunParseHardwareAndDumpBuildProperties(ctx *types.Context) error { - command := ParseHardwareAndDumpBuildProperties{} - return command.Run(ctx) -} - -func RunPreprocess(ctx *types.Context) error { - command := Preprocess{} - return command.Run(ctx) -} diff --git a/builder_utils/utils.go b/builder_utils/utils.go deleted file mode 100644 index 9b4cb536..00000000 --- a/builder_utils/utils.go +++ /dev/null @@ -1,567 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder_utils - -import ( - "io" - "os" - "os/exec" - "path/filepath" - "sort" - "strconv" - "strings" - "sync" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) { - - if !ctx.Progress.PrintEnabled { - return - } - - log := ctx.GetLogger() - if log.Name() == "machine" { - log.Println(constants.LOG_LEVEL_INFO, constants.MSG_PROGRESS, strconv.FormatFloat(ctx.Progress.Progress, 'f', 2, 32)) - ctx.Progress.Progress += ctx.Progress.Steps - } -} - -func CompileFilesRecursive(ctx *types.Context, objectFiles []string, sourcePath string, buildPath string, buildProperties properties.Map, includes []string) ([]string, error) { - objectFiles, err := CompileFiles(ctx, objectFiles, sourcePath, false, buildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - objectFiles, err = CompileFilesRecursive(ctx, objectFiles, filepath.Join(sourcePath, folder.Name()), filepath.Join(buildPath, folder.Name()), buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - } - - return objectFiles, nil -} - -func CompileFiles(ctx *types.Context, objectFiles []string, sourcePath string, recurse bool, buildPath string, buildProperties properties.Map, includes []string) ([]string, error) { - objectFiles, err := compileFilesWithExtensionWithRecipe(ctx, objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".S", constants.RECIPE_S_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles, err = compileFilesWithExtensionWithRecipe(ctx, objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".c", constants.RECIPE_C_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles, err = compileFilesWithExtensionWithRecipe(ctx, objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".cpp", constants.RECIPE_CPP_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - return objectFiles, nil -} - -func compileFilesWithExtensionWithRecipe(ctx *types.Context, objectFiles []string, sourcePath string, recurse bool, buildPath string, buildProperties properties.Map, includes []string, extension string, recipe string) ([]string, error) { - sources, err := findFilesInFolder(sourcePath, extension, recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - return compileFilesWithRecipe(ctx, objectFiles, sourcePath, sources, buildPath, buildProperties, includes, recipe) -} - -func findFilesInFolder(sourcePath string, extension string, recurse bool) ([]string, error) { - files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFilesWithExtensions(extension)) - if err != nil { - return nil, i18n.WrapError(err) - } - var sources []string - for _, file := range files { - sources = append(sources, filepath.Join(sourcePath, file.Name())) - } - - if recurse { - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - otherSources, err := findFilesInFolder(filepath.Join(sourcePath, folder.Name()), extension, recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - sources = append(sources, otherSources...) - } - } - - return sources, nil -} - -func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) { - files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFiles()) - if err != nil { - return nil, i18n.WrapError(err) - } - var sources []string - for _, file := range files { - sources = append(sources, filepath.Join(sourcePath, file.Name())) - } - - if recurse { - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - otherSources, err := findAllFilesInFolder(filepath.Join(sourcePath, folder.Name()), recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - sources = append(sources, otherSources...) - } - } - - return sources, nil -} - -func compileFilesWithRecipe(ctx *types.Context, objectFiles []string, sourcePath string, sources []string, buildPath string, buildProperties properties.Map, includes []string, recipe string) ([]string, error) { - if len(sources) == 0 { - return objectFiles, nil - } - objectFilesChan := make(chan string) - errorsChan := make(chan error) - doneChan := make(chan struct{}) - - ctx.Progress.Steps = ctx.Progress.Steps / float64(len(sources)) - var wg sync.WaitGroup - wg.Add(len(sources)) - - for _, source := range sources { - go func(source string) { - defer wg.Done() - PrintProgressIfProgressEnabledAndMachineLogger(ctx) - objectFile, err := compileFileWithRecipe(ctx, sourcePath, source, buildPath, buildProperties, includes, recipe) - if err != nil { - errorsChan <- err - } else { - objectFilesChan <- objectFile - } - }(source) - } - - go func() { - wg.Wait() - doneChan <- struct{}{} - }() - - for { - select { - case objectFile := <-objectFilesChan: - objectFiles = append(objectFiles, objectFile) - case err := <-errorsChan: - return nil, i18n.WrapError(err) - case <-doneChan: - close(objectFilesChan) - for objectFile := range objectFilesChan { - objectFiles = append(objectFiles, objectFile) - } - sort.Strings(objectFiles) - return objectFiles, nil - } - } -} - -func compileFileWithRecipe(ctx *types.Context, sourcePath string, source string, buildPath string, buildProperties properties.Map, includes []string, recipe string) (string, error) { - logger := ctx.GetLogger() - properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] - properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includes, constants.SPACE) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = source - relativeSource, err := filepath.Rel(sourcePath, source) - if err != nil { - return "", i18n.WrapError(err) - } - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = filepath.Join(buildPath, relativeSource+".o") - - err = utils.EnsureFolderExists(filepath.Dir(properties[constants.BUILD_PROPERTIES_OBJECT_FILE])) - if err != nil { - return "", i18n.WrapError(err) - } - - objIsUpToDate, err := ObjFileIsUpToDate(ctx, properties[constants.BUILD_PROPERTIES_SOURCE_FILE], properties[constants.BUILD_PROPERTIES_OBJECT_FILE], filepath.Join(buildPath, relativeSource+".d")) - if err != nil { - return "", i18n.WrapError(err) - } - - if !objIsUpToDate { - _, _, err = ExecRecipe(ctx, properties, recipe, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return "", i18n.WrapError(err) - } - } else if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, properties[constants.BUILD_PROPERTIES_OBJECT_FILE]) - } - - return properties[constants.BUILD_PROPERTIES_OBJECT_FILE], nil -} - -func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFile string) (bool, error) { - sourceFile = filepath.Clean(sourceFile) - objectFile = filepath.Clean(objectFile) - dependencyFile = filepath.Clean(dependencyFile) - logger := ctx.GetLogger() - debugLevel := ctx.DebugLevel - - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Checking previous results for {0} (result = {1}, dep = {2})", sourceFile, objectFile, dependencyFile) - } - - sourceFileStat, err := os.Stat(sourceFile) - if err != nil { - return false, i18n.WrapError(err) - } - - objectFileStat, err := os.Stat(objectFile) - if err != nil { - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", objectFile) - } - return false, nil - } else { - return false, i18n.WrapError(err) - } - } - - dependencyFileStat, err := os.Stat(dependencyFile) - if err != nil { - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", dependencyFile) - } - return false, nil - } else { - return false, i18n.WrapError(err) - } - } - - if sourceFileStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", sourceFile, objectFile) - } - return false, nil - } - if sourceFileStat.ModTime().After(dependencyFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", sourceFile, dependencyFile) - } - return false, nil - } - - rows, err := utils.ReadFileToRows(dependencyFile) - if err != nil { - return false, i18n.WrapError(err) - } - - rows = utils.Map(rows, removeEndingBackSlash) - rows = utils.Map(rows, strings.TrimSpace) - rows = utils.Map(rows, unescapeDep) - rows = utils.Filter(rows, nonEmptyString) - - if len(rows) == 0 { - return true, nil - } - - firstRow := rows[0] - if !strings.HasSuffix(firstRow, ":") { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "No colon in first line of depfile") - } - return false, nil - } - objFileInDepFile := firstRow[:len(firstRow)-1] - if objFileInDepFile != objectFile { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Depfile is about different file: {0}", objFileInDepFile) - } - return false, nil - } - - rows = rows[1:] - for _, row := range rows { - depStat, err := os.Stat(row) - if err != nil && !os.IsNotExist(err) { - // There is probably a parsing error of the dep file - // Ignore the error and trigger a full rebuild anyway - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Failed to read: {0}", row) - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, i18n.WrapError(err).Error()) - } - return false, nil - } - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", row) - } - return false, nil - } - if depStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", row, objectFile) - } - return false, nil - } - } - - return true, nil -} - -func unescapeDep(s string) string { - s = strings.Replace(s, "\\ ", " ", -1) - s = strings.Replace(s, "\\\t", "\t", -1) - s = strings.Replace(s, "\\#", "#", -1) - s = strings.Replace(s, "$$", "$", -1) - s = strings.Replace(s, "\\\\", "\\", -1) - return s -} - -func removeEndingBackSlash(s string) string { - if strings.HasSuffix(s, "\\") { - s = s[:len(s)-1] - } - return s -} - -func nonEmptyString(s string) bool { - return s != constants.EMPTY_STRING -} - -func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile string) bool { - - targetFileStat, err := os.Stat(targetFile) - if err == nil { - files, err := findAllFilesInFolder(corePath, true) - if err != nil { - return true - } - for _, file := range files { - fileStat, err := os.Stat(file) - if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) { - return true - } - } - if targetCorePath != constants.EMPTY_STRING && !strings.EqualFold(corePath, targetCorePath) { - return CoreOrReferencedCoreHasChanged(targetCorePath, constants.EMPTY_STRING, targetFile) - } - return false - } - return true -} - -func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile string) bool { - - targetFileStat, err := os.Stat(targetFile) - if err == nil { - files, err := findAllFilesInFolder(corePath, true) - if err != nil { - return true - } - for _, file := range files { - // report changes only for .txt files - if filepath.Ext(file) != ".txt" { - continue - } - fileStat, err := os.Stat(file) - if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) { - return true - } - } - if targetCorePath != constants.EMPTY_STRING && !strings.EqualFold(corePath, targetCorePath) { - return TXTBuildRulesHaveChanged(targetCorePath, constants.EMPTY_STRING, targetFile) - } - return false - } - return true -} - -func ArchiveCompiledFiles(ctx *types.Context, buildPath string, archiveFile string, objectFiles []string, buildProperties properties.Map) (string, error) { - logger := ctx.GetLogger() - archiveFilePath := filepath.Join(buildPath, archiveFile) - - rebuildArchive := false - - if archiveFileStat, err := os.Stat(archiveFilePath); err == nil { - - for _, objectFile := range objectFiles { - objectFileStat, _ := os.Stat(objectFile) - if objectFileStat.ModTime().After(archiveFileStat.ModTime()) { - // need to rebuild the archive - rebuildArchive = true - break - } - } - - // something changed, rebuild the core archive - if rebuildArchive { - err = os.Remove(archiveFilePath) - if err != nil { - return "", i18n.WrapError(err) - } - } else { - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, archiveFilePath) - } - return archiveFilePath, nil - } - } - - for _, objectFile := range objectFiles { - properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = filepath.Base(archiveFilePath) - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = archiveFilePath - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = objectFile - - _, _, err := ExecRecipe(ctx, properties, constants.RECIPE_AR_PATTERN, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return "", i18n.WrapError(err) - } - } - - return archiveFilePath, nil -} - -// See util.ExecCommand for stdout/stderr arguments -func ExecRecipe(ctx *types.Context, buildProperties properties.Map, recipe string, removeUnsetProperties bool, stdout int, stderr int) ([]byte, []byte, error) { - command, err := PrepareCommandForRecipe(ctx, buildProperties, recipe, removeUnsetProperties) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - return utils.ExecCommand(ctx, command, stdout, stderr) -} - -const COMMANDLINE_LIMIT = 30000 - -func PrepareCommandForRecipe(ctx *types.Context, buildProperties properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) { - logger := ctx.GetLogger() - pattern := buildProperties[recipe] - if pattern == constants.EMPTY_STRING { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, recipe) - } - - var err error - commandLine := buildProperties.ExpandPropsInString(pattern) - if removeUnsetProperties { - commandLine = properties.DeleteUnexpandedPropsFromString(commandLine) - } - - relativePath := "" - - if len(commandLine) > COMMANDLINE_LIMIT { - relativePath = buildProperties[constants.BUILD_PROPERTIES_BUILD_PATH] - } - - command, err := utils.PrepareCommand(commandLine, logger, relativePath) - if err != nil { - return nil, i18n.WrapError(err) - } - - return command, nil -} - -// CopyFile copies the contents of the file named src to the file named -// by dst. The file will be created if it does not already exist. If the -// destination file exists, all it's contents will be replaced by the contents -// of the source file. The file mode will be copied from the source and -// the copied data is synced/flushed to stable storage. -func CopyFile(src, dst string) (err error) { - in, err := os.Open(src) - if err != nil { - return - } - defer in.Close() - - out, err := os.Create(dst) - if err != nil { - return - } - defer func() { - if e := out.Close(); e != nil { - err = e - } - }() - - _, err = io.Copy(out, in) - if err != nil { - return - } - - err = out.Sync() - if err != nil { - return - } - - si, err := os.Stat(src) - if err != nil { - return - } - err = os.Chmod(dst, si.Mode()) - if err != nil { - return - } - - return -} - -// GetCachedCoreArchiveFileName returns the filename to be used to store -// the global cached core.a. -func GetCachedCoreArchiveFileName(fqbn, coreFolder string) string { - fqbnToUnderscore := strings.Replace(fqbn, ":", "_", -1) - fqbnToUnderscore = strings.Replace(fqbnToUnderscore, "=", "_", -1) - if absCoreFolder, err := filepath.Abs(coreFolder); err == nil { - coreFolder = absCoreFolder - } // silently continue if absolute path can't be detected - hash := utils.MD5Sum([]byte(coreFolder)) - realName := "core_" + fqbnToUnderscore + "_" + hash + ".a" - if len(realName) > 100 { - // avoid really long names, simply hash the final part - realName = "core_" + utils.MD5Sum([]byte(fqbnToUnderscore+"_"+hash)) + ".a" - } - return realName -} diff --git a/client/client.go b/client/client.go deleted file mode 100644 index 29e2ce7c..00000000 --- a/client/client.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "io" - "log" - - pb "github.com/arduino/arduino-builder/grpc/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" -) - -// printFeature gets the feature for the given point. -func autocomplete(client pb.BuilderClient, in *pb.BuildParams) { - resp, err := client.Autocomplete(context.Background(), in) - if err != nil { - log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err) - } - log.Println(resp) -} - -// printFeatures lists all the features within the given bounding Rectangle. -func build(client pb.BuilderClient, in *pb.BuildParams) { - stream, err := client.Build(context.Background(), in) - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - for { - line, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(line) - } -} - -func main() { - conn, err := grpc.Dial("localhost:12345", grpc.WithInsecure()) - if err != nil { - log.Fatalf("fail to dial: %v", err) - } - defer conn.Close() - - client := pb.NewBuilderClient(conn) - - exampleParames := pb.BuildParams{ - BuiltInLibrariesFolders: "/ssd/Arduino-master/build/linux/work/libraries", - CustomBuildProperties: "build.warn_data_percentage=75", - FQBN: "arduino:avr:mega:cpu=atmega2560", - HardwareFolders: "/ssd/Arduino-master/build/linux/work/hardware,/home/martino/.arduino15/packages,/home/martino/eslov-sk/hardware", - OtherLibrariesFolders: "/home/martino/eslov-sk/libraries", - ArduinoAPIVersion: "10805", - SketchLocation: "/home/martino/eslov-sk/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino", - ToolsFolders: "/ssd/Arduino-master/build/linux/work/tools-builder,/ssd/Arduino-master/build/linux/work/hardware/tools/avr,/home/martino/.arduino15/packages", - Verbose: true, - WarningsLevel: "all", - BuildCachePath: "/tmp/arduino_cache_761418/", - CodeCompleteAt: "/home/martino/eslov-sk/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino:56:9", - } - - //build(client, &exampleParames) - autocomplete(client, &exampleParames) -} diff --git a/constants/constants.go b/constants/constants.go deleted file mode 100644 index 366b22b0..00000000 --- a/constants/constants.go +++ /dev/null @@ -1,240 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package constants - -const BOARD_PROPERTIES_MENU = "menu" -const BUILD_OPTIONS_FILE = "build.options.json" -const BUILD_PROPERTIES_ARCHIVE_FILE = "archive_file" -const BUILD_PROPERTIES_ARCHIVE_FILE_PATH = "archive_file_path" -const BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK = "architecture.override_check" -const BUILD_PROPERTIES_BOOTLOADER_FILE = "bootloader.file" -const BUILD_PROPERTIES_BOOTLOADER_NOBLINK = "bootloader.noblink" -const BUILD_PROPERTIES_BUILD_ARCH = "build.arch" -const BUILD_PROPERTIES_BUILD_BOARD = "build.board" -const BUILD_PROPERTIES_BUILD_CORE = "build.core" -const BUILD_PROPERTIES_BUILD_CORE_PATH = "build.core.path" -const BUILD_PROPERTIES_BUILD_MCU = "build.mcu" -const BUILD_PROPERTIES_BUILD_PATH = "build.path" -const BUILD_PROPERTIES_BUILD_PROJECT_NAME = "build.project_name" -const BUILD_PROPERTIES_BUILD_SYSTEM_PATH = "build.system.path" -const BUILD_PROPERTIES_BUILD_VARIANT = "build.variant" -const BUILD_PROPERTIES_BUILD_VARIANT_PATH = "build.variant.path" -const BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS = "compiler.c.elf.flags" -const BUILD_PROPERTIES_COMPILER_LDFLAGS = "compiler.ldflags" -const BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS = "compiler.libraries.ldflags" -const BUILD_PROPERTIES_COMPILER_CPP_FLAGS = "compiler.cpp.flags" -const BUILD_PROPERTIES_COMPILER_PATH = "compiler.path" -const BUILD_PROPERTIES_COMPILER_WARNING_FLAGS = "compiler.warning_flags" -const BUILD_PROPERTIES_COMPILER_EXPORT_CMAKE_FLAGS = "compiler.export_cmake" -const BUILD_PROPERTIES_EXTRA_TIME_DST = "extra.time.dst" -const BUILD_PROPERTIES_EXTRA_TIME_LOCAL = "extra.time.local" -const BUILD_PROPERTIES_EXTRA_TIME_UTC = "extra.time.utc" -const BUILD_PROPERTIES_EXTRA_TIME_ZONE = "extra.time.zone" -const BUILD_PROPERTIES_FQBN = "build.fqbn" -const BUILD_PROPERTIES_INCLUDES = "includes" -const BUILD_PROPERTIES_OBJECT_FILE = "object_file" -const BUILD_PROPERTIES_OBJECT_FILES = "object_files" -const BUILD_PROPERTIES_PATTERN = "pattern" -const BUILD_PROPERTIES_PID = "pid" -const BUILD_PROPERTIES_PREPROCESSED_FILE_PATH = "preprocessed_file_path" -const BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH = "runtime.hardware.path" -const BUILD_PROPERTIES_RUNTIME_IDE_PATH = "runtime.ide.path" -const BUILD_PROPERTIES_RUNTIME_OS = "runtime.os" -const BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH = "runtime.platform.path" -const BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX = "runtime.tools." -const BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX = ".path" -const BUILD_PROPERTIES_RUNTIME_IDE_VERSION = "runtime.ide.version" -const BUILD_PROPERTIES_SOFTWARE = "software" -const BUILD_PROPERTIES_SOURCE_FILE = "source_file" -const BUILD_PROPERTIES_SOURCE_PATH = "build.source.path" -const BUILD_PROPERTIES_TOOLS_KEY = "tools" -const BUILD_PROPERTIES_VID = "vid" -const CTAGS = "ctags" -const EMPTY_STRING = "" -const FILE_BOARDS_LOCAL_TXT = "boards.local.txt" -const FILE_BOARDS_TXT = "boards.txt" -const FILE_BUILTIN_TOOLS_VERSIONS_TXT = "builtin_tools_versions.txt" -const FILE_CTAGS_TARGET = "ctags_target.cpp" -const FILE_CTAGS_TARGET_FOR_GCC_MINUS_E = "ctags_target_for_gcc_minus_e.cpp" -const FILE_GCC_PREPROC_TARGET = "gcc_preproc_target.cpp" -const FILE_PLATFORM_KEYS_REWRITE_TXT = "platform.keys.rewrite.txt" -const FILE_PLATFORM_LOCAL_TXT = "platform.local.txt" -const FILE_PLATFORM_TXT = "platform.txt" -const FILE_PROGRAMMERS_TXT = "programmers.txt" -const FILE_INCLUDES_CACHE = "includes.cache" -const FOLDER_BOOTLOADERS = "bootloaders" -const FOLDER_CORE = "core" -const FOLDER_CORES = "cores" -const FOLDER_HARDWARE = "hardware" -const FOLDER_LIBRARIES = "libraries" -const FOLDER_PREPROC = "preproc" -const FOLDER_SKETCH = "sketch" -const FOLDER_SYSTEM = "system" -const FOLDER_TOOLS = "tools" -const FOLDER_VARIANTS = "variants" -const hooks_core = hooks + ".core" -const HOOKS_CORE_POSTBUILD = hooks_core + hooks_postbuild_suffix -const HOOKS_CORE_PREBUILD = hooks_core + hooks_prebuild_suffix -const hooks_libraries = hooks + ".libraries" -const HOOKS_LIBRARIES_POSTBUILD = hooks_libraries + hooks_postbuild_suffix -const HOOKS_LIBRARIES_PREBUILD = hooks_libraries + hooks_prebuild_suffix -const hooks_linking = hooks + ".linking" -const HOOKS_LINKING_POSTLINK = hooks_linking + hooks_postlink_suffix -const HOOKS_LINKING_PRELINK = hooks_linking + hooks_prelink_suffix -const hooks_objcopy = hooks + ".objcopy" -const HOOKS_OBJCOPY_POSTOBJCOPY = hooks_objcopy + hooks_postobjcopy_suffix -const HOOKS_OBJCOPY_PREOBJCOPY = hooks_objcopy + hooks_preobjcopy_suffix -const HOOKS_PATTERN_SUFFIX = ".pattern" -const HOOKS_POSTBUILD = hooks + hooks_postbuild_suffix -const hooks_postbuild_suffix = ".postbuild" -const hooks_postlink_suffix = ".postlink" -const hooks_postobjcopy_suffix = ".postobjcopy" -const HOOKS_PREBUILD = hooks + hooks_prebuild_suffix -const hooks_prebuild_suffix = ".prebuild" -const hooks_prelink_suffix = ".prelink" -const hooks_preobjcopy_suffix = ".preobjcopy" -const hooks = "recipe.hooks" -const hooks_sketch = hooks + ".sketch" -const HOOKS_SKETCH_POSTBUILD = hooks_sketch + hooks_postbuild_suffix -const HOOKS_SKETCH_PREBUILD = hooks_sketch + hooks_prebuild_suffix -const IDE_VERSION = "ide_version" -const ID = "_id" -const LIB_CATEGORY_UNCATEGORIZED = "Uncategorized" -const LIB_LICENSE_UNSPECIFIED = "Unspecified" -const LIBRARY_ALL_ARCHS = "*" -const LIBRARY_ARCHITECTURES = "architectures" -const LIBRARY_AUTHOR = "author" -const LIBRARY_CATEGORY = "category" -const LIBRARY_DOT_A_LINKAGE = "dot_a_linkage" -const LIBRARY_EMAIL = "email" -const LIBRARY_FOLDER_ARCH = "arch" -const LIBRARY_FOLDER_SRC = "src" -const LIBRARY_FOLDER_UTILITY = "utility" -const LIBRARY_LICENSE = "license" -const LIBRARY_MAINTAINER = "maintainer" -const LIBRARY_NAME = "name" -const LIBRARY_PARAGRAPH = "paragraph" -const LIBRARY_PRECOMPILED = "precompiled" -const LIBRARY_LDFLAGS = "ldflags" -const LIBRARY_PROPERTIES = "library.properties" -const LIBRARY_SENTENCE = "sentence" -const LIBRARY_URL = "url" -const LIBRARY_VERSION = "version" -const LOG_LEVEL_DEBUG = "debug" -const LOG_LEVEL_ERROR = "error" -const LOG_LEVEL_INFO = "info" -const LOG_LEVEL_WARN = "warn" -const MSG_ARCH_FOLDER_NOT_SUPPORTED = "'arch' folder is no longer supported! See http://goo.gl/gfFJzU for more information" -const MSG_ARCHIVING_CORE_CACHE = "Archiving built core (caching) in: {0}" -const MSG_ERROR_ARCHIVING_CORE_CACHE = "Error archiving built core (caching) in {0}: {1}" -const MSG_CORE_CACHE_UNAVAILABLE = "Unable to cache built core, please tell {0} maintainers to follow http://goo.gl/QdCUjo" -const MSG_BOARD_UNKNOWN = "Board {0} (platform {1}, package {2}) is unknown" -const MSG_BOOTLOADER_FILE_MISSING = "Bootloader file specified but missing: {0}" -const MSG_BUILD_OPTIONS_CHANGED = "Build options changed, rebuilding all" -const MSG_CANT_FIND_SKETCH_IN_PATH = "Unable to find {0} in {1}" -const MSG_FQBN_INVALID = "{0} is not a valid fully qualified board name. Required format is targetPackageName:targetPlatformName:targetBoardName." -const MSG_FIND_INCLUDES_FAILED = "Error while detecting libraries included by {0}" -const MSG_INVALID_QUOTING = "Invalid quoting: no closing [{0}] char found." -const MSG_IGNORED_BUILTIN_TOOLS_TXT = "Skipping {0}; please consider removing that file since it may hurt older Arduino installations" -const MSG_LIB_LEGACY = "(legacy)" -const MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR = "Multiple libraries were found for \"{0}\"" -const MSG_LIBRARIES_NOT_USED = " Not used: {0}" -const MSG_LIBRARIES_USED = " Used: {0}" -const MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS = "Library can't use both 'src' and 'utility' folders. Double check {0}" -const MSG_LIBRARY_INCOMPATIBLE_ARCH = "WARNING: library {0} claims to run on {1} architecture(s) and may be incompatible with your current board which runs on {2} architecture(s)." -const MSG_LOOKING_FOR_RECIPES = "Looking for recipes like {0}*{1}" -const MSG_MISSING_BUILD_BOARD = "Warning: Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}" -const MSG_MISSING_CORE_FOR_BOARD = "Selected board depends on '{0}' core (not installed)." -const MSG_MUST_BE_A_FOLDER = "{0} must be a folder" -const MSG_PACKAGE_UNKNOWN = "{0}: Unknown package" -const MSG_PATTERN_MISSING = "{0} pattern is missing" -const MSG_PLATFORM_UNKNOWN = "Platform {0} (package {1}) is unknown" -const MSG_PROGRESS = "Progress {0}" -const MSG_PROP_IN_LIBRARY = "Missing '{0}' from library in {1}" -const MSG_RUNNING_COMMAND = "Ts: {0} - Running: {1}" -const MSG_RUNNING_RECIPE = "Running recipe: {0}" -const MSG_SETTING_BUILD_PATH = "Setting build path to {0}" -const MSG_SIZER_TEXT_FULL = "Sketch uses {0} bytes ({2}%%) of program storage space. Maximum is {1} bytes." -const MSG_SIZER_DATA_FULL = "Global variables use {0} bytes ({2}%%) of dynamic memory, leaving {3} bytes for local variables. Maximum is {1} bytes." -const MSG_SIZER_DATA = "Global variables use {0} bytes of dynamic memory." -const MSG_SIZER_TEXT_TOO_BIG = "Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it." -const MSG_SIZER_DATA_TOO_BIG = "Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint." -const MSG_SIZER_LOW_MEMORY = "Low memory available, stability problems may occur." -const MSG_SIZER_ERROR_NO_RULE = "Couldn't determine program size" -const MSG_SKETCH_CANT_BE_IN_BUILDPATH = "Sketch cannot be located in build path. Please specify a different build path" -const MSG_SKIPPING_TAG_ALREADY_DEFINED = "Skipping tag {0} because prototype is already defined" -const MSG_SKIPPING_TAG_BECAUSE_HAS_FIELD = "Skipping tag {0} because it has field {0}" -const MSG_SKIPPING_TAG_WITH_REASON = "Skipping tag {0}. Reason: {1}" -const MSG_UNHANDLED_TYPE_IN_CONTEXT = "Unhandled type {0} in context key {1}" -const MSG_UNKNOWN_SKETCH_EXT = "Unknown sketch file extension: {0}" -const MSG_USING_LIBRARY_AT_VERSION = "Using library {0} at version {1} in folder: {2} {3}" -const MSG_USING_LIBRARY = "Using library {0} in folder: {1} {2}" -const MSG_USING_BOARD = "Using board '{0}' from platform in folder: {1}" -const MSG_USING_CORE = "Using core '{0}' from platform in folder: {1}" -const MSG_USING_PREVIOUS_COMPILED_FILE = "Using previously compiled file: {0}" -const MSG_USING_CACHED_INCLUDES = "Using cached library dependencies for file: {0}" -const MSG_WARNING_LIB_INVALID_CATEGORY = "WARNING: Category '{0}' in library {1} is not valid. Setting to '{2}'" -const MSG_WARNING_PLATFORM_MISSING_VALUE = "Warning: platform.txt from core '{0}' misses property '{1}', using default value '{2}'. Consider upgrading this core." -const MSG_WARNING_PLATFORM_OLD_VALUES = "Warning: platform.txt from core '{0}' contains deprecated {1}, automatically converted to {2}. Consider upgrading this core." -const MSG_WARNING_SPURIOUS_FILE_IN_LIB = "WARNING: Spurious {0} folder in '{1}' library" -const MSG_WRONG_PROPERTIES_FILE = "Property line '{0}' in file {1} is invalid" -const MSG_WRONG_PROPERTIES = "Property line '{0}' is invalid" -const PACKAGE_NAME = "name" -const PACKAGE_TOOLS = "tools" -const PLATFORM_ARCHITECTURE = "architecture" -const PLATFORM_NAME = "name" -const PLATFORM_REWRITE_ADDED = "added" -const PLATFORM_REWRITE_NEW = "new" -const PLATFORM_REWRITE_OLD = "old" -const PLATFORM_URL = "url" -const PLATFORM_VERSION = "version" -const PROPERTY_WARN_DATA_PERCENT = "build.warn_data_percentage" -const PROPERTY_UPLOAD_MAX_SIZE = "upload.maximum_size" -const PROPERTY_UPLOAD_MAX_DATA_SIZE = "upload.maximum_data_size" -const PROGRAMMER_NAME = "name" -const RECIPE_AR_PATTERN = "recipe.ar.pattern" -const RECIPE_C_COMBINE_PATTERN = "recipe.c.combine.pattern" -const RECIPE_C_PATTERN = "recipe.c.o.pattern" -const RECIPE_CPP_PATTERN = "recipe.cpp.o.pattern" -const RECIPE_SIZE_PATTERN = "recipe.size.pattern" -const RECIPE_PREPROC_INCLUDES = "recipe.preproc.includes" -const RECIPE_PREPROC_MACROS = "recipe.preproc.macros" -const RECIPE_S_PATTERN = "recipe.S.o.pattern" -const RECIPE_SIZE_REGEXP = "recipe.size.regex" -const RECIPE_SIZE_REGEXP_DATA = "recipe.size.regex.data" -const RECIPE_SIZE_REGEXP_EEPROM = "recipe.size.regex.eeprom" -const REWRITING_DISABLED = "disabled" -const REWRITING = "rewriting" -const SPACE = " " -const SKETCH_FOLDER_SRC = "src" -const TOOL_NAME = "name" -const TOOL_URL = "url" -const TOOL_VERSION = "version" diff --git a/container_add_prototypes.go b/container_add_prototypes.go deleted file mode 100644 index 13b777d3..00000000 --- a/container_add_prototypes.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "path/filepath" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type ContainerAddPrototypes struct{} - -func (s *ContainerAddPrototypes) Run(ctx *types.Context) error { - sourceFile := filepath.Join(ctx.SketchBuildPath, filepath.Base(ctx.Sketch.MainFile.Name)+".cpp") - - // Generate the full pathname for the preproc output file - err := utils.EnsureFolderExists(ctx.PreprocPath) - if err != nil { - return i18n.WrapError(err) - } - targetFilePath := filepath.Join(ctx.PreprocPath, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E) - - // Run preprocessor - err = GCCPreprocRunner(ctx, sourceFile, targetFilePath, ctx.IncludeFolders) - if err != nil { - return i18n.WrapError(err) - } - commands := []types.Command{ - &ReadFileAndStoreInContext{FileToRead: targetFilePath, Target: &ctx.SourceGccMinusE}, - &FilterSketchSource{Source: &ctx.SourceGccMinusE}, - &CTagsTargetFileSaver{Source: &ctx.SourceGccMinusE, TargetFileName: constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E}, - &CTagsRunner{}, - &PrototypesAdder{}, - &SketchSaver{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} diff --git a/container_build_options.go b/container_build_options.go deleted file mode 100644 index d2e22513..00000000 --- a/container_build_options.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerBuildOptions struct{} - -func (s *ContainerBuildOptions) Run(ctx *types.Context) error { - commands := []types.Command{ - &CreateBuildOptionsMap{}, - &LoadPreviousBuildOptionsMap{}, - &WipeoutBuildPathIfBuildOptionsChanged{}, - &StoreBuildOptionsMap{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil - -} diff --git a/container_find_includes.go b/container_find_includes.go deleted file mode 100644 index a58ea68c..00000000 --- a/container_find_includes.go +++ /dev/null @@ -1,407 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -/* - -Include detection - -This code is responsible for figuring out what libraries the current -sketch needs an populates both Context.ImportedLibraries with a list of -Library objects, and Context.IncludeFolders with a list of folders to -put on the include path. - -Simply put, every #include in a source file pulls in the library that -provides that source file. This includes source files in the selected -libraries, so libraries can recursively include other libraries as well. - -To implement this, the gcc preprocessor is used. A queue is created -containing, at first, the source files in the sketch. Each of the files -in the queue is processed in turn by running the preprocessor on it. If -the preprocessor provides an error, the output is examined to see if the -error is a missing header file originating from a #include directive. - -The filename is extracted from that #include directive, and a library is -found that provides it. If multiple libraries provide the same file, one -is slected (how this selection works is not described here, see the -ResolveLibrary function for that). The library selected in this way is -added to the include path through Context.IncludeFolders and the list of -libraries to include in the link through Context.ImportedLibraries. - -Furthermore, all of the library source files are added to the queue, to -be processed as well. When the preprocessor completes without showing an -#include error, processing of the file is complete and it advances to -the next. When no library can be found for a included filename, an error -is shown and the process is aborted. - -Caching - -Since this process is fairly slow (requiring at least one invocation of -the preprocessor per source file), its results are cached. - -Just caching the complete result (i.e. the resulting list of imported -libraries) seems obvious, but such a cache is hard to invalidate. Making -a list of all the source and header files used to create the list and -check if any of them changed is probably feasible, but this would also -require caching the full list of libraries to invalidate the cache when -the include to library resolution might have a different result. Another -downside of a complete cache is that any changes requires re-running -everything, even if no includes were actually changed. - -Instead, caching happens by keeping a sort of "journal" of the steps in -the include detection, essentially tracing each file processed and each -include path entry added. The cache is used by retracing these steps: -The include detection process is executed normally, except that instead -of running the preprocessor, the include filenames are (when possible) -read from the cache. Then, the include file to library resolution is -again executed normally. The results are checked against the cache and -as long as the results match, the cache is considered valid. - -When a source file (or any of the files it includes, as indicated by the -.d file) is changed, the preprocessor is executed as normal for the -file, ignoring any includes from the cache. This does not, however, -invalidate the cache: If the results from the preprocessor match the -entries in the cache, the cache remains valid and can again be used for -the next (unchanged) file. - -The cache file uses the JSON format and contains a list of entries. Each -entry represents a discovered library and contains: - - Sourcefile: The source file that the include was found in - - Include: The included filename found - - Includepath: The addition to the include path - -There are also some special entries: - - When adding the initial include path entries, such as for the core - and variant paths. These are not discovered, so the Sourcefile and - Include fields will be empty. - - When a file contains no (more) missing includes, an entry with an - empty Include and IncludePath is generated. - -*/ - -package builder - -import ( - "encoding/json" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - - "github.com/go-errors/errors" -) - -type ContainerFindIncludes struct{} - -func (s *ContainerFindIncludes) Run(ctx *types.Context) error { - cachePath := filepath.Join(ctx.BuildPath, constants.FILE_INCLUDES_CACHE) - cache := readCache(cachePath) - - appendIncludeFolder(ctx, cache, "", "", ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH]) - if ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] != constants.EMPTY_STRING { - appendIncludeFolder(ctx, cache, "", "", ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH]) - } - - sketch := ctx.Sketch - mergedfile, err := types.MakeSourceFile(ctx, sketch, filepath.Base(sketch.MainFile.Name)+".cpp") - if err != nil { - return i18n.WrapError(err) - } - ctx.CollectedSourceFiles.Push(mergedfile) - - sourceFilePaths := ctx.CollectedSourceFiles - queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, ctx.SketchBuildPath, false /* recurse */) - srcSubfolderPath := filepath.Join(ctx.SketchBuildPath, constants.SKETCH_FOLDER_SRC) - if info, err := os.Stat(srcSubfolderPath); err == nil && info.IsDir() { - queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, srcSubfolderPath, true /* recurse */) - } - - for !sourceFilePaths.Empty() { - err := findIncludesUntilDone(ctx, cache, sourceFilePaths.Pop()) - if err != nil { - os.Remove(cachePath) - return i18n.WrapError(err) - } - } - - // Finalize the cache - cache.ExpectEnd() - err = writeCache(cache, cachePath) - if err != nil { - return i18n.WrapError(err) - } - - err = runCommand(ctx, &FailIfImportedLibraryIsWrong{}) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -// Append the given folder to the include path and match or append it to -// the cache. sourceFilePath and include indicate the source of this -// include (e.g. what #include line in what file it was resolved from) -// and should be the empty string for the default include folders, like -// the core or variant. -func appendIncludeFolder(ctx *types.Context, cache *includeCache, sourceFilePath string, include string, folder string) { - ctx.IncludeFolders = append(ctx.IncludeFolders, folder) - cache.ExpectEntry(sourceFilePath, include, folder) -} - -func runCommand(ctx *types.Context, command types.Command) error { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - return nil -} - -type includeCacheEntry struct { - Sourcefile string - Include string - Includepath string -} - -type includeCache struct { - // Are the cache contents valid so far? - valid bool - // Index into entries of the next entry to be processed. Unused - // when the cache is invalid. - next int - entries []includeCacheEntry -} - -// Return the next cache entry. Should only be called when the cache is -// valid and a next entry is available (the latter can be checked with -// ExpectFile). Does not advance the cache. -func (cache *includeCache) Next() includeCacheEntry { - return cache.entries[cache.next] -} - -// Check that the next cache entry is about the given file. If it is -// not, or no entry is available, the cache is invalidated. Does not -// advance the cache. -func (cache *includeCache) ExpectFile(sourcefile string) { - if cache.valid && (cache.next >= len(cache.entries) || cache.Next().Sourcefile != sourcefile) { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } -} - -// Check that the next entry matches the given values. If so, advance -// the cache. If not, the cache is invalidated. If the cache is -// invalidated, or was already invalid, an entry with the given values -// is appended. -func (cache *includeCache) ExpectEntry(sourcefile string, include string, librarypath string) { - entry := includeCacheEntry{Sourcefile: sourcefile, Include: include, Includepath: librarypath} - if cache.valid { - if cache.next < len(cache.entries) && cache.Next() == entry { - cache.next++ - } else { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } - } - - if !cache.valid { - cache.entries = append(cache.entries, entry) - } -} - -// Check that the cache is completely consumed. If not, the cache is -// invalidated. -func (cache *includeCache) ExpectEnd() { - if cache.valid && cache.next < len(cache.entries) { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } -} - -// Read the cache from the given file -func readCache(path string) *includeCache { - bytes, err := ioutil.ReadFile(path) - if err != nil { - // Return an empty, invalid cache - return &includeCache{} - } - result := &includeCache{} - err = json.Unmarshal(bytes, &result.entries) - if err != nil { - // Return an empty, invalid cache - return &includeCache{} - } - result.valid = true - return result -} - -// Write the given cache to the given file if it is invalidated. If the -// cache is still valid, just update the timestamps of the file. -func writeCache(cache *includeCache, path string) error { - // If the cache was still valid all the way, just touch its file - // (in case any source file changed without influencing the - // includes). If it was invalidated, overwrite the cache with - // the new contents. - if cache.valid { - os.Chtimes(path, time.Now(), time.Now()) - } else { - bytes, err := json.MarshalIndent(cache.entries, "", " ") - if err != nil { - return i18n.WrapError(err) - } - err = utils.WriteFileBytes(path, bytes) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile types.SourceFile) error { - sourcePath := sourceFile.SourcePath(ctx) - depPath := sourceFile.DepfilePath(ctx) - objPath := sourceFile.ObjectPath(ctx) - targetFilePath := utils.NULLFile() - - // TODO: This should perhaps also compare against the - // include.cache file timestamp. Now, it only checks if the file - // changed after the object file was generated, but if it - // changed between generating the cache and the object file, - // this could show the file as unchanged when it really is - // changed. Changing files during a build isn't really - // supported, but any problems from it should at least be - // resolved when doing another build, which is not currently the - // case. - // TODO: This reads the dependency file, but the actual building - // does it again. Should the result be somehow cached? Perhaps - // remove the object file if it is found to be stale? - unchanged, err := builder_utils.ObjFileIsUpToDate(ctx, sourcePath, objPath, depPath) - if err != nil { - return i18n.WrapError(err) - } - - first := true - for { - var include string - cache.ExpectFile(sourcePath) - - includes := ctx.IncludeFolders - if library, ok := sourceFile.Origin.(*types.Library); ok && library.UtilityFolder != "" { - includes = append(includes, library.UtilityFolder) - } - var preproc_err error - var preproc_stderr []byte - if unchanged && cache.valid { - include = cache.Next().Include - if first && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CACHED_INCLUDES, sourcePath) - } - } else { - preproc_stderr, preproc_err = GCCPreprocRunnerForDiscoveringIncludes(ctx, sourcePath, targetFilePath, includes) - // Unwrap error and see if it is an ExitError. - _, is_exit_error := i18n.UnwrapError(preproc_err).(*exec.ExitError) - if preproc_err == nil { - // Preprocessor successful, done - include = "" - } else if !is_exit_error || preproc_stderr == nil { - // Ignore ExitErrors (e.g. gcc returning - // non-zero status), but bail out on - // other errors - return i18n.WrapError(preproc_err) - } else { - include = IncludesFinderWithRegExp(ctx, string(preproc_stderr)) - if include == "" && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_DEBUG, constants.MSG_FIND_INCLUDES_FAILED, sourcePath) - } - } - } - - if include == "" { - // No missing includes found, we're done - cache.ExpectEntry(sourcePath, "", "") - return nil - } - - library := ResolveLibrary(ctx, include) - if library == nil { - // Library could not be resolved, show error - if preproc_err == nil || preproc_stderr == nil { - // Filename came from cache, so run preprocessor to obtain error to show - preproc_stderr, preproc_err = GCCPreprocRunnerForDiscoveringIncludes(ctx, sourcePath, targetFilePath, includes) - if preproc_err == nil { - // If there is a missing #include in the cache, but running - // gcc does not reproduce that, there is something wrong. - // Returning an error here will cause the cache to be - // deleted, so hopefully the next compilation will succeed. - return errors.New("Internal error in cache") - } - } - os.Stderr.Write(preproc_stderr) - return i18n.WrapError(preproc_err) - } - - // Add this library to the list of libraries, the - // include path and queue its source files for further - // include scanning - ctx.ImportedLibraries = append(ctx.ImportedLibraries, library) - appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder) - sourceFolders := types.LibraryToSourceFolder(library) - for _, sourceFolder := range sourceFolders { - queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder, sourceFolder.Recurse) - } - first = false - } -} - -func queueSourceFilesFromFolder(ctx *types.Context, queue *types.UniqueSourceFileQueue, origin interface{}, folder string, recurse bool) error { - extensions := func(ext string) bool { return ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS[ext] } - - filePaths := []string{} - err := utils.FindFilesInFolder(&filePaths, folder, extensions, recurse) - if err != nil { - return i18n.WrapError(err) - } - - for _, filePath := range filePaths { - sourceFile, err := types.MakeSourceFile(ctx, origin, filePath) - if err != nil { - return i18n.WrapError(err) - } - queue.Push(sourceFile) - } - - return nil -} diff --git a/container_merge_copy_sketch_files.go b/container_merge_copy_sketch_files.go deleted file mode 100644 index e84f29ba..00000000 --- a/container_merge_copy_sketch_files.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerMergeCopySketchFiles struct{} - -func (s *ContainerMergeCopySketchFiles) Run(ctx *types.Context) error { - commands := []types.Command{ - &SketchSourceMerger{}, - &SketchSaver{}, - &AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil - -} diff --git a/container_setup.go b/container_setup.go deleted file mode 100644 index 57749aa2..00000000 --- a/container_setup.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerSetupHardwareToolsLibsSketchAndProps struct{} - -func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context) error { - commands := []types.Command{ - &AddAdditionalEntriesToContext{}, - &FailIfBuildPathEqualsSketchPath{}, - &HardwareLoader{}, - &PlatformKeysRewriteLoader{}, - &RewriteHardwareKeys{}, - &ToolsLoader{}, - &TargetBoardResolver{}, - &AddBuildBoardPropertyIfMissing{}, - &LibrariesLoader{}, - &SketchLoader{}, - &SetupBuildProperties{}, - &LoadVIDPIDSpecificProperties{}, - &SetCustomBuildProperties{}, - &AddMissingBuildPropertiesFromParentPlatformTxtFiles{}, - } - - ctx.Progress.Steps = ctx.Progress.Steps / float64(len(commands)) - - for _, command := range commands { - builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx) - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} diff --git a/create_build_options_map.go b/create_build_options_map.go deleted file mode 100644 index 490a2188..00000000 --- a/create_build_options_map.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "encoding/json" -) - -type CreateBuildOptionsMap struct{} - -func (s *CreateBuildOptionsMap) Run(ctx *types.Context) error { - buildOptions := ctx.ExtractBuildOptions() - bytes, err := json.MarshalIndent(buildOptions, "", " ") - if err != nil { - return i18n.WrapError(err) - } - - ctx.BuildOptionsJson = string(bytes) - - return nil -} diff --git a/create_cmake_rule.go b/create_cmake_rule.go deleted file mode 100644 index 9d316457..00000000 --- a/create_cmake_rule.go +++ /dev/null @@ -1,266 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/arduino/go-properties-map" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -var VALID_EXPORT_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true, ".a": true, ".properties": true} -var DOTHEXTENSION = map[string]bool{".h": true, ".hh": true, ".hpp": true} -var DOTAEXTENSION = map[string]bool{".a": true} - -type ExportProjectCMake struct { - // Was there an error while compiling the sketch? - SketchError bool -} - -func (s *ExportProjectCMake) Run(ctx *types.Context) error { - //verbose := ctx.Verbose - logger := ctx.GetLogger() - - if s.SketchError || !canExportCmakeProject(ctx) { - return nil - } - - // Create new cmake subFolder - clean if the folder is already there - cmakeFolder := filepath.Join(ctx.BuildPath, "_cmake") - if _, err := os.Stat(cmakeFolder); err == nil { - os.RemoveAll(cmakeFolder) - } - os.Mkdir(cmakeFolder, 0777) - - // Create lib and build subfolders - libBaseFolder := filepath.Join(cmakeFolder, "lib") - os.Mkdir(libBaseFolder, 0777) - buildBaseFolder := filepath.Join(cmakeFolder, "build") - os.Mkdir(buildBaseFolder, 0777) - - // Create core subfolder path (don't create it yet) - coreFolder := filepath.Join(cmakeFolder, "core") - cmakeFile := filepath.Join(cmakeFolder, "CMakeLists.txt") - - dynamicLibsFromPkgConfig := map[string]bool{} - extensions := func(ext string) bool { return VALID_EXPORT_EXTENSIONS[ext] } - staticLibsExtensions := func(ext string) bool { return DOTAEXTENSION[ext] } - for _, library := range ctx.ImportedLibraries { - // Copy used libraries in the correct folder - libFolder := filepath.Join(libBaseFolder, library.Name) - mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - utils.CopyDir(library.Folder, libFolder, extensions) - - // Read cmake options if available - isStaticLib := true - if cmakeOptions, err := properties.Load(filepath.Join(libFolder, "src", mcu, "arduino_builder.properties")); err == nil { - // If the library can be linked dynamically do not copy the library folder - if pkgs, ok := cmakeOptions["cmake.pkg_config"]; ok { - isStaticLib = false - for _, pkg := range strings.Split(pkgs, " ") { - dynamicLibsFromPkgConfig[pkg] = true - } - } - } - - // Remove examples folder - if _, err := os.Stat(filepath.Join(libFolder, "examples")); err == nil { - os.RemoveAll(filepath.Join(libFolder, "examples")) - } - - // Remove stray folders contining incompatible or not needed libraries archives - var files []string - utils.FindFilesInFolder(&files, filepath.Join(libFolder, "src"), staticLibsExtensions, true) - for _, file := range files { - staticLibDir := filepath.Dir(file) - if !isStaticLib || !strings.Contains(staticLibDir, mcu) { - os.RemoveAll(staticLibDir) - } - } - } - - // Copy core + variant in use + preprocessed sketch in the correct folders - err := utils.CopyDir(ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH], coreFolder, extensions) - if err != nil { - fmt.Println(err) - } - err = utils.CopyDir(ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH], filepath.Join(coreFolder, "variant"), extensions) - if err != nil { - fmt.Println(err) - } - - // Use old ctags method to generate export file - commands := []types.Command{ - //&ContainerMergeCopySketchFiles{}, - &ContainerAddPrototypes{}, - //&FilterSketchSource{Source: &ctx.Source, RemoveLineMarkers: true}, - //&SketchSaver{}, - } - - for _, command := range commands { - command.Run(ctx) - } - - err = utils.CopyDir(ctx.SketchBuildPath, filepath.Join(cmakeFolder, "sketch"), extensions) - if err != nil { - fmt.Println(err) - } - - // Extract CFLAGS, CPPFLAGS and LDFLAGS - var defines []string - var linkerflags []string - var dynamicLibsFromGccMinusL []string - var linkDirectories []string - - extractCompileFlags(ctx, constants.RECIPE_C_COMBINE_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) - extractCompileFlags(ctx, constants.RECIPE_C_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) - extractCompileFlags(ctx, constants.RECIPE_CPP_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) - - // Extract folders with .h in them for adding in include list - var headerFiles []string - isHeader := func(ext string) bool { return DOTHEXTENSION[ext] } - utils.FindFilesInFolder(&headerFiles, cmakeFolder, isHeader, true) - foldersContainingDotH := findUniqueFoldersRelative(headerFiles, cmakeFolder) - - // Extract folders with .a in them for adding in static libs paths list - var staticLibs []string - utils.FindFilesInFolder(&staticLibs, cmakeFolder, staticLibsExtensions, true) - - // Generate the CMakeLists global file - - projectName := strings.TrimSuffix(filepath.Base(ctx.Sketch.MainFile.Name), filepath.Ext(ctx.Sketch.MainFile.Name)) - - cmakelist := "cmake_minimum_required(VERSION 3.5.0)\n" - cmakelist += "INCLUDE(FindPkgConfig)\n" - cmakelist += "project (" + projectName + " C CXX)\n" - cmakelist += "add_definitions (" + strings.Join(defines, " ") + " " + strings.Join(linkerflags, " ") + ")\n" - cmakelist += "include_directories (" + foldersContainingDotH + ")\n" - - // Make link directories relative - // We can totally discard them since they mostly are outside the core folder - // If they are inside the core they are not getting copied :) - var relLinkDirectories []string - for _, dir := range linkDirectories { - if strings.Contains(dir, cmakeFolder) { - relLinkDirectories = append(relLinkDirectories, strings.TrimPrefix(dir, cmakeFolder)) - } - } - - // Add SO_PATHS option for libraries not getting found by pkg_config - cmakelist += "set(EXTRA_LIBS_DIRS \"\" CACHE STRING \"Additional paths for dynamic libraries\")\n" - - linkGroup := "" - for _, lib := range dynamicLibsFromGccMinusL { - // Dynamic libraries should be discovered by pkg_config - cmakelist += "pkg_search_module (" + strings.ToUpper(lib) + " " + lib + ")\n" - relLinkDirectories = append(relLinkDirectories, "${"+strings.ToUpper(lib)+"_LIBRARY_DIRS}") - linkGroup += " " + lib - } - for lib := range dynamicLibsFromPkgConfig { - cmakelist += "pkg_search_module (" + strings.ToUpper(lib) + " " + lib + ")\n" - relLinkDirectories = append(relLinkDirectories, "${"+strings.ToUpper(lib)+"_LIBRARY_DIRS}") - linkGroup += " ${" + strings.ToUpper(lib) + "_LIBRARIES}" - } - cmakelist += "link_directories (" + strings.Join(relLinkDirectories, " ") + " ${EXTRA_LIBS_DIRS})\n" - for _, staticLib := range staticLibs { - // Static libraries are fully configured - lib := filepath.Base(staticLib) - lib = strings.TrimPrefix(lib, "lib") - lib = strings.TrimSuffix(lib, ".a") - if !utils.SliceContains(dynamicLibsFromGccMinusL, lib) { - linkGroup += " " + lib - cmakelist += "add_library (" + lib + " STATIC IMPORTED)\n" - location := strings.TrimPrefix(staticLib, cmakeFolder) - cmakelist += "set_property(TARGET " + lib + " PROPERTY IMPORTED_LOCATION " + "${PROJECT_SOURCE_DIR}" + location + " )\n" - } - } - - // Include source files - // TODO: remove .cpp and .h from libraries example folders - cmakelist += "file (GLOB_RECURSE SOURCES core/*.c* lib/*.c* sketch/*.c*)\n" - - // Compile and link project - cmakelist += "add_executable (" + projectName + " ${SOURCES} ${SOURCES_LIBS})\n" - cmakelist += "target_link_libraries( " + projectName + " -Wl,--as-needed -Wl,--start-group " + linkGroup + " -Wl,--end-group)\n" - - utils.WriteFile(cmakeFile, cmakelist) - - return nil -} - -func canExportCmakeProject(ctx *types.Context) bool { - return ctx.BuildProperties[constants.BUILD_PROPERTIES_COMPILER_EXPORT_CMAKE_FLAGS] != "" -} - -func extractCompileFlags(ctx *types.Context, receipe string, defines, dynamicLibs, linkerflags, linkDirectories *[]string, logger i18n.Logger) { - command, _ := builder_utils.PrepareCommandForRecipe(ctx, ctx.BuildProperties, receipe, true) - - for _, arg := range command.Args { - if strings.HasPrefix(arg, "-D") { - *defines = utils.AppendIfNotPresent(*defines, arg) - continue - } - if strings.HasPrefix(arg, "-l") { - *dynamicLibs = utils.AppendIfNotPresent(*dynamicLibs, arg[2:]) - continue - } - if strings.HasPrefix(arg, "-L") { - *linkDirectories = utils.AppendIfNotPresent(*linkDirectories, arg[2:]) - continue - } - if strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "-I") && !strings.HasPrefix(arg, "-o") { - // HACK : from linkerflags remove MMD (no cache is produced) - if !strings.HasPrefix(arg, "-MMD") { - *linkerflags = utils.AppendIfNotPresent(*linkerflags, arg) - } - } - } -} - -func findUniqueFoldersRelative(slice []string, base string) string { - var out []string - for _, element := range slice { - path := filepath.Dir(element) - path = strings.TrimPrefix(path, base+"/") - if !utils.SliceContains(out, path) { - out = append(out, path) - } - } - return strings.Join(out, " ") -} diff --git a/ctags/ctags_has_issues.go b/ctags/ctags_has_issues.go deleted file mode 100644 index f61ab70a..00000000 --- a/ctags/ctags_has_issues.go +++ /dev/null @@ -1,310 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "bufio" - "os" - "strings" - - "github.com/arduino/arduino-builder/types" -) - -func (p *CTagsParser) FixCLinkageTagsDeclarations(tags []*types.CTag) { - - linesMap := p.FindCLinkageLines(tags) - for i, _ := range tags { - - if sliceContainsInt(linesMap[tags[i].Filename], tags[i].Line) && - !strings.Contains(tags[i].PrototypeModifiers, EXTERN) { - tags[i].PrototypeModifiers = tags[i].PrototypeModifiers + " " + EXTERN - } - } -} - -func sliceContainsInt(s []int, e int) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - -func (p *CTagsParser) prototypeAndCodeDontMatch(tag *types.CTag) bool { - if tag.SkipMe { - return true - } - - code := removeSpacesAndTabs(tag.Code) - - if strings.Index(code, ")") == -1 { - // Add to code non-whitespace non-comments tokens until we find a closing round bracket - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - line := 1 - - // skip lines until we get to the start of this tag - for scanner.Scan() && line < tag.Line { - line++ - } - - // read up to 10 lines in search of a closing paren - multilinecomment := false - temp := "" - - code, multilinecomment = removeComments(scanner.Text(), multilinecomment) - for scanner.Scan() && line < (tag.Line+10) && strings.Index(temp, ")") == -1 { - temp, multilinecomment = removeComments(scanner.Text(), multilinecomment) - code += temp - } - } - } - - code = removeSpacesAndTabs(code) - - prototype := removeSpacesAndTabs(tag.Prototype) - prototype = removeTralingSemicolon(prototype) - - // Prototype matches exactly with the code? - ret := strings.Index(code, prototype) - - if ret == -1 { - // If the definition is multiline ctags uses the function name as line number - // Try to match functions in the form - // void - // foo() {} - - // Add to code n non-whitespace non-comments tokens before the code line - - code = removeEverythingAfterClosingRoundBracket(code) - // Get how many characters are "missing" - n := strings.Index(prototype, code) - line := 0 - // Add these characters to "code" string - code, line = getFunctionProtoWithNPreviousCharacters(tag, code, n) - // Check again for perfect matching - ret = strings.Index(code, prototype) - if ret != -1 { - tag.Line = line - } - } - - return ret == -1 -} - -func findTemplateMultiline(tag *types.CTag) string { - code, _ := getFunctionProtoUntilTemplateToken(tag, tag.Code) - return removeEverythingAfterClosingRoundBracket(code) -} - -func removeEverythingAfterClosingRoundBracket(s string) string { - n := strings.Index(s, ")") - return s[0 : n+1] -} - -func getFunctionProtoUntilTemplateToken(tag *types.CTag, code string) (string, int) { - - /* FIXME I'm ugly */ - line := 0 - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - multilinecomment := false - var textBuffer []string - - // buffer lines until we get to the start of this tag - for scanner.Scan() && line < (tag.Line-1) { - line++ - text := scanner.Text() - textBuffer = append(textBuffer, text) - } - - for line > 0 && !strings.Contains(code, TEMPLATE) { - - line = line - 1 - text := textBuffer[line] - - text, multilinecomment = removeComments(text, multilinecomment) - - code = text + code - } - } - return code, line -} - -func getFunctionProtoWithNPreviousCharacters(tag *types.CTag, code string, n int) (string, int) { - - /* FIXME I'm ugly */ - expectedPrototypeLen := len(code) + n - line := 0 - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - multilinecomment := false - var textBuffer []string - - // buffer lines until we get to the start of this tag - for scanner.Scan() && line < (tag.Line-1) { - line++ - text := scanner.Text() - textBuffer = append(textBuffer, text) - } - - for line > 0 && len(code) < expectedPrototypeLen { - - line = line - 1 - text := textBuffer[line] - - text, multilinecomment = removeComments(text, multilinecomment) - - code = text + code - code = removeSpacesAndTabs(code) - } - } - return code, line -} - -func removeComments(text string, multilinecomment bool) (string, bool) { - // Remove C++ style comments - if strings.Index(text, "//") != -1 { - text = text[0:strings.Index(text, "//")] - } - - // Remove C style comments - if strings.Index(text, "*/") != -1 { - if strings.Index(text, "/*") != -1 { - // C style comments on the same line - text = text[0:strings.Index(text, "/*")] + text[strings.Index(text, "*/")+1:len(text)-1] - } else { - text = text[strings.Index(text, "*/")+1 : len(text)-1] - multilinecomment = true - } - } - - if multilinecomment { - if strings.Index(text, "/*") != -1 { - text = text[0:strings.Index(text, "/*")] - multilinecomment = false - } else { - text = "" - } - } - return text, multilinecomment -} - -/* This function scans the source files searching for "extern C" context - * It save the line numbers in a map filename -> {lines...} - */ -func (p *CTagsParser) FindCLinkageLines(tags []*types.CTag) map[string][]int { - - lines := make(map[string][]int) - - for _, tag := range tags { - - if lines[tag.Filename] != nil { - break - } - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - lines[tag.Filename] = append(lines[tag.Filename], -1) - - scanner := bufio.NewScanner(file) - - // we can't remove the comments otherwise the line number will be wrong - // there are three cases: - // 1 - extern "C" void foo() - // 2 - extern "C" { - // void foo(); - // void bar(); - // } - // 3 - extern "C" - // { - // void foo(); - // void bar(); - // } - // case 1 and 2 can be simply recognized with string matching and indent level count - // case 3 needs specia attention: if the line ONLY contains `extern "C"` string, don't bail out on indent level = 0 - - inScope := false - enteringScope := false - indentLevels := 0 - line := 0 - - externCDecl := removeSpacesAndTabs(EXTERN) - - for scanner.Scan() { - line++ - str := removeSpacesAndTabs(scanner.Text()) - - if len(str) == 0 { - continue - } - - // check if we are on the first non empty line after externCDecl in case 3 - if enteringScope == true { - enteringScope = false - } - - // check if the line contains externCDecl - if strings.Contains(str, externCDecl) { - inScope = true - if len(str) == len(externCDecl) { - // case 3 - enteringScope = true - } - } - if inScope == true { - lines[tag.Filename] = append(lines[tag.Filename], line) - } - indentLevels += strings.Count(str, "{") - strings.Count(str, "}") - - // Bail out if indentLevel is zero and we are not in case 3 - if indentLevels == 0 && enteringScope == false { - inScope = false - } - } - } - - } - return lines -} diff --git a/ctags/ctags_parser.go b/ctags/ctags_parser.go deleted file mode 100644 index fc45b8ff..00000000 --- a/ctags/ctags_parser.go +++ /dev/null @@ -1,252 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "strconv" - "strings" - - "github.com/arduino/arduino-builder/types" -) - -const KIND_PROTOTYPE = "prototype" -const KIND_FUNCTION = "function" - -//const KIND_PROTOTYPE_MODIFIERS = "prototype_modifiers" - -const TEMPLATE = "template" -const STATIC = "static" -const EXTERN = "extern \"C\"" - -var KNOWN_TAG_KINDS = map[string]bool{ - "prototype": true, - "function": true, -} - -type CTagsParser struct { - tags []*types.CTag - mainFile string -} - -func (p *CTagsParser) Parse(ctagsOutput string, mainFile string) []*types.CTag { - rows := strings.Split(ctagsOutput, "\n") - rows = removeEmpty(rows) - - p.mainFile = mainFile - - for _, row := range rows { - p.tags = append(p.tags, parseTag(row)) - } - - p.skipTagsWhere(tagIsUnknown) - p.skipTagsWhere(tagIsUnhandled) - p.addPrototypes() - p.removeDefinedProtypes() - p.skipDuplicates() - p.skipTagsWhere(p.prototypeAndCodeDontMatch) - - return p.tags -} - -func (p *CTagsParser) addPrototypes() { - for _, tag := range p.tags { - if !tag.SkipMe { - addPrototype(tag) - } - } -} - -func addPrototype(tag *types.CTag) { - if strings.Index(tag.Prototype, TEMPLATE) == 0 { - if strings.Index(tag.Code, TEMPLATE) == 0 { - code := tag.Code - if strings.Contains(code, "{") { - code = code[:strings.Index(code, "{")] - } else { - code = code[:strings.LastIndex(code, ")")+1] - } - tag.Prototype = code + ";" - } else { - //tag.Code is 99% multiline, recreate it - code := findTemplateMultiline(tag) - tag.Prototype = code + ";" - } - return - } - - tag.PrototypeModifiers = "" - if strings.Index(tag.Code, STATIC+" ") != -1 { - tag.PrototypeModifiers = tag.PrototypeModifiers + " " + STATIC - } - - // Extern "C" modifier is now added in FixCLinkageTagsDeclarations - - tag.PrototypeModifiers = strings.TrimSpace(tag.PrototypeModifiers) -} - -func (p *CTagsParser) removeDefinedProtypes() { - definedPrototypes := make(map[string]bool) - for _, tag := range p.tags { - if tag.Kind == KIND_PROTOTYPE { - definedPrototypes[tag.Prototype] = true - } - } - - for _, tag := range p.tags { - if definedPrototypes[tag.Prototype] { - //if ctx.DebugLevel >= 10 { - // ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_SKIPPING_TAG_ALREADY_DEFINED, tag.FunctionName) - //} - tag.SkipMe = true - } - } -} - -func (p *CTagsParser) skipDuplicates() { - definedPrototypes := make(map[string]bool) - - for _, tag := range p.tags { - if !definedPrototypes[tag.Prototype] && tag.SkipMe == false { - definedPrototypes[tag.Prototype] = true - } else { - tag.SkipMe = true - } - } -} - -type skipFuncType func(tag *types.CTag) bool - -func (p *CTagsParser) skipTagsWhere(skipFunc skipFuncType) { - for _, tag := range p.tags { - if !tag.SkipMe { - skip := skipFunc(tag) - //if skip && p.debugLevel >= 10 { - // ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_SKIPPING_TAG_WITH_REASON, tag.FunctionName, runtime.FuncForPC(reflect.ValueOf(skipFunc).Pointer()).Name()) - //} - tag.SkipMe = skip - } - } -} - -func removeTralingSemicolon(s string) string { - return s[0 : len(s)-1] -} - -func removeSpacesAndTabs(s string) string { - s = strings.Replace(s, " ", "", -1) - s = strings.Replace(s, "\t", "", -1) - return s -} - -func tagIsUnhandled(tag *types.CTag) bool { - return !isHandled(tag) -} - -func isHandled(tag *types.CTag) bool { - if tag.Class != "" { - return false - } - if tag.Struct != "" { - return false - } - if tag.Namespace != "" { - return false - } - return true -} - -func tagIsUnknown(tag *types.CTag) bool { - return !KNOWN_TAG_KINDS[tag.Kind] -} - -func parseTag(row string) *types.CTag { - tag := &types.CTag{} - parts := strings.Split(row, "\t") - - tag.FunctionName = parts[0] - // This unescapes any backslashes in the filename. These - // filenames that ctags outputs originate from the line markers - // in the source, as generated by gcc. gcc escapes both - // backslashes and double quotes, but ctags ignores any escaping - // and just cuts off the filename at the first double quote it - // sees. This means any backslashes are still escaped, and need - // to be unescape, and any quotes will just break the build. - tag.Filename = strings.Replace(parts[1], "\\\\", "\\", -1) - - parts = parts[2:] - - returntype := "" - for _, part := range parts { - if strings.Contains(part, ":") { - colon := strings.Index(part, ":") - field := part[:colon] - value := strings.TrimSpace(part[colon+1:]) - switch field { - case "kind": - tag.Kind = value - case "line": - val, _ := strconv.Atoi(value) - // TODO: Check err from strconv.Atoi - tag.Line = val - case "typeref": - tag.Typeref = value - case "signature": - tag.Signature = value - case "returntype": - returntype = value - case "class": - tag.Class = value - case "struct": - tag.Struct = value - case "namespace": - tag.Namespace = value - } - } - } - tag.Prototype = returntype + " " + tag.FunctionName + tag.Signature + ";" - - if strings.Contains(row, "/^") && strings.Contains(row, "$/;") { - tag.Code = row[strings.Index(row, "/^")+2 : strings.Index(row, "$/;")] - } - - return tag -} - -func removeEmpty(rows []string) []string { - var newRows []string - for _, row := range rows { - row = strings.TrimSpace(row) - if len(row) > 0 { - newRows = append(newRows, row) - } - } - - return newRows -} diff --git a/ctags/ctags_parser_test.go b/ctags/ctags_parser_test.go deleted file mode 100644 index 8813e772..00000000 --- a/ctags/ctags_parser_test.go +++ /dev/null @@ -1,347 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "io/ioutil" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder/types" - - "github.com/stretchr/testify/require" -) - -func produceTags(t *testing.T, filename string) []*types.CTag { - bytes, err := ioutil.ReadFile(filepath.Join("test_data", filename)) - require.NoError(t, err) - - parser := CTagsParser{} - return parser.Parse(string(bytes), "") -} - -func TestCTagsParserShouldListPrototypes(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListPrototypes.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "server", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "process", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "process", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "digitalCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "analogCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "modeCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) -} - -func TestCTagsParserShouldListTemplates(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListTemplates.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "minimum", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template T minimum (T a, T b);", tags[idx].Prototype) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void setup();", tags[idx].Prototype) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void loop();", tags[idx].Prototype) -} - -func TestCTagsParserShouldListTemplates2(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListTemplates2.txt") - - require.Equal(t, 4, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "SRAM_writeAnything", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template int SRAM_writeAnything(int ee, const T& value);", tags[idx].Prototype) - idx++ - require.Equal(t, "SRAM_readAnything", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template int SRAM_readAnything(int ee, T& value);", tags[idx].Prototype) -} - -func TestCTagsParserShouldDealWithClasses(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithClasses.txt") - - require.Equal(t, 2, len(tags)) - idx := 0 - require.Equal(t, "SleepCycle", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - idx++ - require.Equal(t, "SleepCycle", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealWithStructs(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithStructs.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "A_NEW_TYPE", tags[idx].FunctionName) - require.Equal(t, "struct", tags[idx].Kind) - idx++ - require.Equal(t, "foo", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - require.Equal(t, "struct:A_NEW_TYPE", tags[idx].Typeref) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "dostuff", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealWithMacros(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithMacros.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "DEBUG", tags[idx].FunctionName) - require.Equal(t, "macro", tags[idx].Kind) - idx++ - require.Equal(t, "DISABLED", tags[idx].FunctionName) - require.Equal(t, "macro", tags[idx].Kind) - idx++ - require.Equal(t, "hello", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "debug", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "disabledIsDefined", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "useMyType", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealFunctionWithDifferentSignatures(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - idx++ - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserClassMembersAreFilteredOut(t *testing.T) { - tags := produceTags(t, "TestCTagsParserClassMembersAreFilteredOut.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "set_values", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "area", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "set_values", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserStructWithFunctions(t *testing.T) { - tags := produceTags(t, "TestCTagsParserStructWithFunctions.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "struct", tags[idx].Kind) - idx++ - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "sensorData", tags[idx].Struct) - idx++ - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "sensorData", tags[idx].Struct) - idx++ - require.Equal(t, "sensors", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "sensor1", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "sensor2", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserDefaultArguments(t *testing.T) { - tags := produceTags(t, "TestCTagsParserDefaultArguments.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "test", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void test(int x = 1);", tags[idx].Prototype) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserNamespace(t *testing.T) { - tags := produceTags(t, "TestCTagsParserNamespace.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "value", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Test", tags[idx].Namespace) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserStatic(t *testing.T) { - tags := produceTags(t, "TestCTagsParserStatic.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "doStuff", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserFunctionPointer(t *testing.T) { - tags := produceTags(t, "TestCTagsParserFunctionPointer.txt") - - require.Equal(t, 4, len(tags)) - idx := 0 - require.Equal(t, "t1Callback", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "t1Callback", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserFunctionPointers(t *testing.T) { - tags := produceTags(t, "TestCTagsParserFunctionPointers.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "func", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "funcArr", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "int funcArr();", tags[idx].Prototype) - idx++ - require.Equal(t, "funcCombo", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void funcCombo(void (*(&in)[5])(int));", tags[idx].Prototype) -} diff --git a/ctags/ctags_to_prototypes.go b/ctags/ctags_to_prototypes.go deleted file mode 100644 index 4492704a..00000000 --- a/ctags/ctags_to_prototypes.go +++ /dev/null @@ -1,120 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "strings" - - "github.com/arduino/arduino-builder/types" -) - -func (p *CTagsParser) GeneratePrototypes() ([]*types.Prototype, int) { - return p.toPrototypes(), p.findLineWhereToInsertPrototypes() -} - -func (p *CTagsParser) findLineWhereToInsertPrototypes() int { - firstFunctionLine := p.firstFunctionAtLine() - firstFunctionPointerAsArgument := p.firstFunctionPointerUsedAsArgument() - if firstFunctionLine != -1 && firstFunctionPointerAsArgument != -1 { - if firstFunctionLine < firstFunctionPointerAsArgument { - return firstFunctionLine - } else { - return firstFunctionPointerAsArgument - } - } else if firstFunctionLine != -1 { - return firstFunctionLine - } else if firstFunctionPointerAsArgument != -1 { - return firstFunctionPointerAsArgument - } else { - return 0 - } -} - -func (p *CTagsParser) firstFunctionPointerUsedAsArgument() int { - functionTags := p.collectFunctions() - for _, tag := range p.tags { - if functionNameUsedAsFunctionPointerIn(tag, functionTags) { - return tag.Line - } - } - return -1 -} - -func functionNameUsedAsFunctionPointerIn(tag *types.CTag, functionTags []*types.CTag) bool { - for _, functionTag := range functionTags { - if tag.Line != functionTag.Line && strings.Index(tag.Code, "&"+functionTag.FunctionName) != -1 { - return true - } - if tag.Line != functionTag.Line && strings.Index(strings.TrimSpace(tag.Code), "("+functionTag.FunctionName+")") != -1 { - return true - } - } - return false -} - -func (p *CTagsParser) collectFunctions() []*types.CTag { - functionTags := []*types.CTag{} - for _, tag := range p.tags { - if tag.Kind == KIND_FUNCTION && !tag.SkipMe { - functionTags = append(functionTags, tag) - } - } - return functionTags -} - -func (p *CTagsParser) firstFunctionAtLine() int { - for _, tag := range p.tags { - if !tagIsUnknown(tag) && isHandled(tag) && tag.Kind == KIND_FUNCTION && tag.Filename == p.mainFile { - return tag.Line - } - } - return -1 -} - -func (p *CTagsParser) toPrototypes() []*types.Prototype { - prototypes := []*types.Prototype{} - for _, tag := range p.tags { - if strings.TrimSpace(tag.Prototype) == "" { - continue - } - if !tag.SkipMe { - prototype := &types.Prototype{ - FunctionName: tag.FunctionName, - File: tag.Filename, - Prototype: tag.Prototype, - Modifiers: tag.PrototypeModifiers, - Line: tag.Line, - //Fields: tag, - } - prototypes = append(prototypes, prototype) - } - } - return prototypes -} diff --git a/ctags/ctags_to_prototypes_test.go b/ctags/ctags_to_prototypes_test.go deleted file mode 100644 index 9388747d..00000000 --- a/ctags/ctags_to_prototypes_test.go +++ /dev/null @@ -1,238 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "io/ioutil" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func producePrototypes(t *testing.T, filename string, mainFile string) ([]*types.Prototype, int) { - bytes, err := ioutil.ReadFile(filepath.Join("test_data", filename)) - require.NoError(t, err) - - parser := &CTagsParser{} - parser.Parse(string(bytes), mainFile) - return parser.GeneratePrototypes() -} - -func TestCTagsToPrototypesShouldListPrototypes(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListPrototypes.txt", "/tmp/sketch7210316334309249705.cpp") - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void digitalCommand(YunClient client);", prototypes[2].Prototype) - require.Equal(t, "void analogCommand(YunClient client);", prototypes[3].Prototype) - require.Equal(t, "void modeCommand(YunClient client);", prototypes[4].Prototype) - - require.Equal(t, 33, line) -} - -func TestCTagsToPrototypesShouldListTemplates(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListTemplates.txt", "/tmp/sketch8398023134925534708.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "template T minimum (T a, T b);", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch8398023134925534708.cpp", prototypes[0].File) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesShouldListTemplates2(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListTemplates2.txt", "/tmp/sketch463160524247569568.cpp") - - require.Equal(t, 4, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch463160524247569568.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "template int SRAM_writeAnything(int ee, const T& value);", prototypes[2].Prototype) - require.Equal(t, "template int SRAM_readAnything(int ee, T& value);", prototypes[3].Prototype) - - require.Equal(t, 1, line) -} - -func TestCTagsToPrototypesShouldDealWithClasses(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithClasses.txt", "/tmp/sketch9043227824785312266.cpp") - - require.Equal(t, 0, len(prototypes)) - - require.Equal(t, 8, line) -} - -func TestCTagsToPrototypesShouldDealWithStructs(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithStructs.txt", "/tmp/sketch8930345717354294915.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch8930345717354294915.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void dostuff(A_NEW_TYPE * bar);", prototypes[2].Prototype) - - require.Equal(t, 9, line) -} - -func TestCTagsToPrototypesShouldDealWithMacros(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithMacros.txt", "/tmp/sketch5976699731718729500.cpp") - - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch5976699731718729500.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void debug();", prototypes[2].Prototype) - require.Equal(t, "void disabledIsDefined();", prototypes[3].Prototype) - require.Equal(t, "int useMyType(MyType type);", prototypes[4].Prototype) - - require.Equal(t, 18, line) -} - -func TestCTagsToPrototypesShouldDealFunctionWithDifferentSignatures(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt", "/tmp/test260613593/preproc/ctags_target.cpp") - - require.Equal(t, 1, len(prototypes)) - require.Equal(t, "boolean getBytes( byte addr, int amount );", prototypes[0].Prototype) - require.Equal(t, "/tmp/test260613593/preproc/ctags_target.cpp", prototypes[0].File) - - require.Equal(t, 5031, line) -} - -func TestCTagsToPrototypesClassMembersAreFilteredOut(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserClassMembersAreFilteredOut.txt", "/tmp/test834438754/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test834438754/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 14, line) -} - -func TestCTagsToPrototypesStructWithFunctions(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserStructWithFunctions.txt", "/tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 16, line) -} - -func TestCTagsToPrototypesDefaultArguments(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserDefaultArguments.txt", "/tmp/test179252494/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void test(int x = 1);", prototypes[0].Prototype) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "/tmp/test179252494/preproc/ctags_target.cpp", prototypes[1].File) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesNamespace(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserNamespace.txt", "/tmp/test030883150/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test030883150/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 8, line) -} - -func TestCTagsToPrototypesStatic(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserStatic.txt", "/tmp/test542833488/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test542833488/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void doStuff();", prototypes[2].Prototype) - require.Equal(t, "static", prototypes[2].Modifiers) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointer(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointer.txt", "/tmp/test547238273/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void t1Callback();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test547238273/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointers(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointers.txt", "/tmp/test907446433/preproc/ctags_target.cpp") - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test907446433/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointersNoIndirect(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointersNoIndirect.txt", "/tmp/test547238273/preproc/bug_callback.ino") - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test547238273/preproc/bug_callback.ino", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 10, line) -} - -func TestCTagsRunnerSketchWithClassFunction(t *testing.T) { - prototypes, _ := producePrototypes(t, "TestCTagsRunnerSketchWithClassFunction.txt", "/home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void asdf();", prototypes[2].Prototype) -} - -func TestCTagsRunnerSketchWithMultiFile(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsRunnerSketchWithMultifile.txt", "/tmp/apUNI8a/main.ino") - - require.Equal(t, 0, line) - require.Equal(t, "void A7105_Setup();", prototypes[0].Prototype) - require.Equal(t, "void A7105_Reset();", prototypes[1].Prototype) - require.Equal(t, "int A7105_calibrate_VCB(uint8_t channel);", prototypes[2].Prototype) -} diff --git a/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt b/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt deleted file mode 100644 index 12313597..00000000 --- a/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt +++ /dev/null @@ -1,6 +0,0 @@ -set_values /tmp/test834438754/preproc/ctags_target.cpp /^ void set_values (int,int);$/;" kind:prototype line:5 class:Rectangle signature:(int,int) returntype:void -area /tmp/test834438754/preproc/ctags_target.cpp /^ int area() {return width*height;}$/;" kind:function line:6 class:Rectangle signature:() returntype:int -set_values /tmp/test834438754/preproc/ctags_target.cpp /^void Rectangle::set_values (int x, int y) {$/;" kind:function line:9 class:Rectangle signature:(int x, int y) returntype:void -setup /tmp/test834438754/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:14 signature:() returntype:void -loop /tmp/test834438754/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:18 signature:() returntype:void - diff --git a/ctags/test_data/TestCTagsParserDefaultArguments.txt b/ctags/test_data/TestCTagsParserDefaultArguments.txt deleted file mode 100644 index 7735d974..00000000 --- a/ctags/test_data/TestCTagsParserDefaultArguments.txt +++ /dev/null @@ -1,3 +0,0 @@ -test /tmp/test179252494/preproc/ctags_target.cpp /^void test(int x = 1) {$/;" kind:function line:2 signature:(int x = 1) returntype:void -setup /tmp/test179252494/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:5 signature:() returntype:void -loop /tmp/test179252494/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:8 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointer.txt b/ctags/test_data/TestCTagsParserFunctionPointer.txt deleted file mode 100644 index b36c5928..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointer.txt +++ /dev/null @@ -1,4 +0,0 @@ -t1Callback /tmp/test547238273/preproc/ctags_target.cpp /^Task t1(&t1Callback);$/;" kind:variable line:2 -t1Callback /tmp/test547238273/preproc/ctags_target.cpp /^void t1Callback() {}$/;" kind:function line:3 signature:() returntype:void -setup /tmp/test547238273/preproc/ctags_target.cpp /^void setup() {}$/;" kind:function line:4 signature:() returntype:void -loop /tmp/test547238273/preproc/ctags_target.cpp /^void loop() {}$/;" kind:function line:5 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointers.txt b/ctags/test_data/TestCTagsParserFunctionPointers.txt deleted file mode 100644 index 0aa1e06a..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointers.txt +++ /dev/null @@ -1,5 +0,0 @@ -setup /tmp/test907446433/preproc/ctags_target.cpp /^void setup(){$/;" kind:function line:2 signature:() returntype:void -loop /tmp/test907446433/preproc/ctags_target.cpp /^void loop(){}$/;" kind:function line:5 signature:() returntype:void -func /tmp/test907446433/preproc/ctags_target.cpp /^void (*func())(){$/;" kind:function line:7 signature:() returntype:void -funcArr /tmp/test907446433/preproc/ctags_target.cpp /^int (&funcArr())[5]{$/;" kind:function line:11 signature:() returntype:int -funcCombo /tmp/test907446433/preproc/ctags_target.cpp /^void (*(&funcCombo(void (*(&in)[5])(int)))[5])(int){$/;" kind:function line:15 signature:(void (*(&in)[5])(int)) returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt b/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt deleted file mode 100644 index d32e2099..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt +++ /dev/null @@ -1,7 +0,0 @@ -BUG /tmp/test547238273/preproc/bug_callback.ino /^ public: BUG(void (*fn)(void)) {}$/;" kind:function line:6 class:BUG signature:(void (*fn)(void)) -b /tmp/test547238273/preproc/bug_callback.ino /^BUG b(makeItBreak); \/\/this will break$/;" kind:prototype line:10 signature:(makeItBreak)returntype:BUG -setup /tmp/test547238273/preproc/bug_callback.ino /^void setup() {$/;" kind:function line:12 signature:() returntype:void -loop /tmp/test547238273/preproc/bug_callback.ino /^void loop() {}$/;" kind:function line:16 signature:() returntype:void -makeItBreak /tmp/test547238273/preproc/bug_callback.ino /^void makeItBreak() {}$/;" kind:function line:18 signature:() returntype:void -caller /tmp/test547238273/preproc/bug_callback.ino /^void caller(int (*cc)(int ),int a) {$/;" kind:function line:20 signature:(int (*cc)(int ),int a) returntype:void -blub /tmp/test547238273/preproc/bug_callback.ino /^int blub(int a) {$/;" kind:function line:24 signature:(int a) returntype:int diff --git a/ctags/test_data/TestCTagsParserNamespace.txt b/ctags/test_data/TestCTagsParserNamespace.txt deleted file mode 100644 index 8a12c235..00000000 --- a/ctags/test_data/TestCTagsParserNamespace.txt +++ /dev/null @@ -1,4 +0,0 @@ -value /tmp/test030883150/preproc/ctags_target.cpp /^ int value() {$/;" kind:function line:3 namespace:Test signature:() returntype:int -setup /tmp/test030883150/preproc/ctags_target.cpp /^void setup() {}$/;" kind:function line:8 signature:() returntype:void -loop /tmp/test030883150/preproc/ctags_target.cpp /^void loop() {}$/;" kind:function line:9 signature:() returntype:void - diff --git a/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt b/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt deleted file mode 100644 index f052e995..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt +++ /dev/null @@ -1,3 +0,0 @@ -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^ void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;$/;" kind:prototype line:4330 signature:(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const returntype:void -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address$/;" kind:function line:5031 signature:( byte addr, int amount ) returntype:boolean -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address$/;" kind:function line:214 signature:( byte addr, int amount ) returntype:boolean diff --git a/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt b/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt deleted file mode 100644 index 12317759..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt +++ /dev/null @@ -1,2 +0,0 @@ -SleepCycle /tmp/sketch9043227824785312266.cpp /^ SleepCycle( const char* name );$/;" kind:prototype line:4 signature:( const char* name ) -SleepCycle /tmp/sketch9043227824785312266.cpp /^ SleepCycle::SleepCycle( const char* name )$/;" kind:function line:8 signature:( const char* name ) diff --git a/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt b/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt deleted file mode 100644 index f972e00c..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt +++ /dev/null @@ -1,8 +0,0 @@ -DEBUG /tmp/sketch5976699731718729500.cpp 1;" kind:macro line:1 -DISABLED /tmp/sketch5976699731718729500.cpp 2;" kind:macro line:2 -hello /tmp/sketch5976699731718729500.cpp /^String hello = "world!";$/;" kind:variable line:16 -setup /tmp/sketch5976699731718729500.cpp /^void setup() {$/;" kind:function line:18 signature:() returntype:void -loop /tmp/sketch5976699731718729500.cpp /^void loop() {$/;" kind:function line:23 signature:() returntype:void -debug /tmp/sketch5976699731718729500.cpp /^void debug() {$/;" kind:function line:35 signature:() returntype:void -disabledIsDefined /tmp/sketch5976699731718729500.cpp /^void disabledIsDefined() {$/;" kind:function line:46 signature:() returntype:void -useMyType /tmp/sketch5976699731718729500.cpp /^int useMyType(MyType type) {$/;" kind:function line:50 signature:(MyType type) returntype:int diff --git a/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt b/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt deleted file mode 100644 index 240ed27b..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt +++ /dev/null @@ -1,5 +0,0 @@ -A_NEW_TYPE /tmp/sketch8930345717354294915.cpp /^struct A_NEW_TYPE {$/;" kind:struct line:3 -foo /tmp/sketch8930345717354294915.cpp /^} foo;$/;" kind:variable line:7 typeref:struct:A_NEW_TYPE -setup /tmp/sketch8930345717354294915.cpp /^void setup() {$/;" kind:function line:9 signature:() returntype:void -loop /tmp/sketch8930345717354294915.cpp /^void loop() {$/;" kind:function line:13 signature:() returntype:void -dostuff /tmp/sketch8930345717354294915.cpp /^void dostuff (A_NEW_TYPE * bar)$/;" kind:function line:17 signature:(A_NEW_TYPE * bar) returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListPrototypes.txt b/ctags/test_data/TestCTagsParserShouldListPrototypes.txt deleted file mode 100644 index 4e678f51..00000000 --- a/ctags/test_data/TestCTagsParserShouldListPrototypes.txt +++ /dev/null @@ -1,8 +0,0 @@ -server /tmp/sketch7210316334309249705.cpp /^YunServer server;$/;" kind:variable line:31 -setup /tmp/sketch7210316334309249705.cpp /^void setup() {$/;" kind:function line:33 signature:() returntype:void -loop /tmp/sketch7210316334309249705.cpp /^void loop() {$/;" kind:function line:46 signature:() returntype:void -process /tmp/sketch7210316334309249705.cpp /^void process(YunClient client);$/;" kind:prototype line:61 signature:(YunClient client) returntype:void -process /tmp/sketch7210316334309249705.cpp /^void process(YunClient client) {$/;" kind:function line:62 signature:(YunClient client) returntype:void -digitalCommand /tmp/sketch7210316334309249705.cpp /^void digitalCommand(YunClient client) {$/;" kind:function line:82 signature:(YunClient client) returntype:void -analogCommand /tmp/sketch7210316334309249705.cpp /^void analogCommand(YunClient client) {$/;" kind:function line:110 signature:(YunClient client) returntype:void -modeCommand /tmp/sketch7210316334309249705.cpp /^void modeCommand(YunClient client) {$/;" kind:function line:151 signature:(YunClient client) returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListTemplates.txt b/ctags/test_data/TestCTagsParserShouldListTemplates.txt deleted file mode 100644 index 3281e49c..00000000 --- a/ctags/test_data/TestCTagsParserShouldListTemplates.txt +++ /dev/null @@ -1,3 +0,0 @@ -minimum /tmp/sketch8398023134925534708.cpp /^template T minimum (T a, T b) $/;" kind:function line:2 signature:(T a, T b) returntype:templateT -setup /tmp/sketch8398023134925534708.cpp /^void setup () $/;" kind:function line:9 signature:() returntype:void -loop /tmp/sketch8398023134925534708.cpp /^void loop () { }$/;" kind:function line:13 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListTemplates2.txt b/ctags/test_data/TestCTagsParserShouldListTemplates2.txt deleted file mode 100644 index c08ddba0..00000000 --- a/ctags/test_data/TestCTagsParserShouldListTemplates2.txt +++ /dev/null @@ -1,4 +0,0 @@ -setup /tmp/sketch463160524247569568.cpp /^void setup() {$/;" kind:function line:1 signature:() returntype:void -loop /tmp/sketch463160524247569568.cpp /^void loop() {$/;" kind:function line:6 signature:() returntype:void -SRAM_writeAnything /tmp/sketch463160524247569568.cpp /^template int SRAM_writeAnything(int ee, const T& value)$/;" kind:function line:11 signature:(int ee, const T& value) returntype:template int -SRAM_readAnything /tmp/sketch463160524247569568.cpp /^template int SRAM_readAnything(int ee, T& value)$/;" kind:function line:21 signature:(int ee, T& value) returntype:template int diff --git a/ctags/test_data/TestCTagsParserStatic.txt b/ctags/test_data/TestCTagsParserStatic.txt deleted file mode 100644 index ec1bdb14..00000000 --- a/ctags/test_data/TestCTagsParserStatic.txt +++ /dev/null @@ -1,3 +0,0 @@ -setup /tmp/test542833488/preproc/ctags_target.cpp /^void setup(){}$/;" kind:function line:2 signature:() returntype:void -loop /tmp/test542833488/preproc/ctags_target.cpp /^void loop(){}$/;" kind:function line:3 signature:() returntype:void -doStuff /tmp/test542833488/preproc/ctags_target.cpp /^static void doStuff() {}$/;" kind:function line:4 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserStructWithFunctions.txt b/ctags/test_data/TestCTagsParserStructWithFunctions.txt deleted file mode 100644 index 5519aec5..00000000 --- a/ctags/test_data/TestCTagsParserStructWithFunctions.txt +++ /dev/null @@ -1,8 +0,0 @@ -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^struct sensorData {$/;" kind:struct line:2 -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^ sensorData(int iStatus, float iTemp, float iMinTemp) : status(iStatus), temp(iTemp), minTemp(iMinTemp) {}$/;" kind:function line:3 struct:sensorData signature:(int iStatus, float iTemp, float iMinTemp) -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^ sensorData() : status(-1), temp(1023.0), minTemp(1023.0) {}$/;" kind:function line:4 struct:sensorData signature:() -sensors /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensors[2];$/;" kind:variable line:10 -sensor1 /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensor1; \/\/(-1,1023.0,1023.0);$/;" kind:variable line:12 -sensor2 /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensor2; \/\/(-1,1023.0,1023.0);$/;" kind:variable line:13 -setup /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:16 signature:() returntype:void -loop /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:22 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt b/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt deleted file mode 100644 index 42f3b5ca..00000000 --- a/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt +++ /dev/null @@ -1,4 +0,0 @@ -asdf /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^ void asdf() {}$/;" kind:function line:2 class:test signature:() returntype:void -setup /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void setup() {$/;" kind:function line:4 signature:() returntype:void -loop /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void loop() {}$/;" kind:function line:7 signature:() returntype:void -asdf /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void asdf() {}$/;" kind:function line:8 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt b/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt deleted file mode 100644 index 626b8ef0..00000000 --- a/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt +++ /dev/null @@ -1,77 +0,0 @@ -allowed_ch /tmp/apUNI8a/a7105.ino /^const uint8_t allowed_ch[] = {0x14, 0x1e, 0x28, 0x32, 0x3c, 0x46, 0x50, 0x5a, 0x64, 0x6e, 0x78, 0x82};$/;" kind:variable line:21 -no_allowed_channels /tmp/apUNI8a/a7105.ino /^int no_allowed_channels = 12;$/;" kind:variable line:22 -A7105_Setup /tmp/apUNI8a/a7105.ino /^void A7105_Setup() {$/;" kind:function line:26 signature:() returntype:void -A7105_Reset /tmp/apUNI8a/a7105.ino /^void A7105_Reset()$/;" kind:function line:43 signature:() returntype:void -A7105_calibrate_IF /tmp/apUNI8a/a7105.ino /^int A7105_calibrate_IF() {$/;"kind:function line:52 signature:() returntype:int -A7105_calibrate_VCB /tmp/apUNI8a/a7105.ino /^int A7105_calibrate_VCB(uint8_t channel) {$/;" kind:function line:87 signature:(uint8_t channel) returntype:int -A7105_SetPower /tmp/apUNI8a/a7105.ino /^void A7105_SetPower(int power)$/;" kind:function line:120 signature:(int power) returntype:void -A7105_Strobe /tmp/apUNI8a/a7105.ino /^void A7105_Strobe(enum A7105_State state);$/;" kind:prototype line:176 signature:(enum A7105_State state) returntype:void -A7105_Strobe /tmp/apUNI8a/a7105.ino /^void A7105_Strobe(enum A7105_State state)$/;" kind:function line:179 signature:(enum A7105_State state) returntype:void -A7105_WriteReg /tmp/apUNI8a/a7105.ino /^void A7105_WriteReg(uint8_t address, uint8_t data)$/;" kind:function line:190 signature:(uint8_t address, uint8_t data) returntype:void -A7105_ReadReg /tmp/apUNI8a/a7105.ino /^uint8_t A7105_ReadReg(uint8_t address)$/;" kind:function line:197 signature:(uint8_t address) returntype:uint8_t -A7105_WriteData /tmp/apUNI8a/a7105.ino /^void A7105_WriteData(uint8_t *dpbuffer, uint8_t len, uint8_t channel)$/;" kind:function line:211 signature:(uint8_t *dpbuffer, uint8_t len, uint8_t channel) returntype:void -A7105_ReadData /tmp/apUNI8a/a7105.ino /^void A7105_ReadData(uint8_t *dpbuffer, uint8_t len)$/;" kind:function line:229 signature:(uint8_t *dpbuffer, uint8_t len) returntype:void -A7105_WriteID /tmp/apUNI8a/a7105.ino /^void A7105_WriteID(unsigned long id)$/;" kind:function line:247 signature:(unsigned long id) returntype:void -A7105_ReadID /tmp/apUNI8a/a7105.ino /^void A7105_ReadID()$/;" kind:function line:258 signature:() returntype:void -k13 /tmp/apUNI8a/a7105.ino /^unsigned char k13;$/;" kind:variable line:272 -make_test_packet /tmp/apUNI8a/a7105.ino /^void make_test_packet(uint8_t testpacket[]) {$/;" kind:function line:275 signature:(uint8_t testpacket[]) returntype:void -printpacket /tmp/apUNI8a/a7105.ino /^void printpacket(uint8_t packet[]) {$/;" kind:function line:295 signature:(uint8_t packet[]) returntype:void -A7105_shoutchannel /tmp/apUNI8a/a7105.ino /^void A7105_shoutchannel() {$/;" kind:function line:308 signature:() returntype:void -A7105_oneShout /tmp/apUNI8a/a7105.ino /^int A7105_oneShout() {$/;" kind:function line:337 signature:() returntype:int -A7105_oneShoutRAM /tmp/apUNI8a/a7105.ino /^int A7105_oneShoutRAM(unsigned char xState, unsigned char xType) {$/;" kind:function line:361 signature:(unsigned char xState, unsigned char xType) returntype:int -eavesdrop /tmp/apUNI8a/a7105.ino /^void eavesdrop() {$/;" kind:function line:391 signature:() returntype:void -A7105_findchannel /tmp/apUNI8a/a7105.ino /^uint8_t A7105_findchannel() {$/;" kind:function line:442 signature:() returntype:uint8_t -A7105_sniffchannel /tmp/apUNI8a/a7105.ino /^int A7105_sniffchannel() {$/;"kind:function line:464 signature:() returntype:int -A7105_sniffchannel /tmp/apUNI8a/a7105.ino /^void A7105_sniffchannel(uint8_t _channel) {$/;" kind:function line:484 signature:(uint8_t _channel) returntype:void -A7105_scanchannels /tmp/apUNI8a/a7105.ino /^void A7105_scanchannels(const uint8_t channels[]) {$/;" kind:function line:498 signature:(const uint8_t channels[]) returntype:void -Channels /tmp/apUNI8a/hubsan.ino /^volatile int16_t Channels[12];$/;" kind:variable line:6 -initialize /tmp/apUNI8a/hubsan.ino /^static void initialize() {$/;" kind:function line:8 signature:() returntype:void -hubsan_init /tmp/apUNI8a/hubsan.ino /^int hubsan_init()$/;" kind:function line:22 signature:() returntype:int -update_crc /tmp/apUNI8a/hubsan.ino /^static void update_crc()$/;" kind:function line:80 signature:() returntype:void -recdState /tmp/apUNI8a/main.ino /^unsigned char recdState, recdType;$/;"kind:variable line:5 -recdType /tmp/apUNI8a/main.ino /^unsigned char recdState, recdType;$/;"kind:variable line:5 -retries /tmp/apUNI8a/main.ino /^unsigned char retries;$/;" kind:variable line:6 -bwMap /tmp/apUNI8a/main.ino /^const unsigned char bwMap[4 \/* new cycle green yellow red blue (green) *\/] = {2, 6, 4, 1};$/;" kind:variable line:27 -bwButton /tmp/apUNI8a/main.ino /^unsigned char bwButton, bwCycle;$/;" kind:variable line:28 -bwCycle /tmp/apUNI8a/main.ino /^unsigned char bwButton, bwCycle;$/;" kind:variable line:28 -checkBW /tmp/apUNI8a/main.ino /^void checkBW(void); \/* watch button increment bwCycle *\/$/;" kind:prototype line:29 signature:(void) returntype:void -ledState /tmp/apUNI8a/main.ino /^unsigned char ledState;$/;" kind:variable line:31 -mySwitches /tmp/apUNI8a/main.ino /^unsigned char mySwitches;$/;" kind:variable line:32 -BWMODE /tmp/apUNI8a/main.ino /^unsigned char BWMODE, BLINKMODE;$/;" kind:variable line:34 -BLINKMODE /tmp/apUNI8a/main.ino /^unsigned char BWMODE, BLINKMODE;$/;" kind:variable line:34 -lightFSM /tmp/apUNI8a/main.ino /^void lightFSM(void);$/;" kind:prototype line:36 signature:(void) returntype:void -blinkLEDs /tmp/apUNI8a/main.ino /^void blinkLEDs(void);$/;" kind:prototype line:37 signature:(void) returntype:void -touchTimer /tmp/apUNI8a/main.ino /^unsigned touchTimer, lastTouch;$/;" kind:variable line:38 -lastTouch /tmp/apUNI8a/main.ino /^unsigned touchTimer, lastTouch;$/;" kind:variable line:38 -lightTimer /tmp/apUNI8a/main.ino /^unsigned char lightTimer;$/;" kind:variable line:40 -lamp /tmp/apUNI8a/main.ino /^unsigned int lamp;$/;" kind:variable line:45 -loops /tmp/apUNI8a/main.ino /^unsigned long loops;$/;" kind:variable line:46 -recFlag /tmp/apUNI8a/main.ino /^unsigned char recFlag; \/\/ have "we" asked for a packet?$/;" kind:variable line:48 -needAck /tmp/apUNI8a/main.ino /^unsigned char needAck;$/;" kind:variable line:49 -fsmFSM /tmp/apUNI8a/main.ino /^void fsmFSM(void);$/;" kind:prototype line:51 signature:(void) returntype:void -printFlag /tmp/apUNI8a/main.ino /^unsigned int printFlag;$/;" kind:variable line:52 -fsmTimer /tmp/apUNI8a/main.ino /^unsigned long fsmTimer;$/;" kind:variable line:53 -startval /tmp/apUNI8a/main.ino /^uint8_t startval, command;$/;" kind:variable line:57 -command /tmp/apUNI8a/main.ino /^uint8_t startval, command;$/;" kind:variable line:57 -iCnt /tmp/apUNI8a/main.ino /^int iCnt;$/;" kind:variable line:58 -myMessage /tmp/apUNI8a/main.ino /^char myMessage[8];$/;" kind:variable line:60 -ackMessage /tmp/apUNI8a/main.ino /^char ackMessage[8];$/;" kind:variable line:61 -setup /tmp/apUNI8a/main.ino /^void setup() {$/;" kind:function line:63signature:() returntype:void -valid /tmp/apUNI8a/main.ino /^unsigned char valid;$/;" kind:variable line:114 -loop /tmp/apUNI8a/main.ino /^void loop() {$/;" kind:function line:116signature:() returntype:void -listeni /tmp/apUNI8a/main.ino /^void listeni()$/;" kind:function line:165signature:() returntype:void -kickIt /tmp/apUNI8a/main.ino /^void kickIt(unsigned char xType)$/;" kind:function line:172 signature:(unsigned char xType) returntype:void -lightFSM /tmp/apUNI8a/main.ino /^void lightFSM()$/;" kind:function line:181 signature:() returntype:void -touchFSM /tmp/apUNI8a/main.ino /^void touchFSM()$/;" kind:function line:188 signature:() returntype:void -tween /tmp/apUNI8a/main.ino /^unsigned char tween[4] = {3, 5, 7, 11};$/;" kind:variable line:206 -fsmFSM /tmp/apUNI8a/main.ino /^void fsmFSM()$/;" kind:function line:207signature:() returntype:void -doBW /tmp/apUNI8a/main.ino /^void doBW(void) {$/;" kind:function line:243signature:(void) returntype:void -checkBW /tmp/apUNI8a/main.ino /^void checkBW()$/;" kind:function line:249signature:() returntype:void -getSwitches /tmp/apUNI8a/main.ino /^unsigned char getSwitches()$/;" kind:function line:260 signature:() returntype:unsigned char -xxLamp /tmp/apUNI8a/main.ino /^unsigned char xxLamp;$/;" kind:variable line:292 -setLEDs /tmp/apUNI8a/main.ino /^void setLEDs(unsigned char xx)$/;" kind:function line:294 signature:(unsigned char xx) returntype:void -blinks /tmp/apUNI8a/main.ino /^const unsigned char blinks[8] = {0, 1, 0, 1, 0, 0, 1, 1};$/;" kind:variable line:311 -blinkLEDs /tmp/apUNI8a/main.ino /^void blinkLEDs()$/;" kind:function line:312 signature:() returntype:void -proto_state /tmp/apUNI8a/protocol.ino /^static uint8_t proto_state;$/;" kind:variable line:4 -bind_time /tmp/apUNI8a/protocol.ino /^static uint32_t bind_time;$/;"kind:variable line:5 -PROTOCOL_SetBindState /tmp/apUNI8a/protocol.ino /^void PROTOCOL_SetBindState(uint32_t msec)$/;" kind:function line:11 signature:(uint32_t msec) returntype:void diff --git a/ctags_runner.go b/ctags_runner.go deleted file mode 100644 index 44960f9a..00000000 --- a/ctags_runner.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/ctags" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type CTagsRunner struct{} - -func (s *CTagsRunner) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - ctagsTargetFilePath := ctx.CTagsTargetFile - logger := ctx.GetLogger() - - properties := buildProperties.Clone() - properties.Merge(buildProperties.SubTree(constants.BUILD_PROPERTIES_TOOLS_KEY).SubTree(constants.CTAGS)) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = ctagsTargetFilePath - - pattern := properties[constants.BUILD_PROPERTIES_PATTERN] - if pattern == constants.EMPTY_STRING { - return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, constants.CTAGS) - } - - commandLine := properties.ExpandPropsInString(pattern) - command, err := utils.PrepareCommand(commandLine, logger, "") - if err != nil { - return i18n.WrapError(err) - } - - sourceBytes, _, err := utils.ExecCommand(ctx, command, utils.Capture /* stdout */, utils.Ignore /* stderr */) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CTagsOutput = string(sourceBytes) - - parser := &ctags.CTagsParser{} - - ctx.CTagsOfPreprocessedSource = parser.Parse(ctx.CTagsOutput, ctx.Sketch.MainFile.Name) - parser.FixCLinkageTagsDeclarations(ctx.CTagsOfPreprocessedSource) - - protos, line := parser.GeneratePrototypes() - if line != -1 { - ctx.PrototypesLineWhereToInsert = line - } - ctx.Prototypes = protos - - return nil -} diff --git a/ctags_target_file_saver.go b/ctags_target_file_saver.go deleted file mode 100644 index 3c79b31f..00000000 --- a/ctags_target_file_saver.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" -) - -type CTagsTargetFileSaver struct { - Source *string - TargetFileName string -} - -func (s *CTagsTargetFileSaver) Run(ctx *types.Context) error { - source := *s.Source - - preprocPath := ctx.PreprocPath - err := utils.EnsureFolderExists(preprocPath) - if err != nil { - return i18n.WrapError(err) - } - - ctagsTargetFilePath := filepath.Join(preprocPath, s.TargetFileName) - err = utils.WriteFile(ctagsTargetFilePath, source) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CTagsTargetFile = ctagsTargetFilePath - - return nil -} diff --git a/dump_build_properties.go b/dump_build_properties.go deleted file mode 100644 index 36959161..00000000 --- a/dump_build_properties.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "sort" - - "github.com/arduino/arduino-builder/types" -) - -type DumpBuildProperties struct{} - -func (s *DumpBuildProperties) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - - keys := buildProperties.Keys() - sort.Strings(keys) - - for _, key := range keys { - fmt.Println(key + "=" + buildProperties[key]) - } - - return nil -} diff --git a/ensure_buildpath_exists.go b/ensure_buildpath_exists.go deleted file mode 100644 index 495b8d83..00000000 --- a/ensure_buildpath_exists.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type EnsureBuildPathExists struct{} - -func (s *EnsureBuildPathExists) Run(ctx *types.Context) error { - err := utils.EnsureFolderExists(ctx.BuildPath) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} diff --git a/fail_if_buildpath_equals_sketchpath.go b/fail_if_buildpath_equals_sketchpath.go deleted file mode 100644 index 4a3ac711..00000000 --- a/fail_if_buildpath_equals_sketchpath.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "path/filepath" -) - -type FailIfBuildPathEqualsSketchPath struct{} - -func (s *FailIfBuildPathEqualsSketchPath) Run(ctx *types.Context) error { - if ctx.BuildPath == "" || ctx.SketchLocation == "" { - return nil - } - - buildPath, err := filepath.Abs(ctx.BuildPath) - if err != nil { - return i18n.WrapError(err) - } - - sketchPath, err := filepath.Abs(ctx.SketchLocation) - if err != nil { - return i18n.WrapError(err) - } - sketchPath = filepath.Dir(sketchPath) - - if buildPath == sketchPath { - return i18n.ErrorfWithLogger(ctx.GetLogger(), constants.MSG_SKETCH_CANT_BE_IN_BUILDPATH) - } - - return nil -} diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go deleted file mode 100644 index 2620560c..00000000 --- a/fail_if_imported_library_is_wrong.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "os" - "path/filepath" -) - -type FailIfImportedLibraryIsWrong struct{} - -func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { - if len(ctx.ImportedLibraries) == 0 { - return nil - } - - logger := ctx.GetLogger() - - for _, library := range ctx.ImportedLibraries { - if !library.IsLegacy { - if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_ARCH)); err == nil && stat.IsDir() { - return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) - } - for _, propName := range LIBRARY_MANDATORY_PROPERTIES { - if _, ok := library.Properties[propName]; !ok { - return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.Folder) - } - } - if library.Layout == types.LIBRARY_RECURSIVE { - if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY)); err == nil && stat.IsDir() { - return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) - } - } - } - } - - return nil -} diff --git a/filter_sketch_source.go b/filter_sketch_source.go deleted file mode 100644 index a6abd730..00000000 --- a/filter_sketch_source.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "bufio" - "strconv" - "strings" - - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type FilterSketchSource struct { - Source *string - RemoveLineMarkers bool -} - -func (s *FilterSketchSource) Run(ctx *types.Context) error { - fileNames := []string{ctx.Sketch.MainFile.Name} - for _, file := range ctx.Sketch.OtherSketchFiles { - fileNames = append(fileNames, file.Name) - } - - inSketch := false - filtered := "" - - scanner := bufio.NewScanner(strings.NewReader(*s.Source)) - for scanner.Scan() { - line := scanner.Text() - filename := parseLineMarker(line) - if filename != "" { - inSketch = utils.SliceContains(fileNames, filename) - if inSketch && s.RemoveLineMarkers { - continue - } - } - - if inSketch { - filtered += line + "\n" - } - } - - *s.Source = filtered - return nil -} - -// Parses the given line as a gcc line marker and returns the contained -// filename. -func parseLineMarker(line string) string { - // A line marker contains the line number and filename and looks like: - // # 123 /path/to/file.cpp - // It can be followed by zero or more flag number that indicate the - // preprocessor state and can be ignored. - // For exact details on this format, see: - // https://github.com/gcc-mirror/gcc/blob/edd716b6b1caa1a5cb320a8cd7f626f30198e098/gcc/c-family/c-ppoutput.c#L413-L415 - - split := strings.SplitN(line, " ", 3) - if len(split) < 3 || len(split[0]) == 0 || split[0][0] != '#' { - return "" - } - - _, err := strconv.Atoi(split[1]) - if err != nil { - return "" - } - - // If we get here, we found a # followed by a line number, so - // assume this is a line marker and see if the rest of the line - // starts with a string containing the filename - str, rest, ok := utils.ParseCppString(split[2]) - - if ok && (rest == "" || rest[0] == ' ') { - return str - } - return "" -} diff --git a/gcc_preproc_runner.go b/gcc_preproc_runner.go deleted file mode 100644 index 3c801f89..00000000 --- a/gcc_preproc_runner.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os/exec" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -func GCCPreprocRunner(ctx *types.Context, sourceFilePath string, targetFilePath string, includes []string) error { - cmd, err := prepareGCCPreprocRecipeProperties(ctx, sourceFilePath, targetFilePath, includes) - if err != nil { - return i18n.WrapError(err) - } - - _, _, err = utils.ExecCommand(ctx, cmd /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func GCCPreprocRunnerForDiscoveringIncludes(ctx *types.Context, sourceFilePath string, targetFilePath string, includes []string) ([]byte, error) { - cmd, err := prepareGCCPreprocRecipeProperties(ctx, sourceFilePath, targetFilePath, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - - _, stderr, err := utils.ExecCommand(ctx, cmd /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Capture) - if err != nil { - return stderr, i18n.WrapError(err) - } - - return stderr, nil -} - -func prepareGCCPreprocRecipeProperties(ctx *types.Context, sourceFilePath string, targetFilePath string, includes []string) (*exec.Cmd, error) { - properties := ctx.BuildProperties.Clone() - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = sourceFilePath - properties[constants.BUILD_PROPERTIES_PREPROCESSED_FILE_PATH] = targetFilePath - - includes = utils.Map(includes, utils.WrapWithHyphenI) - properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includes, constants.SPACE) - - if properties[constants.RECIPE_PREPROC_MACROS] == constants.EMPTY_STRING { - //generate PREPROC_MACROS from RECIPE_CPP_PATTERN - properties[constants.RECIPE_PREPROC_MACROS] = GeneratePreprocPatternFromCompile(properties[constants.RECIPE_CPP_PATTERN]) - } - - cmd, err := builder_utils.PrepareCommandForRecipe(ctx, properties, constants.RECIPE_PREPROC_MACROS, true) - if err != nil { - return nil, i18n.WrapError(err) - } - - // Remove -MMD argument if present. Leaving it will make gcc try - // to create a /dev/null.d dependency file, which won't work. - cmd.Args = utils.Filter(cmd.Args, func(a string) bool { return a != "-MMD" }) - - return cmd, nil -} - -func GeneratePreprocPatternFromCompile(compilePattern string) string { - // add {preproc.macros.flags} - // replace "{object_file}" with "{preprocessed_file_path}" - returnString := compilePattern - returnString = strings.Replace(returnString, "{compiler.cpp.flags}", "{compiler.cpp.flags} {preproc.macros.flags}", 1) - returnString = strings.Replace(returnString, "{object_file}", "{preprocessed_file_path}", 1) - return returnString -} diff --git a/generate_buildpath_if_missing.go b/generate_buildpath_if_missing.go deleted file mode 100644 index 7b11ae13..00000000 --- a/generate_buildpath_if_missing.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" - "strings" -) - -type GenerateBuildPathIfMissing struct{} - -func (s *GenerateBuildPathIfMissing) Run(ctx *types.Context) error { - if ctx.BuildPath != "" { - return nil - } - - md5sum := utils.MD5Sum([]byte(ctx.SketchLocation)) - - buildPath := filepath.Join(os.TempDir(), "arduino-sketch-"+strings.ToUpper(md5sum)) - _, err := os.Stat(buildPath) - if err != nil && !os.IsNotExist(err) { - return i18n.WrapError(err) - } - - if ctx.DebugLevel > 5 { - logger := ctx.GetLogger() - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_SETTING_BUILD_PATH, buildPath) - } - - ctx.BuildPath = buildPath - - return nil -} diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..7e464b40 --- /dev/null +++ b/go.mod @@ -0,0 +1,12 @@ +module github.com/arduino/arduino-builder + +go 1.12 + +require ( + github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366 + github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 + github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 + github.com/go-errors/errors v1.0.1 + github.com/juju/errors v0.0.0-20190207033735-e65537c515d7 // indirect + github.com/sirupsen/logrus v1.4.2 +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..074ef4a0 --- /dev/null +++ b/go.sum @@ -0,0 +1,165 @@ +bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366 h1:W7aS1f8JsCCLvHzj4UiSzYIdbRnIK1Hu/fHXKmvbaCI= +github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366/go.mod h1:XFDg7LwMgVGiJAkVLQ0AM3Gei5LjfuDIKwOcrU9rnsI= +github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c h1:agh2JT96G8egU7FEb13L4dq3fnCN7lxXhJ86t69+W7s= +github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c/go.mod h1:HK7SpkEax/3P+0w78iRQx1sz1vCDYYw9RXwHjQTB5i8= +github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 h1:S0NpDSqjlkNA510vmRCP5Cq9mPgu3rWDSdeN4SI1Mwc= +github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1/go.mod h1:OGL+FS3aTrS01YsBAJJhkGuxtEGsFRSgZYo8b3vefdc= +github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 h1:aWZoiBr2fCXtZzY4e/TOyQHEFyFpsF9eph7rEDZRv0Y= +github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3/go.mod h1:kiSuHm7yz3chiy8rb2MphC7ECn3MlkQFAIe4SXmQg6o= +github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b h1:9hDi4F2st6dbLC3y4i02zFT5quS4X6iioWifGlVwfy4= +github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b/go.mod h1:uwGy5PpN4lqW97FiLnbcx+xx8jly5YuPMJWfVwwjJiQ= +github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b h1:3PjgYG5gVPA7cipp7vIR2lF96KkEJIFBJ+ANnuv6J20= +github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b/go.mod h1:iIPnclBMYm1g32Q5kXoqng4jLhMStReIP7ZxaoUC2y8= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cmaglie/pb v1.0.27 h1:ynGj8vBXR+dtj4B7Q/W/qGt31771Ux5iFfRQBnwdQiA= +github.com/cmaglie/pb v1.0.27/go.mod h1:GilkKZMXYjBA4NxItWFfO+lwkp59PLHQ+IOW/b/kmZI= +github.com/codeclysm/cc v1.2.2 h1:1ChS4EvWTjw6bH2sd6QiMcmih0itVVrWdh9MmOliX/I= +github.com/codeclysm/cc v1.2.2/go.mod h1:XtW4ArCNgQwFphcRGG9+sPX5WM1J6/u0gMy5ZdV3obA= +github.com/codeclysm/extract v2.2.0+incompatible h1:q3wyckoA30bhUSiwdQezMqVhwd8+WGE64/GL//LtUhI= +github.com/codeclysm/extract v2.2.0+incompatible/go.mod h1:2nhFMPHiU9At61hz+12bfrlpXSUrOnK+wR+KlGO4Uks= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/goselect v0.0.0-20180328191401-176c667f75aa h1:tIUhmTixVssck4oJ9jKcqaNOF8ua4YxN3UHP0ymBHuQ= +github.com/creack/goselect v0.0.0-20180328191401-176c667f75aa/go.mod h1:gHrIcH/9UZDn2qgeTUeW5K9eZsVYCH6/60J/FHysWyE= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fluxio/iohelpers v0.0.0-20160419043813-3a4dd67a94d2 h1:C6sOwknxwWfLBEQ91zhmptlfxf7pVEs5s6wOnDxNpS4= +github.com/fluxio/iohelpers v0.0.0-20160419043813-3a4dd67a94d2/go.mod h1:c7sGIpDbBo0JZZ1tKyC1p5smWf8QcUjK4bFtZjHAecg= +github.com/fluxio/multierror v0.0.0-20160419044231-9c68d39025e5 h1:R8jFW6G/bjoXjWPFrEfw9G5YQDlYhwV4AC+Eonu6wmk= +github.com/fluxio/multierror v0.0.0-20160419044231-9c68d39025e5/go.mod h1:BEUDl7FG1cc76sM0J0x8dqr6RhiL4uqvk6oFkwuNyuM= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gosuri/uitable v0.0.0-20160404203958-36ee7e946282 h1:KFqmdzEPbU7Uck2tn50t+HQXZNVkxe8M9qRb/ZoSHaE= +github.com/gosuri/uitable v0.0.0-20160404203958-36ee7e946282/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= +github.com/h2non/filetype v1.0.8 h1:le8gpf+FQA0/DlDABbtisA1KiTS0Xi+YSC/E8yY3Y14= +github.com/h2non/filetype v1.0.8/go.mod h1:isekKqOuhMj+s/7r3rIeTErIRy4Rub5uBWHfvMusLMU= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/errors v0.0.0-20190207033735-e65537c515d7 h1:dMIPRDg6gi7CUp0Kj2+HxqJ5kTr1iAdzsXYIrLCNSmU= +github.com/juju/errors v0.0.0-20190207033735-e65537c515d7/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8 h1:UUHMLvzt/31azWTN/ifGWef4WUqvXk0iRqdhdy/2uzI= +github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= +github.com/juju/testing v0.0.0-20190429233213-dfc56b8c09fc h1:5xUWujf6ES9tEpFHFzI34vcHm8U07lGjxAuJML3qwqM= +github.com/juju/testing v0.0.0-20190429233213-dfc56b8c09fc/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-runewidth v0.0.2 h1:UnlwIPBGaTZfPQ6T1IGzPI0EkYAQmT9fAEJ/poFC63o= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/miekg/dns v1.0.5 h1:MQBGf2JEJDu0rg9WOpQZzeO+zW8UKwgkvP3R1dUU1Yw= +github.com/miekg/dns v1.0.5/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/oleksandr/bonjour v0.0.0-20160508152359-5dcf00d8b228 h1:Cvfd2dOlXIPTeEkOT/h8PyK4phBngOM4at9/jlgy7d4= +github.com/oleksandr/bonjour v0.0.0-20160508152359-5dcf00d8b228/go.mod h1:MGuVJ1+5TX1SCoO2Sx0eAnjpdRytYla2uC1YIZfkC9c= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583 h1:ogHi8YLNeIxABOaH6UgtbwkODheuAK+ErP8gWXYQVj0= +github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583/go.mod h1:sFPiU/UgDcsQVu3vkqpZLCXWFwUoQRpHGu9ATihPAl0= +github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk= +github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +go.bug.st/cleanup v1.0.0 h1:XVj1HZxkBXeq3gMT7ijWUpHyIC1j8XAoNSyQ06CskgA= +go.bug.st/cleanup v1.0.0/go.mod h1:EqVmTg2IBk4znLbPD28xne3abjsJftMdqqJEjhn70bk= +go.bug.st/downloader v1.1.0 h1:LipC9rqRCe8kwa+ah3ZDfCqneVaf34cB/TKjXZiZt54= +go.bug.st/downloader v1.1.0/go.mod h1:l+RPbNbrTB+MoAIp8nrZsP22nRPDy26XJZQqmm4gNT4= +go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852 h1:NimumSJtLf9QOiV8/LKi0IelbgbaSUGK/NTfKXc/gU8= +go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852/go.mod h1:WWVH9tve4kargu9fsX18qW/UHxE37QcgPXRtE/xSvxY= +go.bug.st/serial.v1 v0.0.0-20180827123349-5f7892a7bb45 h1:mACY1anK6HNCZtm/DK2Rf2ZPHggVqeB0+7rY9Gl6wyI= +go.bug.st/serial.v1 v0.0.0-20180827123349-5f7892a7bb45/go.mod h1:dRSl/CVCTf56CkXgJMDOdSwNfo2g1orOGE/gBGdvjZw= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d h1:XB2jc5XQ9uhizGTS2vWcN01bc4dI6z3C4KY5MQm8SS8= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/gohasissues/go_has_issues.go b/gohasissues/go_has_issues.go deleted file mode 100644 index 60c422ac..00000000 --- a/gohasissues/go_has_issues.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package gohasissues - -import ( - "io/ioutil" - "os" - "path/filepath" - "sort" - "strconv" - "strings" -) - -func Walk(root string, walkFn filepath.WalkFunc) error { - info, err := os.Stat(root) - if err != nil { - return walkFn(root, nil, err) - } - return walk(root, info, walkFn) -} - -func walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - err := walkFn(path, info, nil) - if err != nil { - if info.IsDir() && err == filepath.SkipDir { - return nil - } - return err - } - - if !info.IsDir() { - return nil - } - - names, err := readDirNames(path) - if err != nil { - return walkFn(path, info, err) - } - - for _, name := range names { - filename := filepath.Join(path, name) - fileInfo, err := os.Stat(filename) - if err != nil { - if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { - return err - } - } else { - err = walk(filename, fileInfo, walkFn) - if err != nil { - if !fileInfo.IsDir() || err != filepath.SkipDir { - return err - } - } - } - } - return nil -} - -// readDirNames reads the directory named by dirname and returns -// a sorted list of directory entries. -func readDirNames(dirname string) ([]string, error) { - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - names, err := f.Readdirnames(-1) - f.Close() - if err != nil { - return nil, err - } - sort.Strings(names) - return names, nil -} - -func ReadDir(dirname string) ([]os.FileInfo, error) { - infos, err := ioutil.ReadDir(dirname) - if err != nil { - return nil, err - } - - for idx, info := range infos { - info, err := resolveSymlink(dirname, info) - if err != nil { - // unresolvable symlinks should be skipped silently - continue - } - infos[idx] = info - } - - return infos, nil -} - -func resolveSymlink(parentFolder string, info os.FileInfo) (os.FileInfo, error) { - if !isSymlink(info) { - return info, nil - } - return os.Stat(filepath.Join(parentFolder, info.Name())) -} - -func isSymlink(info os.FileInfo) bool { - return info.Mode()&os.ModeSymlink != 0 -} - -func Unquote(s string) (string, error) { - if stringStartsEndsWith(s, "'") { - s = s[1 : len(s)-1] - } - - if !stringStartsEndsWith(s, "\"") { - return s, nil - } - - return strconv.Unquote(s) -} - -func stringStartsEndsWith(s string, c string) bool { - return strings.HasPrefix(s, c) && strings.HasSuffix(s, c) -} diff --git a/grpc/proto/builder.pb.go b/grpc/proto/builder.pb.go deleted file mode 100644 index 4690c81c..00000000 --- a/grpc/proto/builder.pb.go +++ /dev/null @@ -1,396 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: builder.proto - -/* -Package proto is a generated protocol buffer package. - -It is generated from these files: - builder.proto - -It has these top-level messages: - BuildParams - VerboseParams - Response -*/ -package proto - -import proto1 "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto1.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto1.ProtoPackageIsVersion2 // please upgrade the proto package - -type BuildParams struct { - HardwareFolders string `protobuf:"bytes,1,opt,name=hardwareFolders" json:"hardwareFolders,omitempty"` - ToolsFolders string `protobuf:"bytes,2,opt,name=toolsFolders" json:"toolsFolders,omitempty"` - BuiltInLibrariesFolders string `protobuf:"bytes,3,opt,name=builtInLibrariesFolders" json:"builtInLibrariesFolders,omitempty"` - OtherLibrariesFolders string `protobuf:"bytes,4,opt,name=otherLibrariesFolders" json:"otherLibrariesFolders,omitempty"` - SketchLocation string `protobuf:"bytes,5,opt,name=sketchLocation" json:"sketchLocation,omitempty"` - FQBN string `protobuf:"bytes,6,opt,name=fQBN" json:"fQBN,omitempty"` - ArduinoAPIVersion string `protobuf:"bytes,7,opt,name=arduinoAPIVersion" json:"arduinoAPIVersion,omitempty"` - CustomBuildProperties string `protobuf:"bytes,8,opt,name=customBuildProperties" json:"customBuildProperties,omitempty"` - BuildCachePath string `protobuf:"bytes,9,opt,name=buildCachePath" json:"buildCachePath,omitempty"` - BuildPath string `protobuf:"bytes,10,opt,name=buildPath" json:"buildPath,omitempty"` - WarningsLevel string `protobuf:"bytes,11,opt,name=warningsLevel" json:"warningsLevel,omitempty"` - CodeCompleteAt string `protobuf:"bytes,12,opt,name=codeCompleteAt" json:"codeCompleteAt,omitempty"` - Verbose bool `protobuf:"varint,13,opt,name=verbose" json:"verbose,omitempty"` -} - -func (m *BuildParams) Reset() { *m = BuildParams{} } -func (m *BuildParams) String() string { return proto1.CompactTextString(m) } -func (*BuildParams) ProtoMessage() {} -func (*BuildParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *BuildParams) GetHardwareFolders() string { - if m != nil { - return m.HardwareFolders - } - return "" -} - -func (m *BuildParams) GetToolsFolders() string { - if m != nil { - return m.ToolsFolders - } - return "" -} - -func (m *BuildParams) GetBuiltInLibrariesFolders() string { - if m != nil { - return m.BuiltInLibrariesFolders - } - return "" -} - -func (m *BuildParams) GetOtherLibrariesFolders() string { - if m != nil { - return m.OtherLibrariesFolders - } - return "" -} - -func (m *BuildParams) GetSketchLocation() string { - if m != nil { - return m.SketchLocation - } - return "" -} - -func (m *BuildParams) GetFQBN() string { - if m != nil { - return m.FQBN - } - return "" -} - -func (m *BuildParams) GetArduinoAPIVersion() string { - if m != nil { - return m.ArduinoAPIVersion - } - return "" -} - -func (m *BuildParams) GetCustomBuildProperties() string { - if m != nil { - return m.CustomBuildProperties - } - return "" -} - -func (m *BuildParams) GetBuildCachePath() string { - if m != nil { - return m.BuildCachePath - } - return "" -} - -func (m *BuildParams) GetBuildPath() string { - if m != nil { - return m.BuildPath - } - return "" -} - -func (m *BuildParams) GetWarningsLevel() string { - if m != nil { - return m.WarningsLevel - } - return "" -} - -func (m *BuildParams) GetCodeCompleteAt() string { - if m != nil { - return m.CodeCompleteAt - } - return "" -} - -func (m *BuildParams) GetVerbose() bool { - if m != nil { - return m.Verbose - } - return false -} - -type VerboseParams struct { - Verbose bool `protobuf:"varint,1,opt,name=verbose" json:"verbose,omitempty"` -} - -func (m *VerboseParams) Reset() { *m = VerboseParams{} } -func (m *VerboseParams) String() string { return proto1.CompactTextString(m) } -func (*VerboseParams) ProtoMessage() {} -func (*VerboseParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *VerboseParams) GetVerbose() bool { - if m != nil { - return m.Verbose - } - return false -} - -type Response struct { - Line string `protobuf:"bytes,1,opt,name=line" json:"line,omitempty"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto1.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *Response) GetLine() string { - if m != nil { - return m.Line - } - return "" -} - -func init() { - proto1.RegisterType((*BuildParams)(nil), "proto.BuildParams") - proto1.RegisterType((*VerboseParams)(nil), "proto.VerboseParams") - proto1.RegisterType((*Response)(nil), "proto.Response") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Builder service - -type BuilderClient interface { - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - Build(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (Builder_BuildClient, error) - Autocomplete(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (*Response, error) - DropCache(ctx context.Context, in *VerboseParams, opts ...grpc.CallOption) (*Response, error) -} - -type builderClient struct { - cc *grpc.ClientConn -} - -func NewBuilderClient(cc *grpc.ClientConn) BuilderClient { - return &builderClient{cc} -} - -func (c *builderClient) Build(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (Builder_BuildClient, error) { - stream, err := grpc.NewClientStream(ctx, &_Builder_serviceDesc.Streams[0], c.cc, "/proto.Builder/Build", opts...) - if err != nil { - return nil, err - } - x := &builderBuildClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Builder_BuildClient interface { - Recv() (*Response, error) - grpc.ClientStream -} - -type builderBuildClient struct { - grpc.ClientStream -} - -func (x *builderBuildClient) Recv() (*Response, error) { - m := new(Response) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *builderClient) Autocomplete(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (*Response, error) { - out := new(Response) - err := grpc.Invoke(ctx, "/proto.Builder/Autocomplete", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *builderClient) DropCache(ctx context.Context, in *VerboseParams, opts ...grpc.CallOption) (*Response, error) { - out := new(Response) - err := grpc.Invoke(ctx, "/proto.Builder/DropCache", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Builder service - -type BuilderServer interface { - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - Build(*BuildParams, Builder_BuildServer) error - Autocomplete(context.Context, *BuildParams) (*Response, error) - DropCache(context.Context, *VerboseParams) (*Response, error) -} - -func RegisterBuilderServer(s *grpc.Server, srv BuilderServer) { - s.RegisterService(&_Builder_serviceDesc, srv) -} - -func _Builder_Build_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(BuildParams) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(BuilderServer).Build(m, &builderBuildServer{stream}) -} - -type Builder_BuildServer interface { - Send(*Response) error - grpc.ServerStream -} - -type builderBuildServer struct { - grpc.ServerStream -} - -func (x *builderBuildServer) Send(m *Response) error { - return x.ServerStream.SendMsg(m) -} - -func _Builder_Autocomplete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(BuildParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BuilderServer).Autocomplete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/proto.Builder/Autocomplete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BuilderServer).Autocomplete(ctx, req.(*BuildParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Builder_DropCache_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerboseParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BuilderServer).DropCache(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/proto.Builder/DropCache", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BuilderServer).DropCache(ctx, req.(*VerboseParams)) - } - return interceptor(ctx, in, info, handler) -} - -var _Builder_serviceDesc = grpc.ServiceDesc{ - ServiceName: "proto.Builder", - HandlerType: (*BuilderServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Autocomplete", - Handler: _Builder_Autocomplete_Handler, - }, - { - MethodName: "DropCache", - Handler: _Builder_DropCache_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Build", - Handler: _Builder_Build_Handler, - ServerStreams: true, - }, - }, - Metadata: "builder.proto", -} - -func init() { proto1.RegisterFile("builder.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 420 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0x6f, 0x6b, 0x13, 0x41, - 0x10, 0xc6, 0x3d, 0x4d, 0x9a, 0x64, 0x9a, 0x58, 0x1c, 0x14, 0x17, 0x11, 0x29, 0xa1, 0x48, 0x04, - 0x09, 0x45, 0x2b, 0xf8, 0x36, 0x57, 0x11, 0x0a, 0x41, 0xce, 0xbc, 0xe8, 0xfb, 0xbd, 0xcd, 0xe8, - 0x2d, 0x5e, 0x6e, 0x8e, 0xdd, 0x4d, 0xfb, 0x59, 0xfc, 0x06, 0x7e, 0x4c, 0xd9, 0x3f, 0xd1, 0x5e, - 0x13, 0xc1, 0x57, 0x99, 0x3c, 0xcf, 0x6f, 0x6e, 0x9f, 0xdb, 0x99, 0x83, 0x49, 0xb9, 0xd5, 0xf5, - 0x9a, 0xcc, 0xbc, 0x35, 0xec, 0x18, 0xfb, 0xe1, 0x67, 0xfa, 0xb3, 0x07, 0xc7, 0xb9, 0x37, 0x0a, - 0x69, 0xe4, 0xc6, 0xe2, 0x0c, 0x4e, 0x2a, 0x69, 0xd6, 0xb7, 0xd2, 0xd0, 0x67, 0xf6, 0xb8, 0x15, - 0xd9, 0x69, 0x36, 0x1b, 0xad, 0xee, 0xcb, 0x38, 0x85, 0xb1, 0x63, 0xae, 0xed, 0x0e, 0x7b, 0x18, - 0xb0, 0x8e, 0x86, 0x1f, 0xe1, 0xb9, 0x3f, 0xd5, 0x5d, 0x35, 0x4b, 0x5d, 0x1a, 0x69, 0x34, 0xfd, - 0xc1, 0x1f, 0x05, 0xfc, 0x5f, 0x36, 0x5e, 0xc0, 0x33, 0x76, 0x15, 0x99, 0xbd, 0xbe, 0x5e, 0xe8, - 0x3b, 0x6c, 0xe2, 0x6b, 0x78, 0x6c, 0x7f, 0x90, 0x53, 0xd5, 0x92, 0x95, 0x74, 0x9a, 0x1b, 0xd1, - 0x0f, 0xf8, 0x3d, 0x15, 0x11, 0x7a, 0xdf, 0xbe, 0xe6, 0x5f, 0xc4, 0x51, 0x70, 0x43, 0x8d, 0x6f, - 0xe1, 0x89, 0x34, 0xeb, 0xad, 0x6e, 0x78, 0x51, 0x5c, 0x5d, 0x93, 0xb1, 0xbe, 0x7d, 0x10, 0x80, - 0x7d, 0xc3, 0xe7, 0x53, 0x5b, 0xeb, 0x78, 0x13, 0x2f, 0xcf, 0x70, 0x4b, 0xc6, 0x69, 0xb2, 0x62, - 0x18, 0xf3, 0x1d, 0x34, 0x7d, 0xbe, 0x30, 0x85, 0x4b, 0xa9, 0x2a, 0x2a, 0xa4, 0xab, 0xc4, 0x28, - 0xe6, 0xeb, 0xaa, 0xf8, 0x12, 0x46, 0x65, 0x1c, 0x8a, 0xab, 0x04, 0x04, 0xe4, 0xaf, 0x80, 0x67, - 0x30, 0xb9, 0x95, 0xa6, 0xd1, 0xcd, 0x77, 0xbb, 0xa4, 0x1b, 0xaa, 0xc5, 0x71, 0x20, 0xba, 0xa2, - 0x3f, 0x4b, 0xf1, 0x9a, 0x2e, 0x79, 0xd3, 0xd6, 0xe4, 0x68, 0xe1, 0xc4, 0x38, 0x9e, 0xd5, 0x55, - 0x51, 0xc0, 0xe0, 0x86, 0x4c, 0xc9, 0x96, 0xc4, 0xe4, 0x34, 0x9b, 0x0d, 0x57, 0xbb, 0xbf, 0xd3, - 0x37, 0x30, 0xb9, 0x8e, 0x65, 0x5a, 0x8e, 0x3b, 0x68, 0xd6, 0x45, 0x5f, 0xc1, 0x70, 0x45, 0xb6, - 0xe5, 0xc6, 0x92, 0xbf, 0xdc, 0x5a, 0x37, 0x94, 0xf6, 0x26, 0xd4, 0xef, 0x7e, 0x65, 0x30, 0xc8, - 0xe3, 0xfe, 0xe1, 0x39, 0xf4, 0x43, 0x89, 0x18, 0x57, 0x71, 0x7e, 0x67, 0xff, 0x5e, 0x9c, 0x24, - 0x6d, 0xf7, 0xb4, 0xe9, 0x83, 0xf3, 0x0c, 0x3f, 0xc0, 0x78, 0xb1, 0x75, 0xac, 0x52, 0xe8, 0xff, - 0x6c, 0xc4, 0x0b, 0x18, 0x7d, 0x32, 0xdc, 0x86, 0x6b, 0xc5, 0xa7, 0xc9, 0xef, 0xbc, 0xd1, 0x81, - 0xae, 0xfc, 0x0c, 0x50, 0xa9, 0x79, 0x9a, 0xf8, 0x3c, 0x7d, 0x34, 0xf9, 0x38, 0xa5, 0x2f, 0x3c, - 0x5e, 0x64, 0xe5, 0x51, 0xe8, 0x7b, 0xff, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x39, 0x66, 0x51, - 0x56, 0x03, 0x00, 0x00, -} diff --git a/grpc/proto/builder.proto b/grpc/proto/builder.proto deleted file mode 100644 index 9b310284..00000000 --- a/grpc/proto/builder.proto +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// compile me with: protoc -I proto/ proto/builder.proto --go_out=plugins=grpc:proto - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "cc.arduino.builder"; -option java_outer_classname = "BuilderProto"; - -package proto; - -// Interface exported by the server. -service Builder { - - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - rpc Build(BuildParams) returns (stream Response) {} - - rpc Autocomplete(BuildParams) returns (Response) {} - - rpc DropCache(VerboseParams) returns (Response) {} -} - -message BuildParams { - string hardwareFolders = 1; - string toolsFolders = 2; - string builtInLibrariesFolders = 3; - string otherLibrariesFolders = 4; - string sketchLocation = 5; - string fQBN = 6; - string arduinoAPIVersion = 7; - string customBuildProperties = 8; - string buildCachePath = 9; - string buildPath = 10; - string warningsLevel = 11; - string codeCompleteAt = 12; - bool verbose = 13; -} - -message VerboseParams { - bool verbose = 1; -} - -message Response { - string line = 1; -} diff --git a/grpc/rpc.go b/grpc/rpc.go deleted file mode 100644 index 55cd78ff..00000000 --- a/grpc/rpc.go +++ /dev/null @@ -1,224 +0,0 @@ -package jsonrpc - -import ( - "fmt" - "io" - "log" - "net" - "os" - "strings" - - builder "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/fsnotify/fsnotify" - "golang.org/x/net/context" - "google.golang.org/grpc" - - pb "github.com/arduino/arduino-builder/grpc/proto" -) - -type StreamLogger struct { - stream pb.Builder_BuildServer -} - -func (s StreamLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - s.stream.Send(&pb.Response{Line: fmt.Sprintf(format, a...)}) -} - -func (s StreamLogger) UnformattedFprintln(w io.Writer, str string) { - s.stream.Send(&pb.Response{Line: str}) -} - -func (s StreamLogger) UnformattedWrite(w io.Writer, data []byte) { - s.stream.Send(&pb.Response{Line: string(data)}) -} - -func (s StreamLogger) Println(level string, format string, a ...interface{}) { - s.stream.Send(&pb.Response{Line: fmt.Sprintf(format, a...)}) -} - -func (s StreamLogger) Flush() string { - return "" -} - -func (s StreamLogger) Name() string { - return "streamlogger" -} - -type builderServer struct { - resp []*pb.Response - ctx *types.Context - watcher *fsnotify.Watcher -} - -func (s *builderServer) watch() { - folders := [][]string{s.ctx.HardwareFolders, s.ctx.ToolsFolders, s.ctx.BuiltInLibrariesFolders, s.ctx.OtherLibrariesFolders} - - for _, category := range folders { - for _, folder := range category { - if !utils.SliceContains(s.ctx.WatchedLocations, folder) { - var subfolders []string - utils.FindAllSubdirectories(folder, &subfolders) - subfolders = append(subfolders, folder) - for _, element := range subfolders { - s.watcher.Add(element) - s.ctx.WatchedLocations = utils.AppendIfNotPresent(s.ctx.WatchedLocations, element) - } - } - } - } -} - -func (s *builderServer) DropCache(ctx context.Context, args *pb.VerboseParams) (*pb.Response, error) { - s.ctx.CanUseCachedTools = false - response := pb.Response{Line: "Tools cache dropped"} - return &response, nil -} - -// GetFeature returns the feature at the given point. -func (s *builderServer) Autocomplete(ctx context.Context, args *pb.BuildParams) (*pb.Response, error) { - - s.ctx.HardwareFolders = strings.Split(args.HardwareFolders, ",") - s.ctx.ToolsFolders = strings.Split(args.ToolsFolders, ",") - s.ctx.BuiltInLibrariesFolders = strings.Split(args.BuiltInLibrariesFolders, ",") - s.ctx.OtherLibrariesFolders = strings.Split(args.OtherLibrariesFolders, ",") - s.ctx.SketchLocation = args.SketchLocation - s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") - s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - s.ctx.FQBN = args.FQBN - s.ctx.Verbose = false //p.Verbose - s.ctx.BuildCachePath = args.BuildCachePath - s.ctx.BuildPath = args.BuildPath - s.ctx.WarningsLevel = args.WarningsLevel - s.ctx.PrototypesSection = "" - s.ctx.CodeCompleteAt = args.CodeCompleteAt - s.ctx.CodeCompletions = "" - - s.ctx.IncludeFolders = s.ctx.IncludeFolders[0:0] - s.ctx.LibrariesObjectFiles = s.ctx.LibrariesObjectFiles[0:0] - s.ctx.CoreObjectsFiles = s.ctx.CoreObjectsFiles[0:0] - s.ctx.SketchObjectFiles = s.ctx.SketchObjectFiles[0:0] - - s.ctx.ImportedLibraries = s.ctx.ImportedLibraries[0:0] - - //s.watch() - - oldlogger := s.ctx.GetLogger() - logger := i18n.NoopLogger{} - s.ctx.SetLogger(logger) - - err := builder.RunPreprocess(s.ctx) - - response := pb.Response{Line: s.ctx.CodeCompletions} - s.ctx.SetLogger(oldlogger) - - return &response, err -} - -// GetFeature returns the feature at the given point. -func (s *builderServer) Build(args *pb.BuildParams, stream pb.Builder_BuildServer) error { - - s.ctx.HardwareFolders = strings.Split(args.HardwareFolders, ",") - s.ctx.ToolsFolders = strings.Split(args.ToolsFolders, ",") - s.ctx.BuiltInLibrariesFolders = strings.Split(args.BuiltInLibrariesFolders, ",") - s.ctx.OtherLibrariesFolders = strings.Split(args.OtherLibrariesFolders, ",") - s.ctx.SketchLocation = args.SketchLocation - s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") - s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - s.ctx.FQBN = args.FQBN - s.ctx.Verbose = args.Verbose - s.ctx.BuildCachePath = args.BuildCachePath - s.ctx.BuildPath = args.BuildPath - s.ctx.WarningsLevel = args.WarningsLevel - s.ctx.PrototypesSection = "" - s.ctx.CodeCompleteAt = "" - - s.ctx.IncludeFolders = s.ctx.IncludeFolders[0:0] - s.ctx.LibrariesObjectFiles = s.ctx.LibrariesObjectFiles[0:0] - s.ctx.CoreObjectsFiles = s.ctx.CoreObjectsFiles[0:0] - s.ctx.SketchObjectFiles = s.ctx.SketchObjectFiles[0:0] - - s.ctx.ImportedLibraries = s.ctx.ImportedLibraries[0:0] - - // setup logger to send via protobuf - oldlogger := s.ctx.GetLogger() - logger := StreamLogger{stream} - s.ctx.SetLogger(logger) - - //s.watch() - - err := builder.RunBuilder(s.ctx) - s.ctx.SetLogger(oldlogger) - if err != nil { - return err - } - - // No feature was found, return an unnamed feature - return nil -} - -/* -func (h *WatchHandler) ServeJSONRPC(c context.Context, params *json.RawMessage) (interface{}, *jsonrpc.Error) { - - var p WatchParams - if err := jsonrpc.Unmarshal(params, &p); err != nil { - return nil, err - } - - err := h.watcher.Add(p.Path) - if err != nil { - return nil, jsonrpc.ErrInvalidParams() - } - return BuildResult{ - Message: "OK " + p.Path, - }, nil -} -*/ - -func startWatching(ctx *types.Context) *fsnotify.Watcher { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - - go func() { - for { - select { - case event := <-watcher.Events: - ctx.CanUseCachedTools = false - log.Println("event:", event) - case err := <-watcher.Errors: - log.Println("error:", err) - } - } - }() - return watcher -} - -func newServerWithWatcher(ctx *types.Context, watcher *fsnotify.Watcher) *builderServer { - s := new(builderServer) - s.ctx = ctx - s.watcher = watcher - return s -} - -func newServer(ctx *types.Context) *builderServer { - s := new(builderServer) - s.ctx = ctx - return s -} - -func RegisterAndServeJsonRPC(ctx *types.Context) { - lis, err := net.Listen("tcp", "localhost:12345") - if err != nil { - //can't spawn two grpc servers on the same port - os.Exit(0) - } - //watcher := startWatching(ctx) - - grpcServer := grpc.NewServer() - pb.RegisterBuilderServer(grpcServer, newServer(ctx)) - grpcServer.Serve(lis) -} diff --git a/hardware/platform.keys.rewrite.txt b/hardware/platform.keys.rewrite.txt deleted file mode 100644 index 4e8c93fb..00000000 --- a/hardware/platform.keys.rewrite.txt +++ /dev/null @@ -1,42 +0,0 @@ -old.0.compiler.path={runtime.ide.path}/hardware/tools/avr/bin/ -new.0.compiler.path={runtime.tools.avr-gcc.path}/bin/ - -old.1.tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude -new.1.tools.avrdude.cmd.path={path}/bin/avrdude - -old.2.tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf -new.2.tools.avrdude.config.path={path}/etc/avrdude.conf - -old.3.compiler.path={runtime.ide.path}/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/ -new.3.compiler.path={runtime.tools.arm-none-eabi-gcc.path}/bin/ - -old.4.tools.bossac.path={runtime.ide.path}/hardware/tools -new.4.tools.bossac.path={runtime.tools.bossac.path} - -old.5.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group "{build.path}/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc -new.5.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group "{build.path}/core/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc - -#specific to RedBearLab nRF51822 Boards -old.6.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb -Wl,--gc-sections --specs=nano.specs -Wl,--wrap,main -Wl,-Map={build.path}/{build.project_name}.map,--cref "-T{build.variant.path}/{build.ldscript}" -o "{build.path}/{build.project_name}.elf" -Wl,--start-group "{build.path}/system_nrf51.c.o" {object_files} "{build.path}/startup_NRF51822.s.o" "{build.path}/{archive_file}" -Wl,--end-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys -new.6.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb -Wl,--gc-sections --specs=nano.specs -Wl,--wrap,main -Wl,-Map={build.path}/{build.project_name}.map,--cref "-T{build.variant.path}/{build.ldscript}" -o "{build.path}/{build.project_name}.elf" -Wl,--start-group "{build.path}/core/mbed/targets/cmsis/TARGET_NORDIC/TARGET_MCU_NRF51822/system_nrf51.c.o" {object_files} "{build.path}/core/startup_NRF51822.S.o" "{build.path}/{archive_file}" -Wl,--end-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys - -#specific to RFduino 1.6.3 -old.7.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} {build.extra_flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" -Wl,--cref -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/syscalls.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.variant.path}/libRFduino.a" "{build.variant.path}/libRFduinoBLE.a" "{build.variant.path}/libRFduinoGZLL.a" "{build.path}/{archive_file}" -Wl,--end-group -new.7.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} {build.extra_flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" -Wl,--cref -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/core/syscalls.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.variant.path}/libRFduino.a" "{build.variant.path}/libRFduinoBLE.a" "{build.variant.path}/libRFduinoGZLL.a" "{build.path}/{archive_file}" -Wl,--end-group - -old.8.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}" -new.8.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" - -old.9.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc -new.9.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/core/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc - -#specific to Digistump AVR Boards 1.5.4 -old.10.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} "{build.path}/{archive_file}" "{object_file}" -new.10.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} "{archive_file_path}" "{object_file}" - -old.11.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} -o "{build.path}/{build.project_name}.elf" {object_files} "{build.path}/{archive_file}" "-L{build.path}" -lm -new.11.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} -o "{build.path}/{build.project_name}.elf" {object_files} "{archive_file_path}" "-L{build.path}" -lm - -#generic again -old.12.recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -new.12.recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{preprocessed_file_path}" \ No newline at end of file diff --git a/hardware/platform.txt b/hardware/platform.txt deleted file mode 100644 index 144df2fb..00000000 --- a/hardware/platform.txt +++ /dev/null @@ -1,19 +0,0 @@ -# arduino-preprocessor -# -------------------- - -tools.arduino-preprocessor.path={runtime.tools.arduino-preprocessor.path} -tools.arduino-preprocessor.cmd.path={path}/arduino-preprocessor -tools.arduino-preprocessor.pattern="{cmd.path}" "{source_file}" "{codecomplete}" -- -std=gnu++11 - -# ctags -# ------------------------------ -tools.ctags.path={runtime.tools.ctags.path} -tools.ctags.cmd.path={path}/ctags -tools.ctags.pattern="{cmd.path}" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "{source_file}" - -# additional entries -tools.avrdude.path={runtime.tools.avrdude.path} - -preproc.macros.flags=-w -x c++ -E -CC -#preproc.macros.compatibility_flags={build.mbed_api_include} {build.nRF51822_api_include} {build.ble_api_include} {compiler.libsam.c.flags} {compiler.arm.cmsis.path} {build.variant_system_include} -#recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} {preproc.macros.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {preproc.macros.compatibility_flags} {includes} "{source_file}" -o "{preprocessed_file_path}" diff --git a/hardware_loader.go b/hardware_loader.go deleted file mode 100644 index 321e9d48..00000000 --- a/hardware_loader.go +++ /dev/null @@ -1,246 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type HardwareLoader struct{} - -func (s *HardwareLoader) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - packages.Properties = make(map[string]string) - - folders := ctx.HardwareFolders - folders, err := utils.AbsolutizePaths(folders) - if err != nil { - return i18n.WrapError(err) - } - - for _, folder := range folders { - stat, err := os.Stat(folder) - if err != nil { - return i18n.WrapError(err) - } - if !stat.IsDir() { - return i18n.ErrorfWithLogger(logger, constants.MSG_MUST_BE_A_FOLDER, folder) - } - - hardwarePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - packages.Properties.Merge(hardwarePlatformTxt) - - subfolders, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - subfolders = utils.FilterOutFoldersByNames(subfolders, constants.FOLDER_TOOLS) - - for _, subfolder := range subfolders { - subfolderPath := filepath.Join(folder, subfolder.Name()) - packageId := subfolder.Name() - - if _, err := os.Stat(filepath.Join(subfolderPath, constants.FOLDER_HARDWARE)); err == nil { - subfolderPath = filepath.Join(subfolderPath, constants.FOLDER_HARDWARE) - } - - targetPackage := getOrCreatePackage(packages, packageId) - err = loadPackage(targetPackage, subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - packages.Packages[packageId] = targetPackage - } - } - - ctx.Hardware = packages - - return nil -} - -func getOrCreatePackage(packages *types.Packages, packageId string) *types.Package { - if _, ok := packages.Packages[packageId]; ok { - return packages.Packages[packageId] - } - - targetPackage := types.Package{} - targetPackage.PackageId = packageId - targetPackage.Platforms = make(map[string]*types.Platform) - targetPackage.Properties = make(map[string]string) - - return &targetPackage -} - -func loadPackage(targetPackage *types.Package, folder string) error { - packagePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - targetPackage.Properties.Merge(packagePlatformTxt) - - subfolders, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - - subfolders = utils.FilterOutFoldersByNames(subfolders, constants.FOLDER_TOOLS) - - platforms := targetPackage.Platforms - for _, subfolder := range subfolders { - subfolderPath := filepath.Join(folder, subfolder.Name()) - platformId := subfolder.Name() - - _, err := os.Stat(filepath.Join(subfolderPath, constants.FILE_BOARDS_TXT)) - if err != nil && os.IsNotExist(err) { - theOnlySubfolder, err := utils.TheOnlySubfolderOf(subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - - if theOnlySubfolder != constants.EMPTY_STRING { - subfolderPath = filepath.Join(subfolderPath, theOnlySubfolder) - } - } - - platform := getOrCreatePlatform(platforms, platformId) - err = loadPlatform(platform, subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - platforms[platformId] = platform - } - - return nil -} - -func getOrCreatePlatform(platforms map[string]*types.Platform, platformId string) *types.Platform { - if _, ok := platforms[platformId]; ok { - return platforms[platformId] - } - - targetPlatform := types.Platform{} - targetPlatform.PlatformId = platformId - targetPlatform.Boards = make(map[string]*types.Board) - targetPlatform.Properties = make(map[string]string) - targetPlatform.Programmers = make(map[string]properties.Map) - - return &targetPlatform -} - -func loadPlatform(targetPlatform *types.Platform, folder string) error { - _, err := os.Stat(filepath.Join(folder, constants.FILE_BOARDS_TXT)) - if err != nil && !os.IsNotExist(err) { - return i18n.WrapError(err) - } - - if os.IsNotExist(err) { - return nil - } - - targetPlatform.Folder = folder - - err = loadBoards(targetPlatform.Boards, folder) - if err != nil { - return i18n.WrapError(err) - } - - platformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - localPlatformProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_LOCAL_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - targetPlatform.Properties = targetPlatform.Properties.Clone() - targetPlatform.Properties.Merge(platformTxt) - targetPlatform.Properties.Merge(localPlatformProperties) - - programmersProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PROGRAMMERS_TXT)) - if err != nil { - return i18n.WrapError(err) - } - targetPlatform.Programmers = properties.MergeMapsOfProperties(make(map[string]properties.Map), targetPlatform.Programmers, programmersProperties.FirstLevelOf()) - - return nil -} - -func loadBoards(boards map[string]*types.Board, folder string) error { - boardsProperties, err := properties.Load(filepath.Join(folder, constants.FILE_BOARDS_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - localProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_BOARDS_LOCAL_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - boardsProperties = boardsProperties.Merge(localProperties) - - propertiesByBoardId := boardsProperties.FirstLevelOf() - delete(propertiesByBoardId, constants.BOARD_PROPERTIES_MENU) - - for boardID, boardProperties := range propertiesByBoardId { - boardProperties[constants.ID] = boardID - board := getOrCreateBoard(boards, boardID) - board.Properties.Merge(boardProperties) - boards[boardID] = board - } - - return nil -} - -func getOrCreateBoard(boards map[string]*types.Board, boardId string) *types.Board { - if _, ok := boards[boardId]; ok { - return boards[boardId] - } - - board := types.Board{} - board.BoardId = boardId - board.Properties = make(properties.Map) - - return &board -} diff --git a/i18n/errors.go b/i18n/errors.go deleted file mode 100644 index b3617800..00000000 --- a/i18n/errors.go +++ /dev/null @@ -1,31 +0,0 @@ -package i18n - -import "github.com/arduino/arduino-builder/constants" -import "github.com/go-errors/errors" -import "os" - -func ErrorfWithLogger(logger Logger, format string, a ...interface{}) *errors.Error { - if logger.Name() == "machine" { - logger.Fprintln(os.Stderr, constants.LOG_LEVEL_ERROR, format, a...) - return errors.Errorf("") - } - return errors.Errorf(Format(format, a...)) -} - -func WrapError(err error) error { - if err == nil { - return nil - } - return errors.Wrap(err, 0) -} - -func UnwrapError(err error) error { - // Perhaps go-errors can do this already in later versions? - // See https://github.com/go-errors/errors/issues/14 - switch e := err.(type) { - case *errors.Error: - return e.Err - default: - return err - } -} diff --git a/i18n/i18n.go b/i18n/i18n.go deleted file mode 100644 index 202d51c7..00000000 --- a/i18n/i18n.go +++ /dev/null @@ -1,233 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package i18n - -import ( - "fmt" - "io" - "net/url" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "sync" -) - -var PLACEHOLDER = regexp.MustCompile("{(\\d)}") - -type Logger interface { - Fprintln(w io.Writer, level string, format string, a ...interface{}) - UnformattedFprintln(w io.Writer, s string) - UnformattedWrite(w io.Writer, data []byte) - Println(level string, format string, a ...interface{}) - Name() string - Flush() string -} - -type NoopLogger struct{} - -func (s NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {} - -func (s NoopLogger) UnformattedFprintln(w io.Writer, str string) {} - -func (s NoopLogger) UnformattedWrite(w io.Writer, data []byte) {} - -func (s NoopLogger) Println(level string, format string, a ...interface{}) {} - -func (s NoopLogger) Flush() string { - return "" -} - -func (s NoopLogger) Name() string { - return "noop" -} - -type AccumulatorLogger struct { - Buffer *[]string -} - -func (s AccumulatorLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - *s.Buffer = append(*s.Buffer, Format(format, a...)) -} - -func (s AccumulatorLogger) UnformattedFprintln(w io.Writer, str string) { - *s.Buffer = append(*s.Buffer, str) -} - -func (s AccumulatorLogger) UnformattedWrite(w io.Writer, data []byte) { - *s.Buffer = append(*s.Buffer, string(data)) -} - -func (s AccumulatorLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(nil, level, format, a...) -} - -func (s AccumulatorLogger) Flush() string { - str := strings.Join(*s.Buffer, "\n") - *s.Buffer = (*s.Buffer)[0:0] - return str -} - -func (s AccumulatorLogger) Name() string { - return "accumulator" -} - -type HumanTagsLogger struct{} - -func (s HumanTagsLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - format = "[" + level + "] " + format - fprintln(w, Format(format, a...)) -} - -func (s HumanTagsLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(os.Stdout, level, format, a...) -} - -func (s HumanTagsLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s HumanTagsLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func (s HumanTagsLogger) Flush() string { - return "" -} - -func (s HumanTagsLogger) Name() string { - return "humantags" -} - -type HumanLogger struct{} - -func (s HumanLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - fprintln(w, Format(format, a...)) -} - -func (s HumanLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(os.Stdout, level, format, a...) -} - -func (s HumanLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s HumanLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func (s HumanLogger) Flush() string { - return "" -} - -func (s HumanLogger) Name() string { - return "human" -} - -type MachineLogger struct{} - -func (s MachineLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - printMachineFormattedLogLine(w, level, format, a) -} - -func (s MachineLogger) Println(level string, format string, a ...interface{}) { - printMachineFormattedLogLine(os.Stdout, level, format, a) -} - -func (s MachineLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s MachineLogger) Flush() string { - return "" -} - -func (s MachineLogger) Name() string { - return "machine" -} - -func (s MachineLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func printMachineFormattedLogLine(w io.Writer, level string, format string, a []interface{}) { - a = append([]interface{}(nil), a...) - for idx, value := range a { - typeof := reflect.Indirect(reflect.ValueOf(value)).Kind() - if typeof == reflect.String { - a[idx] = url.QueryEscape(value.(string)) - } - } - fprintf(w, "===%s ||| %s ||| %s\n", level, format, a) -} - -var lock sync.Mutex - -func fprintln(w io.Writer, s string) { - lock.Lock() - defer lock.Unlock() - fmt.Fprintln(w, s) -} - -func write(w io.Writer, data []byte) { - lock.Lock() - defer lock.Unlock() - w.Write(data) -} - -func fprintf(w io.Writer, format string, a ...interface{}) { - lock.Lock() - defer lock.Unlock() - fmt.Fprintf(w, format, a...) -} - -func FromJavaToGoSyntax(s string) string { - submatches := PLACEHOLDER.FindAllStringSubmatch(s, -1) - for _, submatch := range submatches { - idx, err := strconv.Atoi(submatch[1]) - if err != nil { - panic(err) - } - idx = idx + 1 - s = strings.Replace(s, submatch[0], "%["+strconv.Itoa(idx)+"]v", -1) - } - - s = strings.Replace(s, "''", "'", -1) - - return s -} - -func Format(format string, a ...interface{}) string { - format = FromJavaToGoSyntax(format) - message := fmt.Sprintf(format, a...) - return message -} diff --git a/includes_finder_with_regexp.go b/includes_finder_with_regexp.go deleted file mode 100644 index abfe7635..00000000 --- a/includes_finder_with_regexp.go +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/types" - "regexp" - "strings" -) - -var INCLUDE_REGEXP = regexp.MustCompile("(?ms)^\\s*#[ \t]*include\\s*[<\"](\\S+)[\">]") - -func IncludesFinderWithRegExp(ctx *types.Context, source string) string { - match := INCLUDE_REGEXP.FindStringSubmatch(source) - if match != nil { - return strings.TrimSpace(match[1]) - } else { - return findIncludeForOldCompilers(source) - } -} - -func findIncludeForOldCompilers(source string) string { - lines := strings.Split(source, "\n") - for _, line := range lines { - splittedLine := strings.Split(line, ":") - for i, _ := range splittedLine { - if strings.Contains(splittedLine[i], "fatal error") { - return strings.TrimSpace(splittedLine[i+1]) - } - } - } - return "" -} diff --git a/libraries_loader.go b/libraries_loader.go deleted file mode 100644 index 1730bf44..00000000 --- a/libraries_loader.go +++ /dev/null @@ -1,222 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type LibrariesLoader struct{} - -func (s *LibrariesLoader) Run(ctx *types.Context) error { - builtInLibrariesFolders := ctx.BuiltInLibrariesFolders - builtInLibrariesFolders, err := utils.AbsolutizePaths(builtInLibrariesFolders) - if err != nil { - return i18n.WrapError(err) - } - sortedLibrariesFolders := []string{} - sortedLibrariesFolders = utils.AppendIfNotPresent(sortedLibrariesFolders, builtInLibrariesFolders...) - - platform := ctx.TargetPlatform - debugLevel := ctx.DebugLevel - logger := ctx.GetLogger() - - actualPlatform := ctx.ActualPlatform - if actualPlatform != platform { - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(actualPlatform.Folder, constants.FOLDER_LIBRARIES)) - } - - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(platform.Folder, constants.FOLDER_LIBRARIES)) - - librariesFolders := ctx.OtherLibrariesFolders - librariesFolders, err = utils.AbsolutizePaths(librariesFolders) - if err != nil { - return i18n.WrapError(err) - } - sortedLibrariesFolders = utils.AppendIfNotPresent(sortedLibrariesFolders, librariesFolders...) - - ctx.LibrariesFolders = sortedLibrariesFolders - - var libraries []*types.Library - for _, libraryFolder := range sortedLibrariesFolders { - subFolders, err := utils.ReadDirFiltered(libraryFolder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - for _, subFolder := range subFolders { - library, err := makeLibrary(filepath.Join(libraryFolder, subFolder.Name()), debugLevel, logger) - if err != nil { - return i18n.WrapError(err) - } - libraries = append(libraries, library) - } - } - - ctx.Libraries = libraries - - headerToLibraries := make(map[string][]*types.Library) - for _, library := range libraries { - headers, err := utils.ReadDirFiltered(library.SrcFolder, utils.FilterFilesWithExtensions(".h", ".hpp", ".hh")) - if err != nil { - return i18n.WrapError(err) - } - for _, header := range headers { - headerFileName := header.Name() - headerToLibraries[headerFileName] = append(headerToLibraries[headerFileName], library) - } - } - - ctx.HeaderToLibraries = headerToLibraries - - return nil -} - -func makeLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*types.Library, error) { - if _, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)); os.IsNotExist(err) { - return makeLegacyLibrary(libraryFolder) - } - return makeNewLibrary(libraryFolder, debugLevel, logger) -} - -func addUtilityFolder(library *types.Library) { - utilitySourcePath := filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY) - stat, err := os.Stat(utilitySourcePath) - if err == nil && stat.IsDir() { - library.UtilityFolder = utilitySourcePath - } -} - -func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*types.Library, error) { - libProperties, err := properties.Load(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)) - if err != nil { - return nil, i18n.WrapError(err) - } - - if libProperties[constants.LIBRARY_MAINTAINER] == constants.EMPTY_STRING && libProperties[constants.LIBRARY_EMAIL] != constants.EMPTY_STRING { - libProperties[constants.LIBRARY_MAINTAINER] = libProperties[constants.LIBRARY_EMAIL] - } - - for _, propName := range LIBRARY_NOT_SO_MANDATORY_PROPERTIES { - if libProperties[propName] == constants.EMPTY_STRING { - libProperties[propName] = "-" - } - } - - library := &types.Library{} - library.Folder = libraryFolder - if stat, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC)); err == nil && stat.IsDir() { - library.Layout = types.LIBRARY_RECURSIVE - library.SrcFolder = filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC) - } else { - library.Layout = types.LIBRARY_FLAT - library.SrcFolder = libraryFolder - addUtilityFolder(library) - } - - subFolders, err := utils.ReadDirFiltered(libraryFolder, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - if debugLevel >= 0 { - for _, subFolder := range subFolders { - if utils.IsSCCSOrHiddenFile(subFolder) { - if !utils.IsSCCSFile(subFolder) && utils.IsHiddenFile(subFolder) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_WARNING_SPURIOUS_FILE_IN_LIB, filepath.Base(subFolder.Name()), libProperties[constants.LIBRARY_NAME]) - } - } - } - } - - if libProperties[constants.LIBRARY_ARCHITECTURES] == constants.EMPTY_STRING { - libProperties[constants.LIBRARY_ARCHITECTURES] = constants.LIBRARY_ALL_ARCHS - } - library.Archs = []string{} - for _, arch := range strings.Split(libProperties[constants.LIBRARY_ARCHITECTURES], ",") { - library.Archs = append(library.Archs, strings.TrimSpace(arch)) - } - - libProperties[constants.LIBRARY_CATEGORY] = strings.TrimSpace(libProperties[constants.LIBRARY_CATEGORY]) - if !LIBRARY_CATEGORIES[libProperties[constants.LIBRARY_CATEGORY]] { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_WARNING_LIB_INVALID_CATEGORY, libProperties[constants.LIBRARY_CATEGORY], libProperties[constants.LIBRARY_NAME], constants.LIB_CATEGORY_UNCATEGORIZED) - libProperties[constants.LIBRARY_CATEGORY] = constants.LIB_CATEGORY_UNCATEGORIZED - } - library.Category = libProperties[constants.LIBRARY_CATEGORY] - - if libProperties[constants.LIBRARY_LICENSE] == constants.EMPTY_STRING { - libProperties[constants.LIBRARY_LICENSE] = constants.LIB_LICENSE_UNSPECIFIED - } - library.License = libProperties[constants.LIBRARY_LICENSE] - - library.Name = filepath.Base(libraryFolder) - library.RealName = strings.TrimSpace(libProperties[constants.LIBRARY_NAME]) - library.Version = strings.TrimSpace(libProperties[constants.LIBRARY_VERSION]) - library.Author = strings.TrimSpace(libProperties[constants.LIBRARY_AUTHOR]) - library.Maintainer = strings.TrimSpace(libProperties[constants.LIBRARY_MAINTAINER]) - library.Sentence = strings.TrimSpace(libProperties[constants.LIBRARY_SENTENCE]) - library.Paragraph = strings.TrimSpace(libProperties[constants.LIBRARY_PARAGRAPH]) - library.URL = strings.TrimSpace(libProperties[constants.LIBRARY_URL]) - library.IsLegacy = false - library.DotALinkage = strings.TrimSpace(libProperties[constants.LIBRARY_DOT_A_LINKAGE]) == "true" - library.Precompiled = strings.TrimSpace(libProperties[constants.LIBRARY_PRECOMPILED]) == "true" - library.LDflags = strings.TrimSpace(libProperties[constants.LIBRARY_LDFLAGS]) - library.Properties = libProperties - - return library, nil -} - -func makeLegacyLibrary(libraryFolder string) (*types.Library, error) { - library := &types.Library{ - Folder: libraryFolder, - SrcFolder: libraryFolder, - Layout: types.LIBRARY_FLAT, - Name: filepath.Base(libraryFolder), - Archs: []string{constants.LIBRARY_ALL_ARCHS}, - IsLegacy: true, - } - addUtilityFolder(library) - return library, nil -} - -func appendPathToLibrariesFolders(librariesFolders []string, newLibrariesFolder string) []string { - if stat, err := os.Stat(newLibrariesFolder); os.IsNotExist(err) || !stat.IsDir() { - return librariesFolders - } - - return utils.AppendIfNotPresent(librariesFolders, newLibrariesFolder) -} diff --git a/load_previous_build_options.go b/load_previous_build_options.go deleted file mode 100644 index 3b9bd5d0..00000000 --- a/load_previous_build_options.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "io/ioutil" - "os" - "path/filepath" -) - -type LoadPreviousBuildOptionsMap struct{} - -func (s *LoadPreviousBuildOptionsMap) Run(ctx *types.Context) error { - buildOptionsFile := filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE) - - _, err := os.Stat(buildOptionsFile) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return i18n.WrapError(err) - } - - bytes, err := ioutil.ReadFile(buildOptionsFile) - if err != nil { - return i18n.WrapError(err) - } - - ctx.BuildOptionsJsonPrevious = string(bytes) - - return nil -} diff --git a/load_vid_pid_specific_properties.go b/load_vid_pid_specific_properties.go deleted file mode 100644 index df3cc434..00000000 --- a/load_vid_pid_specific_properties.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "strconv" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" -) - -type LoadVIDPIDSpecificProperties struct{} - -func (s *LoadVIDPIDSpecificProperties) Run(ctx *types.Context) error { - if ctx.USBVidPid == "" { - return nil - } - - vidPid := ctx.USBVidPid - vidPid = strings.ToLower(vidPid) - vidPidParts := strings.Split(vidPid, "_") - vid := vidPidParts[0] - pid := vidPidParts[1] - - buildProperties := ctx.BuildProperties - VIDPIDIndex, err := findVIDPIDIndex(buildProperties, vid, pid) - if err != nil { - return i18n.WrapError(err) - } - if VIDPIDIndex < 0 { - return nil - } - - vidPidSpecificProperties := buildProperties.SubTree(constants.BUILD_PROPERTIES_VID).SubTree(strconv.Itoa(VIDPIDIndex)) - buildProperties.Merge(vidPidSpecificProperties) - - return nil -} - -func findVIDPIDIndex(buildProperties properties.Map, vid, pid string) (int, error) { - for key, value := range buildProperties.SubTree(constants.BUILD_PROPERTIES_VID) { - if !strings.Contains(key, ".") { - if vid == strings.ToLower(value) && pid == strings.ToLower(buildProperties[constants.BUILD_PROPERTIES_PID+"."+key]) { - return strconv.Atoi(key) - } - } - } - - return -1, nil -} diff --git a/arduino-builder/main.go b/main.go similarity index 87% rename from arduino-builder/main.go rename to main.go index e55d1caf..2b7dba33 100644 --- a/arduino-builder/main.go +++ b/main.go @@ -37,22 +37,22 @@ import ( "io/ioutil" "os" "os/exec" - "path/filepath" "runtime" - "strings" - "syscall" - "runtime/pprof" "runtime/trace" + "strings" + "syscall" - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/grpc" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" + "github.com/arduino/arduino-cli/arduino/cores" + "github.com/arduino/arduino-cli/legacy/builder" + "github.com/arduino/arduino-cli/legacy/builder/gohasissues" + jsonrpc "github.com/arduino/arduino-cli/legacy/builder/grpc" + "github.com/arduino/arduino-cli/legacy/builder/i18n" + "github.com/arduino/arduino-cli/legacy/builder/types" + paths "github.com/arduino/go-paths-helper" + properties "github.com/arduino/go-properties-orderedmap" "github.com/go-errors/errors" + "github.com/sirupsen/logrus" ) const VERSION = "1.4.5" @@ -230,7 +230,7 @@ func main() { } if *buildOptionsFileFlag != "" { - buildOptions := make(properties.Map) + buildOptions := properties.NewMap() if _, err := os.Stat(*buildOptionsFileFlag); err == nil { data, err := ioutil.ReadFile(*buildOptionsFileFlag) if err != nil { @@ -248,9 +248,9 @@ func main() { if hardwareFolders, err := toSliceOfUnquoted(hardwareFoldersFlag); err != nil { printCompleteError(err) } else if len(hardwareFolders) > 0 { - ctx.HardwareFolders = hardwareFolders + ctx.HardwareDirs = paths.NewPathList(hardwareFolders...) } - if len(ctx.HardwareFolders) == 0 { + if len(ctx.HardwareDirs) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_HARDWARE + "' is mandatory")) } @@ -258,9 +258,9 @@ func main() { if toolsFolders, err := toSliceOfUnquoted(toolsFoldersFlag); err != nil { printCompleteError(err) } else if len(toolsFolders) > 0 { - ctx.ToolsFolders = toolsFolders + ctx.ToolsDirs = paths.NewPathList(toolsFolders...) } - if len(ctx.ToolsFolders) == 0 { + if len(ctx.ToolsDirs) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_TOOLS + "' is mandatory")) } @@ -268,14 +268,14 @@ func main() { if librariesFolders, err := toSliceOfUnquoted(librariesFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesFolders) > 0 { - ctx.OtherLibrariesFolders = librariesFolders + ctx.OtherLibrariesDirs = paths.NewPathList(librariesFolders...) } // FLAG_BUILT_IN_LIBRARIES if librariesBuiltInFolders, err := toSliceOfUnquoted(librariesBuiltInFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesBuiltInFolders) > 0 { - ctx.BuiltInLibrariesFolders = librariesBuiltInFolders + ctx.BuiltInLibrariesDirs = paths.NewPathList(librariesBuiltInFolders...) } // FLAG_PREFS @@ -286,48 +286,52 @@ func main() { } // FLAG_FQBN - if fqbn, err := gohasissues.Unquote(*fqbnFlag); err != nil { + if fqbnIn, err := gohasissues.Unquote(*fqbnFlag); err != nil { printCompleteError(err) - } else if fqbn != "" { - ctx.FQBN = fqbn + } else if fqbnIn != "" { + if fqbn, err := cores.ParseFQBN(fqbnIn); err != nil { + printCompleteError(err) + } else { + ctx.FQBN = fqbn + } } - if ctx.FQBN == "" { + if ctx.FQBN == nil { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_FQBN + "' is mandatory")) } // FLAG_BUILD_PATH - buildPath, err := gohasissues.Unquote(*buildPathFlag) + buildPathUnquoted, err := gohasissues.Unquote(*buildPathFlag) if err != nil { printCompleteError(err) } - if buildPath != "" { - _, err := os.Stat(buildPath) - if err != nil { + buildPath := paths.New(buildPathUnquoted) + if buildPath != nil { + // TODO: mmmmhhh... this one looks like a bug, why check existence? + if _, err := buildPath.Stat(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } - err = utils.EnsureFolderExists(buildPath) - if err != nil { + if err := buildPath.MkdirAll(); err != nil { printCompleteError(err) } - ctx.BuildPath, _ = filepath.Abs(buildPath) + ctx.BuildPath, _ = buildPath.Abs() } // FLAG_BUILD_CACHE - buildCachePath, err := gohasissues.Unquote(*buildCachePathFlag) + buildCachePathUnquoted, err := gohasissues.Unquote(*buildCachePathFlag) if err != nil { printCompleteError(err) } - if buildCachePath != "" { - _, err := os.Stat(buildCachePath) - if err != nil { + buildCachePath := paths.New(buildCachePathUnquoted) + if buildCachePath != nil { + // TODO: mmmmhhh... this one looks like a bug, why check existence? + if _, err := buildCachePath.Stat(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } - err = utils.EnsureFolderExists(buildCachePath) - if err != nil { + if err := buildCachePath.MkdirAll(); err != nil { printCompleteError(err) } } @@ -339,12 +343,11 @@ func main() { } if flag.NArg() > 0 { - sketchLocation := flag.Arg(0) - sketchLocation, err := gohasissues.Unquote(sketchLocation) + sketchLocationUnquoted, err := gohasissues.Unquote(flag.Arg(0)) if err != nil { printCompleteError(err) } - ctx.SketchLocation = sketchLocation + ctx.SketchLocation = paths.New(sketchLocationUnquoted) } if *verboseFlag && *quietFlag { @@ -371,6 +374,9 @@ func main() { if *debugLevelFlag > -1 { ctx.DebugLevel = *debugLevelFlag } + if ctx.DebugLevel < 10 { + logrus.SetOutput(ioutil.Discard) + } if *quietFlag { ctx.SetLogger(i18n.NoopLogger{}) @@ -430,14 +436,6 @@ func toSliceOfUnquoted(value []string) ([]string, error) { return values, nil } -func printError(err error, printStackTrace bool) { - if printStackTrace { - printCompleteError(err) - } else { - printErrorMessageAndFlagUsage(err) - } -} - func printCompleteError(err error) { err = i18n.WrapError(err) fmt.Fprintln(os.Stderr, err.(*errors.Error).ErrorStack()) diff --git a/merge_sketch_with_bootloader.go b/merge_sketch_with_bootloader.go deleted file mode 100644 index ebefa77e..00000000 --- a/merge_sketch_with_bootloader.go +++ /dev/null @@ -1,149 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" - "strings" -) - -type MergeSketchWithBootloader struct{} - -func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - if !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) && !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_FILE) { - return nil - } - - buildPath := ctx.BuildPath - sketch := ctx.Sketch - sketchFileName := filepath.Base(sketch.MainFile.Name) - logger := ctx.GetLogger() - - sketchInBuildPath := filepath.Join(buildPath, sketchFileName+".hex") - sketchInSubfolder := filepath.Join(buildPath, constants.FOLDER_SKETCH, sketchFileName+".hex") - - builtSketchPath := constants.EMPTY_STRING - if _, err := os.Stat(sketchInBuildPath); err == nil { - builtSketchPath = sketchInBuildPath - } else if _, err := os.Stat(sketchInSubfolder); err == nil { - builtSketchPath = sketchInSubfolder - } else { - return nil - } - - bootloader := constants.EMPTY_STRING - if utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) { - bootloader = buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK] - } else { - bootloader = buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_FILE] - } - bootloader = buildProperties.ExpandPropsInString(bootloader) - - bootloaderPath := filepath.Join(buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH], constants.FOLDER_BOOTLOADERS, bootloader) - if _, err := os.Stat(bootloaderPath); err != nil { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_BOOTLOADER_FILE_MISSING, bootloaderPath) - return nil - } - - mergedSketchPath := filepath.Join(filepath.Dir(builtSketchPath), sketchFileName+".with_bootloader.hex") - - err := merge(builtSketchPath, bootloaderPath, mergedSketchPath) - - return err -} - -func hexLineOnlyContainsFF(line string) bool { - //:206FE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB1 - if len(line) <= 11 { - return false - } - byteArray := []byte(line) - for _, char := range byteArray[9:(len(byteArray) - 2)] { - if char != 'F' { - return false - } - } - return true -} - -func extractActualBootloader(bootloader []string) []string { - - var realBootloader []string - - // skip until we find a line full of FFFFFF (except address and checksum) - for i, row := range bootloader { - if hexLineOnlyContainsFF(row) { - realBootloader = bootloader[i:len(bootloader)] - break - } - } - - // drop all "empty" lines - for i, row := range realBootloader { - if !hexLineOnlyContainsFF(row) { - realBootloader = realBootloader[i:len(realBootloader)] - break - } - } - - if len(realBootloader) == 0 { - // we didn't find any line full of FFFF, thus it's a standalone bootloader - realBootloader = bootloader - } - - return realBootloader -} - -func merge(builtSketchPath, bootloaderPath, mergedSketchPath string) error { - sketch, err := utils.ReadFileToRows(builtSketchPath) - if err != nil { - return i18n.WrapError(err) - } - sketch = sketch[:len(sketch)-2] - - bootloader, err := utils.ReadFileToRows(bootloaderPath) - if err != nil { - return i18n.WrapError(err) - } - - realBootloader := extractActualBootloader(bootloader) - - for _, row := range realBootloader { - sketch = append(sketch, row) - } - - return utils.WriteFile(mergedSketchPath, strings.Join(sketch, "\n")) -} diff --git a/phases/core_builder.go b/phases/core_builder.go deleted file mode 100644 index ee5d9c72..00000000 --- a/phases/core_builder.go +++ /dev/null @@ -1,141 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "os" - "path/filepath" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type CoreBuilder struct{} - -func (s *CoreBuilder) Run(ctx *types.Context) error { - coreBuildPath := ctx.CoreBuildPath - coreBuildCachePath := ctx.CoreBuildCachePath - buildProperties := ctx.BuildProperties - - err := utils.EnsureFolderExists(coreBuildPath) - if err != nil { - return i18n.WrapError(err) - } - - if coreBuildCachePath != "" { - err := utils.EnsureFolderExists(coreBuildCachePath) - if err != nil { - return i18n.WrapError(err) - } - } - - archiveFile, objectFiles, err := compileCore(ctx, coreBuildPath, coreBuildCachePath, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CoreArchiveFilePath = archiveFile - ctx.CoreObjectsFiles = objectFiles - - return nil -} - -func compileCore(ctx *types.Context, buildPath string, buildCachePath string, buildProperties properties.Map) (string, []string, error) { - logger := ctx.GetLogger() - coreFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] - variantFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] - - targetCoreFolder := buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] - - includes := []string{} - includes = append(includes, coreFolder) - if variantFolder != constants.EMPTY_STRING { - includes = append(includes, variantFolder) - } - includes = utils.Map(includes, utils.WrapWithHyphenI) - - var err error - - variantObjectFiles := []string{} - if variantFolder != constants.EMPTY_STRING { - variantObjectFiles, err = builder_utils.CompileFiles(ctx, variantObjectFiles, variantFolder, true, buildPath, buildProperties, includes) - if err != nil { - return "", nil, i18n.WrapError(err) - } - } - - // Recreate the archive if ANY of the core files (including platform.txt) has changed - realCoreFolder := utils.GetParentFolder(coreFolder, 2) - - var targetArchivedCore string - if buildCachePath != "" { - archivedCoreName := builder_utils.GetCachedCoreArchiveFileName(buildProperties[constants.BUILD_PROPERTIES_FQBN], realCoreFolder) - targetArchivedCore = filepath.Join(buildCachePath, archivedCoreName) - canUseArchivedCore := !builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, targetArchivedCore) - - if canUseArchivedCore { - // use archived core - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, "Using precompiled core: {0}", targetArchivedCore) - } - return targetArchivedCore, variantObjectFiles, nil - } - } - - coreObjectFiles, err := builder_utils.CompileFiles(ctx, []string{}, coreFolder, true, buildPath, buildProperties, includes) - if err != nil { - return "", nil, i18n.WrapError(err) - } - - archiveFile, err := builder_utils.ArchiveCompiledFiles(ctx, buildPath, "core.a", coreObjectFiles, buildProperties) - if err != nil { - return "", nil, i18n.WrapError(err) - } - - // archive core.a - if targetArchivedCore != "" { - err := builder_utils.CopyFile(archiveFile, targetArchivedCore) - if ctx.Verbose { - if err == nil { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_ARCHIVING_CORE_CACHE, targetArchivedCore) - } else if os.IsNotExist(err) { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_CORE_CACHE_UNAVAILABLE, ctx.ActualPlatform.PlatformId) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_ERROR_ARCHIVING_CORE_CACHE, targetArchivedCore, err) - } - } - } - - return archiveFile, variantObjectFiles, nil -} diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go deleted file mode 100644 index dc0fdf12..00000000 --- a/phases/libraries_builder.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC = map[string]bool{".a": true} -var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_DYNAMIC = map[string]bool{".so": true} - -type LibrariesBuilder struct{} - -func (s *LibrariesBuilder) Run(ctx *types.Context) error { - librariesBuildPath := ctx.LibrariesBuildPath - buildProperties := ctx.BuildProperties - includes := ctx.IncludeFolders - includes = utils.Map(includes, utils.WrapWithHyphenI) - libraries := ctx.ImportedLibraries - - err := utils.EnsureFolderExists(librariesBuildPath) - if err != nil { - return i18n.WrapError(err) - } - - objectFiles, err := compileLibraries(ctx, libraries, librariesBuildPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - - ctx.LibrariesObjectFiles = objectFiles - - // Search for precompiled libraries - fixLDFLAGforPrecompiledLibraries(ctx, libraries) - - return nil -} - -func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*types.Library) error { - - for _, library := range libraries { - if library.Precompiled { - // add library src path to compiler.c.elf.extra_flags - // use library.Name as lib name and srcPath/{mcpu} as location - mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - path := filepath.Join(library.SrcFolder, mcu) - // find all library names in the folder and prepend -l - filePaths := []string{} - libs_cmd := library.LDflags + " " - extensions := func(ext string) bool { return PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_DYNAMIC[ext] } - utils.FindFilesInFolder(&filePaths, path, extensions, true) - for _, lib := range filePaths { - name := strings.TrimSuffix(filepath.Base(lib), filepath.Ext(lib)) - // strip "lib" first occurrence - name = strings.Replace(name, "lib", "", 1) - libs_cmd += "-l" + name + " " - } - ctx.BuildProperties[constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS] += "\"-L" + path + "\" " + libs_cmd + " " - } - } - return nil -} - -func compileLibraries(ctx *types.Context, libraries []*types.Library, buildPath string, buildProperties properties.Map, includes []string) ([]string, error) { - objectFiles := []string{} - for _, library := range libraries { - libraryObjectFiles, err := compileLibrary(ctx, library, buildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles = append(objectFiles, libraryObjectFiles...) - } - - return objectFiles, nil - -} - -func compileLibrary(ctx *types.Context, library *types.Library, buildPath string, buildProperties properties.Map, includes []string) ([]string, error) { - logger := ctx.GetLogger() - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, "Compiling library \"{0}\"", library.Name) - } - libraryBuildPath := filepath.Join(buildPath, library.Name) - - err := utils.EnsureFolderExists(libraryBuildPath) - if err != nil { - return nil, i18n.WrapError(err) - } - - objectFiles := []string{} - - if library.Precompiled { - // search for files with PRECOMPILED_LIBRARIES_VALID_EXTENSIONS - extensions := func(ext string) bool { return PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC[ext] } - - filePaths := []string{} - mcu := buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - err := utils.FindFilesInFolder(&filePaths, filepath.Join(library.SrcFolder, mcu), extensions, true) - if err != nil { - return nil, i18n.WrapError(err) - } - for _, path := range filePaths { - if strings.Contains(filepath.Base(path), library.RealName) { - objectFiles = append(objectFiles, path) - } - } - } - - if library.Layout == types.LIBRARY_RECURSIVE { - objectFiles, err = builder_utils.CompileFilesRecursive(ctx, objectFiles, library.SrcFolder, libraryBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - if library.DotALinkage { - archiveFile, err := builder_utils.ArchiveCompiledFiles(ctx, libraryBuildPath, library.Name+".a", objectFiles, buildProperties) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles = []string{archiveFile} - } - } else { - if library.UtilityFolder != "" { - includes = append(includes, utils.WrapWithHyphenI(library.UtilityFolder)) - } - objectFiles, err = builder_utils.CompileFiles(ctx, objectFiles, library.SrcFolder, false, libraryBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - - if library.UtilityFolder != "" { - utilityBuildPath := filepath.Join(libraryBuildPath, constants.LIBRARY_FOLDER_UTILITY) - objectFiles, err = builder_utils.CompileFiles(ctx, objectFiles, library.UtilityFolder, false, utilityBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - } - } - - return objectFiles, nil -} diff --git a/phases/linker.go b/phases/linker.go deleted file mode 100644 index 2514b406..00000000 --- a/phases/linker.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type Linker struct{} - -func (s *Linker) Run(ctx *types.Context) error { - objectFilesSketch := ctx.SketchObjectFiles - objectFilesLibraries := ctx.LibrariesObjectFiles - objectFilesCore := ctx.CoreObjectsFiles - - var objectFiles []string - objectFiles = append(objectFiles, objectFilesSketch...) - objectFiles = append(objectFiles, objectFilesLibraries...) - objectFiles = append(objectFiles, objectFilesCore...) - - coreArchiveFilePath := ctx.CoreArchiveFilePath - buildPath := ctx.BuildPath - coreDotARelPath, err := filepath.Rel(buildPath, coreArchiveFilePath) - if err != nil { - return i18n.WrapError(err) - } - - buildProperties := ctx.BuildProperties - - err = link(ctx, objectFiles, coreDotARelPath, coreArchiveFilePath, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func link(ctx *types.Context, objectFiles []string, coreDotARelPath string, coreArchiveFilePath string, buildProperties properties.Map) error { - optRelax := addRelaxTrickIfATMEGA2560(buildProperties) - - objectFiles = utils.Map(objectFiles, wrapWithDoubleQuotes) - objectFileList := strings.Join(objectFiles, constants.SPACE) - - properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] + optRelax - properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = coreDotARelPath - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = coreArchiveFilePath - properties[constants.BUILD_PROPERTIES_OBJECT_FILES] = objectFileList - - _, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_C_COMBINE_PATTERN, false, /* stdout */ utils.ShowIfVerbose, /* stderr */ utils.Show) - return err -} - -func wrapWithDoubleQuotes(value string) string { - return "\"" + value + "\"" -} - -func addRelaxTrickIfATMEGA2560(buildProperties properties.Map) string { - if buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] == "atmega2560" { - return ",--relax" - } - return constants.EMPTY_STRING -} diff --git a/phases/sizer.go b/phases/sizer.go deleted file mode 100644 index fa719e18..00000000 --- a/phases/sizer.go +++ /dev/null @@ -1,182 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2016 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "errors" - "regexp" - "strconv" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type Sizer struct { - SketchError bool -} - -func (s *Sizer) Run(ctx *types.Context) error { - - if s.SketchError { - return nil - } - - buildProperties := ctx.BuildProperties - - err := checkSize(ctx, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func checkSize(ctx *types.Context, buildProperties properties.Map) error { - logger := ctx.GetLogger() - - properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] - - maxTextSizeString := properties[constants.PROPERTY_UPLOAD_MAX_SIZE] - maxDataSizeString := properties[constants.PROPERTY_UPLOAD_MAX_DATA_SIZE] - - if maxTextSizeString == "" { - return nil - } - - maxTextSize, err := strconv.Atoi(maxTextSizeString) - if err != nil { - return err - } - - maxDataSize := -1 - if maxDataSizeString != "" { - maxDataSize, err = strconv.Atoi(maxDataSizeString) - if err != nil { - return err - } - } - - textSize, dataSize, _, err := execSizeRecipe(ctx, properties) - if err != nil { - logger.Println(constants.LOG_LEVEL_WARN, constants.MSG_SIZER_ERROR_NO_RULE) - return nil - } - - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_TEXT_FULL, strconv.Itoa(textSize), strconv.Itoa(maxTextSize), strconv.Itoa(textSize*100/maxTextSize)) - if dataSize >= 0 { - if maxDataSize > 0 { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_DATA_FULL, strconv.Itoa(dataSize), strconv.Itoa(maxDataSize), strconv.Itoa(dataSize*100/maxDataSize), strconv.Itoa(maxDataSize-dataSize)) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_DATA, strconv.Itoa(dataSize)) - } - } - - if textSize > maxTextSize { - logger.Println(constants.LOG_LEVEL_ERROR, constants.MSG_SIZER_TEXT_TOO_BIG) - return errors.New("") - } - - if maxDataSize > 0 && dataSize > maxDataSize { - logger.Println(constants.LOG_LEVEL_ERROR, constants.MSG_SIZER_DATA_TOO_BIG) - return errors.New("") - } - - if properties[constants.PROPERTY_WARN_DATA_PERCENT] != "" { - warnDataPercentage, err := strconv.Atoi(properties[constants.PROPERTY_WARN_DATA_PERCENT]) - if err != nil { - return err - } - if maxDataSize > 0 && dataSize > maxDataSize*warnDataPercentage/100 { - logger.Println(constants.LOG_LEVEL_WARN, constants.MSG_SIZER_LOW_MEMORY) - } - } - - return nil -} - -func execSizeRecipe(ctx *types.Context, properties properties.Map) (textSize int, dataSize int, eepromSize int, resErr error) { - out, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_SIZE_PATTERN, false /* stdout */, utils.Capture /* stderr */, utils.Show) - if err != nil { - resErr = errors.New("Error while determining sketch size: " + err.Error()) - return - } - - // force multiline match prepending "(?m)" to the actual regexp - // return an error if RECIPE_SIZE_REGEXP doesn't exist - - textSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP], out) - if err != nil { - resErr = errors.New("Invalid size regexp: " + err.Error()) - return - } - if textSize == -1 { - resErr = errors.New("Missing size regexp") - return - } - - dataSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP_DATA], out) - if err != nil { - resErr = errors.New("Invalid data size regexp: " + err.Error()) - return - } - - eepromSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP_EEPROM], out) - if err != nil { - resErr = errors.New("Invalid eeprom size regexp: " + err.Error()) - return - } - - return -} - -func computeSize(re string, output []byte) (int, error) { - if re == "" { - return -1, nil - } - r, err := regexp.Compile("(?m)" + re) - if err != nil { - return -1, err - } - result := r.FindAllSubmatch(output, -1) - size := 0 - for _, b := range result { - for _, c := range b { - if res, err := strconv.Atoi(string(c)); err == nil { - size += res - } - } - } - return size, nil -} diff --git a/phases/sizer_test.go b/phases/sizer_test.go deleted file mode 100644 index 3f0f704f..00000000 --- a/phases/sizer_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2016 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSizerWithAVRData(t *testing.T) { - output := []byte(`/tmp/test597119152/sketch.ino.elf : -section size addr -.data 36 8388864 -.text 3966 0 -.bss 112 8388900 -.comment 17 0 -.debug_aranges 704 0 -.debug_info 21084 0 -.debug_abbrev 4704 0 -.debug_line 5456 0 -.debug_frame 1964 0 -.debug_str 8251 0 -.debug_loc 7747 0 -.debug_ranges 856 0 -Total 54897 -`) - - size, err := computeSize(`^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 4002, size) - - size, err = computeSize(`^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 148, size) - - size, err = computeSize(`^(?:\.eeprom)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 0, size) -} - -func TestSizerWithSAMDData(t *testing.T) { - output := []byte(`/tmp/test737785204/sketch_usbhost.ino.elf : -section size addr -.text 8076 8192 -.data 152 536870912 -.bss 1984 536871064 -.ARM.attributes 40 0 -.comment 128 0 -.debug_info 178841 0 -.debug_abbrev 14968 0 -.debug_aranges 2080 0 -.debug_ranges 3840 0 -.debug_line 26068 0 -.debug_str 55489 0 -.debug_frame 5036 0 -.debug_loc 20978 0 -Total 317680 -`) - - size, err := computeSize(`\.text\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 8076, size) -} - -func TestSizerEmptyRegexpReturnsMinusOne(t *testing.T) { - size, err := computeSize(``, []byte(`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)) - require.NoError(t, err) - require.Equal(t, -1, size) -} - -func TestSizerWithInvalidRegexp(t *testing.T) { - _, err := computeSize(`[xx`, []byte(`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)) - require.Error(t, err) -} diff --git a/phases/sketch_builder.go b/phases/sketch_builder.go deleted file mode 100644 index 8a3158d9..00000000 --- a/phases/sketch_builder.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" -) - -type SketchBuilder struct{} - -func (s *SketchBuilder) Run(ctx *types.Context) error { - sketchBuildPath := ctx.SketchBuildPath - buildProperties := ctx.BuildProperties - includes := ctx.IncludeFolders - includes = utils.Map(includes, utils.WrapWithHyphenI) - - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { - return i18n.WrapError(err) - } - - var objectFiles []string - objectFiles, err = builder_utils.CompileFiles(ctx, objectFiles, sketchBuildPath, false, sketchBuildPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - - // The "src/" subdirectory of a sketch is compiled recursively - sketchSrcPath := filepath.Join(sketchBuildPath, constants.SKETCH_FOLDER_SRC) - if info, err := os.Stat(sketchSrcPath); err == nil && info.IsDir() { - objectFiles, err = builder_utils.CompileFiles(ctx, objectFiles, sketchSrcPath, true, sketchSrcPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - } - - ctx.SketchObjectFiles = objectFiles - - return nil -} diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go deleted file mode 100644 index adbd8553..00000000 --- a/platform_keys_rewrite_loader.go +++ /dev/null @@ -1,111 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - "sort" - "strconv" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" -) - -type PlatformKeysRewriteLoader struct{} - -func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { - folders := ctx.HardwareFolders - - platformKeysRewriteTxtPath, err := findPlatformKeysRewriteTxt(folders) - if err != nil { - return i18n.WrapError(err) - } - if platformKeysRewriteTxtPath == constants.EMPTY_STRING { - return nil - } - - platformKeysRewrite := types.PlatforKeysRewrite{} - platformKeysRewrite.Rewrites = []types.PlatforKeyRewrite{} - - txt, err := properties.Load(platformKeysRewriteTxtPath) - if err != nil { - return i18n.WrapError(err) - } - keys := txt.Keys() - sort.Strings(keys) - - for _, key := range keys { - keyParts := strings.Split(key, ".") - if keyParts[0] == constants.PLATFORM_REWRITE_OLD { - index, err := strconv.Atoi(keyParts[1]) - if err != nil { - return i18n.WrapError(err) - } - rewriteKey := strings.Join(keyParts[2:], ".") - oldValue := txt[key] - newValue := txt[constants.PLATFORM_REWRITE_NEW+"."+strings.Join(keyParts[1:], ".")] - platformKeyRewrite := types.PlatforKeyRewrite{Key: rewriteKey, OldValue: oldValue, NewValue: newValue} - platformKeysRewrite.Rewrites = growSliceOfRewrites(platformKeysRewrite.Rewrites, index) - platformKeysRewrite.Rewrites[index] = platformKeyRewrite - } - } - - ctx.PlatformKeyRewrites = platformKeysRewrite - - return nil -} - -func findPlatformKeysRewriteTxt(folders []string) (string, error) { - for _, folder := range folders { - txtPath := filepath.Join(folder, constants.FILE_PLATFORM_KEYS_REWRITE_TXT) - _, err := os.Stat(txtPath) - if err == nil { - return txtPath, nil - } - if !os.IsNotExist(err) { - return constants.EMPTY_STRING, i18n.WrapError(err) - } - } - - return constants.EMPTY_STRING, nil -} - -func growSliceOfRewrites(originalSlice []types.PlatforKeyRewrite, maxIndex int) []types.PlatforKeyRewrite { - if cap(originalSlice) > maxIndex { - return originalSlice - } - newSlice := make([]types.PlatforKeyRewrite, maxIndex+1) - copy(newSlice, originalSlice) - return newSlice -} diff --git a/preprocess_sketch.go b/preprocess_sketch.go deleted file mode 100644 index d36c04c5..00000000 --- a/preprocess_sketch.go +++ /dev/null @@ -1,152 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "errors" - "fmt" - "os/exec" - "path/filepath" - "runtime" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type PreprocessSketchArduino struct{} - -func (s *PreprocessSketchArduino) Run(ctx *types.Context) error { - sourceFile := filepath.Join(ctx.SketchBuildPath, filepath.Base(ctx.Sketch.MainFile.Name)+".cpp") - commands := []types.Command{ - &ArduinoPreprocessorRunner{}, - } - - err := utils.EnsureFolderExists(ctx.PreprocPath) - if err != nil { - return i18n.WrapError(err) - } - - if ctx.CodeCompleteAt != "" { - commands = append(commands, &OutputCodeCompletions{}) - } else { - commands = append(commands, &SketchSaver{}) - } - - GCCPreprocRunner(ctx, sourceFile, filepath.Join(ctx.PreprocPath, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E), ctx.IncludeFolders) - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -type ArduinoPreprocessorRunner struct{} - -func (s *ArduinoPreprocessorRunner) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - targetFilePath := filepath.Join(ctx.PreprocPath, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E) - logger := ctx.GetLogger() - - properties := buildProperties.Clone() - toolProps := buildProperties.SubTree("tools").SubTree("arduino-preprocessor") - properties.Merge(toolProps) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = targetFilePath - if ctx.CodeCompleteAt != "" { - if runtime.GOOS == "windows" { - //use relative filepath to avoid ":" escaping - splt := strings.Split(ctx.CodeCompleteAt, ":") - if len(splt) == 3 { - //all right, do nothing - } else { - splt[1] = filepath.Base(splt[0] + ":" + splt[1]) - ctx.CodeCompleteAt = strings.Join(splt[1:], ":") - } - } - properties["codecomplete"] = "-output-code-completions=" + ctx.CodeCompleteAt - } else { - properties["codecomplete"] = "" - } - - pattern := properties[constants.BUILD_PROPERTIES_PATTERN] - if pattern == constants.EMPTY_STRING { - return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, "arduino-preprocessor") - } - - commandLine := properties.ExpandPropsInString(pattern) - command, err := utils.PrepareCommand(commandLine, logger, "") - if err != nil { - return i18n.WrapError(err) - } - - if runtime.GOOS == "windows" { - // chdir in the uppermost directory to avoid UTF-8 bug in clang (https://github.com/arduino/arduino-preprocessor/issues/2) - command.Dir = filepath.VolumeName(command.Args[0]) + "/" - //command.Args[0], _ = filepath.Rel(command.Dir, command.Args[0]) - } - - verbose := ctx.Verbose - if verbose { - fmt.Println(commandLine) - } - - buf, err := command.Output() - if err != nil { - return errors.New(i18n.WrapError(err).Error() + string(err.(*exec.ExitError).Stderr)) - } - - result := utils.NormalizeUTF8(buf) - - //fmt.Printf("PREPROCESSOR OUTPUT:\n%s\n", output) - if ctx.CodeCompleteAt != "" { - ctx.CodeCompletions = string(result) - } else { - ctx.Source = string(result) - } - return nil -} - -type OutputCodeCompletions struct{} - -func (s *OutputCodeCompletions) Run(ctx *types.Context) error { - if ctx.CodeCompletions == "" { - // we assume it is a json, let's make it compliant at least - ctx.CodeCompletions = "[]" - } - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, ctx.CodeCompletions) - return nil -} diff --git a/print_preprocessed_source.go b/print_preprocessed_source.go deleted file mode 100644 index b320c127..00000000 --- a/print_preprocessed_source.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - - "github.com/arduino/arduino-builder/types" -) - -type PrintPreprocessedSource struct{} - -func (s *PrintPreprocessedSource) Run(ctx *types.Context) error { - if ctx.SourceGccMinusE != "" { - fmt.Println(ctx.SourceGccMinusE) - } - return nil -} diff --git a/print_used_and_not_used_libraries.go b/print_used_and_not_used_libraries.go deleted file mode 100644 index b60a6bf0..00000000 --- a/print_used_and_not_used_libraries.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "os" - "time" -) - -type PrintUsedAndNotUsedLibraries struct { - // Was there an error while compiling the sketch? - SketchError bool -} - -func (s *PrintUsedAndNotUsedLibraries) Run(ctx *types.Context) error { - var logLevel string - // Print this message as warning when the sketch didn't compile, - // as info when we're verbose and not all otherwise - if s.SketchError { - logLevel = constants.LOG_LEVEL_WARN - } else if ctx.Verbose { - logLevel = constants.LOG_LEVEL_INFO - } else { - return nil - } - - logger := ctx.GetLogger() - libraryResolutionResults := ctx.LibrariesResolutionResults - - for header, libResResult := range libraryResolutionResults { - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR, header) - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_USED, libResResult.Library.Folder) - for _, notUsedLibrary := range libResResult.NotUsedLibraries { - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_NOT_USED, notUsedLibrary.Folder) - } - } - - time.Sleep(100 * time.Millisecond) - - return nil -} diff --git a/print_used_libraries_if_verbose.go b/print_used_libraries_if_verbose.go deleted file mode 100644 index 3489c9a0..00000000 --- a/print_used_libraries_if_verbose.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "time" -) - -type PrintUsedLibrariesIfVerbose struct{} - -func (s *PrintUsedLibrariesIfVerbose) Run(ctx *types.Context) error { - verbose := ctx.Verbose - logger := ctx.GetLogger() - - if !verbose || len(ctx.ImportedLibraries) == 0 { - return nil - } - - for _, library := range ctx.ImportedLibraries { - legacy := constants.EMPTY_STRING - if library.IsLegacy { - legacy = constants.MSG_LIB_LEGACY - } - if library.Version == constants.EMPTY_STRING { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY, library.Name, library.Folder, legacy) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY_AT_VERSION, library.Name, library.Version, library.Folder, legacy) - } - } - - time.Sleep(100 * time.Millisecond) - - return nil -} diff --git a/prototypes_adder.go b/prototypes_adder.go deleted file mode 100644 index db283519..00000000 --- a/prototypes_adder.go +++ /dev/null @@ -1,120 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "fmt" - "strconv" - "strings" -) - -type PrototypesAdder struct{} - -func (s *PrototypesAdder) Run(ctx *types.Context) error { - debugOutput := ctx.DebugPreprocessor - source := ctx.Source - - source = strings.Replace(source, "\r\n", "\n", -1) - source = strings.Replace(source, "\r", "\n", -1) - - sourceRows := strings.Split(source, "\n") - - firstFunctionLine := ctx.PrototypesLineWhereToInsert - if isFirstFunctionOutsideOfSource(firstFunctionLine, sourceRows) { - return nil - } - - insertionLine := firstFunctionLine + ctx.LineOffset - 1 - firstFunctionChar := len(strings.Join(sourceRows[:insertionLine], "\n")) + 1 - prototypeSection := composePrototypeSection(firstFunctionLine, ctx.Prototypes) - ctx.PrototypesSection = prototypeSection - source = source[:firstFunctionChar] + prototypeSection + source[firstFunctionChar:] - - if debugOutput { - fmt.Println("#PREPROCESSED SOURCE") - prototypesRows := strings.Split(prototypeSection, "\n") - prototypesRows = prototypesRows[:len(prototypesRows)-1] - for i := 0; i < len(sourceRows)+len(prototypesRows); i++ { - if i < insertionLine { - fmt.Printf(" |%s\n", sourceRows[i]) - } else if i < insertionLine+len(prototypesRows) { - fmt.Printf("PRO|%s\n", prototypesRows[i-insertionLine]) - } else { - fmt.Printf(" |%s\n", sourceRows[i-len(prototypesRows)]) - } - } - fmt.Println("#END OF PREPROCESSED SOURCE") - } - ctx.Source = source - - return nil -} - -func composePrototypeSection(line int, prototypes []*types.Prototype) string { - if len(prototypes) == 0 { - return constants.EMPTY_STRING - } - - str := joinPrototypes(prototypes) - str += "\n#line " - str += strconv.Itoa(line) - str += " " + utils.QuoteCppString(prototypes[0].File) - str += "\n" - - return str -} - -func joinPrototypes(prototypes []*types.Prototype) string { - prototypesSlice := []string{} - for _, proto := range prototypes { - if signatureContainsaDefaultArg(proto) { - continue - } - prototypesSlice = append(prototypesSlice, "#line "+strconv.Itoa(proto.Line)+" "+utils.QuoteCppString(proto.File)) - prototypeParts := []string{} - if proto.Modifiers != "" { - prototypeParts = append(prototypeParts, proto.Modifiers) - } - prototypeParts = append(prototypeParts, proto.Prototype) - prototypesSlice = append(prototypesSlice, strings.Join(prototypeParts, " ")) - } - return strings.Join(prototypesSlice, "\n") -} - -func signatureContainsaDefaultArg(proto *types.Prototype) bool { - return strings.Contains(proto.Prototype, "=") -} - -func isFirstFunctionOutsideOfSource(firstFunctionLine int, sourceRows []string) bool { - return firstFunctionLine > len(sourceRows)-1 -} diff --git a/read_file_and_store_in_context.go b/read_file_and_store_in_context.go deleted file mode 100644 index bd165617..00000000 --- a/read_file_and_store_in_context.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "io/ioutil" -) - -type ReadFileAndStoreInContext struct { - FileToRead string - Target *string -} - -func (s *ReadFileAndStoreInContext) Run(ctx *types.Context) error { - bytes, err := ioutil.ReadFile(s.FileToRead) - if err != nil { - return i18n.WrapError(err) - } - - *s.Target = string(bytes) - - return nil -} diff --git a/recipe_runner.go b/recipe_runner.go deleted file mode 100644 index bb1bb962..00000000 --- a/recipe_runner.go +++ /dev/null @@ -1,84 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "sort" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type RecipeByPrefixSuffixRunner struct { - Prefix string - Suffix string -} - -func (s *RecipeByPrefixSuffixRunner) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - if ctx.DebugLevel >= 10 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_LOOKING_FOR_RECIPES, s.Prefix, s.Suffix) - } - - buildProperties := ctx.BuildProperties.Clone() - recipes := findRecipes(buildProperties, s.Prefix, s.Suffix) - - properties := buildProperties.Clone() - for _, recipe := range recipes { - if ctx.DebugLevel >= 10 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_RUNNING_RECIPE, recipe) - } - _, _, err := builder_utils.ExecRecipe(ctx, properties, recipe, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil - -} - -func findRecipes(buildProperties map[string]string, patternPrefix string, patternSuffix string) []string { - var recipes []string - for key, _ := range buildProperties { - if strings.HasPrefix(key, patternPrefix) && strings.HasSuffix(key, patternSuffix) && buildProperties[key] != constants.EMPTY_STRING { - recipes = append(recipes, key) - } - } - - sort.Strings(recipes) - - return recipes -} diff --git a/resolve_library.go b/resolve_library.go deleted file mode 100644 index 849940be..00000000 --- a/resolve_library.go +++ /dev/null @@ -1,284 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/schollz/closestmatch" -) - -func ResolveLibrary(ctx *types.Context, header string) *types.Library { - headerToLibraries := ctx.HeaderToLibraries - platforms := []*types.Platform{ctx.ActualPlatform, ctx.TargetPlatform} - libraryResolutionResults := ctx.LibrariesResolutionResults - importedLibraries := ctx.ImportedLibraries - - libraries := append([]*types.Library{}, headerToLibraries[header]...) - - if libraries == nil || len(libraries) == 0 { - return nil - } - - if importedLibraryContainsOneOfCandidates(importedLibraries, libraries) { - return nil - } - - if len(libraries) == 1 { - return libraries[0] - } - - reverse(libraries) - - var library *types.Library - - for _, platform := range platforms { - if platform != nil { - library = findBestLibraryWithHeader(header, librariesCompatibleWithPlatform(libraries, platform, true)) - } - } - - if library == nil { - library = findBestLibraryWithHeader(header, libraries) - } - - if library == nil { - // reorder libraries to promote fully compatible ones - for _, platform := range platforms { - if platform != nil { - libraries = append(librariesCompatibleWithPlatform(libraries, platform, false), libraries...) - } - } - library = libraries[0] - } - - library = useAlreadyImportedLibraryWithSameNameIfExists(library, importedLibraries) - - libraryResolutionResults[header] = types.LibraryResolutionResult{ - Library: library, - NotUsedLibraries: filterOutLibraryFrom(libraries, library), - } - - return library -} - -//facepalm. sort.Reverse needs an Interface that implements Len/Less/Swap. It's a slice! What else for reversing it?!? -func reverse(data []*types.Library) { - for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 { - data[i], data[j] = data[j], data[i] - } -} - -func importedLibraryContainsOneOfCandidates(imported []*types.Library, candidates []*types.Library) bool { - for _, i := range imported { - for _, j := range candidates { - if i == j { - return true - } - } - } - return false -} - -func useAlreadyImportedLibraryWithSameNameIfExists(library *types.Library, imported []*types.Library) *types.Library { - for _, lib := range imported { - if lib.Name == library.Name { - return lib - } - } - return library -} - -func filterOutLibraryFrom(libraries []*types.Library, libraryToRemove *types.Library) []*types.Library { - filteredOutLibraries := []*types.Library{} - for _, lib := range libraries { - if lib != libraryToRemove { - filteredOutLibraries = append(filteredOutLibraries, lib) - } - } - return filteredOutLibraries -} - -func findLibraryIn(libraries []*types.Library, library *types.Library) *types.Library { - for _, lib := range libraries { - if lib == library { - return lib - } - } - return nil -} - -func libraryCompatibleWithPlatform(library *types.Library, platform *types.Platform) (bool, bool) { - if len(library.Archs) == 0 { - return true, true - } - if utils.SliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { - return true, true - } - return utils.SliceContains(library.Archs, platform.PlatformId), false -} - -func libraryCompatibleWithAllPlatforms(library *types.Library) bool { - if utils.SliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { - return true - } - return false -} - -func librariesCompatibleWithPlatform(libraries []*types.Library, platform *types.Platform, reorder bool) []*types.Library { - var compatibleLibraries []*types.Library - for _, library := range libraries { - compatible, generic := libraryCompatibleWithPlatform(library, platform) - if compatible { - if !generic && len(compatibleLibraries) != 0 && libraryCompatibleWithAllPlatforms(compatibleLibraries[0]) && reorder == true { - //priority inversion - compatibleLibraries = append([]*types.Library{library}, compatibleLibraries...) - } else { - compatibleLibraries = append(compatibleLibraries, library) - } - } - } - - return compatibleLibraries -} - -func librariesWithinPlatform(libraries []*types.Library, platform *types.Platform) []*types.Library { - librariesWithinSpecifiedPlatform := []*types.Library{} - for _, library := range libraries { - cleanPlatformFolder := filepath.Clean(platform.Folder) - cleanLibraryFolder := filepath.Clean(library.SrcFolder) - if strings.Contains(cleanLibraryFolder, cleanPlatformFolder) { - librariesWithinSpecifiedPlatform = append(librariesWithinSpecifiedPlatform, library) - } - } - - return librariesWithinSpecifiedPlatform - -} - -func findBestLibraryWithHeader(header string, libraries []*types.Library) *types.Library { - headerName := strings.Replace(header, filepath.Ext(header), constants.EMPTY_STRING, -1) - - var library *types.Library - for _, headerName := range []string{headerName, strings.ToLower(headerName)} { - library = findLibWithName(headerName, libraries) - if library != nil { - return library - } - library = findLibWithName(headerName+"-master", libraries) - if library != nil { - return library - } - library = findLibWithNameStartingWith(headerName, libraries) - if library != nil { - return library - } - library = findLibWithNameEndingWith(headerName, libraries) - if library != nil { - return library - } - library = findLibWithNameContaining(headerName, libraries) - if library != nil { - return library - } - library = findLibWithNameBestDistance(headerName, libraries) - if library != nil { - return library - } - } - - return nil -} - -func findLibWithName(name string, libraries []*types.Library) *types.Library { - for _, library := range libraries { - if simplifyName(library.Name) == simplifyName(name) { - return library - } - } - return nil -} - -func findLibWithNameStartingWith(name string, libraries []*types.Library) *types.Library { - for _, library := range libraries { - if strings.HasPrefix(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func findLibWithNameEndingWith(name string, libraries []*types.Library) *types.Library { - for _, library := range libraries { - if strings.HasSuffix(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func findLibWithNameContaining(name string, libraries []*types.Library) *types.Library { - for _, library := range libraries { - if strings.Contains(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func findLibWithNameBestDistance(name string, libraries []*types.Library) *types.Library { - // create closestmatch DB - var wordsToTest []string - - for _, library := range libraries { - wordsToTest = append(wordsToTest, simplifyName(library.Name)) - } - // Choose a set of bag sizes, more is more accurate but slower - bagSizes := []int{2} - // Create a closestmatch object - cm := closestmatch.New(wordsToTest, bagSizes) - closest_name := cm.Closest(name) - - for _, library := range libraries { - if (closest_name == simplifyName(library.Name)) { - return library - } - } - - return nil -} - -func simplifyName(name string) string { - return strings.ToLower(strings.Replace(name, "_", " ", -1)) -} diff --git a/resolve_library_test.go b/resolve_library_test.go deleted file mode 100644 index 1eff3c53..00000000 --- a/resolve_library_test.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2017 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "testing" - - "github.com/arduino/arduino-builder/types" - - "github.com/stretchr/testify/require" -) - -func TestFindBestLibraryWithHeader(t *testing.T) { - l1 := &types.Library{Name: "Calculus Lib"} - l2 := &types.Library{Name: "Calculus Lib-master"} - l3 := &types.Library{Name: "Calculus Lib Improved"} - l4 := &types.Library{Name: "Another Calculus Lib"} - l5 := &types.Library{Name: "Yet Another Calculus Lib Improved"} - l6 := &types.Library{Name: "Calculus Unified Lib"} - l7 := &types.Library{Name: "AnotherLib"} - - // Test exact name matching - res := findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6, l5, l4, l3, l2, l1}) - require.Equal(t, l1.Name, res.Name) - - // Test exact name with "-master" postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6, l5, l4, l3, l2}) - require.Equal(t, l2.Name, res.Name) - - // Test prefix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6, l5, l4, l3}) - require.Equal(t, l3.Name, res.Name) - - // Test postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6, l5, l4}) - require.Equal(t, l4.Name, res.Name) - - // Test "contains"" matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6, l5}) - require.Equal(t, l5.Name, res.Name) - - // Test lexicographic similarity matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7, l6}) - require.Equal(t, l6.Name, res.Name) - - // Test lexicographic similarity matching (2) - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l7}) - require.Equal(t, l6.Name, res.Name) - - // Test none matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l7}) - require.Equal(t, l7.Name, res.Name) -} diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go deleted file mode 100644 index 97f7aef4..00000000 --- a/rewrite_hardware_keys.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" -) - -type RewriteHardwareKeys struct{} - -func (s *RewriteHardwareKeys) Run(ctx *types.Context) error { - if ctx.PlatformKeyRewrites.Empty() { - return nil - } - - packages := ctx.Hardware - platformKeysRewrite := ctx.PlatformKeyRewrites - hardwareRewriteResults := ctx.HardwareRewriteResults - - for _, aPackage := range packages.Packages { - for _, platform := range aPackage.Platforms { - if platform.Properties[constants.REWRITING] != constants.REWRITING_DISABLED { - for _, rewrite := range platformKeysRewrite.Rewrites { - if platform.Properties[rewrite.Key] != constants.EMPTY_STRING && platform.Properties[rewrite.Key] == rewrite.OldValue { - platform.Properties[rewrite.Key] = rewrite.NewValue - appliedRewrites := rewritesAppliedToPlatform(platform, hardwareRewriteResults) - appliedRewrites = append(appliedRewrites, rewrite) - hardwareRewriteResults[platform] = appliedRewrites - } - } - } - } - } - - return nil -} - -func rewritesAppliedToPlatform(platform *types.Platform, hardwareRewriteResults map[*types.Platform][]types.PlatforKeyRewrite) []types.PlatforKeyRewrite { - if hardwareRewriteResults[platform] == nil { - hardwareRewriteResults[platform] = []types.PlatforKeyRewrite{} - } - return hardwareRewriteResults[platform] -} diff --git a/set_custom_build_properties.go b/set_custom_build_properties.go deleted file mode 100644 index 12b3467a..00000000 --- a/set_custom_build_properties.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" -) - -type SetCustomBuildProperties struct{} - -func (s *SetCustomBuildProperties) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - customBuildProperties, err := properties.LoadFromSlice(ctx.CustomBuildProperties) - if err != nil { - return i18n.WrapError(err) - } - - for key, value := range customBuildProperties { - buildProperties[key] = value - } - - return nil -} diff --git a/setup_build_properties.go b/setup_build_properties.go deleted file mode 100644 index c1983551..00000000 --- a/setup_build_properties.go +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" - "github.com/arduino/go-timeutils" -) - -type SetupBuildProperties struct{} - -func (s *SetupBuildProperties) Run(ctx *types.Context) error { - packages := ctx.Hardware - - targetPlatform := ctx.TargetPlatform - actualPlatform := ctx.ActualPlatform - targetBoard := ctx.TargetBoard - - buildProperties := make(properties.Map) - buildProperties.Merge(actualPlatform.Properties) - buildProperties.Merge(targetPlatform.Properties) - buildProperties.Merge(targetBoard.Properties) - - if ctx.BuildPath != "" { - buildProperties[constants.BUILD_PROPERTIES_BUILD_PATH] = ctx.BuildPath - } - if ctx.Sketch != nil { - buildProperties[constants.BUILD_PROPERTIES_BUILD_PROJECT_NAME] = filepath.Base(ctx.Sketch.MainFile.Name) - } - buildProperties[constants.BUILD_PROPERTIES_BUILD_ARCH] = strings.ToUpper(targetPlatform.PlatformId) - - // get base folder and use it to populate BUILD_PROPERTIES_RUNTIME_IDE_PATH (arduino and arduino-builder live in the same dir) - ex, err := os.Executable() - exPath := "" - if err == nil { - exPath = filepath.Dir(ex) - } - - buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE] = ctx.BuildCore - buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] = filepath.Join(actualPlatform.Folder, constants.FOLDER_CORES, buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE]) - buildProperties[constants.BUILD_PROPERTIES_BUILD_SYSTEM_PATH] = filepath.Join(actualPlatform.Folder, constants.FOLDER_SYSTEM) - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] = targetPlatform.Folder - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH] = filepath.Join(targetPlatform.Folder, "..") - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION] = ctx.ArduinoAPIVersion - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_PATH] = exPath - buildProperties[constants.BUILD_PROPERTIES_FQBN] = ctx.FQBN - buildProperties[constants.IDE_VERSION] = ctx.ArduinoAPIVersion - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS] = utils.PrettyOSName() - - variant := buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT] - if variant == constants.EMPTY_STRING { - buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] = constants.EMPTY_STRING - } else { - var variantPlatform *types.Platform - variantParts := strings.Split(variant, ":") - if len(variantParts) > 1 { - variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.PlatformId] - variant = variantParts[1] - } else { - variantPlatform = targetPlatform - } - buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] = filepath.Join(variantPlatform.Folder, constants.FOLDER_VARIANTS, variant) - } - - tools := ctx.Tools - for _, tool := range tools { - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX+tool.Name+constants.BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX] = tool.Folder - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX+tool.Name+"-"+tool.Version+constants.BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX] = tool.Folder - } - - if !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_SOFTWARE) { - buildProperties[constants.BUILD_PROPERTIES_SOFTWARE] = DEFAULT_SOFTWARE - } - - if ctx.SketchLocation != "" { - sourcePath, err := filepath.Abs(ctx.SketchLocation) - if err != nil { - return err - } - sourcePath = filepath.Dir(sourcePath) - buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH] = sourcePath - } - - now := time.Now() - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_UTC] = strconv.FormatInt(now.Unix(), 10) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL] = strconv.FormatInt(timeutils.LocalUnix(now), 10) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE] = strconv.Itoa(timeutils.TimezoneOffsetNoDST(now)) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_DST] = strconv.Itoa(timeutils.DaylightSavingsOffset(now)) - - ctx.BuildProperties = buildProperties - - return nil -} diff --git a/sketch_loader.go b/sketch_loader.go deleted file mode 100644 index 3ba588fa..00000000 --- a/sketch_loader.go +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type SketchLoader struct{} - -func (s *SketchLoader) Run(ctx *types.Context) error { - if ctx.SketchLocation == "" { - return nil - } - - sketchLocation := ctx.SketchLocation - - sketchLocation, err := filepath.Abs(sketchLocation) - if err != nil { - return i18n.WrapError(err) - } - mainSketchStat, err := os.Stat(sketchLocation) - if err != nil { - return i18n.WrapError(err) - } - if mainSketchStat.IsDir() { - sketchLocation = filepath.Join(sketchLocation, mainSketchStat.Name()+".ino") - } - - ctx.SketchLocation = sketchLocation - - allSketchFilePaths, err := collectAllSketchFiles(filepath.Dir(sketchLocation)) - if err != nil { - return i18n.WrapError(err) - } - - logger := ctx.GetLogger() - - if !utils.SliceContains(allSketchFilePaths, sketchLocation) { - return i18n.ErrorfWithLogger(logger, constants.MSG_CANT_FIND_SKETCH_IN_PATH, sketchLocation, filepath.Dir(sketchLocation)) - } - - sketch, err := makeSketch(sketchLocation, allSketchFilePaths, ctx.BuildPath, logger) - if err != nil { - return i18n.WrapError(err) - } - - ctx.SketchLocation = sketchLocation - ctx.Sketch = sketch - - return nil -} - -func collectAllSketchFiles(from string) ([]string, error) { - filePaths := []string{} - // Source files in the root are compiled, non-recursively. This - // is the only place where .ino files can be present. - rootExtensions := func(ext string) bool { return MAIN_FILE_VALID_EXTENSIONS[ext] || ADDITIONAL_FILE_VALID_EXTENSIONS[ext] } - err := utils.FindFilesInFolder(&filePaths, from, rootExtensions, true /* recurse */) - if err != nil { - return nil, i18n.WrapError(err) - } - - return filePaths, i18n.WrapError(err) -} - -func makeSketch(sketchLocation string, allSketchFilePaths []string, buildLocation string, logger i18n.Logger) (*types.Sketch, error) { - sketchFilesMap := make(map[string]types.SketchFile) - for _, sketchFilePath := range allSketchFilePaths { - source, err := ioutil.ReadFile(sketchFilePath) - if err != nil { - return nil, i18n.WrapError(err) - } - sketchFilesMap[sketchFilePath] = types.SketchFile{Name: sketchFilePath, Source: string(source)} - } - - mainFile := sketchFilesMap[sketchLocation] - delete(sketchFilesMap, sketchLocation) - - additionalFiles := []types.SketchFile{} - otherSketchFiles := []types.SketchFile{} - mainFileDir := filepath.Dir(mainFile.Name) - for _, sketchFile := range sketchFilesMap { - ext := strings.ToLower(filepath.Ext(sketchFile.Name)) - if MAIN_FILE_VALID_EXTENSIONS[ext] { - if filepath.Dir(sketchFile.Name) == mainFileDir { - otherSketchFiles = append(otherSketchFiles, sketchFile) - } - } else if ADDITIONAL_FILE_VALID_EXTENSIONS[ext] { - if !strings.Contains(filepath.Dir(sketchFile.Name), buildLocation) || buildLocation == "" { - additionalFiles = append(additionalFiles, sketchFile) - } - } else { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_UNKNOWN_SKETCH_EXT, sketchFile.Name) - } - } - - sort.Sort(types.SketchFileSortByName(additionalFiles)) - sort.Sort(types.SketchFileSortByName(otherSketchFiles)) - - return &types.Sketch{MainFile: mainFile, OtherSketchFiles: otherSketchFiles, AdditionalFiles: additionalFiles}, nil -} diff --git a/sketch_saver.go b/sketch_saver.go deleted file mode 100644 index b377e872..00000000 --- a/sketch_saver.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" -) - -type SketchSaver struct{} - -func (s *SketchSaver) Run(ctx *types.Context) error { - sketch := ctx.Sketch - sketchBuildPath := ctx.SketchBuildPath - - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { - return i18n.WrapError(err) - } - - err = utils.WriteFile(filepath.Join(sketchBuildPath, filepath.Base(sketch.MainFile.Name)+".cpp"), ctx.Source) - return i18n.WrapError(err) -} diff --git a/sketch_source_merger.go b/sketch_source_merger.go deleted file mode 100644 index bbfaad0d..00000000 --- a/sketch_source_merger.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "regexp" -) - -type SketchSourceMerger struct{} - -func (s *SketchSourceMerger) Run(ctx *types.Context) error { - sketch := ctx.Sketch - - lineOffset := 0 - includeSection := "" - if !sketchIncludesArduinoH(&sketch.MainFile) { - includeSection += "#include \n" - lineOffset++ - } - includeSection += "#line 1 " + utils.QuoteCppString(sketch.MainFile.Name) + "\n" - lineOffset++ - ctx.IncludeSection = includeSection - - source := includeSection - source += addSourceWrappedWithLineDirective(&sketch.MainFile) - lineOffset += 1 - for _, file := range sketch.OtherSketchFiles { - source += addSourceWrappedWithLineDirective(&file) - } - - ctx.LineOffset = lineOffset - ctx.Source = source - - return nil -} - -func sketchIncludesArduinoH(sketch *types.SketchFile) bool { - if matched, err := regexp.MatchString("(?m)^\\s*#\\s*include\\s*[<\"]Arduino\\.h[>\"]", sketch.Source); err != nil { - panic(err) - } else { - return matched - } -} - -func addSourceWrappedWithLineDirective(sketch *types.SketchFile) string { - source := "#line 1 " + utils.QuoteCppString(sketch.Name) + "\n" - source += sketch.Source - source += "\n" - - return source -} diff --git a/store_build_options_map.go b/store_build_options_map.go deleted file mode 100644 index dc0c3220..00000000 --- a/store_build_options_map.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" -) - -type StoreBuildOptionsMap struct{} - -func (s *StoreBuildOptionsMap) Run(ctx *types.Context) error { - utils.WriteFile(filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE), ctx.BuildOptionsJson) - return nil -} diff --git a/target_board_resolver.go b/target_board_resolver.go deleted file mode 100644 index 4c6d15e0..00000000 --- a/target_board_resolver.go +++ /dev/null @@ -1,137 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "strings" -) - -type TargetBoardResolver struct{} - -func (s *TargetBoardResolver) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - - fqbn := ctx.FQBN - - fqbnParts := strings.Split(fqbn, ":") - if len(fqbnParts) < 3 { - return i18n.ErrorfWithLogger(logger, constants.MSG_FQBN_INVALID, fqbn) - } - targetPackageName := fqbnParts[0] - targetPlatformName := fqbnParts[1] - targetBoardName := fqbnParts[2] - - packages := ctx.Hardware - - targetPackage := packages.Packages[targetPackageName] - if targetPackage == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_PACKAGE_UNKNOWN, targetPackageName) - } - - targetPlatform := targetPackage.Platforms[targetPlatformName] - if targetPlatform == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) - } - - targetBoard := targetPlatform.Boards[targetBoardName] - if targetBoard == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_BOARD_UNKNOWN, targetBoardName, targetPlatformName, targetPackageName) - } - - ctx.TargetPackage = targetPackage - ctx.TargetPlatform = targetPlatform - ctx.TargetBoard = targetBoard - - if len(fqbnParts) > 3 { - addAdditionalPropertiesToTargetBoard(targetBoard, fqbnParts[3]) - } - - core := targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_CORE] - if core == constants.EMPTY_STRING { - core = DEFAULT_BUILD_CORE - } - - var corePlatform *types.Platform - coreParts := strings.Split(core, ":") - if len(coreParts) > 1 { - core = coreParts[1] - if packages.Packages[coreParts[0]] == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_MISSING_CORE_FOR_BOARD, coreParts[0]) - - } - corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatform.PlatformId] - } - - var actualPlatform *types.Platform - if corePlatform != nil { - actualPlatform = corePlatform - } else { - actualPlatform = targetPlatform - } - - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Folder) - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.Folder) - } - - ctx.BuildCore = core - ctx.ActualPlatform = actualPlatform - - return nil -} - -func addAdditionalPropertiesToTargetBoard(board *types.Board, options string) { - optionsParts := strings.Split(options, ",") - optionsParts = utils.Map(optionsParts, utils.TrimSpace) - - for _, optionPart := range optionsParts { - parts := strings.Split(optionPart, "=") - parts = utils.Map(parts, utils.TrimSpace) - - key := parts[0] - value := parts[1] - if key != constants.EMPTY_STRING && value != constants.EMPTY_STRING { - menu := board.Properties.SubTree(constants.BOARD_PROPERTIES_MENU) - if len(menu) == 0 { - return - } - propertiesOfKey := menu.SubTree(key) - if len(propertiesOfKey) == 0 { - return - } - propertiesOfKeyValue := propertiesOfKey.SubTree(value) - board.Properties.Merge(propertiesOfKeyValue) - } - } -} diff --git a/test/.gitignore b/test/.gitignore deleted file mode 100644 index c49bbb5b..00000000 --- a/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -downloaded_* diff --git a/test/add_additional_entries_to_context_test.go b/test/add_additional_entries_to_context_test.go deleted file mode 100644 index daf31135..00000000 --- a/test/add_additional_entries_to_context_test.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "path/filepath" - "testing" -) - -func TestAddAdditionalEntriesToContextNoBuildPath(t *testing.T) { - ctx := &types.Context{} - - command := builder.AddAdditionalEntriesToContext{} - NoError(t, command.Run(ctx)) - - require.Empty(t, ctx.PreprocPath) - require.Empty(t, ctx.SketchBuildPath) - require.Empty(t, ctx.LibrariesBuildPath) - require.Empty(t, ctx.CoreBuildPath) - - require.NotNil(t, ctx.WarningsLevel) - - require.True(t, ctx.CollectedSourceFiles.Empty()) - - require.Equal(t, 0, len(ctx.LibrariesResolutionResults)) -} - -func TestAddAdditionalEntriesToContextWithBuildPath(t *testing.T) { - ctx := &types.Context{} - ctx.BuildPath = "folder" - - command := builder.AddAdditionalEntriesToContext{} - NoError(t, command.Run(ctx)) - - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_PREPROC)), ctx.PreprocPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_SKETCH)), ctx.SketchBuildPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_LIBRARIES)), ctx.LibrariesBuildPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_CORE)), ctx.CoreBuildPath) - - require.NotNil(t, ctx.WarningsLevel) - - require.True(t, ctx.CollectedSourceFiles.Empty()) - - require.Equal(t, 0, len(ctx.LibrariesResolutionResults)) -} diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go deleted file mode 100644 index 34f74b51..00000000 --- a/test/add_build_board_property_if_missing_test.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "path/filepath" - "testing" -) - -func TestAddBuildBoardPropertyIfMissing(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - FQBN: "my_avr_platform:avr:mymega", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.AddBuildBoardPropertyIfMissing{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardId) - require.Equal(t, constants.EMPTY_STRING, targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MYMEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) -} - -func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.AddBuildBoardPropertyIfMissing{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardId) - require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) -} diff --git a/test/additional_sketch_files_copier_test.go b/test/additional_sketch_files_copier_test.go deleted file mode 100644 index 1a138fd0..00000000 --- a/test/additional_sketch_files_copier_test.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "sort" - "testing" - "time" -) - -type ByFileInfoName []os.FileInfo - -func (s ByFileInfoName) Len() int { - return len(s) -} -func (s ByFileInfoName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByFileInfoName) Less(i, j int) bool { - return s[i].Name() < s[j].Name() -} - -func TestCopyOtherFiles(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.SketchLoader{}, - &builder.AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - _, err1 := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) - NoError(t, err1) - - files, err1 := gohasissues.ReadDir(filepath.Join(buildPath, constants.FOLDER_SKETCH)) - NoError(t, err1) - require.Equal(t, 3, len(files)) - - sort.Sort(ByFileInfoName(files)) - require.Equal(t, "header.h", files[0].Name()) - require.Equal(t, "s_file.S", files[1].Name()) - require.Equal(t, "src", files[2].Name()) - - files, err1 = gohasissues.ReadDir(filepath.Join(buildPath, constants.FOLDER_SKETCH, "src")) - NoError(t, err1) - require.Equal(t, 1, len(files)) - require.Equal(t, "helper.h", files[0].Name()) -} - -func TestCopyOtherFilesOnlyIfChanged(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.SketchLoader{}, - &builder.AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - headerStatBefore, err := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) - NoError(t, err) - - time.Sleep(2 * time.Second) - - ctx = &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - BuildPath: buildPath, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - headerStatAfter, err := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) - NoError(t, err) - - require.Equal(t, headerStatBefore.ModTime().Unix(), headerStatAfter.ModTime().Unix()) -} diff --git a/test/builder_test.go b/test/builder_test.go deleted file mode 100644 index da51844e..00000000 --- a/test/builder_test.go +++ /dev/null @@ -1,383 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os" - "os/exec" - "path/filepath" - "testing" - "time" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func prepareBuilderTestContext(sketchPath, fqbn string) *types.Context { - return &types.Context{ - SketchLocation: sketchPath, - FQBN: fqbn, - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - ArduinoAPIVersion: "10600", - Verbose: false, - } -} - -func TestBuilderEmptySketch(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") - ctx.DebugLevel = 10 - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "sketch.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.hex")) - NoError(t, err) -} - -func TestBuilderBridge(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) - NoError(t, err) -} - -func TestBuilderSketchWithConfig(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch_with_config.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch_with_config.ino.hex")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) - NoError(t, err) -} - -func TestBuilderBridgeTwice(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - // Run builder again - command = builder.Builder{} - err = command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) - NoError(t, err) -} - -func TestBuilderBridgeSAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") - ctx.WarningsLevel = "all" - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "syscalls_sam3.c.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "avr", "dtostrf.c.d")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.bin")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) - NoError(t, err) - - cmd := exec.Command(filepath.Join("downloaded_tools", "arm-none-eabi-gcc", "4.8.3-2014q1", "bin", "arm-none-eabi-objdump"), "-f", filepath.Join(buildPath, constants.FOLDER_CORE, "core.a")) - bytes, err := cmd.CombinedOutput() - NoError(t, err) - require.NotContains(t, string(bytes), "variant.cpp.o") -} - -func TestBuilderBridgeRedBearLab(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) - NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) - NoError(t, err) -} - -func TestBuilderSketchNoFunctions(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - require.Error(t, err) -} - -func TestBuilderSketchWithBackup(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchWithOldLib(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchWithSubfolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - NoError(t, os.MkdirAll(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "SPI"), os.FileMode(0755))) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge")) - NoError(t, err) -} - -func TestBuilderWithBuildPathInSketchDir(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") - - var err error - ctx.BuildPath, err = filepath.Abs(filepath.Join("sketch1", "build")) - NoError(t, err) - defer os.RemoveAll(ctx.BuildPath) - - // Run build - command := builder.Builder{} - err = command.Run(ctx) - NoError(t, err) - - // Run build twice, to verify the build still works when the - // build directory is present at the start - err = command.Run(ctx) - NoError(t, err) -} - -func TestBuilderCacheCoreAFile(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") - - SetupBuildPath(t, ctx) - defer os.RemoveAll(ctx.BuildPath) - SetupBuildCachePath(t, ctx) - defer os.RemoveAll(ctx.BuildCachePath) - - // Run build - bldr := builder.Builder{} - err := bldr.Run(ctx) - NoError(t, err) - - // Pick timestamp of cached core - coreFolder := filepath.Join("downloaded_hardware", "arduino", "avr") - coreFileName := builder_utils.GetCachedCoreArchiveFileName(ctx.FQBN, coreFolder) - cachedCoreFile := filepath.Join(ctx.CoreBuildCachePath, coreFileName) - coreStatBefore, err := os.Stat(cachedCoreFile) - require.NoError(t, err) - - // Run build again, to verify that the builder skips rebuilding core.a - err = bldr.Run(ctx) - NoError(t, err) - - coreStatAfterRebuild, err := os.Stat(cachedCoreFile) - require.NoError(t, err) - require.Equal(t, coreStatBefore.ModTime(), coreStatAfterRebuild.ModTime()) - - // Touch a file of the core and check if the builder invalidate the cache - time.Sleep(time.Second) - now := time.Now().Local() - err = os.Chtimes(filepath.Join(coreFolder, "cores", "arduino", "Arduino.h"), now, now) - require.NoError(t, err) - - // Run build again, to verify that the builder rebuilds core.a - err = bldr.Run(ctx) - NoError(t, err) - - coreStatAfterTouch, err := os.Stat(cachedCoreFile) - require.NoError(t, err) - require.NotEqual(t, coreStatBefore.ModTime(), coreStatAfterTouch.ModTime()) -} diff --git a/test/builder_utils_test.go b/test/builder_utils_test.go deleted file mode 100644 index ef07ddf0..00000000 --- a/test/builder_utils_test.go +++ /dev/null @@ -1,188 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "io/ioutil" - "os" - "testing" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" -) - -func sleep(t *testing.T) { - dur, err := time.ParseDuration("1s") - NoError(t, err) - time.Sleep(dur) -} - -func tempFile(t *testing.T, prefix string) string { - file, err := ioutil.TempFile("", prefix) - NoError(t, err) - return file.Name() -} - -func TestObjFileIsUpToDateObjMissing(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, "", "") - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateDepMissing(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, "") - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateObjOlder(t *testing.T) { - ctx := &types.Context{} - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) - - sleep(t) - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateObjNewer(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - sleep(t) - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.True(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsNewer(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - sleep(t) - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) - - sleep(t) - - headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) - - utils.WriteFile(depFile, objFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsOlder(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) - - sleep(t) - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) - - utils.WriteFile(depFile, objFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.True(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsWrong(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) - - sleep(t) - - objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) - depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) - - sleep(t) - - headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) - - utils.WriteFile(depFile, sourceFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} diff --git a/test/create_build_options_map_test.go b/test/create_build_options_map_test.go deleted file mode 100644 index d3fde15e..00000000 --- a/test/create_build_options_map_test.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestCreateBuildOptionsMap(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"hardware", "hardware2"}, - ToolsFolders: []string{"tools"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: "sketchLocation", - FQBN: "fqbn", - ArduinoAPIVersion: "ideVersion", - Verbose: true, - BuildPath: "buildPath", - DebugLevel: 5, - } - - create := builder.CreateBuildOptionsMap{} - err := create.Run(ctx) - NoError(t, err) - - require.Equal(t, "{\n"+ - " \"additionalFiles\": \"\",\n"+ - " \"builtInLibrariesFolders\": \"\",\n"+ - " \"customBuildProperties\": \"\",\n"+ - " \"fqbn\": \"fqbn\",\n"+ - " \"hardwareFolders\": \"hardware,hardware2\",\n"+ - " \"otherLibrariesFolders\": \"libraries\",\n"+ - " \"runtime.ide.version\": \"ideVersion\",\n"+ - " \"sketchLocation\": \"sketchLocation\",\n"+ - " \"toolsFolders\": \"tools\"\n"+ - "}", ctx.BuildOptionsJson) -} diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go deleted file mode 100644 index ddd56dc7..00000000 --- a/test/ctags_runner_test.go +++ /dev/null @@ -1,280 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func TestCTagsRunner(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino")) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "server " + sketchLocation + " /^BridgeServer server;$/;\" kind:variable line:31\n" + - "setup " + sketchLocation + " /^void setup() {$/;\" kind:function line:33 signature:() returntype:void\n" + - "loop " + sketchLocation + " /^void loop() {$/;\" kind:function line:46 signature:() returntype:void\n" + - "process " + sketchLocation + " /^void process(BridgeClient client) {$/;\" kind:function line:62 signature:(BridgeClient client) returntype:void\n" + - "digitalCommand " + sketchLocation + " /^void digitalCommand(BridgeClient client) {$/;\" kind:function line:82 signature:(BridgeClient client) returntype:void\n" + - "analogCommand " + sketchLocation + " /^void analogCommand(BridgeClient client) {$/;\" kind:function line:109 signature:(BridgeClient client) returntype:void\n" + - "modeCommand " + sketchLocation + " /^void modeCommand(BridgeClient client) {$/;\" kind:function line:149 signature:(BridgeClient client) returntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithClass(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, filepath.Join("sketch_with_class", "sketch.ino")) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "set_values\t" + sketchLocation + "\t/^ void set_values (int,int);$/;\"\tkind:prototype\tline:4\tclass:Rectangle\tsignature:(int,int)\treturntype:void\n" + - "area\t" + sketchLocation + "\t/^ int area() {return width*height;}$/;\"\tkind:function\tline:5\tclass:Rectangle\tsignature:()\treturntype:int\n" + - "set_values\t" + sketchLocation + "\t/^void Rectangle::set_values (int x, int y) {$/;\"\tkind:function\tline:8\tclass:Rectangle\tsignature:(int x, int y)\treturntype:void\n" + - "setup\t" + sketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:13\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {$/;\"\tkind:function\tline:17\tsignature:()\treturntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithTypename(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, filepath.Join("sketch_with_typename", "sketch.ino")) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "Foo\t" + sketchLocation + "\t/^ struct Foo{$/;\"\tkind:struct\tline:2\n" + - "setup\t" + sketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:6\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "func\t" + sketchLocation + "\t/^typename Foo::Bar func(){$/;\"\tkind:function\tline:12\tsignature:()\treturntype:Foo::Bar\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithNamespace(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, filepath.Join("sketch_with_namespace", "sketch.ino")) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "value\t" + sketchLocation + "\t/^\tint value() {$/;\"\tkind:function\tline:2\tnamespace:Test\tsignature:()\treturntype:int\n" + - "setup\t" + sketchLocation + "\t/^void setup() {}$/;\"\tkind:function\tline:7\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:8\tsignature:()\treturntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithTemplates(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, filepath.Join("sketch_with_templates_and_shift", "template_and_shift.cpp")) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "printGyro\t" + sketchLocation + "\t/^void printGyro()$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "bVar\t" + sketchLocation + "\t/^c< 8 > bVar;$/;\"\tkind:variable\tline:15\n" + - "aVar\t" + sketchLocation + "\t/^c< 1<<8 > aVar;$/;\"\tkind:variable\tline:16\n" + - "func\t" + sketchLocation + "\t/^template func( c< 1< & aParam) {$/;\"\tkind:function\tline:18\tsignature:( c< 1< & aParam)\treturntype:template\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} diff --git a/test/dependent_libraries/library1/library1.h b/test/dependent_libraries/library1/library1.h deleted file mode 100644 index 20e0d9eb..00000000 --- a/test/dependent_libraries/library1/library1.h +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/dependent_libraries/library2/library2.h b/test/dependent_libraries/library2/library2.h deleted file mode 100644 index a5d75ad7..00000000 --- a/test/dependent_libraries/library2/library2.h +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/dependent_libraries/library3/library3.cpp b/test/dependent_libraries/library3/library3.cpp deleted file mode 100644 index be5c8d45..00000000 --- a/test/dependent_libraries/library3/library3.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include -#include \ No newline at end of file diff --git a/test/dependent_libraries/library3/library3.h b/test/dependent_libraries/library3/library3.h deleted file mode 100644 index 0be00b9c..00000000 --- a/test/dependent_libraries/library3/library3.h +++ /dev/null @@ -1 +0,0 @@ -#warning included! \ No newline at end of file diff --git a/test/dependent_libraries/library4/library4.h b/test/dependent_libraries/library4/library4.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/eol_processing/sketch.ino b/test/eol_processing/sketch.ino deleted file mode 100644 index 9037a7fa..00000000 --- a/test/eol_processing/sketch.ino +++ /dev/null @@ -1 +0,0 @@ -int led = 7; void setup() { } void loop() { } \ No newline at end of file diff --git a/test/fail_if_buildpath_equals_sketchpath_test.go b/test/fail_if_buildpath_equals_sketchpath_test.go deleted file mode 100644 index b29dc361..00000000 --- a/test/fail_if_buildpath_equals_sketchpath_test.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestFailIfBuildPathEqualsSketchPath(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "buildPath/sketch.ino", - BuildPath: "buildPath", - } - - command := builder.FailIfBuildPathEqualsSketchPath{} - require.Error(t, command.Run(ctx)) -} - -func TestFailIfBuildPathEqualsSketchPathSketchPathDiffers(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "sketchPath/sketch.ino", - BuildPath: "buildPath", - } - - command := builder.FailIfBuildPathEqualsSketchPath{} - NoError(t, command.Run(ctx)) -} diff --git a/test/generate_buildpath_if_missing_test.go b/test/generate_buildpath_if_missing_test.go deleted file mode 100644 index 05d17e22..00000000 --- a/test/generate_buildpath_if_missing_test.go +++ /dev/null @@ -1,100 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" -) - -func TestGenerateBuildPathIfMissing(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "test", - } - - command := builder.GenerateBuildPathIfMissing{} - err := command.Run(ctx) - NoError(t, err) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) - _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - require.True(t, os.IsNotExist(err)) -} - -func TestGenerateBuildPathIfEmpty(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "test", - } - - createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} - err := createBuildPathIfMissing.Run(ctx) - NoError(t, err) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) - _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - require.True(t, os.IsNotExist(err)) -} - -func TestDontGenerateBuildPathIfPresent(t *testing.T) { - ctx := &types.Context{} - ctx.BuildPath = "test" - - createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} - err := createBuildPathIfMissing.Run(ctx) - NoError(t, err) - - require.Equal(t, "test", ctx.BuildPath) -} - -func TestGenerateBuildPathAndEnsureItExists(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "test", - } - - commands := []types.Command{ - &builder.GenerateBuildPathIfMissing{}, - &builder.EnsureBuildPathExists{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - defer os.RemoveAll(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) - _, err := os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - NoError(t, err) -} diff --git a/test/hardware/arduino/avr/boards.local.txt b/test/hardware/arduino/avr/boards.local.txt deleted file mode 100644 index b3f7e812..00000000 --- a/test/hardware/arduino/avr/boards.local.txt +++ /dev/null @@ -1,11 +0,0 @@ -## Arduino Duemilanove or Diecimila w/ ATmega123 -## --------------------------------------------- -diecimila.menu.cpu.atmega123=ATmega123 - -diecimila.menu.cpu.atmega123.upload.maximum_size=14336 -diecimila.menu.cpu.atmega123.upload.maximum_data_size=1024 -diecimila.menu.cpu.atmega123.upload.speed=19200 - -diecimila.menu.cpu.atmega123.bootloader.high_fuses=0xdd -diecimila.menu.cpu.atmega123.bootloader.extended_fuses=0x00 -diecimila.menu.cpu.atmega123.bootloader.file=atmega/ATmegaBOOT_123_diecimila.hex diff --git a/test/hardware/arduino/avr/boards.txt b/test/hardware/arduino/avr/boards.txt deleted file mode 100644 index bcea2331..00000000 --- a/test/hardware/arduino/avr/boards.txt +++ /dev/null @@ -1,18 +0,0 @@ - -micro.vid.4=0x2341 -micro.pid.4=0x0237 -# If the board is a 2341:0237 use 2341:8237 for build and set -# other parameters as well -micro.vid.4.build.vid=0x2341 -micro.vid.4.build.pid=0x8237 -micro.vid.4.build.usb_product="Genuino Micro" -micro.vid.4.bootloader.file=caterina/Caterina-Genuino-Micro.hex - -micro.vid.5=0x2341 -micro.pid.5=0x8237 -# If the board is a 2341:8237 use 2341:8237 for build and set -# other paramters as well -micro.vid.5.build.vid=0x2341 -micro.vid.5.build.pid=0x8237 -micro.vid.5.build.usb_product="Genuino Micro" -micro.vid.5.bootloader.file=caterina/Caterina-Genuino-Micro.hex diff --git a/test/hardware/arduino/avr/platform.local.txt b/test/hardware/arduino/avr/platform.local.txt deleted file mode 100644 index aef16166..00000000 --- a/test/hardware/arduino/avr/platform.local.txt +++ /dev/null @@ -1 +0,0 @@ -tools.avrdude.cmd.path=/my/personal/avrdude \ No newline at end of file diff --git a/test/hardware/platform.txt b/test/hardware/platform.txt deleted file mode 100644 index 8b137891..00000000 --- a/test/hardware/platform.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/test/hardware/watterott/avr/boards.txt b/test/hardware/watterott/avr/boards.txt deleted file mode 100644 index be844787..00000000 --- a/test/hardware/watterott/avr/boards.txt +++ /dev/null @@ -1,130 +0,0 @@ -# VID 0x6666 is a prototype product Vendor ID -# http://www.linux-usb.org/usb.ids - -menu.speed=Speed -menu.core=Core -menu.info=Info - - -# ATmega32u4 @ 16 MHz -atmega32u4.name=ATmega32u4 -atmega32u4.menu.speed.16mhz=16 MHz -atmega32u4.menu.speed.16mhz.build.f_cpu=16000000L -atmega32u4.menu.speed.16mhz.bootloader.file=caterina_16mhz.hex -atmega32u4.menu.speed.8mhz=8 MHz -atmega32u4.menu.speed.8mhz.build.f_cpu=8000000L -atmega32u4.menu.speed.8mhz.bootloader.file=caterina_8mhz.hex -atmega32u4.vid.0=0x1D50 -atmega32u4.pid.0=0x60B0 -atmega32u4.vid.1=0x6666 -atmega32u4.pid.1=0x60B0 -atmega32u4.vid.2=0x2341 -atmega32u4.pid.2=0x0036 -atmega32u4.vid.3=0x2341 -atmega32u4.pid.3=0x8036 -atmega32u4.vid.4=0x2A03 -atmega32u4.pid.4=0x0036 -atmega32u4.vid.5=0x2A03 -atmega32u4.pid.5=0x8036 -atmega32u4.bootloader.tool=avrdude -atmega32u4.bootloader.low_fuses=0xff -atmega32u4.bootloader.high_fuses=0xd8 -atmega32u4.bootloader.extended_fuses=0xcb -#atmega32u4.bootloader.file=caterina_16mhz.hex -atmega32u4.bootloader.unlock_bits=0x3F -atmega32u4.bootloader.lock_bits=0x2F -atmega32u4.upload.tool=avrdude -atmega32u4.upload.protocol=avr109 -atmega32u4.upload.maximum_size=28672 -atmega32u4.upload.maximum_data_size=2560 -atmega32u4.upload.speed=57600 -atmega32u4.upload.disable_flushing=true -atmega32u4.upload.use_1200bps_touch=true -atmega32u4.upload.wait_for_upload_port=true -atmega32u4.build.mcu=atmega32u4 -#atmega32u4.build.f_cpu=16000000L -atmega32u4.build.vid=0x6666 -atmega32u4.build.pid=0x60B0 -atmega32u4.build.usb_product="USB IO Board" -atmega32u4.build.usb_manufacturer="ATmega32u4" -atmega32u4.build.board=AVR_LEONARDO -atmega32u4.build.core=arduino:arduino -atmega32u4.build.variant=leonardo -atmega32u4.build.extra_flags={build.usb_flags} -DMOUSE_ABS_ENABLED - - -# ATtiny841 @ internal 8 MHz -attiny841.name=ATtiny841 (8 MHz) -# use Standard Arduino Core -attiny841.menu.core.arduino=Standard Arduino -attiny841.menu.core.arduino.build.core=arduino:arduino -attiny841.menu.core.arduino.build.variant=tiny14 -# use Spence Konde Core: https://github.com/SpenceKonde/arduino-tiny-841/ -attiny841.menu.core.spencekonde=ATtiny841 (by Spence Konde) -#attiny841.menu.core.spencekonde.build.core=arduino-tiny-841:tiny -attiny841.menu.core.spencekonde.build.core=tiny841 -attiny841.menu.core.spencekonde.build.variant=tiny14 -# info menu item -attiny841.menu.info.info=Press Reset, when Uploading is shown. -attiny841.vid.0=0x16D0 -attiny841.pid.0=0x0753 -attiny841.bootloader.tool=avrdude -attiny841.bootloader.low_fuses=0xE2 -attiny841.bootloader.high_fuses=0xDD -attiny841.bootloader.extended_fuses=0xFE -attiny841.bootloader.unlock_bits=0xFF -attiny841.bootloader.lock_bits=0xFF -attiny841.bootloader.file=micronucleus-t841.hex -attiny841.upload.tool=micronucleus -attiny841.upload.protocol=usb -attiny841.upload.wait_for_upload_port=false -attiny841.upload.use_1200bps_touch=false -attiny841.upload.disable_flushing=false -attiny841.upload.maximum_size=6500 -attiny841.build.mcu=attiny841 -attiny841.build.f_cpu=8000000L -attiny841.build.board=AVR_ATTINY841 -#attiny841.build.core=arduino:arduino -#attiny841.build.variant=tiny14 - - -# ATtiny85 @ internal 16.5 MHz -attiny85.name=ATtiny85 (16.5 MHz) -# use Standard Arduino Core -attiny85.menu.core.arduino=Standard Arduino -attiny85.menu.core.arduino.build.board=AVR_ATTINY85 -attiny85.menu.core.arduino.build.core=arduino:arduino -attiny85.menu.core.arduino.build.variant=tiny8 -# use Spence Konde Core: https://github.com/SpenceKonde/ATTinyCore -attiny85.menu.core.spencekonde=ATtiny85 (by Spence Konde) -attiny85.menu.core.spencekonde.build.board=AVR_ATTINY85 -#attiny85.menu.core.spencekonde.build.core=ATTinyCore:tiny -attiny85.menu.core.spencekonde.build.core=tiny85 -attiny85.menu.core.spencekonde.build.variant=tiny8 -# use Digistump Core: https://github.com/digistump/DigistumpArduino -attiny85.menu.core.digistump=Digistump/Digispark -attiny85.menu.core.digistump.build.board=AVR_DIGISPARK -attiny85.menu.core.digistump.build.core=digistump:tiny -attiny85.menu.core.digistump.build.variant=digispark -# info menu item -attiny85.menu.info.info=Press Reset, when Uploading is shown. -attiny85.vid.0=0x16D0 -attiny85.pid.0=0x0753 -attiny85.bootloader.tool=avrdude -attiny85.bootloader.low_fuses=0xE1 -attiny85.bootloader.high_fuses=0xDD -attiny85.bootloader.extended_fuses=0xFE -attiny85.bootloader.unlock_bits=0xFF -attiny85.bootloader.lock_bits=0xFF -attiny85.bootloader.file=micronucleus-t85.hex -attiny85.upload.tool=micronucleus -attiny85.upload.protocol=usb -attiny85.upload.wait_for_upload_port=false -attiny85.upload.use_1200bps_touch=false -attiny85.upload.disable_flushing=false -attiny85.upload.maximum_size=6300 -attiny85.build.mcu=attiny85 -attiny85.build.f_cpu=16500000L -attiny85.build.board=AVR_ATTINY85 -#attiny85.build.core=arduino:arduino -#attiny85.build.variant=tiny8 diff --git a/test/hardware/watterott/avr/platform.txt b/test/hardware/watterott/avr/platform.txt deleted file mode 100644 index 13d46cea..00000000 --- a/test/hardware/watterott/avr/platform.txt +++ /dev/null @@ -1,146 +0,0 @@ - -# Watterott AVR Core and platform. -# ------------------------------ -# -# For more info: -# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification - -name=Watterott AVR Boards -version=1.0.0 - -# AVR compile variables -# --------------------- - -compiler.warning_flags=-w -compiler.warning_flags.none=-w -compiler.warning_flags.default= -compiler.warning_flags.more=-Wall -compiler.warning_flags.all=-Wall -Wextra - -# Default "compiler.path" is correct, change only if you want to overidde the initial value -#compiler.path={runtime.ide.path}/hardware/tools/avr/bin/ -compiler.path={runtime.tools.avr-gcc.path}/bin/ -compiler.c.cmd=avr-gcc -compiler.c.flags=-c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD -# -w flag added to avoid printing a wrong warning http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59396 -# This is fixed in gcc 4.8.3 and will be removed as soon as we update the toolchain -compiler.c.elf.flags=-Os {compiler.warning_flags} -Wl,--gc-sections -compiler.c.elf.cmd=avr-gcc -compiler.S.flags=-c -g -x assembler-with-cpp -compiler.cpp.cmd=avr-g++ -compiler.cpp.flags=-c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -compiler.ar.cmd=avr-ar -compiler.ar.flags=rcs -compiler.objcopy.cmd=avr-objcopy -compiler.objcopy.eep.flags=-O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 -compiler.elf2hex.flags=-O ihex -R .eeprom -compiler.elf2hex.cmd=avr-objcopy -compiler.ldflags= -compiler.size.cmd=avr-size - -# This can be overriden in boards.txt -build.extra_flags= - -# These can be overridden in platform.local.txt -compiler.c.extra_flags= -compiler.c.elf.extra_flags= -compiler.S.extra_flags= -compiler.cpp.extra_flags= -compiler.ar.extra_flags= -compiler.objcopy.eep.extra_flags= -compiler.elf2hex.extra_flags= - -# AVR compile patterns -# -------------------- - -## Compile c files -recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Compile c++ files -recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Compile S files -recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.S.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Create archives -recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}" - -## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" {object_files} "{build.path}/{archive_file}" "-L{build.path}" -lm - -## Create output files (.eep and .hex) -recipe.objcopy.eep.pattern="{compiler.path}{compiler.objcopy.cmd}" {compiler.objcopy.eep.flags} {compiler.objcopy.eep.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.eep" -recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex" - -## Save hex -recipe.output.tmp_file={build.project_name}.hex -recipe.output.save_file={build.project_name}.{build.variant}.hex - -## Compute size -recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf" -recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).* -recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).* -recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).* - -## Preprocessor -preproc.includes.flags=-w -x c++ -M -MG -MP -recipe.preproc.includes="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -preproc.macros.flags=-w -x c++ -E -CC -recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" - - -# AVR Uploader/Programmers tools -# ------------------------------ - -## AVRdude -#tools.avrdude.path={runtime.ide.path}/hardware/tools/avr/ -tools.avrdude.path={runtime.tools.avrdude.path} -tools.avrdude.cmd.path={path}/bin/avrdude -#tools.avrdude.config.path={path}/etc/avrdude.conf -tools.avrdude.config.path={runtime.platform.path}/tools/avrdude.conf - -tools.avrdude.upload.params.verbose=-v -tools.avrdude.upload.params.quiet=-q -q -tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i" - -tools.avrdude.program.params.verbose=-v -tools.avrdude.program.params.quiet=-q -q -tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i" - -tools.avrdude.erase.params.verbose=-v -tools.avrdude.erase.params.quiet=-q -q -tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m - -tools.avrdude.bootloader.params.verbose=-v -tools.avrdude.bootloader.params.quiet=-q -q -tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m - -## Micronucleus -tools.micronucleus.path={runtime.tools.micronucleus.path} -tools.micronucleus.cmd=micronucleus -tools.micronucleus.cmd.windows=micronucleus.exe - -tools.micronucleus.upload.params.verbose= -tools.micronucleus.upload.params.quiet= -tools.micronucleus.upload.pattern="{path}/{cmd}" --run --timeout 60 "{build.path}/{build.project_name}.hex" - -tools.micronucleus.program.params.verbose= -tools.micronucleus.program.params.quiet= -tools.micronucleus.program.pattern="{path}/{cmd}" --run --timeout 60 "{build.path}/{build.project_name}.hex" - -tools.micronucleus.erase.params.verbose= -tools.micronucleus.erase.params.quiet= -tools.micronucleus.erase.pattern= -#tools.micronucleus.erase.pattern="{path}/{cmd}" --erase-only --timeout 60 - -tools.micronucleus.bootloader.params.verbose= -tools.micronucleus.bootloader.params.quiet= -tools.micronucleus.bootloader.pattern="{path}/{cmd}" --run --timeout 60 "{runtime.platform.path}/bootloaders/{bootloader.file}" - - -# USB Default Flags -# Default blank usb manufacturer will be filled it at compile time -# - from numeric vendor ID, set to Unknown otherwise -build.usb_manufacturer="Unknown" -build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' - diff --git a/test/hardware/watterott/avr/programmers.txt b/test/hardware/watterott/avr/programmers.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go deleted file mode 100644 index 147396e7..00000000 --- a/test/hardware_loader_test.go +++ /dev/null @@ -1,243 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "path/filepath" - "runtime" - "testing" -) - -func TestLoadHardware(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware"}, - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - require.Equal(t, 2, len(packages.Packages)) - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].Properties[constants.ID]) - - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].BoardId) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].Properties["upload.wait_for_upload_port"]) - - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Boards["robotMotor"].Properties["build.extra_flags"]) - - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Boards["arduino_due_x"].BoardId) - - require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Boards["diecimila"].Properties["menu.cpu.atmega123"]) - - avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties[constants.PLATFORM_NAME]) - require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) - - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) - - require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) -} - -func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"}, - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.PlatformKeysRewriteLoader{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - - if runtime.GOOS == "windows" { - //a package is a symlink, and windows does not support them - require.Equal(t, 3, len(packages.Packages)) - } else { - require.Equal(t, 4, len(packages.Packages)) - } - - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].Properties[constants.ID]) - - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].BoardId) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].Properties["upload.wait_for_upload_port"]) - - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Boards["robotMotor"].Properties["build.extra_flags"]) - - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Boards["arduino_due_x"].BoardId) - - avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties[constants.PLATFORM_NAME]) - require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) - - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) - - require.Equal(t, "-w -x c++ -M -MG -MP", avrPlatform.Properties["preproc.includes.flags"]) - require.Equal(t, "-w -x c++ -E -CC", avrPlatform.Properties["preproc.macros.flags"]) - require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties[constants.RECIPE_PREPROC_INCLUDES]) - require.False(t, utils.MapStringStringHas(avrPlatform.Properties, "preproc.macros.compatibility_flags")) - - require.NotNil(t, packages.Packages["my_avr_platform"]) - myAVRPlatform := packages.Packages["my_avr_platform"] - require.Equal(t, "hello world", myAVRPlatform.Properties["example"]) - myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"] - require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardId) - - require.False(t, utils.MapStringStringHas(myAVRPlatformAvrArch.Properties, "preproc.includes.flags")) - - require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) - - if runtime.GOOS != "windows" { - require.NotNil(t, packages.Packages["my_symlinked_avr_platform"]) - require.NotNil(t, packages.Packages["my_symlinked_avr_platform"].Platforms["avr"]) - } -} - -func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff"}, - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - require.Equal(t, 3, len(packages.Packages)) - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 1, len(packages.Packages["arduino"].Platforms)) - require.NotNil(t, packages.Packages["RedBearLab"]) - require.Equal(t, 1, len(packages.Packages["RedBearLab"].Platforms)) - require.NotNil(t, packages.Packages["RFduino"]) - require.Equal(t, 0, len(packages.Packages["RFduino"].Platforms)) - - samdPlatform := packages.Packages["arduino"].Platforms["samd"] - require.Equal(t, 3, len(samdPlatform.Boards)) - - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardId) - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties[constants.ID]) - - require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties["build.variant"]) - require.Equal(t, "-D__SAMD21G18A__ {build.usb_flags}", samdPlatform.Boards["arduino_zero_native"].Properties["build.extra_flags"]) - - require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties[constants.PLATFORM_NAME]) - require.Equal(t, "-d3", samdPlatform.Properties["tools.openocd.erase.params.verbose"]) - - require.Equal(t, 3, len(samdPlatform.Programmers)) - - require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"][constants.PROGRAMMER_NAME]) - require.Equal(t, "openocd", samdPlatform.Programmers["edbg"]["program.tool"]) - - avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"] - require.Equal(t, 3, len(avrRedBearPlatform.Boards)) - - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardId) - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties[constants.ID]) - require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties[constants.BUILD_PROPERTIES_BUILD_CORE]) -} - -func TestLoadLotsOfHardware(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"}, - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - - if runtime.GOOS == "windows" { - //a package is a symlink, and windows does not support them - require.Equal(t, 5, len(packages.Packages)) - } else { - require.Equal(t, 6, len(packages.Packages)) - } - - require.NotNil(t, packages.Packages["arduino"]) - require.NotNil(t, packages.Packages["my_avr_platform"]) - - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, 20, len(packages.Packages["arduino"].Platforms["avr"].Boards)) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms["sam"].Boards)) - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Boards)) - - require.Equal(t, 1, len(packages.Packages["my_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_avr_platform"].Platforms["avr"].Boards)) - - if runtime.GOOS != "windows" { - require.Equal(t, 1, len(packages.Packages["my_symlinked_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_symlinked_avr_platform"].Platforms["avr"].Boards)) - } -} diff --git a/test/helper.go b/test/helper.go deleted file mode 100644 index b3452c7e..00000000 --- a/test/helper.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "bytes" - "fmt" - "io/ioutil" - "path/filepath" - "testing" - "text/template" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/go-errors/errors" - "github.com/stretchr/testify/assert" -) - -func LoadAndInterpolate(t *testing.T, filename string, ctx *types.Context) string { - funcsMap := template.FuncMap{ - "QuoteCppString": utils.QuoteCppString, - } - - tpl, err := template.New(filepath.Base(filename)).Funcs(funcsMap).ParseFiles(filename) - NoError(t, err) - - var buf bytes.Buffer - data := make(map[string]interface{}) - data["sketch"] = ctx.Sketch - err = tpl.Execute(&buf, data) - NoError(t, err) - - return buf.String() -} - -func Abs(t *testing.T, rel string) string { - toolPath, err := filepath.Abs(rel) - NoError(t, err) - return toolPath -} - -func NoError(t *testing.T, err error, msgAndArgs ...interface{}) { - if !assert.NoError(t, err, msgAndArgs...) { - switch err.(type) { - case *errors.Error: - fmt.Println(err.(*errors.Error).ErrorStack()) - } - t.FailNow() - } -} - -func SetupBuildPath(t *testing.T, ctx *types.Context) string { - buildPath, err := ioutil.TempDir(constants.EMPTY_STRING, "test_build_path") - NoError(t, err) - ctx.BuildPath = buildPath - return buildPath -} - -func SetupBuildCachePath(t *testing.T, ctx *types.Context) string { - buildCachePath, err := ioutil.TempDir(constants.EMPTY_STRING, "test_build_cache") - NoError(t, err) - ctx.BuildCachePath = buildCachePath - return buildCachePath -} - -type ByLibraryName []*types.Library - -func (s ByLibraryName) Len() int { - return len(s) -} -func (s ByLibraryName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByLibraryName) Less(i, j int) bool { - return s[i].Name < s[j].Name -} diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go deleted file mode 100644 index 49aa8470..00000000 --- a/test/helper_tools_downloader.go +++ /dev/null @@ -1,872 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" - "github.com/go-errors/errors" -) - -const HARDWARE_FOLDER = "downloaded_hardware" -const BOARD_MANAGER_FOLDER = "downloaded_board_manager_stuff" -const TOOLS_FOLDER = "downloaded_tools" -const LIBRARIES_FOLDER = "downloaded_libraries" -const PATCHES_FOLDER = "downloaded_stuff_patches" - -type Tool struct { - Name string - Package string - Version string - OsUrls []OsUrl -} - -type OsUrl struct { - Os string - Url string -} - -type Library struct { - Name string - Version string - VersionInLibProperties string - Url string -} - -type Core struct { - Maintainer string - Arch string - Version string - Url string -} - -func DownloadCoresAndToolsAndLibraries(t *testing.T) { - cores := []Core{ - Core{Maintainer: "arduino", Arch: "avr", Version: "1.6.10"}, - Core{Maintainer: "arduino", Arch: "sam", Version: "1.6.7"}, - } - - boardsManagerCores := []Core{ - Core{Maintainer: "arduino", Arch: "samd", Version: "1.6.5"}, - } - - boardsManagerRedBearCores := []Core{ - Core{Maintainer: "RedBearLab", Arch: "avr", Version: "1.0.0", Url: "https://redbearlab.github.io/arduino/Blend/blend_boards.zip"}, - } - - toolsMultipleVersions := []Tool{ - Tool{Name: "bossac", Version: "1.6.1-arduino"}, - Tool{Name: "bossac", Version: "1.5-arduino"}, - } - - tools := []Tool{ - Tool{Name: "avrdude", Version: "6.0.1-arduino5"}, - Tool{Name: "avr-gcc", Version: "4.8.1-arduino5"}, - Tool{Name: "arm-none-eabi-gcc", Version: "4.8.3-2014q1"}, - Tool{Name: "ctags", Version: "5.8-arduino11", - OsUrls: []OsUrl{ - OsUrl{Os: "i686-pc-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-i686-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "x86_64-pc-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-x86_64-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "i686-mingw32", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-i686-mingw32.zip"}, - OsUrl{Os: "x86_64-apple-darwin", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-x86_64-apple-darwin.zip"}, - OsUrl{Os: "arm-linux-gnueabihf", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-armv6-linux-gnueabihf.tar.bz2"}, - OsUrl{Os: "aarch64-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-aarch64-linux-gnu.tar.bz2"}, - }, - }, - Tool{Name: "arduino-preprocessor", Version: "0.1.5", - OsUrls: []OsUrl{ - OsUrl{Os: "i686-pc-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-i686-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "x86_64-pc-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-x86_64-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "i686-mingw32", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-i686-w64-mingw32.tar.bz2"}, - OsUrl{Os: "x86_64-apple-darwin", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-x86_64-apple-darwin11.tar.bz2"}, - OsUrl{Os: "arm-linux-gnueabihf", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-arm-linux-gnueabihf.tar.bz2"}, - OsUrl{Os: "aarch64-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-aarch64-linux-gnu.tar.bz2"}, - }, - }, - } - - boardsManagerTools := []Tool{ - Tool{Name: "openocd", Version: "0.9.0-arduino", Package: "arduino"}, - Tool{Name: "CMSIS", Version: "4.0.0-atmel", Package: "arduino"}, - } - - boardsManagerRFduinoTools := []Tool{ - Tool{Name: "arm-none-eabi-gcc", Version: "4.8.3-2014q1", Package: "RFduino"}, - } - - libraries := []Library{ - Library{Name: "Audio", Version: "1.0.4"}, - Library{Name: "Adafruit PN532", Version: "1.0.0"}, - Library{Name: "Bridge", Version: "1.6.1"}, - Library{Name: "CapacitiveSensor", Version: "0.5.0", VersionInLibProperties: "0.5"}, - Library{Name: "Ethernet", Version: "1.1.1"}, - Library{Name: "Robot IR Remote", Version: "1.0.2"}, - Library{Name: "FastLED", Version: "3.1.0"}, - } - - download(t, cores, boardsManagerCores, boardsManagerRedBearCores, tools, toolsMultipleVersions, boardsManagerTools, boardsManagerRFduinoTools, libraries) - - patchFiles(t) -} - -func patchFiles(t *testing.T) { - err := utils.EnsureFolderExists(PATCHES_FOLDER) - NoError(t, err) - files, err := ioutil.ReadDir(PATCHES_FOLDER) - NoError(t, err) - - for _, file := range files { - if filepath.Ext(file.Name()) == ".patch" { - panic("Patching for downloaded tools is not available! (see https://github.com/arduino/arduino-builder/issues/147)") - // XXX: find an alternative to x/codereview/patch - // https://github.com/arduino/arduino-builder/issues/147 - /* - data, err := ioutil.ReadFile(Abs(t, filepath.Join(PATCHES_FOLDER, file.Name()))) - NoError(t, err) - patchSet, err := patch.Parse(data) - NoError(t, err) - operations, err := patchSet.Apply(ioutil.ReadFile) - for _, op := range operations { - utils.WriteFileBytes(op.Dst, op.Data) - } - */ - } - } -} - -func download(t *testing.T, cores, boardsManagerCores, boardsManagerRedBearCores []Core, tools, toolsMultipleVersions, boardsManagerTools, boardsManagerRFduinoTools []Tool, libraries []Library) { - allCoresDownloaded, err := allCoresAlreadyDownloadedAndUnpacked(HARDWARE_FOLDER, cores) - NoError(t, err) - if allCoresDownloaded && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerCores) && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerRedBearCores) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerTools) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerRFduinoTools) && - allToolsAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, tools) && - allToolsAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, toolsMultipleVersions) && - allLibrariesAlreadyDownloadedAndUnpacked(LIBRARIES_FOLDER, libraries) { - return - } - - index, err := downloadIndex("http://downloads.arduino.cc/packages/package_index.json") - NoError(t, err) - - err = downloadCores(cores, index) - NoError(t, err) - - err = downloadBoardManagerCores(boardsManagerCores, index) - NoError(t, err) - - err = downloadTools(tools, index) - NoError(t, err) - - err = downloadToolsMultipleVersions(toolsMultipleVersions, index) - NoError(t, err) - - err = downloadBoardsManagerTools(boardsManagerTools, index) - NoError(t, err) - - rfduinoIndex, err := downloadIndex("http://downloads.arduino.cc/packages/test_package_rfduino_index.json") - NoError(t, err) - - err = downloadBoardsManagerTools(boardsManagerRFduinoTools, rfduinoIndex) - NoError(t, err) - - err = downloadBoardManagerCores(boardsManagerRedBearCores, nil) - NoError(t, err) - - librariesIndex, err := downloadIndex("http://downloads.arduino.cc/libraries/library_index.json") - NoError(t, err) - - err = downloadLibraries(libraries, librariesIndex) - NoError(t, err) -} - -func downloadIndex(url string) (map[string]interface{}, error) { - res, err := http.Get(url) - if err != nil { - return nil, err - } - - bytes, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - res.Body.Close() - - index := make(map[string]interface{}) - err = json.Unmarshal(bytes, &index) - if err != nil { - return nil, err - } - - return index, nil -} - -func downloadCores(cores []Core, index map[string]interface{}) error { - for _, core := range cores { - url, err := findCoreUrl(index, core) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackCore(core, url, HARDWARE_FOLDER) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func downloadBoardManagerCores(cores []Core, index map[string]interface{}) error { - for _, core := range cores { - url, err := findCoreUrl(index, core) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackBoardManagerCore(core, url, BOARD_MANAGER_FOLDER) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func findCoreUrl(index map[string]interface{}, core Core) (string, error) { - if core.Url != "" { - return core.Url, nil - } - packages := index["packages"].([]interface{}) - for _, p := range packages { - pack := p.(map[string]interface{}) - if pack[constants.PACKAGE_NAME].(string) == core.Maintainer { - packagePlatforms := pack["platforms"].([]interface{}) - for _, pt := range packagePlatforms { - packagePlatform := pt.(map[string]interface{}) - if packagePlatform[constants.PLATFORM_ARCHITECTURE] == core.Arch && packagePlatform[constants.PLATFORM_VERSION] == core.Version { - return packagePlatform[constants.PLATFORM_URL].(string), nil - } - } - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find tool " + core.Maintainer + " " + core.Arch + " " + core.Version) -} - -func downloadTools(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackTool(tool, url, TOOLS_FOLDER, true) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func downloadToolsMultipleVersions(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - if !toolAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, tool) { - _, err := os.Stat(filepath.Join(TOOLS_FOLDER, tool.Name)) - if err == nil { - err = os.RemoveAll(filepath.Join(TOOLS_FOLDER, tool.Name)) - if err != nil { - return i18n.WrapError(err) - } - } - } - } - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackTool(tool, url, TOOLS_FOLDER, false) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func downloadBoardsManagerTools(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackBoardsManagerTool(tool, url, BOARD_MANAGER_FOLDER) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath string, cores []Core) bool { - for _, core := range cores { - if !boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { - return false - } - } - return true -} - -func boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath string, core Core) bool { - _, err := os.Stat(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) - return !os.IsNotExist(err) -} - -func allCoresAlreadyDownloadedAndUnpacked(targetPath string, cores []Core) (bool, error) { - for _, core := range cores { - alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) - if err != nil { - return false, i18n.WrapError(err) - } - if !alreadyDownloaded { - return false, nil - } - } - return true, nil -} - -func coreAlreadyDownloadedAndUnpacked(targetPath string, core Core) (bool, error) { - corePath := filepath.Join(targetPath, core.Maintainer, core.Arch) - - _, err := os.Stat(corePath) - if os.IsNotExist(err) { - return false, nil - } - platform, err := properties.Load(filepath.Join(corePath, "platform.txt")) - if err != nil { - return false, i18n.WrapError(err) - } - - if core.Version != platform["version"] { - err := os.RemoveAll(corePath) - return false, i18n.WrapError(err) - } - - return true, nil -} - -func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath string, tools []Tool) bool { - for _, tool := range tools { - if !boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return false - } - } - return true -} - -func boardManagerToolAlreadyDownloadedAndUnpacked(targetPath string, tool Tool) bool { - _, err := os.Stat(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - return !os.IsNotExist(err) -} - -func allToolsAlreadyDownloadedAndUnpacked(targetPath string, tools []Tool) bool { - for _, tool := range tools { - if !toolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return false - } - } - return true -} - -func toolAlreadyDownloadedAndUnpacked(targetPath string, tool Tool) bool { - _, err := os.Stat(filepath.Join(targetPath, tool.Name, tool.Version)) - return !os.IsNotExist(err) -} - -func allLibrariesAlreadyDownloadedAndUnpacked(targetPath string, libraries []Library) bool { - for _, library := range libraries { - if !libraryAlreadyDownloadedAndUnpacked(targetPath, library) { - return false - } - } - return true -} - -func libraryAlreadyDownloadedAndUnpacked(targetPath string, library Library) bool { - _, err := os.Stat(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if os.IsNotExist(err) { - return false - } - - libProps, err := properties.Load(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1), "library.properties")) - if err != nil { - return false - } - return libProps["version"] == library.Version || libProps["version"] == library.VersionInLibProperties -} - -func downloadAndUnpackCore(core Core, url string, targetPath string) error { - alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) - if err != nil { - return i18n.WrapError(err) - } - if alreadyDownloaded { - return nil - } - - targetPath, err = filepath.Abs(targetPath) - if err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer os.RemoveAll(unpackFolder) - - _, err = os.Stat(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - } - - if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer)) - if err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, core.Maintainer, core.Arch, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath string) error { - if boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { - return nil - } - - targetPath, err := filepath.Abs(targetPath) - if err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer os.RemoveAll(unpackFolder) - - _, err = os.Stat(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - } - - if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath string) error { - if boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return nil - } - - targetPath, err := filepath.Abs(targetPath) - if err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer os.RemoveAll(unpackFolder) - - if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name)) - if err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackTool(tool Tool, url string, targetPath string, deleteIfMissing bool) error { - if toolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return nil - } - - targetPath, err := filepath.Abs(targetPath) - if err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer os.RemoveAll(unpackFolder) - - if deleteIfMissing { - _, err = os.Stat(filepath.Join(targetPath, tool.Name)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, tool.Name)) - if err != nil { - return i18n.WrapError(err) - } - } - } - - if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Name)) - if err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, tool.Name, tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Name, tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, tool.Name, tool.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpack(url string) (string, []os.FileInfo, error) { - fmt.Fprintln(os.Stderr, "Downloading "+url) - - unpackFolder, err := ioutil.TempDir(constants.EMPTY_STRING, "arduino-builder-tool") - if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) - } - - urlParts := strings.Split(url, "/") - archiveFileName := urlParts[len(urlParts)-1] - archiveFilePath := filepath.Join(unpackFolder, archiveFileName) - - res, err := http.Get(url) - if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) - } - - bytes, err := ioutil.ReadAll(res.Body) - if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) - } - res.Body.Close() - - utils.WriteFileBytes(archiveFilePath, bytes) - - cmd := buildUnpackCmd(archiveFilePath) - out, err := cmd.CombinedOutput() - if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) - } - if len(out) > 0 { - fmt.Println(string(out)) - } - - os.Remove(archiveFilePath) - - files, err := gohasissues.ReadDir(unpackFolder) - if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) - } - - return unpackFolder, files, nil -} - -func buildUnpackCmd(file string) *exec.Cmd { - var cmd *exec.Cmd - if strings.HasSuffix(file, "zip") { - cmd = exec.Command("unzip", "-qq", filepath.Base(file)) - } else { - cmd = exec.Command("tar", "xf", filepath.Base(file)) - } - cmd.Dir = filepath.Dir(file) - return cmd -} - -func translateGOOSGOARCHToPackageIndexValue() []string { - switch value := runtime.GOOS + "-" + runtime.GOARCH; value { - case "linux-amd64": - return []string{"x86_64-pc-linux-gnu", "x86_64-linux-gnu"} - case "linux-386": - return []string{"i686-pc-linux-gnu", "i686-linux-gnu"} - case "windows-amd64": - return []string{"i686-mingw32", "i686-cygwin"} - case "windows-386": - return []string{"i686-mingw32", "i686-cygwin"} - case "darwin-amd64": - return []string{"i386-apple-darwin11", "x86_64-apple-darwin"} - case "linux-arm": - return []string{"arm-linux-gnueabihf"} - default: - panic("Unknown OS: " + value) - } -} - -func findToolUrl(index map[string]interface{}, tool Tool, host []string) (string, error) { - if len(tool.OsUrls) > 0 { - for _, osUrl := range tool.OsUrls { - if utils.SliceContains(host, osUrl.Os) { - return osUrl.Url, nil - } - } - } else { - packages := index["packages"].([]interface{}) - for _, p := range packages { - pack := p.(map[string]interface{}) - packageTools := pack[constants.PACKAGE_TOOLS].([]interface{}) - for _, pt := range packageTools { - packageTool := pt.(map[string]interface{}) - name := packageTool[constants.TOOL_NAME].(string) - version := packageTool[constants.TOOL_VERSION].(string) - if name == tool.Name && version == tool.Version { - systems := packageTool["systems"].([]interface{}) - for _, s := range systems { - system := s.(map[string]interface{}) - if utils.SliceContains(host, system["host"].(string)) { - return system[constants.TOOL_URL].(string), nil - } - } - } - } - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find tool " + tool.Name + " " + tool.Version) -} - -func downloadLibraries(libraries []Library, index map[string]interface{}) error { - for _, library := range libraries { - url, err := findLibraryUrl(index, library) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackLibrary(library, url, LIBRARIES_FOLDER) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func findLibraryUrl(index map[string]interface{}, library Library) (string, error) { - if library.Url != "" { - return library.Url, nil - } - libs := index["libraries"].([]interface{}) - for _, l := range libs { - lib := l.(map[string]interface{}) - if library.Name == lib["name"].(string) && library.Version == lib["version"].(string) { - return lib["url"].(string), nil - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find library " + library.Name + " " + library.Version) -} - -func downloadAndUnpackLibrary(library Library, url string, targetPath string) error { - if libraryAlreadyDownloadedAndUnpacked(targetPath, library) { - return nil - } - - targetPath, err := filepath.Abs(targetPath) - if err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer os.RemoveAll(unpackFolder) - - _, err = os.Stat(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if err != nil { - return i18n.WrapError(err) - } - } - - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func copyRecursive(from, to string) error { - copyFunc := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - rel, err := filepath.Rel(from, currentPath) - if err != nil { - return i18n.WrapError(err) - } - targetPath := filepath.Join(to, rel) - if info.IsDir() { - err := os.MkdirAll(targetPath, info.Mode()) - if err != nil { - return i18n.WrapError(err) - } - } else if info.Mode().IsRegular() { - fromFile, err := os.Open(currentPath) - if err != nil { - return i18n.WrapError(err) - } - defer fromFile.Close() - targetFile, err := os.Create(targetPath) - if err != nil { - return i18n.WrapError(err) - } - defer targetFile.Close() - _, err = io.Copy(targetFile, fromFile) - if err != nil { - return i18n.WrapError(err) - } - err = os.Chmod(targetPath, info.Mode()) - if err != nil { - return i18n.WrapError(err) - } - } else if info.Mode()&os.ModeSymlink == os.ModeSymlink { - linkedFile, err := os.Readlink(currentPath) - if err != nil { - return i18n.WrapError(err) - } - fromFile := filepath.Join(filepath.Dir(targetPath), linkedFile) - err = os.Symlink(fromFile, targetPath) - if err != nil { - return i18n.WrapError(err) - } - } else { - return errors.Errorf("unable to copy file " + currentPath) - } - - return nil - } - err := gohasissues.Walk(from, copyFunc) - return i18n.WrapError(err) -} diff --git a/test/i18n_test.go b/test/i18n_test.go deleted file mode 100644 index 7dfb8d4b..00000000 --- a/test/i18n_test.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "fmt" - "github.com/stretchr/testify/require" - "testing" -) - -func TestI18NSyntax(t *testing.T) { - require.Equal(t, "Do you want to remove %[1]v?\nIf you do so you won't be able to use %[1]v any more.", i18n.FromJavaToGoSyntax("Do you want to remove {0}?\nIf you do so you won't be able to use {0} any more.")) - require.Equal(t, "A file named \"%[1]v\" already exists in \"%[2]v\"", i18n.FromJavaToGoSyntax("A file named \"{0}\" already exists in \"{1}\"")) - require.Equal(t, "Board %[1]v:%[2]v:%[3]v doesn't define a 'build.board' preference. Auto-set to: %[4]v", i18n.FromJavaToGoSyntax("Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}")) - - require.Equal(t, "22 11\n", fmt.Sprintf("%[2]d %[1]d\n", 11, 22)) - require.Equal(t, "d c b a", i18n.Format("{3} {2} {1} {0}", "a", "b", "c", "d")) - - require.Equal(t, "e d b a", i18n.Format("{4} {3} {1} {0}", "a", "b", "c", "d", "e")) - - require.Equal(t, "a b", i18n.Format("{0} {1}", "a", "b", "c", "d", "e")) - - require.Equal(t, "%!v(BADINDEX) c b a", i18n.Format("{3} {2} {1} {0}", "a", "b", "c")) - require.Equal(t, "%!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX)", i18n.Format("{3} {2} {1} {0}")) - - require.Equal(t, "I'm %[1]v%% sure", i18n.FromJavaToGoSyntax("I'm {0}%% sure")) - require.Equal(t, "I'm 100% sure", i18n.Format("I'm {0}%% sure", 100)) - - require.Equal(t, "Either in [1] or in [2]", i18n.Format("Either in [{0}] or in [{1}]", 1, 2)) - - require.Equal(t, "Using library a at version b in folder: c ", i18n.Format("Using library {0} at version {1} in folder: {2} {3}", "a", "b", "c", "")) - - require.Equal(t, "Missing 'a' from library in b", i18n.Format("Missing '{0}' from library in {1}", "a", "b")) -} - -func TestI18NInheritance(t *testing.T) { - var logger i18n.Logger - logger = i18n.HumanLogger{} - logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!") - - logger = i18n.MachineLogger{} - logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!") -} diff --git a/test/includes_finder_with_regexp_test.go b/test/includes_finder_with_regexp_test.go deleted file mode 100644 index c3c048cc..00000000 --- a/test/includes_finder_with_regexp_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestIncludesFinderWithRegExp(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:17: fatal error: SPI.h: No such file or directory\n" + - "#include \n" + - "^\n" + - "compilation terminated." - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "SPI.h", include) -} - -func TestIncludesFinderWithRegExpEmptyOutput(t *testing.T) { - ctx := &types.Context{} - - include := builder.IncludesFinderWithRegExp(ctx, "") - - require.Equal(t, "", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: Wire.h: No such file or directory\n" + - " # include \n" + - " ^\n" + - "compilation terminated.\n" - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "Wire.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes2(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: Wire.h: No such file or directory\n" + - " #\t\t\tinclude \n" + - " ^\n" + - "compilation terminated.\n" - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "Wire.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes3(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: SPI.h: No such file or directory\n" + - "compilation terminated.\n" - - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "SPI.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes4(t *testing.T) { - ctx := &types.Context{} - - output := "In file included from /tmp/arduino_modified_sketch_815412/binouts.ino:52:0:\n" + - "/tmp/arduino_build_static/sketch/regtable.h:31:22: fatal error: register.h: No such file or directory\n" - - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "register.h", include) -} diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go deleted file mode 100644 index 29f26d06..00000000 --- a/test/includes_to_include_folders_test.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "fmt" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "sort" - "testing" -) - -func TestIncludesToIncludeFolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "Bridge", importedLibraries[0].Name) -} - -func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - require.Equal(t, 0, len(importedLibraries)) -} - -func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch9", "sketch.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 2, len(importedLibraries)) - require.Equal(t, "Bridge", importedLibraries[0].Name) - require.Equal(t, "IRremote", importedLibraries[1].Name) -} - -func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch10", "sketch.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 2, len(importedLibraries)) - require.Equal(t, "ANewLibrary-master", importedLibraries[0].Name) - require.Equal(t, "IRremote", importedLibraries[1].Name) -} - -func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")), importedLibraries[0].SrcFolder) -} - -func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatform(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "SPI")), importedLibraries[0].SrcFolder) -} - -func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - ToolsFolders: []string{"downloaded_tools", "downloaded_board_manager_stuff"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_usbhost", "sketch_usbhost.ino"), - FQBN: "arduino:samd:arduino_zero_native", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "USBHost", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "USBHost", "src")), importedLibraries[0].SrcFolder) -} - -func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_with_subfolders", "sketch_with_subfolders.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - fmt.Println(importedLibraries) - require.Equal(t, 3, len(importedLibraries)) - require.Equal(t, "testlib1", importedLibraries[0].Name) - require.Equal(t, "testlib2", importedLibraries[1].Name) - require.Equal(t, "testlib3", importedLibraries[2].Name) -} diff --git a/test/libraries/ANewLibrary-master/anewlibrary.h b/test/libraries/ANewLibrary-master/anewlibrary.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Balanduino.h b/test/libraries/Balanduino/Balanduino.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Kalman.h b/test/libraries/Balanduino/Kalman.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/PS3BT.h b/test/libraries/Balanduino/PS3BT.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/SPP.h b/test/libraries/Balanduino/SPP.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Wii.h b/test/libraries/Balanduino/Wii.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/XBOXRECV.h b/test/libraries/Balanduino/XBOXRECV.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/adk.h b/test/libraries/Balanduino/adk.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/usbhub.h b/test/libraries/Balanduino/usbhub.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/FakeAudio/Audio.h b/test/libraries/FakeAudio/Audio.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/FakeAudio/FakeAudio.h b/test/libraries/FakeAudio/FakeAudio.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/IRremote/IRremote.h b/test/libraries/IRremote/IRremote.h deleted file mode 100644 index 5497fbd7..00000000 --- a/test/libraries/IRremote/IRremote.h +++ /dev/null @@ -1 +0,0 @@ -#warning IRRemote included! \ No newline at end of file diff --git a/test/libraries/IRremote/IRremoteInt.h b/test/libraries/IRremote/IRremoteInt.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/SPI/SPI.cpp b/test/libraries/SPI/SPI.cpp deleted file mode 100644 index af14e07b..00000000 --- a/test/libraries/SPI/SPI.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "SPI.h" - -SPIClass SPI; - -uint8_t SPIClass::initialized = 0; -uint8_t SPIClass::interruptMode = 0; -uint8_t SPIClass::interruptMask = 0; -uint8_t SPIClass::interruptSave = 0; -#ifdef SPI_TRANSACTION_MISMATCH_LED -uint8_t SPIClass::inTransactionFlag = 0; -#endif - -void SPIClass::begin() -{ - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - if (!initialized) { - // Set SS to high so a connected chip will be "deselected" by default - uint8_t port = digitalPinToPort(SS); - uint8_t bit = digitalPinToBitMask(SS); - volatile uint8_t *reg = portModeRegister(port); - - // if the SS pin is not already configured as an output - // then set it high (to enable the internal pull-up resistor) - if(!(*reg & bit)){ - digitalWrite(SS, HIGH); - } - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); - } - initialized++; // reference count - SREG = sreg; -} - -void SPIClass::end() { - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - // Decrease the reference counter - if (initialized) - initialized--; - // If there are no more references disable SPI - if (!initialized) { - SPCR &= ~_BV(SPE); - interruptMode = 0; - #ifdef SPI_TRANSACTION_MISMATCH_LED - inTransactionFlag = 0; - #endif - } - SREG = sreg; -} - -// mapping of interrupt numbers to bits within SPI_AVR_EIMSK -#if defined(__AVR_ATmega32U4__) - #define SPI_INT0_MASK (1< - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include - -// SPI_HAS_TRANSACTION means SPI has beginTransaction(), endTransaction(), -// usingInterrupt(), and SPISetting(clock, bitOrder, dataMode) -#define SPI_HAS_TRANSACTION 1 - -// SPI_HAS_NOTUSINGINTERRUPT means that SPI has notUsingInterrupt() method -#define SPI_HAS_NOTUSINGINTERRUPT 1 - -// SPI_ATOMIC_VERSION means that SPI has atomicity fixes and what version. -// This way when there is a bug fix you can check this define to alert users -// of your code if it uses better version of this library. -// This also implies everything that SPI_HAS_TRANSACTION as documented above is -// available too. -#define SPI_ATOMIC_VERSION 1 - -// Uncomment this line to add detection of mismatched begin/end transactions. -// A mismatch occurs if other libraries fail to use SPI.endTransaction() for -// each SPI.beginTransaction(). Connect an LED to this pin. The LED will turn -// on if any mismatch is ever detected. -//#define SPI_TRANSACTION_MISMATCH_LED 5 - -#ifndef LSBFIRST -#define LSBFIRST 0 -#endif -#ifndef MSBFIRST -#define MSBFIRST 1 -#endif - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -// define SPI_AVR_EIMSK for AVR boards with external interrupt pins -#if defined(EIMSK) - #define SPI_AVR_EIMSK EIMSK -#elif defined(GICR) - #define SPI_AVR_EIMSK GICR -#elif defined(GIMSK) - #define SPI_AVR_EIMSK GIMSK -#endif - -class SPISettings { -public: - SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - if (__builtin_constant_p(clock)) { - init_AlwaysInline(clock, bitOrder, dataMode); - } else { - init_MightInline(clock, bitOrder, dataMode); - } - } - SPISettings() { - init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); - } -private: - void init_MightInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - init_AlwaysInline(clock, bitOrder, dataMode); - } - void init_AlwaysInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) - __attribute__((__always_inline__)) { - // Clock settings are defined as follows. Note that this shows SPI2X - // inverted, so the bits form increasing numbers. Also note that - // fosc/64 appears twice - // SPR1 SPR0 ~SPI2X Freq - // 0 0 0 fosc/2 - // 0 0 1 fosc/4 - // 0 1 0 fosc/8 - // 0 1 1 fosc/16 - // 1 0 0 fosc/32 - // 1 0 1 fosc/64 - // 1 1 0 fosc/64 - // 1 1 1 fosc/128 - - // We find the fastest clock that is less than or equal to the - // given clock rate. The clock divider that results in clock_setting - // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the - // slowest (128 == 2 ^^ 7, so clock_div = 6). - uint8_t clockDiv; - - // When the clock is known at compiletime, use this if-then-else - // cascade, which the compiler knows how to completely optimize - // away. When clock is not known, use a loop instead, which generates - // shorter code. - if (__builtin_constant_p(clock)) { - if (clock >= F_CPU / 2) { - clockDiv = 0; - } else if (clock >= F_CPU / 4) { - clockDiv = 1; - } else if (clock >= F_CPU / 8) { - clockDiv = 2; - } else if (clock >= F_CPU / 16) { - clockDiv = 3; - } else if (clock >= F_CPU / 32) { - clockDiv = 4; - } else if (clock >= F_CPU / 64) { - clockDiv = 5; - } else { - clockDiv = 6; - } - } else { - uint32_t clockSetting = F_CPU / 2; - clockDiv = 0; - while (clockDiv < 6 && clock < clockSetting) { - clockSetting /= 2; - clockDiv++; - } - } - - // Compensate for the duplicate fosc/64 - if (clockDiv == 6) - clockDiv = 7; - - // Invert the SPI2X bit - clockDiv ^= 0x1; - - // Pack into the SPISettings class - spcr = _BV(SPE) | _BV(MSTR) | ((bitOrder == LSBFIRST) ? _BV(DORD) : 0) | - (dataMode & SPI_MODE_MASK) | ((clockDiv >> 1) & SPI_CLOCK_MASK); - spsr = clockDiv & SPI_2XCLOCK_MASK; - } - uint8_t spcr; - uint8_t spsr; - friend class SPIClass; -}; - - -class SPIClass { -public: - // Initialize the SPI library - static void begin(); - - // If SPI is used from within an interrupt, this function registers - // that interrupt with the SPI library, so beginTransaction() can - // prevent conflicts. The input interruptNumber is the number used - // with attachInterrupt. If SPI is used from a different interrupt - // (eg, a timer), interruptNumber should be 255. - static void usingInterrupt(uint8_t interruptNumber); - // And this does the opposite. - static void notUsingInterrupt(uint8_t interruptNumber); - // Note: the usingInterrupt and notUsingInterrupt functions should - // not to be called from ISR context or inside a transaction. - // For details see: - // https://github.com/arduino/Arduino/pull/2381 - // https://github.com/arduino/Arduino/pull/2449 - - // Before using SPI.transfer() or asserting chip select pins, - // this function is used to gain exclusive access to the SPI bus - // and configure the correct settings. - inline static void beginTransaction(SPISettings settings) { - if (interruptMode > 0) { - uint8_t sreg = SREG; - noInterrupts(); - - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - interruptSave = SPI_AVR_EIMSK; - SPI_AVR_EIMSK &= ~interruptMask; - SREG = sreg; - } else - #endif - { - interruptSave = sreg; - } - } - - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 1; - #endif - - SPCR = settings.spcr; - SPSR = settings.spsr; - } - - // Write to the SPI bus (MOSI pin) and also receive (MISO pin) - inline static uint8_t transfer(uint8_t data) { - SPDR = data; - /* - * The following NOP introduces a small delay that can prevent the wait - * loop form iterating when running at the maximum speed. This gives - * about 10% more speed, even if it seems counter-intuitive. At lower - * speeds it is unnoticed. - */ - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; // wait - return SPDR; - } - inline static uint16_t transfer16(uint16_t data) { - union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; - in.val = data; - if (!(SPCR & _BV(DORD))) { - SPDR = in.msb; - asm volatile("nop"); // See transfer(uint8_t) function - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - } else { - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - SPDR = in.msb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - } - return out.val; - } - inline static void transfer(void *buf, size_t count) { - if (count == 0) return; - uint8_t *p = (uint8_t *)buf; - SPDR = *p; - while (--count > 0) { - uint8_t out = *(p + 1); - while (!(SPSR & _BV(SPIF))) ; - uint8_t in = SPDR; - SPDR = out; - *p++ = in; - } - while (!(SPSR & _BV(SPIF))) ; - *p = SPDR; - } - // After performing a group of transfers and releasing the chip select - // signal, this function allows others to access the SPI bus - inline static void endTransaction(void) { - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (!inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 0; - #endif - - if (interruptMode > 0) { - #ifdef SPI_AVR_EIMSK - uint8_t sreg = SREG; - #endif - noInterrupts(); - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - SPI_AVR_EIMSK = interruptSave; - SREG = sreg; - } else - #endif - { - SREG = interruptSave; - } - } - } - - // Disable the SPI bus - static void end(); - - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setBitOrder(uint8_t bitOrder) { - if (bitOrder == LSBFIRST) SPCR |= _BV(DORD); - else SPCR &= ~(_BV(DORD)); - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setDataMode(uint8_t dataMode) { - SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode; - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setClockDivider(uint8_t clockDiv) { - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK); - } - // These undocumented functions should not be used. SPI.transfer() - // polls the hardware flag which is automatically cleared as the - // AVR responds to SPI's interrupt - inline static void attachInterrupt() { SPCR |= _BV(SPIE); } - inline static void detachInterrupt() { SPCR &= ~_BV(SPIE); } - -private: - static uint8_t initialized; - static uint8_t interruptMode; // 0=none, 1=mask, 2=global - static uint8_t interruptMask; // which interrupts to mask - static uint8_t interruptSave; // temp storage, to restore state - #ifdef SPI_TRANSACTION_MISMATCH_LED - static uint8_t inTransactionFlag; - #endif -}; - -extern SPIClass SPI; - -#endif diff --git a/test/libraries/SPI/keywords.txt b/test/libraries/SPI/keywords.txt deleted file mode 100644 index fa761658..00000000 --- a/test/libraries/SPI/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SPI KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 -transfer KEYWORD2 -setBitOrder KEYWORD2 -setDataMode KEYWORD2 -setClockDivider KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -SPI_CLOCK_DIV4 LITERAL1 -SPI_CLOCK_DIV16 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_CLOCK_DIV128 LITERAL1 -SPI_CLOCK_DIV2 LITERAL1 -SPI_CLOCK_DIV8 LITERAL1 -SPI_CLOCK_DIV32 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_MODE0 LITERAL1 -SPI_MODE1 LITERAL1 -SPI_MODE2 LITERAL1 -SPI_MODE3 LITERAL1 \ No newline at end of file diff --git a/test/libraries/SPI/library.properties b/test/libraries/SPI/library.properties deleted file mode 100644 index 7e55b100..00000000 --- a/test/libraries/SPI/library.properties +++ /dev/null @@ -1,11 +0,0 @@ -name=SPI -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE. -paragraph= -url=http://arduino.cc/en/Reference/SPI -architectures=avr -types=Arduino -category=Other - diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.h b/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp deleted file mode 100644 index 28fe130c..00000000 --- a/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp +++ /dev/null @@ -1 +0,0 @@ - #error "This file is never supposed to be compiled" diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.h b/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/USBHost/keywords.txt b/test/libraries/USBHost/keywords.txt deleted file mode 100644 index dded4dcf..00000000 --- a/test/libraries/USBHost/keywords.txt +++ /dev/null @@ -1,35 +0,0 @@ -####################################### -# Syntax Coloring Map For USBHost -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -MouseController KEYWORD1 -USBHost KEYWORD1 -KeyboardController KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -Task KEYWORD2 -mouseMoved KEYWORD2 -mouseDragged KEYWORD2 -mousePressed KEYWORD2 -mouseReleased KEYWORD2 -getXChange KEYWORD2 -getYChange KEYWORD2 -getButton KEYWORD2 -keyPressed KEYWORD2 -keyReleased KEYWORD2 -getModifiers KEYWORD2 -getKey KEYWORD2 -getOemKey KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/test/libraries/USBHost/library.properties b/test/libraries/USBHost/library.properties deleted file mode 100644 index b6bdce97..00000000 --- a/test/libraries/USBHost/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=USBHost -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Allows the communication with USB peripherals like mice, keyboards, and thumbdrives. For Arduino Due and Zero. -paragraph=The USBHost library allows the board to appear as a USB host, enabling it to communicate with peripherals like USB mice and keyboards. USBHost does not support devices that are connected through USB hubs. This includes some keyboards that have an internal hub. -url=http://arduino.cc/en/Reference/USBHost -architectures=samd -category=Other diff --git a/test/libraries/USBHost/src/KeyboardController.cpp b/test/libraries/USBHost/src/KeyboardController.cpp deleted file mode 100644 index 70c769f6..00000000 --- a/test/libraries/USBHost/src/KeyboardController.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -extern "C" { -void __keyboardControllerEmptyCallback() { } -} - -void keyPressed() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback"))); -void keyReleased() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback"))); - -void KeyboardController::OnKeyDown(uint8_t _mod, uint8_t _oemKey) { - modifiers = _mod; - keyOem = _oemKey; - key = OemToAscii(_mod, _oemKey); - keyPressed(); -} - -void KeyboardController::OnKeyUp(uint8_t _mod, uint8_t _oemKey) { - modifiers = _mod; - keyOem = _oemKey; - key = OemToAscii(_mod, _oemKey); - keyReleased(); -} diff --git a/test/libraries/USBHost/src/KeyboardController.h b/test/libraries/USBHost/src/KeyboardController.h deleted file mode 100644 index e1b891bf..00000000 --- a/test/libraries/USBHost/src/KeyboardController.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef KEYBOARD_CONTROLLER_H -#define KEYBOARD_CONTROLLER_H - -#include - -enum KeyboardModifiers { - LeftCtrl = 1, - LeftShift = 2, - Alt = 4, - LeftCmd = 8, - RightCtrl = 16, - RightShift = 32, - AltGr = 64, - RightCmd = 128 -}; - -class KeyboardController : public KeyboardReportParser { -public: - KeyboardController(USBHost &usb) : hostKeyboard(&usb), key(0), keyOem(0), modifiers(0) { - hostKeyboard.SetReportParser(0, this); - }; - - uint8_t getKey() { return key; }; - uint8_t getModifiers() { return modifiers; }; - uint8_t getOemKey() { return keyOem; }; - -protected: - virtual void OnKeyDown(uint8_t mod, uint8_t key); - virtual void OnKeyUp(uint8_t mod, uint8_t key); - -private: - HIDBoot hostKeyboard; - uint8_t key, keyOem, modifiers; -}; - -#endif diff --git a/test/libraries/USBHost/src/MouseController.cpp b/test/libraries/USBHost/src/MouseController.cpp deleted file mode 100644 index 3d528bc3..00000000 --- a/test/libraries/USBHost/src/MouseController.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -extern "C" { -void __mouseControllerEmptyCallback() { } -} - -void mouseClicked() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseDragged() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseMoved() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mousePressed() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseReleased() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); - -int MouseController::getXChange() { - int r = dx; - dx = 0; - return r; -} - -int MouseController::getYChange() { - int r = dy; - dy = 0; - return r; -} - -void MouseController::OnMouseMove(MOUSEINFO *mi) { - dx += mi->dX; - dy += mi->dY; - if (buttons != 0) - mouseDragged(); - else - mouseMoved(); -} - -void MouseController::OnLeftButtonUp(MOUSEINFO *mi) { - buttons &= ~LEFT_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnLeftButtonDown(MOUSEINFO *mi) { - buttons |= LEFT_BUTTON; - mousePressed(); -} - -void MouseController::OnMiddleButtonUp(MOUSEINFO *mi) { - buttons &= ~MIDDLE_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnMiddleButtonDown(MOUSEINFO *mi) { - buttons |= MIDDLE_BUTTON; - mousePressed(); -} - -void MouseController::OnRightButtonUp(MOUSEINFO *mi) { - buttons &= ~RIGHT_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnRightButtonDown(MOUSEINFO *mi) { - buttons |= RIGHT_BUTTON; - mousePressed(); -} diff --git a/test/libraries/USBHost/src/MouseController.h b/test/libraries/USBHost/src/MouseController.h deleted file mode 100644 index 4c8c65e9..00000000 --- a/test/libraries/USBHost/src/MouseController.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef MOUSE_CONTROLLER_H -#define MOUSE_CONTROLLER_H - -#include - -enum MouseButton { - LEFT_BUTTON = 0x01, - MIDDLE_BUTTON = 0x02, - RIGHT_BUTTON = 0x04 -}; - -class MouseController : public MouseReportParser -{ -public: - MouseController(USBHost &usb) : hostMouse(&usb), dx(0), dy(0), buttons(0) { - hostMouse.SetReportParser(0, this); - }; - - bool getButton(MouseButton button) { return (buttons & button) == button; }; - int getXChange(); - int getYChange(); - // int getWheelChange(); // Not implemented - -protected: - virtual void OnMouseMove(MOUSEINFO *mi); - virtual void OnLeftButtonUp(MOUSEINFO *mi); - virtual void OnLeftButtonDown(MOUSEINFO *mi); - virtual void OnMiddleButtonUp(MOUSEINFO *mi); - virtual void OnMiddleButtonDown(MOUSEINFO *mi); - virtual void OnRightButtonUp(MOUSEINFO *mi); - virtual void OnRightButtonDown(MOUSEINFO *mi); - -private: - HIDBoot hostMouse; - int dx, dy; - int buttons; -}; - -#endif diff --git a/test/libraries/USBHost/src/Usb.cpp b/test/libraries/USBHost/src/Usb.cpp deleted file mode 100644 index bc821bb1..00000000 --- a/test/libraries/USBHost/src/Usb.cpp +++ /dev/null @@ -1,857 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -/* USB functions */ - -#include -#include "Arduino.h" -#include "Usb.h" - - -#ifdef ARDUINO_SAMD_ZERO - -static uint32_t usb_error = 0; -static uint32_t usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; - -/* constructor */ -USBHost::USBHost() : bmHubPre(0) { - // Set up state machine - usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; //set up state machine -} - -/* Initialize data structures */ -uint32_t USBHost::Init() { - //devConfigIndex = 0; - // Init host stack - init(); - bmHubPre = 0; - UHD_Init(); - return 0; -} - -uint32_t USBHost::getUsbTaskState(void) { - return (usb_task_state); -} - -void USBHost::setUsbTaskState(uint32_t state) { - usb_task_state = state; -} - -EpInfo* USBHost::getEpInfoEntry(uint32_t addr, uint32_t ep) { - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p || !p->epinfo) - return NULL; - - EpInfo *pep = p->epinfo; - - for (uint32_t i = 0; i < p->epcount; i++) { - if(pep->epAddr == ep) - return pep; - - pep++; - } - return NULL; -} - -/* set device table entry */ - -/* each device is different and has different number of endpoints. This function plugs endpoint record structure, defined in application, to devtable */ -uint32_t USBHost::setEpInfoEntry(uint32_t addr, uint32_t epcount, EpInfo* eprecord_ptr) { - if (!eprecord_ptr) - return USB_ERROR_INVALID_ARGUMENT; - - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->address.devAddress = addr; - p->epinfo = eprecord_ptr; - p->epcount = epcount; - - return 0; -} - -uint32_t USBHost::SetPipeAddress(uint32_t addr, uint32_t ep, EpInfo **ppep, uint32_t &nak_limit) { - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - *ppep = getEpInfoEntry(addr, ep); - - if(!*ppep) - return USB_ERROR_EP_NOT_FOUND_IN_TBL; - - nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER ) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower)); - nak_limit--; - TRACE_USBHOST(printf(" => SetPipeAddress deviceEP=%lu configued as hostPIPE=%lu sending to address=%lu\r\n", ep, (*ppep)->epAddr, addr);) - /* - USBTRACE2("\r\nAddress: ", addr); - USBTRACE2(" EP: ", ep); - USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower); - USBTRACE2(" NAK Limit: ", nak_limit); - USBTRACE("\r\n"); - */ - - // CTRL_PIPE.PDADDR: usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PDADDR = addr - uhd_configure_address((*ppep)->epAddr, addr); // Set peripheral address - - return 0; -} - -/* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */ -/* depending on request. Actual requests are defined as inlines */ -/* return codes: */ -/* 00 = success */ -/* 01-0f = non-zero HRSLT */ -uint32_t USBHost::ctrlReq(uint32_t addr, uint32_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, - uint16_t wInd, uint16_t total, uint32_t nbytes, uint8_t* dataptr, USBReadParser *p) { - - uint32_t direction = 0; // Request direction, IN or OUT - uint32_t rcode; - SETUP_PKT setup_pkt; - - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - TRACE_USBHOST(printf(" => ctrlReq\r\n");) - - rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - if(rcode) - return rcode; - - // Allocate Pipe0 with default 64 bytes size if not already initialized - rcode = UHD_Pipe0_Alloc(0, 64); - if (rcode) - { - TRACE_USBHOST(printf("/!\\ USBHost::ctrlReq : EP0 allocation error: %lu\r\n", rcode);) - //USBTRACE2("\n\rUSBHost::ctrlReq : EP0 allocation error: ", rcode"); - return rcode; - } - - // Determine request direction - direction = ((bmReqType & 0x80 ) > 0); - - /* fill in setup packet */ - setup_pkt.ReqType_u.bmRequestType = bmReqType; - setup_pkt.bRequest = bRequest; - setup_pkt.wVal_u.wValueLo = wValLo; - setup_pkt.wVal_u.wValueHi = wValHi; - setup_pkt.wIndex = wInd; - setup_pkt.wLength = total; - - UHD_Pipe_Write(pep->epAddr, sizeof(setup_pkt), (uint8_t *)&setup_pkt); //transfer to setup packet FIFO - - rcode = dispatchPkt(tokSETUP, ep, nak_limit); // Dispatch packet - - if (rcode) //return HRSLT if not zero - return ( rcode); - - if (dataptr != NULL) //data stage, if present - { - if (direction) // IN transfer - { - uint32_t left = total; - TRACE_USBHOST(printf(" => ctrlData IN\r\n");) - - pep->bmRcvToggle = 1; //bmRCVTOG1; - - // Bytes read into buffer - uint32_t read = nbytes; - - rcode = InTransfer(pep, nak_limit, (uint8_t*)&read, dataptr); - - if((rcode&USB_ERROR_DATATOGGLE) == USB_ERROR_DATATOGGLE) { - // yes, we flip it wrong here so that next time it is actually correct! - //pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //continue; - } - - if(rcode) { - //USBTRACE2("\n\rUSBHost::ctrlReq : in transfer: ", rcode"); - return rcode; - } - // Invoke callback function if inTransfer completed successfully and callback function pointer is specified - if(!rcode && p) - ((USBReadParser*)p)->Parse(read, dataptr, total - left); - } - else // OUT transfer - { - pep->bmSndToggle = 1; //bmSNDTOG1; - rcode = OutTransfer(pep, nak_limit, nbytes, dataptr); - } - if(rcode) //return error - return (rcode); - } - - // Status stage - UHD_Pipe_CountZero(pep->epAddr); - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - return dispatchPkt((direction) ? tokOUTHS : tokINHS, pep->epAddr, nak_limit); //GET if direction -} - -/* IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */ -/* Keep sending INs and writes data to memory area pointed by 'data' */ - -/* rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error, - fe USB xfer timeout */ -uint32_t USBHost::inTransfer(uint32_t addr, uint32_t ep, uint8_t *nbytesptr, uint8_t* data) { - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - uint32_t rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - - if(rcode) { - USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); - USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); - USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); - return rcode; - } - return InTransfer(pep, nak_limit, nbytesptr, data); -} - -uint32_t USBHost::InTransfer(EpInfo *pep, uint32_t nak_limit, uint8_t *nbytesptr, uint8_t* data) { - uint32_t rcode = 0; - uint32_t pktsize = 0; - - uint32_t nbytes = *nbytesptr; - uint32_t maxpktsize = pep->maxPktSize; - - *nbytesptr = 0; - //set toggle value - if(pep->bmRcvToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - - usb_pipe_table[pep->epAddr].HostDescBank[0].ADDR.reg = (uint32_t)data; - - // use a 'break' to exit this loop - while (1) { - /* get pipe config from setting register */ - usb_pipe_table[pep->epAddr].HostDescBank[0].ADDR.reg += pktsize; - - rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); //IN packet to EP-'endpoint'. Function takes care of NAKS. - if(rcode == USB_ERROR_DATATOGGLE) { - // yes, we flip it wrong here so that next time it is actually correct! - //pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //set toggle value - if(pep->bmRcvToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - continue; - } - if(rcode) { - //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode); - return(rcode);// break; //should be 0, indicating ACK. Else return error code. - } - /* check for RCVDAVIRQ and generate error if not present */ - /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */ - - pktsize = uhd_byte_count(pep->epAddr); // Number of received bytes - - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_BK0RDY; - - //printf("Got %i bytes \r\n", pktsize); - // This would be OK, but... - //assert(pktsize <= nbytes); - if(pktsize > nbytes) { - // This can happen. Use of assert on Arduino locks up the Arduino. - // So I will trim the value, and hope for the best. - //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize); - pktsize = nbytes; - } - - int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr); - - if(mem_left < 0) - mem_left = 0; - - //data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data); - - //regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer - *nbytesptr += pktsize;// add this packet's byte count to total transfer length - - /* The transfer is complete under two conditions: */ - /* 1. The device sent a short packet (L.T. maxPacketSize) */ - /* 2. 'nbytes' have been transferred. */ - if((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) // have we transferred 'nbytes' bytes? - { - // Save toggle value - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //printf("\r\n"); - rcode = 0; - break; - } // if - } //while( 1 ) - return ( rcode); -} - -/* OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */ -/* Handles NAK bug per Maxim Application Note 4000 for single buffer transfer */ - -/* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */ -uint32_t USBHost::outTransfer(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* data) { - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - uint32_t rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - - if(rcode) - return rcode; - - return OutTransfer(pep, nak_limit, nbytes, data); -} - -uint32_t USBHost::OutTransfer(EpInfo *pep, uint32_t nak_limit, uint32_t nbytes, uint8_t *data) { - uint32_t rcode = 0, retry_count; - uint8_t *data_p = data; //local copy of the data pointer - uint32_t bytes_tosend, nak_count; - uint32_t bytes_left = nbytes; - uint8_t buf[64]; - uint8_t i; - - uint32_t maxpktsize = pep->maxPktSize; - - if(maxpktsize < 1 || maxpktsize > 64) - return USB_ERROR_INVALID_MAX_PKT_SIZE; - - for( i=0; ibmSndToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - - while(bytes_left) { - retry_count = 0; - nak_count = 0; - bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left; - UHD_Pipe_Write(pep->epAddr, bytes_tosend, buf); //filling output FIFO - - //set number of bytes - //dispatch packet - //wait for the completion IRQ - //clear IRQ - - rcode = dispatchPkt(tokOUT, pep->epAddr, nak_limit); - if (rcode) - { - switch(rcode) { - case USB_ERRORFLOW: - nak_count++; - if(nak_limit && (nak_count == nak_limit)) - goto breakout; - return ( rcode); - break; - case USB_ERRORTIMEOUT: - retry_count++; - if(retry_count == USB_RETRY_LIMIT) - goto breakout; - return ( rcode); - break; - case USB_ERROR_DATATOGGLE: - // yes, we flip it wrong here so that next time it is actually correct! - pep->bmSndToggle = USB_HOST_DTGL(pep->epAddr); - //set toggle value - if(pep->bmSndToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - break; - default: - goto breakout; - }//switch( rcode - } - - bytes_left -= bytes_tosend; - data_p += bytes_tosend; - }//while( bytes_left... -breakout: - - pep->bmSndToggle = USB_HOST_DTGL(pep->epAddr); - return ( rcode); //should be 0 in all cases -} - -/* dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty */ -/* If NAK, tries to re-send up to nak_limit times */ -/* If nak_limit == 0, do not count NAKs, exit after timeout */ -/* If bus timeout, re-sends up to USB_RETRY_LIMIT times */ - -/* return codes 0x00-0x0f are HRSLT( 0x00 being success ), 0xff means timeout */ -uint32_t USBHost::dispatchPkt(uint32_t token, uint32_t epAddr, uint32_t nak_limit) { - uint32_t timeout = millis() + USB_XFER_TIMEOUT; - uint32_t nak_count = 0, retry_count=0; - uint32_t rcode = USB_ERROR_TRANSFER_TIMEOUT; - - TRACE_USBHOST(printf(" => dispatchPkt token=%lu pipe=%lu nak_limit=%lu\r\n", token, epAddr, nak_limit);) - - UHD_Pipe_Send(epAddr, token); //launch the transfer - - // Check timeout but don't hold timeout if VBUS is lost - while ((timeout > millis()) && (UHD_GetVBUSState() == UHD_STATE_CONNECTED)) - { - // Wait for transfer completion - if (UHD_Pipe_Is_Transfer_Complete(epAddr, token)) - { - return 0; - } - - //case hrNAK: - if( (usb_pipe_table[epAddr].HostDescBank[0].STATUS_BK.reg & USB_ERRORFLOW ) ) { - nak_count++; - if(nak_limit && (nak_count == nak_limit)) { - rcode = USB_ERRORFLOW; - return (rcode); - } - } - - //case hrTIMEOUT: - if(usb_pipe_table[epAddr].HostDescBank[0].STATUS_PIPE.reg & USB_ERRORTIMEOUT) { - retry_count++; - if(retry_count == USB_RETRY_LIMIT) { - rcode = USB_ERRORTIMEOUT; - return (rcode); - } - } - - if( (usb_pipe_table[epAddr].HostDescBank[0].STATUS_PIPE.reg & USB_ERROR_DATATOGGLE ) ) { - rcode = USB_ERROR_DATATOGGLE; - return (rcode); - } - } - - return rcode; -} - -/* USB main task. Performs enumeration/cleanup */ -void USBHost::Task(void) //USB state machine -{ - uint32_t rcode = 0; - volatile uint32_t tmpdata = 0; - static uint32_t delay = 0; - //USB_DEVICE_DESCRIPTOR buf; - uint32_t lowspeed = 0; - - // Update USB task state on Vbus change - tmpdata = UHD_GetVBUSState(); - - /* modify USB task state if Vbus changed */ - switch (tmpdata) - { - case UHD_STATE_ERROR: //illegal state - usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL; - lowspeed = 0; - break; - - case UHD_STATE_DISCONNECTED: // Disconnected state - if ((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED) - usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; - lowspeed = 0; - break; - - case UHD_STATE_CONNECTED: // Attached state - if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { - delay = millis() + USB_SETTLE_DELAY; - usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE; - } - break; - }// switch( tmpdata - - // Poll connected devices (if required) - for (uint32_t i = 0; i < USB_NUMDEVICES; ++i) - if (devConfig[i]) - rcode = devConfig[i]->Poll(); - - // Perform USB enumeration stage and clean up - switch (usb_task_state) { - case USB_DETACHED_SUBSTATE_INITIALIZE: - TRACE_USBHOST(printf(" + USB_DETACHED_SUBSTATE_INITIALIZE\r\n");) - - // Init USB stack and driver - UHD_Init(); - init(); - - // Free all USB resources - for (uint32_t i = 0; i < USB_NUMDEVICES; ++i) - if (devConfig[i]) - rcode = devConfig[i]->Release(); - - usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE; - break; - case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: //just sit here - // Nothing to do - break; - case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here - // Nothing to do - break; - case USB_ATTACHED_SUBSTATE_SETTLE: // Settle time for just attached device - if((long)(millis() - delay) >= 0L) - usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE; - break; - case USB_ATTACHED_SUBSTATE_RESET_DEVICE: - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_RESET_DEVICE\r\n");) - UHD_BusReset(); //issue bus reset - usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE; - break; - case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE: - if (Is_uhd_reset_sent()) - { - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE\r\n");) - - // Clear Bus Reset flag - uhd_ack_reset_sent(); - - // Enable Start Of Frame generation - uhd_enable_sof(); - - usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF; - - // Wait 20ms after Bus Reset (USB spec) - delay = millis() + 20; - } - break; - case USB_ATTACHED_SUBSTATE_WAIT_SOF: - // Wait for SOF received first - if (Is_uhd_sof()) - { - if (delay < millis()) - { - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_WAIT_SOF\r\n");) - - // 20ms waiting elapsed - usb_task_state = USB_STATE_CONFIGURING; - } - } - break; - case USB_STATE_CONFIGURING: - TRACE_USBHOST(printf(" + USB_STATE_CONFIGURING\r\n");) - rcode = Configuring(0, 0, lowspeed); - - if (rcode) { - TRACE_USBHOST(printf("/!\\ USBHost::Task : USB_STATE_CONFIGURING failed with code: %lu\r\n", rcode);) - if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) { - usb_error = rcode; - usb_task_state = USB_STATE_ERROR; - } - } - else { - usb_task_state = USB_STATE_RUNNING; - TRACE_USBHOST(printf(" + USB_STATE_RUNNING\r\n");) - } - break; - case USB_STATE_RUNNING: - break; - case USB_STATE_ERROR: - break; - } // switch( usb_task_state ) -} - -uint32_t USBHost::DefaultAddressing(uint32_t parent, uint32_t port, uint32_t lowspeed) { - //uint8_t buf[12]; - uint32_t rcode = 0; - UsbDeviceDefinition *p0 = NULL, *p = NULL; - - // Get pointer to pseudo device with address 0 assigned - p0 = addrPool.GetUsbDevicePtr(0); - - if(!p0) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p0->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - p0->lowspeed = (lowspeed) ? 1 : 0; - - // Allocate new address according to device class - uint32_t bAddress = addrPool.AllocAddress(parent, 0, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - // Assign new address to the device - rcode = setAddr(0, 0, bAddress); - - if(rcode) { - TRACE_USBHOST(printf("/!\\ USBHost::DefaultAddressing : Set address failed with code: %lu\r\n", rcode);) - addrPool.FreeAddress(bAddress); - bAddress = 0; - return rcode; - } - return 0; -} - -uint32_t USBHost::AttemptConfig(uint32_t driver, uint32_t parent, uint32_t port, uint32_t lowspeed) { - //printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port); - uint8_t retries = 0; - -again: - uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed); - if(rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) { - if(parent == 0) { - // Send a bus reset on the root interface. - //regWr(rHCTL, bmBUSRST); //issue bus reset - UHD_BusReset(); - delay(102); // delay 102ms, compensate for clock inaccuracy. - } else { - // reset parent port - devConfig[parent]->ResetHubPort(port); - } - } else if(rcode != 0x00/*hrJERR*/ && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works - delay(100); - retries++; - goto again; - } else if(rcode) - return rcode; - - rcode = devConfig[driver]->Init(parent, port, lowspeed); - if(rcode != 0x00/*hrJERR*/ && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works - delay(100); - retries++; - goto again; - } - if(rcode) { - // Issue a bus reset, because the device may be in a limbo state - if(parent == 0) { - // Send a bus reset on the root interface. - //regWr(rHCTL, bmBUSRST); //issue bus reset - UHD_BusReset(); - delay(102); // delay 102ms, compensate for clock inaccuracy. - } else { - // reset parent port - devConfig[parent]->ResetHubPort(port); - } - } - return rcode; -} - -/* - * This is broken. We need to enumerate differently. - * It causes major problems with several devices if detected in an unexpected order. - * - * - * Oleg - I wouldn't do anything before the newly connected device is considered sane. - * i.e.(delays are not indicated for brevity): - * 1. reset - * 2. GetDevDescr(); - * 3a. If ACK, continue with allocating address, addressing, etc. - * 3b. Else reset again, count resets, stop at some number (5?). - * 4. When max.number of resets is reached, toggle power/fail - * If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD() - * it doesn't need to be reset again - * New steps proposal: - * 1: get address pool instance. exit on fail - * 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail. - * 3: bus reset, 100ms delay - * 4: set address - * 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail - * 6: while (configurations) { - * for(each configuration) { - * for (each driver) { - * 6a: Ask device if it likes configuration. Returns 0 on OK. - * If successful, the driver configured device. - * The driver now owns the endpoints, and takes over managing them. - * The following will need codes: - * Everything went well, instance consumed, exit with success. - * Instance already in use, ignore it, try next driver. - * Not a supported device, ignore it, try next driver. - * Not a supported configuration for this device, ignore it, try next driver. - * Could not configure device, fatal, exit with fail. - * } - * } - * } - * 7: for(each driver) { - * 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID - * 8: if we get here, no driver likes the device plugged in, so exit failure. - * - */ -uint32_t USBHost::Configuring(uint32_t parent, uint32_t port, uint32_t lowspeed) { - //uint32_t bAddress = 0; - //printf("Configuring: parent = %i, port = %i\r\n", parent, port); - uint32_t devConfigIndex; - uint32_t rcode = 0; - uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; - USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast(buf); - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - EpInfo epInfo; - - epInfo.epAddr = 0; - epInfo.maxPktSize = 8; - epInfo.epAttribs = 0; - epInfo.bmNakPower = USB_NAK_MAX_POWER; - - //delay(2000); - AddressPool &addrPool = GetAddressPool(); - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - if(!p) { - //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n"); - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to - // avoid toggle inconsistence - - p->epinfo = &epInfo; - - p->lowspeed = lowspeed; - // Get device descriptor - rcode = getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // The first GetDescriptor give us the endpoint 0 max packet size. - epInfo.maxPktSize = buf[7]; - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(rcode) { - //printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n"); - return rcode; - } - - // to-do? - // Allocate new address according to device class - //bAddress = addrPool.AllocAddress(parent, false, port); - - //if (!bAddress) - // return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - uint16_t vid = udd->idVendor; - uint16_t pid = udd->idProduct; - uint8_t klass = udd->bDeviceClass; - - // Attempt to configure if VID/PID or device class matches with a driver - for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if(!devConfig[devConfigIndex]) continue; // no driver - if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) { - rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); - if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED) - break; - } - } - - if(devConfigIndex < USB_NUMDEVICES) { - return rcode; - } - - - // blindly attempt to configure - for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if(!devConfig[devConfigIndex]) continue; - if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above - rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); - - //printf("ERROR ENUMERATING %2.2x\r\n", rcode); - if(!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) { - // in case of an error dev_index should be reset to 0 - // in order to start from the very beginning the - // next time the program gets here - //if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) - // devConfigIndex = 0; - return rcode; - } - } - // if we get here that means that the device class is not supported by any of registered classes - rcode = DefaultAddressing(parent, port, lowspeed); - - return rcode; -} - -uint32_t USBHost::ReleaseDevice(uint32_t addr) { - if(!addr) - return 0; - - for(uint32_t i = 0; i < USB_NUMDEVICES; i++) { - if(!devConfig[i]) continue; - if(devConfig[i]->GetAddress() == addr) - return devConfig[i]->Release(); - } - return 0; -} - -//get device descriptor - -uint32_t USBHost::getDevDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, 0)); -} -//get configuration descriptor - -uint32_t USBHost::getConfDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t conf, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, 0)); -} - -/* Requests Configuration Descriptor. Sends two Get Conf Descr requests. The first one gets the total length of all descriptors, then the second one requests this - total length. The length of the first request can be shorter ( 4 bytes ), however, there are devices which won't work unless this length is set to 9 */ -uint32_t USBHost::getConfDescr(uint32_t addr, uint32_t ep, uint32_t conf, USBReadParser *p) { - const uint32_t bufSize = 64; - uint8_t buf[bufSize]; - USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast(buf); - - uint32_t ret = getConfDescr(addr, ep, 9, conf, buf); - - if(ret) - return ret; - - uint32_t total = ucd->wTotalLength; - - //USBTRACE2("\r\ntotal conf.size:", total); - - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p)); -} - -//get string descriptor - -uint32_t USBHost::getStrDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t index, uint32_t langid, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nbytes, nbytes, dataptr, 0)); -} -//set address - -uint32_t USBHost::setAddr(uint32_t oldaddr, uint32_t ep, uint32_t newaddr) { - uint32_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL); - //delay(2); //per USB 2.0 sect.9.2.6.3 - delay(300); // Older spec says you should wait at least 200ms - return rcode; - //return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); -} -//set configuration - -uint32_t USBHost::setConf(uint32_t addr, uint32_t ep, uint32_t conf_value) { - return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); -} - -#endif //ARDUINO_SAMD_ZERO diff --git a/test/libraries/USBHost/src/Usb.h b/test/libraries/USBHost/src/Usb.h deleted file mode 100644 index e95ebc05..00000000 --- a/test/libraries/USBHost/src/Usb.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -/* USB functions */ - -#ifndef USB_H_INCLUDED -#define USB_H_INCLUDED -#define _usb_h_ - -#include - -#define ARDUINO 101 - -//#include "Arduino.h" -#include "macros.h" -// None of these should ever be included by a driver, or a user's sketch. - -#include "variant.h" -#define USB_HOST_SERIAL SERIAL_PORT_MONITOR -#include "Print.h" -#include "printhex.h" -#include "message.h" -#include "hexdump.h" -#include "sink_parser.h" - -#include "address.h" - -#include "usb_ch9.h" -//#include "usbhost.h" -#include "UsbCore.h" -#include "parsetools.h" - -#include "confdescparser.h" - -#endif /* USB_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/UsbCore.h b/test/libraries/USBHost/src/UsbCore.h deleted file mode 100644 index fdb14c1c..00000000 --- a/test/libraries/USBHost/src/UsbCore.h +++ /dev/null @@ -1,291 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(USBCORE_H) -#error "Never include UsbCore.h directly; include Usb.h instead" -#else -#define USBCORE_H - -// Not used anymore? If anyone uses this, please let us know so that this may be -// moved to the proper place, settings.h. -//#define USB_METHODS_INLINE - -/* shield pins. First parameter - SS pin, second parameter - INT pin */ -#ifdef BOARD_BLACK_WIDDOW -typedef MAX3421e MAX3421E; // Black Widow -#elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) -#if EXT_RAM -typedef MAX3421e MAX3421E; // Teensy++ 2.0 with XMEM2 -#else -typedef MAX3421e MAX3421E; // Teensy++ 1.0 and 2.0 -#endif -#elif defined(BOARD_MEGA_ADK) -typedef MAX3421e MAX3421E; // Arduino Mega ADK -#elif defined(ARDUINO_AVR_BALANDUINO) -typedef MAX3421e MAX3421E; // Balanduino -#else -//typedef MAX3421e MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.) or Teensy 2.0 and 3.0 -#endif - -/* Common setup data constant combinations */ -#define bmREQ_GET_DESCR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //get descriptor request type -#define bmREQ_SET USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //set request type for all but 'set feature' and 'set interface' -#define bmREQ_CL_GET_INTF USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE //get interface request type - -// D7 data transfer direction (0 - host-to-device, 1 - device-to-host) -// D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved) -// D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved) - -// USB Device Classes -#define USB_CLASS_USE_CLASS_INFO 0x00 // Use Class Info in the Interface Descriptors -#define USB_CLASS_AUDIO 0x01 // Audio -#define USB_CLASS_COM_AND_CDC_CTRL 0x02 // Communications and CDC Control -#define USB_CLASS_HID 0x03 // HID -#define USB_CLASS_PHYSICAL 0x05 // Physical -#define USB_CLASS_IMAGE 0x06 // Image -#define USB_CLASS_PRINTER 0x07 // Printer -#define USB_CLASS_MASS_STORAGE 0x08 // Mass Storage -#define USB_CLASS_HUB 0x09 // Hub -#define USB_CLASS_CDC_DATA 0x0a // CDC-Data -#define USB_CLASS_SMART_CARD 0x0b // Smart-Card -#define USB_CLASS_CONTENT_SECURITY 0x0d // Content Security -#define USB_CLASS_VIDEO 0x0e // Video -#define USB_CLASS_PERSONAL_HEALTH 0x0f // Personal Healthcare -#define USB_CLASS_DIAGNOSTIC_DEVICE 0xdc // Diagnostic Device -#define USB_CLASS_WIRELESS_CTRL 0xe0 // Wireless Controller -#define USB_CLASS_MISC 0xef // Miscellaneous -#define USB_CLASS_APP_SPECIFIC 0xfe // Application Specific -#define USB_CLASS_VENDOR_SPECIFIC 0xff // Vendor Specific - -// Additional Error Codes -#define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED 0xD1 -#define USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE 0xD2 -#define USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS 0xD3 -#define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL 0xD4 -#define USB_ERROR_HUB_ADDRESS_OVERFLOW 0xD5 -#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL 0xD6 -#define USB_ERROR_EPINFO_IS_NULL 0xD7 -#define USB_ERROR_INVALID_ARGUMENT 0xD8 -#define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE 0xD9 -#define USB_ERROR_INVALID_MAX_PKT_SIZE 0xDA -#define USB_ERROR_EP_NOT_FOUND_IN_TBL 0xDB -#define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET 0xE0 -#define USB_ERROR_FailGetDevDescr 0xE1 -#define USB_ERROR_FailSetDevTblEntry 0xE2 -#define USB_ERROR_FailGetConfDescr 0xE3 -#define USB_ERROR_TRANSFER_TIMEOUT 0xFF - -#define USB_XFER_TIMEOUT 10000 //30000 // (5000) USB transfer timeout in milliseconds, per section 9.2.6.1 of USB 2.0 spec -//#define USB_NAK_LIMIT 32000 //NAK limit for a transfer. 0 means NAKs are not counted -#define USB_RETRY_LIMIT 3 // 3 retry limit for a transfer -#define USB_SETTLE_DELAY 200 //settle delay in milliseconds - -#define USB_NUMDEVICES 16 //number of USB devices -//#define HUB_MAX_HUBS 7 // maximum number of hubs that can be attached to the host controller -#define HUB_PORT_RESET_DELAY 20 // hub port reset delay 10 ms recomended, can be up to 20 ms - -/* USB state machine states */ -#define USB_STATE_MASK 0xf0 - -#define USB_STATE_DETACHED 0x10 -#define USB_DETACHED_SUBSTATE_INITIALIZE 0x11 -#define USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE 0x12 -#define USB_DETACHED_SUBSTATE_ILLEGAL 0x13 -#define USB_ATTACHED_SUBSTATE_SETTLE 0x20 -#define USB_ATTACHED_SUBSTATE_RESET_DEVICE 0x30 -#define USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE 0x40 -#define USB_ATTACHED_SUBSTATE_WAIT_SOF 0x50 -#define USB_ATTACHED_SUBSTATE_WAIT_RESET 0x51 -#define USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE 0x60 -#define USB_STATE_ADDRESSING 0x70 -#define USB_STATE_CONFIGURING 0x80 -#define USB_STATE_RUNNING 0x90 -#define USB_STATE_ERROR 0xa0 - -class USBDeviceConfig { -public: - - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return 0; - } - - virtual uint32_t ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return 0; - } - - virtual uint32_t Release() { - return 0; - } - - virtual uint32_t Poll() { - return 0; - } - - virtual uint32_t GetAddress() { - return 0; - } - - virtual void ResetHubPort(uint32_t port) { - return; - } // Note used for hubs only! - - virtual uint32_t VIDPIDOK(uint32_t vid, uint32_t pid) { - return false; - } - - virtual uint32_t DEVCLASSOK(uint32_t klass) { - return false; - } -}; - -/* USB Setup Packet Structure */ -typedef struct { - - union { // offset description - uint8_t bmRequestType; // 0 Bit-map of request type - - struct { - uint8_t recipient : 5; // Recipient of the request - uint8_t type : 2; // Type of request - uint8_t direction : 1; // Direction of data X-fer - }; - } ReqType_u; - uint8_t bRequest; // 1 Request - - union { - uint16_t wValue; // 2 Depends on bRequest - - struct { - uint8_t wValueLo; - uint8_t wValueHi; - }; - } wVal_u; - uint16_t wIndex; // 4 Depends on bRequest - uint16_t wLength; // 6 Depends on bRequest -} SETUP_PKT, *PSETUP_PKT; - - - -// Base class for incoming data parser - -class USBReadParser { -public: - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) = 0; -}; - -class USBHost { - AddressPoolImpl addrPool; - USBDeviceConfig* devConfig[USB_NUMDEVICES]; - uint8_t bmHubPre; - -public: - USBHost(void); - - void SetHubPreMask() { - //bmHubPre |= bmHUBPRE; - }; - - void ResetHubPreMask() { - //bmHubPre &= (~bmHUBPRE); - }; - - AddressPool& GetAddressPool() { - return (AddressPool&)addrPool; - }; - - uint32_t RegisterDeviceClass(USBDeviceConfig *pdev) { - for(uint8_t i = 0; i < USB_NUMDEVICES; i++) { - if(!devConfig[i]) { - devConfig[i] = pdev; - return 0; - } - } - return USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS; - }; - - void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { - addrPool.ForEachUsbDevice(pfunc); - }; - uint32_t getUsbTaskState(void); - void setUsbTaskState(uint32_t state); - - EpInfo* getEpInfoEntry(uint32_t addr, uint32_t ep); - uint32_t setEpInfoEntry(uint32_t addr, uint32_t epcount, EpInfo* eprecord_ptr); - - /* Control requests */ - uint32_t getDevDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr); - uint32_t getConfDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t conf, uint8_t* dataptr); - - uint32_t getConfDescr(uint32_t addr, uint32_t ep, uint32_t conf, USBReadParser *p); - - uint32_t getStrDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t index, uint32_t langid, uint8_t* dataptr); - uint32_t setAddr(uint32_t oldaddr, uint32_t ep, uint32_t newaddr); - uint32_t setConf(uint32_t addr, uint32_t ep, uint32_t conf_value); - /**/ - uint32_t ctrlData(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr, uint32_t direction); - uint32_t ctrlStatus(uint32_t ep, uint32_t direction, uint32_t nak_limit); - uint32_t inTransfer(uint32_t addr, uint32_t ep, uint8_t *nbytesptr, uint8_t* data); - uint32_t outTransfer(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* data); - uint32_t dispatchPkt(uint32_t token, uint32_t ep, uint32_t nak_limit); - - void Task(void); - - uint32_t DefaultAddressing(uint32_t parent, uint32_t port, uint32_t lowspeed); - uint32_t Configuring(uint32_t parent, uint32_t port, uint32_t lowspeed); - uint32_t ReleaseDevice(uint32_t addr); - - uint32_t ctrlReq(uint32_t addr, uint32_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, - uint16_t wInd, uint16_t total, uint32_t nbytes, uint8_t* dataptr, USBReadParser *p); - - uint32_t Init(); -private: - uint32_t SetPipeAddress(uint32_t addr, uint32_t ep, EpInfo **ppep, uint32_t &nak_limit); - uint32_t OutTransfer(EpInfo *pep, uint32_t nak_limit, uint32_t nbytes, uint8_t *data); - uint32_t InTransfer(EpInfo *pep, uint32_t nak_limit, uint8_t *nbytesptr, uint8_t *data); - uint32_t AttemptConfig(uint32_t driver, uint32_t parent, uint32_t port, uint32_t lowspeed); -}; - -#if 0 //defined(USB_METHODS_INLINE) -//get device descriptor - -inline uint8_t USBHost::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr)); -} -//get configuration descriptor - -inline uint8_t USBHost::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr)); -} -//get string descriptor - -inline uint8_t USBHost::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr)); -} -//set address - -inline uint8_t USBHost::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { - return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL)); -} -//set configuration - -inline uint8_t USBHost::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { - return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL)); -} - -#endif // defined(USB_METHODS_INLINE) - -#endif /* USBCORE_H */ diff --git a/test/libraries/USBHost/src/address.h b/test/libraries/USBHost/src/address.h deleted file mode 100644 index a9610822..00000000 --- a/test/libraries/USBHost/src/address.h +++ /dev/null @@ -1,280 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(ADDRESS_H_INCLUDED) -#error "Never include address.h directly; include Usb.h instead" -#else -#define ADDRESS_H_INCLUDED - -#include -#include - -/* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */ -/* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */ -#define USB_NAK_MAX_POWER 15 //NAK binary order maximum value -#define USB_NAK_DEFAULT 14 //default 32K-1 NAKs before giving up -#define USB_NAK_NOWAIT 1 //Single NAK stops transfer -#define USB_NAK_NONAK 0 //Do not count NAKs, stop retrying after USB Timeout - -struct EpInfo { - uint32_t epAddr; // Endpoint address - uint32_t maxPktSize; // Maximum packet size - union { - uint8_t epAttribs; - - struct { - uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise - uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise - uint8_t bmNakPower : 6; // Binary order for NAK_LIMIT value - }; - }; -}; - -// 7 6 5 4 3 2 1 0 -// --------------------------------- -// | | H | P | P | P | A | A | A | -// --------------------------------- -// -// H - if 1 the address is a hub address -// P - parent hub address -// A - device address / port number in case of hub -// - -struct UsbDeviceAddress { - union { - struct { - uint32_t bmAddress : 3; // device address/port number - uint32_t bmParent : 3; // parent hub address - uint32_t bmHub : 1; // hub flag - uint32_t bmReserved : 25; // reserved, must be zerro - }; - uint32_t devAddress; - }; -}; - -#define bmUSB_DEV_ADDR_ADDRESS 0x07 -#define bmUSB_DEV_ADDR_PARENT 0x38 -#define bmUSB_DEV_ADDR_HUB 0x40 - -struct UsbDeviceDefinition { - EpInfo *epinfo; // endpoint info pointer - UsbDeviceAddress address; - uint32_t epcount; // number of endpoints - uint32_t lowspeed; // indicates if a device is the low speed one - // uint8_t devclass; // device class -}; - -class AddressPool { -public: - virtual UsbDeviceDefinition* GetUsbDevicePtr(uint32_t addr) = 0; - virtual uint32_t AllocAddress(uint32_t parent, uint32_t is_hub = 0, uint32_t port = 0) = 0; - virtual void FreeAddress(uint32_t addr) = 0; -}; - -typedef void (*UsbDeviceHandleFunc)(UsbDeviceDefinition *pdev); - -#define ADDR_ERROR_INVALID_INDEX 0xFF -#define ADDR_ERROR_INVALID_ADDRESS 0xFF - -template -class AddressPoolImpl : public AddressPool { - EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device - - uint32_t hubCounter; // hub counter is kept - // in order to avoid hub address duplication - - UsbDeviceDefinition thePool[MAX_DEVICES_ALLOWED]; - - // Initializes address pool entry - - void InitEntry(uint32_t index) { - thePool[index].address.devAddress = 0; - thePool[index].epcount = 1; - thePool[index].lowspeed = 0; - thePool[index].epinfo = &dev0ep; - }; - - // Returns thePool index for a given address - - uint32_t FindAddressIndex(uint32_t address = 0) { - for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) { - if(thePool[i].address.devAddress == address) - return i; - } - return 0; - }; - - // Returns thePool child index for a given parent - - uint32_t FindChildIndex(UsbDeviceAddress addr, uint32_t start = 1) { - for (uint32_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { - if(thePool[i].address.bmParent == addr.bmAddress) - return i; - } - return 0; - }; - - // Frees address entry specified by index parameter - - void FreeAddressByIndex(uint32_t index) { - // Zero field is reserved and should not be affected - if(index == 0) - return; - - UsbDeviceAddress uda = thePool[index].address; - // If a hub was switched off all port addresses should be freed - if(uda.bmHub == 1) { - for (uint32_t i = 1; (i = FindChildIndex(uda, i));) - FreeAddressByIndex(i); - - // If the hub had the last allocated address, hubCounter should be decremented - if(hubCounter == uda.bmAddress) - hubCounter--; - } - InitEntry(index); - } - - // Initializes the whole address pool at once - - void InitAllAddresses() { - for (uint32_t i = 1; i < MAX_DEVICES_ALLOWED; i++) - InitEntry(i); - - hubCounter = 0; - }; - -public: - - AddressPoolImpl() : hubCounter(0) { - // Zero address is reserved - InitEntry(0); - - thePool[0].address.devAddress = 0; - thePool[0].epinfo = &dev0ep; - dev0ep.epAddr = 0; - dev0ep.maxPktSize = 8; - dev0ep.epAttribs = 0; //set DATA0/1 toggles to 0 - dev0ep.bmNakPower = USB_NAK_MAX_POWER; - - InitAllAddresses(); - }; - - // Returns a pointer to a specified address entry - - virtual UsbDeviceDefinition* GetUsbDevicePtr(uint32_t addr) { - if(!addr) - return thePool; - - uint32_t index = FindAddressIndex(addr); - - return (!index) ? NULL : thePool + index; - }; - - // Performs an operation specified by pfunc for each addressed device - - void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { - if(!pfunc) - return; - - for (uint32_t i = 1; i < MAX_DEVICES_ALLOWED; i++) - if(thePool[i].address.devAddress) - pfunc(thePool + i); - }; - - // Allocates new address - - virtual uint32_t AllocAddress(uint32_t parent, uint32_t is_hub = 0, uint32_t port = 0) { - /* if (parent != 0 && port == 0) - USB_HOST_SERIAL.println("PRT:0"); */ - UsbDeviceAddress _parent; - _parent.devAddress = parent; - if(_parent.bmReserved || port > 7) - //if(parent > 127 || port > 7) - return 0; - - if(is_hub && hubCounter == 7) - return 0; - - // finds first empty address entry starting from one - uint32_t index = FindAddressIndex(0); - - if(!index) // if empty entry is not found - return 0; - - if(_parent.devAddress == 0) { - if(is_hub) { - thePool[index].address.devAddress = 0x41; - hubCounter++; - } else - thePool[index].address.devAddress = 1; - - return thePool[index].address.devAddress; - } - - UsbDeviceAddress addr; - addr.devAddress = 0; // Ensure all bits are zero - addr.bmParent = _parent.bmAddress; - if(is_hub) { - addr.bmHub = 1; - addr.bmAddress = ++hubCounter; - } else { - addr.bmHub = 0; - addr.bmAddress = port; - } - thePool[index].address = addr; - /* - USB_HOST_SERIAL.print("Addr:"); - USB_HOST_SERIAL.print(addr.bmHub, HEX); - USB_HOST_SERIAL.print("."); - USB_HOST_SERIAL.print(addr.bmParent, HEX); - USB_HOST_SERIAL.print("."); - USB_HOST_SERIAL.println(addr.bmAddress, HEX); - */ - return thePool[index].address.devAddress; - }; - - // Empties pool entry - - virtual void FreeAddress(uint32_t addr) { - // if the root hub is disconnected all the addresses should be initialized - if(addr == 0x41) { - InitAllAddresses(); - return; - } - uint32_t index = FindAddressIndex(addr); - FreeAddressByIndex(index); - }; - - // Returns number of hubs attached - // It can be rather helpfull to find out if there are hubs attached than getting the exact number of hubs. - //uint32_t GetNumHubs() - //{ - // return hubCounter; - //}; - //uint32_t GetNumDevices() - //{ - // uint32_t counter = 0; - - // for (uint32_t i=1; iRegisterDeviceClass(this); //set devConfig[] entry - } -} - -uint32_t ADK::ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return Init(parent, port, lowspeed); // Just call Init. Yes, really! -} - -/* Connection initialization of an Android phone */ -uint32_t ADK::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - uint32_t rcode; - uint32_t num_of_conf; // number of configurations - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - - // get memory address of USB device address pool - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("\r\nADK Init"); - - // check if address has already been assigned to an instance - if(bAddress) { - USBTRACE("\r\nAddress in use"); - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - } - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) { - USBTRACE("\r\nAddress not found"); - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - if(!p->epinfo) { - USBTRACE("epinfo is null\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(0, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(rcode) { - USBTRACE("\r\nGetDevDesc1 Error "); - goto FailGetDevDescr; - } - - // Reset - UHD_BusReset(); - while( Is_uhd_starting_reset() ) {} - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - - // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device SET_ADDRESS - rcode = pUsb->setAddr(0, 0, bAddress); - if(rcode) { - USBTRACE("\r\nsetAddr Error "); - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - TRACE_USBHOST(printf("ADK::Init : setAddr failed with rcode %lu\r\n", rcode);) - return rcode; - }//if (rcode... - - USBTRACE2("\r\nAddr:", bAddress); - // Spec says you should wait at least 200ms. - //delay(300); - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(bAddress, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // Restore p->epinfo - p->epinfo = oldep_ptr; - if (rcode) - { - USBTRACE("\r\nGetDevDesc2 Error "); - goto FailGetDevDescr; - } - - TRACE_USBHOST(printf("ADK::Init : device address is now %lu\r\n", bAddress);) - - p->lowspeed = false; - - //get pointer to assigned address record - p = addrPool.GetUsbDevicePtr(bAddress); - if(!p) { - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - p->lowspeed = lowspeed; - - // Assign epInfo to epinfo pointer - only EP0 is known - rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if(rcode) { - goto FailSetDevTblEntry; - } - - //check if ADK device is already in accessory mode; if yes, configure and exit - if(udd->idVendor == ADK_VID && - (udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) { - USBTRACE("\r\nAcc.mode device detected"); - /* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */ - num_of_conf = udd->bNumConfigurations; - - USBTRACE2("\r\nNC:",num_of_conf); - for (uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser<0, 0, 0, 0> confDescrParser(this); - - delay(1); - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - -#if defined(XOOM) - //added by Jaylen Scott Vanorden - if(rcode) { - TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);) - - // Try once more - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - } -#endif - if(rcode) { - goto FailGetConfDescr; - } - if(bNumEP > 2) { - break; - } - } // for (uint32_t i=0; isetEpInfoEntry(bAddress, 3, epInfo); - if(rcode) { - goto FailSetDevTblEntry; - } - } - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - if(rcode) { - goto FailSetConfDescr; - } - /* print endpoint structure */ - - USBTRACE("\r\nEndpoint Structure:"); - USBTRACE("\r\nEP0:"); - USBTRACE2("\r\nAddr: ", epInfo[0].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[0].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[0].epAttribs); - USBTRACE("\r\nEpout:"); - USBTRACE2("\r\nAddr: ", epInfo[epDataOutIndex].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataOutIndex].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[epDataOutIndex].epAttribs); - USBTRACE("\r\nEpin:"); - USBTRACE2("\r\nAddr: ", epInfo[epDataInIndex].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataInIndex].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[epDataInIndex].epAttribs); - - - USBTRACE("\r\nConfiguration successful"); - ready = true; - return 0; //successful configuration - }//if( buf->idVendor == ADK_VID... - - //probe device - get accessory protocol revision - { - uint32_t adkproto = 0; - delay(1); - //rcode = getProto((uint8_t*) & adkproto); // ADK_GETPROTO 0x33 - rcode = getProto((uint8_t*)buf); - -#if defined(XOOM) - //added by Jaylen Scott Vanorden - if(rcode) { - USBTRACE2("\r\nGot 1st bad code for proto: ", rcode); - // Try once more - rcode = getProto((uint8_t*) & adkproto); - } -#endif - if(rcode) { - goto FailGetProto; //init fails - } - adkproto = buf[0] | (buf[1]<<8); - USBTRACE2("\r\nADK protocol rev. ", adkproto); - } - - delay(100); - - //sending ID strings - // ADK_SENDSTR 0x34 - if( sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_MANUFACTURER"); } - delay(10); - if( sendStr(ACCESSORY_STRING_MODEL, model) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_MODEL"); } - delay(10); - if( sendStr(ACCESSORY_STRING_DESCRIPTION, description) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_DESCRIPTION"); } - delay(10); - if( sendStr(ACCESSORY_STRING_VERSION, version) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_VERSION"); } - delay(10); - if( sendStr(ACCESSORY_STRING_URI, uri) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_URI"); } - delay(10); - if( sendStr(ACCESSORY_STRING_SERIAL, serial) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_SERIAL"); } - - delay(100); - - USBTRACE("\r\nSwitch to accessory mode"); - //switch to accessory mode - //the Android phone will reset - rcode = switchAcc(); - if(rcode) { - goto FailSwAcc; //init fails - } - rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; - delay(100); // Give Android a chance to do its reset. This is a guess, and possibly could be lower. - goto SwAttempt; //switch to accessory mode attempted - - /* diagnostic messages */ -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(rcode); - goto Fail; -#endif - -FailSetDevTblEntry: -#ifdef DEBUG_USB_HOST - NotifyFailSetDevTblEntry(rcode); - goto Fail; -#endif - -FailGetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetConfDescr(rcode); - goto Fail; -#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(rcode); - goto Fail; -#endif - -FailGetProto: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\ngetProto:"); - goto Fail; -#endif - -FailSwAcc: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\nswAcc:"); - goto Fail; -#endif - - //FailOnInit: - // USBTRACE("OnInit:"); - // goto Fail; - // -SwAttempt: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\nAccessory mode switch attempt"); -Fail: -#endif - USBTRACE2("\r\nADK Init Failed, error code: ", rcode); - //NotifyFail(rcode); - Release(); - return rcode; -} - -/* Extracts bulk-IN and bulk-OUT endpoint information from config descriptor */ -void ADK::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - //ErrorMessage(PSTR("Conf.Val"), conf); - //ErrorMessage(PSTR("Iface Num"), iface); - //ErrorMessage(PSTR("Alt.Set"), alt); - - //added by Yuuichi Akagawa - if(bNumEP == 3) { - return; - } - - bConfNum = conf; - - if((pep->bmAttributes & 0x02) == 2) { - uint32_t index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; - // Fill in the endpoint info structure - epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; - - bNumEP++; - - //PrintEndpointDescriptor(pep); - } -} - -/* Performs a cleanup after failed Init() attempt */ -uint32_t ADK::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bNumEP = 1; //must have to be reset to 1 - - bAddress = 0; - ready = false; - return 0; -} - -uint32_t ADK::RcvData(uint8_t *bytes_rcvd, uint8_t *dataptr) { - USBTRACE2("\r\nAddr: ", bAddress ); - USBTRACE2("\r\nEP: ",epInfo[epDataInIndex].epAddr); - return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr); -} - -uint32_t ADK::SndData(uint32_t nbytes, uint8_t *dataptr) { - return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr); -} - -void ADK::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) { - Notify(PSTR("Endpoint descriptor:"), 0x80); - Notify(PSTR("\r\nLength:\t\t"), 0x80); - PrintHex (ep_ptr->bLength, 0x80); - Notify(PSTR("\r\nType:\t\t"), 0x80); - PrintHex (ep_ptr->bDescriptorType, 0x80); - Notify(PSTR("\r\nAddress:\t"), 0x80); - PrintHex (ep_ptr->bEndpointAddress, 0x80); - Notify(PSTR("\r\nAttributes:\t"), 0x80); - PrintHex (ep_ptr->bmAttributes, 0x80); - Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); - PrintHex (ep_ptr->wMaxPacketSize, 0x80); - Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); - PrintHex (ep_ptr->bInterval, 0x80); - Notify(PSTR("\r\n"), 0x80); -} diff --git a/test/libraries/USBHost/src/adk.h b/test/libraries/USBHost/src/adk.h deleted file mode 100644 index ffd22cf3..00000000 --- a/test/libraries/USBHost/src/adk.h +++ /dev/null @@ -1,148 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -/* Google ADK interface support header */ - -#ifndef ADK_H_INCLUDED -#define ADK_H_INCLUDED - -#include -#include "Usb.h" -#include "hid.h" -#include "Arduino.h" - -// #define ADK_VID 0x18D1 -// #define ADK_PID 0x2D00 -// #define ADB_PID 0x2D01 - -// JCB -#define ADK_VID 0x04E8 -#define ADK_PID 0x685C -#define ADB_PID 0x685D - -#define XOOM //enables repeating getProto() and getConf() attempts - //necessary for slow devices such as Motorola XOOM - //defined by default, can be commented out to save memory - -/* requests */ - -#define ADK_GETPROTO 51 //check USB accessory protocol version 0x33 -#define ADK_SENDSTR 52 //send identifying string 0x34 -#define ADK_ACCSTART 53 //start device in accessory mode 0x35 - -#define bmREQ_ADK_GET USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_ADK_SEND USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE - -#define ACCESSORY_STRING_MANUFACTURER 0 -#define ACCESSORY_STRING_MODEL 1 -#define ACCESSORY_STRING_DESCRIPTION 2 -#define ACCESSORY_STRING_VERSION 3 -#define ACCESSORY_STRING_URI 4 -#define ACCESSORY_STRING_SERIAL 5 - -#define ADK_MAX_ENDPOINTS 3 //endpoint 0, bulk_IN, bulk_OUT - -class ADK; - -class ADK : public USBDeviceConfig, public UsbConfigXtracter { -private: - /* ID strings */ - const char* manufacturer; - const char* model; - const char* description; - const char* version; - const char* uri; - const char* serial; - - /* ADK proprietary requests */ - uint32_t getProto(uint8_t* adkproto); - uint32_t sendStr(uint32_t index, const char* str); - uint32_t switchAcc(void); - -protected: - static const uint32_t epDataInIndex; // DataIn endpoint index - static const uint32_t epDataOutIndex; // DataOUT endpoint index - - /* Mandatory members */ - USBHost *pUsb; - uint32_t bAddress; // Device USB address - uint32_t bConfNum; // configuration number - - uint32_t bNumEP; // total number of EP in the configuration - uint32_t ready; - - /* Endpoint data structure */ - EpInfo epInfo[ADK_MAX_ENDPOINTS]; - - void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr); - -public: - ADK(USBHost *pUsb, const char* manufacturer, - const char* model, - const char* description, - const char* version, - const char* uri, - const char* serial); - - // Methods for receiving and sending data - uint32_t RcvData(uint8_t *nbytesptr, uint8_t *dataptr); - uint32_t SndData(uint32_t nbytes, uint8_t *dataptr); - - - // USBDeviceConfig implementation - virtual uint32_t ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - - virtual uint32_t Poll() { - return 0; - }; - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t isReady() { - return ready; - }; - - virtual uint32_t VIDPIDOK(uint32_t vid, uint32_t pid) { - return (vid == ADK_VID && (pid == ADK_PID || pid == ADB_PID)); - }; - - //UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; //class ADK : public USBDeviceConfig ... - -/* get ADK protocol version */ - -/* returns 2 bytes in *adkproto */ -inline uint32_t ADK::getProto(uint8_t* adkproto) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL)); -} - -/* send ADK string */ -inline uint32_t ADK::sendStr(uint32_t index, const char* str) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*)str, NULL)); -} - -/* switch to accessory mode */ -inline uint32_t ADK::switchAcc(void) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL)); -} - -#endif /* ADK_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/confdescparser.h b/test/libraries/USBHost/src/confdescparser.h deleted file mode 100644 index 6ee6a1ee..00000000 --- a/test/libraries/USBHost/src/confdescparser.h +++ /dev/null @@ -1,223 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(__CONFDESCPARSER_H__) -#error "Never include confdescparser.h directly; include Usb.h instead" -#else - -#define __CONFDESCPARSER_H__ - -#include - -//#define TRACE_USBHOST(x) x -#define TRACE_USBHOST(x) - -class UsbConfigXtracter { -public: - //virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0; - //virtual void InterfaceXtract(uint32_t conf, const USB_INTERFACE_DESCRIPTOR *iface) = 0; - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep) = 0; -}; - -#define CP_MASK_COMPARE_CLASS 1 -#define CP_MASK_COMPARE_SUBCLASS 2 -#define CP_MASK_COMPARE_PROTOCOL 4 -#define CP_MASK_COMPARE_ALL 7 - -// Configuration Descriptor Parser Class Template - -template -class ConfigDescParser : public USBReadParser { - UsbConfigXtracter *theXtractor; - MultiValueBuffer theBuffer; - MultiByteValueParser valParser; - ByteSkipper theSkipper; - uint8_t varBuffer[16 /*sizeof(USB_CONFIGURATION_DESCRIPTOR)*/]; - - uint32_t stateParseDescr; // ParseDescriptor state - - uint32_t dscrLen; // Descriptor length - uint32_t dscrType; // Descriptor type - - bool isGoodInterface; // Apropriate interface flag - uint32_t confValue; // Configuration value - uint32_t protoValue; // Protocol value - uint32_t ifaceNumber; // Interface number - uint32_t ifaceAltSet; // Interface alternate settings - - bool UseOr; - bool ParseDescriptor(uint8_t **pp, uint32_t *pcntdn); - void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); - -public: - - void SetOR(void) { - UseOr = true; - } - ConfigDescParser(UsbConfigXtracter *xtractor); - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset); -}; - -template -ConfigDescParser::ConfigDescParser(UsbConfigXtracter *xtractor) : - theXtractor(xtractor), - stateParseDescr(0), - dscrLen(0), - dscrType(0), -UseOr(false) { - theBuffer.pValue = varBuffer; - valParser.Initialize(&theBuffer); - theSkipper.Initialize(&theBuffer); -}; - -template -void ConfigDescParser::Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) { - uint32_t cntdn = len; - uint8_t *p = (uint8_t*)pbuf; - - while (cntdn) - if(!ParseDescriptor(&p, &cntdn)) - return; -} - -/* Parser for the configuration descriptor. Takes values for class, subclass, protocol fields in interface descriptor and - compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ -template -bool ConfigDescParser::ParseDescriptor(uint8_t **pp, uint32_t *pcntdn) { - USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast(varBuffer); - USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast(varBuffer); - switch(stateParseDescr) { - case 0: - theBuffer.valueSize = 2; - valParser.Initialize(&theBuffer); - stateParseDescr = 1; - case 1: - if(!valParser.Parse(pp, pcntdn)) - return false; - dscrLen = *((uint8_t*)theBuffer.pValue); - dscrType = *((uint8_t*)theBuffer.pValue + 1); - stateParseDescr = 2; - case 2: - // This is a sort of hack. Assuming that two bytes are all ready in the buffer - // the pointer is positioned two bytes ahead in order for the rest of descriptor - // to be read right after the size and the type fields. - // This should be used carefully. varBuffer should be used directly to handle data - // in the buffer. - theBuffer.pValue = varBuffer + 2; - stateParseDescr = 3; - case 3: - switch(dscrType) { - case USB_DESCRIPTOR_INTERFACE: - isGoodInterface = false; - case USB_DESCRIPTOR_CONFIGURATION: - theBuffer.valueSize = sizeof (USB_CONFIGURATION_DESCRIPTOR) - 2; - break; - case USB_DESCRIPTOR_ENDPOINT: - theBuffer.valueSize = sizeof (USB_ENDPOINT_DESCRIPTOR) - 2; - break; - case HID_DESCRIPTOR_HID: - theBuffer.valueSize = dscrLen - 2; - break; - } - valParser.Initialize(&theBuffer); - stateParseDescr = 4; - case 4: - switch(dscrType) { - case USB_DESCRIPTOR_CONFIGURATION: - if(!valParser.Parse(pp, pcntdn)) - return false; - confValue = ucd->bConfigurationValue; - break; - case USB_DESCRIPTOR_INTERFACE: - if(!valParser.Parse(pp, pcntdn)) - return false; - if((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID) - break; - if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID) - break; - if(UseOr) { - if((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol))) - break; - } else { - if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) - break; - } - isGoodInterface = true; - ifaceNumber = uid->bInterfaceNumber; - ifaceAltSet = uid->bAlternateSetting; - protoValue = uid->bInterfaceProtocol; - break; - case USB_DESCRIPTOR_ENDPOINT: - if(!valParser.Parse(pp, pcntdn)) - return false; - if(isGoodInterface) - if(theXtractor) - theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*)varBuffer); - break; - //case HID_DESCRIPTOR_HID: - // if (!valParser.Parse(pp, pcntdn)) - // return false; - // PrintHidDescriptor((const USB_HID_DESCRIPTOR*)varBuffer); - // break; - default: - if(!theSkipper.Skip(pp, pcntdn, dscrLen - 2)) - return false; - } - theBuffer.pValue = varBuffer; - stateParseDescr = 0; - } - return true; -} - -template -void ConfigDescParser::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) { - Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80); - Notify(PSTR("bDescLength:\t\t"), 0x80); - PrintHex (pDesc->bLength, 0x80); - - Notify(PSTR("\r\nbDescriptorType:\t"), 0x80); - PrintHex (pDesc->bDescriptorType, 0x80); - - Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80); - PrintHex (pDesc->bcdHID, 0x80); - - Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80); - PrintHex (pDesc->bCountryCode, 0x80); - - Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80); - PrintHex (pDesc->bNumDescriptors, 0x80); - - //Notify(PSTR("\r\nbDescrType:\t\t")); - //PrintHex(pDesc->bDescrType); - // - //Notify(PSTR("\r\nwDescriptorLength:\t")); - //PrintHex(pDesc->wDescriptorLength); - - for (uint32_t i = 0; i < pDesc->bNumDescriptors; i++) { - HID_CLASS_DESCRIPTOR_LEN_AND_TYPE *pLT = (HID_CLASS_DESCRIPTOR_LEN_AND_TYPE*)&(pDesc->bDescrType); - - Notify(PSTR("\r\nbDescrType:\t\t"), 0x80); - PrintHex (pLT[i].bDescrType, 0x80); - - Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80); - PrintHex (pLT[i].wDescriptorLength, 0x80); - } - Notify(PSTR("\r\n"), 0x80); -} - - -#endif // __CONFDESCPARSER_H__ diff --git a/test/libraries/USBHost/src/hexdump.h b/test/libraries/USBHost/src/hexdump.h deleted file mode 100644 index 3818d850..00000000 --- a/test/libraries/USBHost/src/hexdump.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__HEXDUMP_H__) -#error "Never include hexdump.h directly; include Usb.h instead" -#else -#define __HEXDUMP_H__ - -extern int UsbDEBUGlvl; - -template -class HexDumper : public BASE_CLASS { - uint8_t byteCount; - OFFSET_TYPE byteTotal; - -public: - - HexDumper() : byteCount(0), byteTotal(0) { - }; - - void Initialize() { - byteCount = 0; - byteTotal = 0; - }; - - virtual void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset); -}; - -template -void HexDumper::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { - if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. - for(LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) { - if(!byteCount) { - PrintHex (byteTotal, 0x80); - E_Notify(PSTR(": "), 0x80); - } - PrintHex (pbuf[j], 0x80); - E_Notify(PSTR(" "), 0x80); - - if(byteCount == 15) { - E_Notify(PSTR("\r\n"), 0x80); - byteCount = 0xFF; - } - } - } -} - -#endif // __HEXDUMP_H__ diff --git a/test/libraries/USBHost/src/hid.cpp b/test/libraries/USBHost/src/hid.cpp deleted file mode 100644 index 70c785b3..00000000 --- a/test/libraries/USBHost/src/hid.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "hid.h" - -//get HID report descriptor - -/* WRONG! Endpoint is _ALWAYS_ ZERO for HID! We want the _INTERFACE_ value here! -uint32_t HID::GetReportDescr(uint32_t ep, USBReadParser *parser) { - const uint8_t constBufLen = 64; - uint8_t buf[constBufLen]; - - uint8_t rcode = pUsb->ctrlReq(bAddress, ep, bmREQ_HIDREPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00, - HID_DESCRIPTOR_REPORT, 0x0000, 128, constBufLen, buf, (USBReadParser*)parser); - - //return ((rcode != hrSTALL) ? rcode : 0); - return rcode; -} - */ -uint32_t HID::GetReportDescr(uint32_t wIndex, USBReadParser *parser) { - const uint8_t constBufLen = 64; - uint8_t buf[constBufLen]; - - uint8_t rcode = pUsb->ctrlReq(bAddress, 0x00, bmREQ_HIDREPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00, - HID_DESCRIPTOR_REPORT, wIndex, 128, constBufLen, buf, (USBReadParser*)parser); - - //return ((rcode != hrSTALL) ? rcode : 0); - return rcode; -} - -//uint32_t HID::getHidDescr( uint8_t ep, uint16_t nbytes, uint8_t* dataptr ) -//{ -// return( pUsb->ctrlReq( bAddress, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, HID_DESCRIPTOR_HID, 0x0000, nbytes, dataptr )); -//} - -uint32_t HID::SetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HIDOUT, HID_REQUEST_SET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL)); -} - -uint32_t HID::GetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HIDIN, HID_REQUEST_GET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL)); -} - -uint32_t HID::GetIdle(uint32_t iface, uint32_t reportID, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDIN, HID_REQUEST_GET_IDLE, reportID, 0, iface, 0x0001, 0x0001, dataptr, NULL)); -} - -uint32_t HID::SetIdle(uint32_t iface, uint32_t reportID, uint32_t duration) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDOUT, HID_REQUEST_SET_IDLE, reportID, duration, iface, 0x0000, 0x0000, NULL, NULL)); -} - -uint32_t HID::SetProtocol(uint32_t iface, uint32_t protocol) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDOUT, HID_REQUEST_SET_PROTOCOL, protocol, 0x00, iface, 0x0000, 0x0000, NULL, NULL)); -} - -uint32_t HID::GetProtocol(uint32_t iface, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDIN, HID_REQUEST_GET_PROTOCOL, 0x00, 0x00, iface, 0x0001, 0x0001, dataptr, NULL)); -} - -void HID::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) { - Notify(PSTR("Endpoint descriptor:"), 0x80); - Notify(PSTR("\r\nLength:\t\t"), 0x80); - D_PrintHex (ep_ptr->bLength, 0x80); - Notify(PSTR("\r\nType:\t\t"), 0x80); - D_PrintHex (ep_ptr->bDescriptorType, 0x80); - Notify(PSTR("\r\nAddress:\t"), 0x80); - D_PrintHex (ep_ptr->bEndpointAddress, 0x80); - Notify(PSTR("\r\nAttributes:\t"), 0x80); - D_PrintHex (ep_ptr->bmAttributes, 0x80); - Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); - D_PrintHex (ep_ptr->wMaxPacketSize, 0x80); - Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); - D_PrintHex (ep_ptr->bInterval, 0x80); -} - -void HID::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) { - Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80); - Notify(PSTR("bDescLength:\t\t"), 0x80); - D_PrintHex (pDesc->bLength, 0x80); - - Notify(PSTR("\r\nbDescriptorType:\t"), 0x80); - D_PrintHex (pDesc->bDescriptorType, 0x80); - - Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80); - D_PrintHex (pDesc->bcdHID, 0x80); - - Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80); - D_PrintHex (pDesc->bCountryCode, 0x80); - - Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80); - D_PrintHex (pDesc->bNumDescriptors, 0x80); - - Notify(PSTR("\r\nbDescrType:\t\t"), 0x80); - D_PrintHex (pDesc->bDescrType, 0x80); - - Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80); - D_PrintHex (pDesc->wDescriptorLength, 0x80); -} diff --git a/test/libraries/USBHost/src/hid.h b/test/libraries/USBHost/src/hid.h deleted file mode 100644 index ca697a56..00000000 --- a/test/libraries/USBHost/src/hid.h +++ /dev/null @@ -1,183 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#if !defined(__HID_H__) -#define __HID_H__ - -#include "Usb.h" -#include "hidusagestr.h" - -#define MAX_REPORT_PARSERS 2 -#define HID_MAX_HID_CLASS_DESCRIPTORS 5 - -#define DATA_SIZE_MASK 0x03 -#define TYPE_MASK 0x0C -#define TAG_MASK 0xF0 - -#define DATA_SIZE_0 0x00 -#define DATA_SIZE_1 0x01 -#define DATA_SIZE_2 0x02 -#define DATA_SIZE_4 0x03 - -#define TYPE_MAIN 0x00 -#define TYPE_GLOBAL 0x04 -#define TYPE_LOCAL 0x08 - -#define TAG_MAIN_INPUT 0x80 -#define TAG_MAIN_OUTPUT 0x90 -#define TAG_MAIN_COLLECTION 0xA0 -#define TAG_MAIN_FEATURE 0xB0 -#define TAG_MAIN_ENDCOLLECTION 0xC0 - -#define TAG_GLOBAL_USAGEPAGE 0x00 -#define TAG_GLOBAL_LOGICALMIN 0x10 -#define TAG_GLOBAL_LOGICALMAX 0x20 -#define TAG_GLOBAL_PHYSMIN 0x30 -#define TAG_GLOBAL_PHYSMAX 0x40 -#define TAG_GLOBAL_UNITEXP 0x50 -#define TAG_GLOBAL_UNIT 0x60 -#define TAG_GLOBAL_REPORTSIZE 0x70 -#define TAG_GLOBAL_REPORTID 0x80 -#define TAG_GLOBAL_REPORTCOUNT 0x90 -#define TAG_GLOBAL_PUSH 0xA0 -#define TAG_GLOBAL_POP 0xB0 - -#define TAG_LOCAL_USAGE 0x00 -#define TAG_LOCAL_USAGEMIN 0x10 -#define TAG_LOCAL_USAGEMAX 0x20 - -/* HID requests */ -#define bmREQ_HIDOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDREPORT USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE - -/* HID constants. Not part of chapter 9 */ -/* Class-Specific Requests */ -#define HID_REQUEST_GET_REPORT 0x01 -#define HID_REQUEST_GET_IDLE 0x02 -#define HID_REQUEST_GET_PROTOCOL 0x03 -#define HID_REQUEST_SET_REPORT 0x09 -#define HID_REQUEST_SET_IDLE 0x0A -#define HID_REQUEST_SET_PROTOCOL 0x0B - -/* Class Descriptor Types */ -#define HID_DESCRIPTOR_HID 0x21 -#define HID_DESCRIPTOR_REPORT 0x22 -#define HID_DESRIPTOR_PHY 0x23 - -/* Protocol Selection */ -#define HID_BOOT_PROTOCOL 0x00 -#define HID_RPT_PROTOCOL 0x01 - -/* HID Interface Class Code */ -#define HID_INTF 0x03 - -/* HID Interface Class SubClass Codes */ -#define HID_BOOT_INTF_SUBCLASS 0x01 - -/* HID Interface Class Protocol Codes */ -#define HID_PROTOCOL_NONE 0x00 -#define HID_PROTOCOL_KEYBOARD 0x01 -#define HID_PROTOCOL_MOUSE 0x02 - -#define HID_ITEM_TYPE_MAIN 0 -#define HID_ITEM_TYPE_GLOBAL 1 -#define HID_ITEM_TYPE_LOCAL 2 -#define HID_ITEM_TYPE_RESERVED 3 - -#define HID_LONG_ITEM_PREFIX 0xfe // Long item prefix value - -#define bmHID_MAIN_ITEM_TAG 0xfc // Main item tag mask - -#define bmHID_MAIN_ITEM_INPUT 0x80 // Main item Input tag value -#define bmHID_MAIN_ITEM_OUTPUT 0x90 // Main item Output tag value -#define bmHID_MAIN_ITEM_FEATURE 0xb0 // Main item Feature tag value -#define bmHID_MAIN_ITEM_COLLECTION 0xa0 // Main item Collection tag value -#define bmHID_MAIN_ITEM_END_COLLECTION 0xce // Main item End Collection tag value - -#define HID_MAIN_ITEM_COLLECTION_PHYSICAL 0 -#define HID_MAIN_ITEM_COLLECTION_APPLICATION 1 -#define HID_MAIN_ITEM_COLLECTION_LOGICAL 2 -#define HID_MAIN_ITEM_COLLECTION_REPORT 3 -#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY 4 -#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH 5 -#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6 - -struct HidItemPrefix { - uint8_t bSize : 2; - uint8_t bType : 2; - uint8_t bTag : 4; -}; - -struct MainItemIOFeature { - uint8_t bmIsConstantOrData : 1; - uint8_t bmIsArrayOrVariable : 1; - uint8_t bmIsRelativeOrAbsolute : 1; - uint8_t bmIsWrapOrNoWrap : 1; - uint8_t bmIsNonLonearOrLinear : 1; - uint8_t bmIsNoPreferedOrPrefered : 1; - uint8_t bmIsNullOrNoNull : 1; - uint8_t bmIsVolatileOrNonVolatile : 1; -}; - -class HID; - -class HIDReportParser { -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf)= 0; -}; - -class HID : public USBDeviceConfig, public UsbConfigXtracter { -protected: - USBHost *pUsb; // USB class instance pointer - uint32_t bAddress; // address - -protected: - static const uint32_t epInterruptInIndex = 1; // InterruptIN endpoint index - static const uint32_t epInterruptOutIndex = 2; // InterruptOUT endpoint index - - static const uint32_t maxHidInterfaces = 3; - static const uint32_t maxEpPerInterface = 2; - static const uint32_t totalEndpoints = (maxHidInterfaces * maxEpPerInterface + 1); - - void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr); - void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); - - virtual HIDReportParser* GetReportParser(uint32_t id); - -public: - - HID(USBHost *pusb) : pUsb(pusb) { - }; - - const USBHost* GetUsb() { - return pUsb; - }; - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs); - - uint32_t SetProtocol(uint32_t iface, uint32_t protocol); - uint32_t GetProtocol(uint32_t iface, uint8_t* dataptr); - uint32_t GetIdle(uint32_t iface, uint32_t reportID, uint8_t* dataptr); - uint32_t SetIdle(uint32_t iface, uint32_t reportID, uint32_t duration); - - uint32_t GetReportDescr(uint32_t ep, USBReadParser *parser = NULL); - - uint32_t GetHidDescr(uint32_t ep, uint32_t nbytes, uint8_t* dataptr); - uint32_t GetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr); -}; - -#endif // __HID_H__ diff --git a/test/libraries/USBHost/src/hidboot.cpp b/test/libraries/USBHost/src/hidboot.cpp deleted file mode 100644 index 9f6b8743..00000000 --- a/test/libraries/USBHost/src/hidboot.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#include "hidboot.h" - -void MouseReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - MOUSEINFO *pmi = (MOUSEINFO*)buf; - // Future: - // bool event; - -#if 0 - if (prevState.mouseInfo.bmLeftButton == 0 && pmi->bmLeftButton == 1) - OnLeftButtonDown(pmi); - - if (prevState.mouseInfo.bmLeftButton == 1 && pmi->bmLeftButton == 0) - OnLeftButtonUp(pmi); - - if (prevState.mouseInfo.bmRightButton == 0 && pmi->bmRightButton == 1) - OnRightButtonDown(pmi); - - if (prevState.mouseInfo.bmRightButton == 1 && pmi->bmRightButton == 0) - OnRightButtonUp(pmi); - - if (prevState.mouseInfo.bmMiddleButton == 0 && pmi->bmMiddleButton == 1) - OnMiddleButtonDown(pmi); - - if (prevState.mouseInfo.bmMiddleButton == 1 && pmi->bmMiddleButton == 0) - OnMiddleButtonUp(pmi); - - if (prevState.mouseInfo.dX != pmi->dX || prevState.mouseInfo.dY != pmi->dY) - OnMouseMove(pmi); - - if (len > sizeof (MOUSEINFO)) - for (uint32_t i = 0; ibmLeftButton ) { - if(pmi->bmLeftButton) { - OnLeftButtonDown(pmi); - } else { - OnLeftButtonUp(pmi); - } - // Future: - // event = true; - } - - if(prevState.mouseInfo.bmRightButton != pmi->bmRightButton) { - if(pmi->bmRightButton) { - OnRightButtonDown(pmi); - } else { - OnRightButtonUp(pmi); - } - // Future: - // event = true; - } - - if(prevState.mouseInfo.bmMiddleButton != pmi->bmMiddleButton) { - if(pmi->bmMiddleButton) { - OnMiddleButtonDown(pmi); - } else { - OnMiddleButtonUp(pmi); - } - // Future: - // event = true; - } - - // - // Scroll wheel(s), are not part of the spec, but we could support it. - // Logitech wireless keyboard and mouse combo reports scroll wheel in byte 4 - // We wouldn't even need to save this information. - //if(len > 3) { - //} - // - - // Mice only report motion when they actually move! - // Why not just pass the x/y values to simplify things?? - if(pmi->dX || pmi->dY) { - OnMouseMove(pmi); - // Future: - // event = true; - } - - // - // Future: - // Provide a callback that operates on the gathered events from above. - // - // if(event) OnMouse(); - // - - // Only the first byte matters (buttons). We do NOT need to save position info. - prevState.bInfo[0] = buf[0]; -#endif - -}; - -void KeyboardReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - // On error - return - if (buf[2] == 1) - return; - - //KBDINFO *pki = (KBDINFO*)buf; - - // provide event for changed control key state - if (prevState.bInfo[0x00] != buf[0x00]) { - OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]); - } - - for (uint32_t i = 2; i < 8; i++) { - bool down = false; - bool up = false; - - for (uint8_t j = 2; j < 8; j++) { - if (buf[i] == prevState.bInfo[j] && buf[i] != 1) - down = true; - if (buf[j] == prevState.bInfo[i] && prevState.bInfo[i] != 1) - up = true; - } - if (!down) { - HandleLockingKeys(hid, buf[i]); - OnKeyDown(*buf, buf[i]); - } - if (!up) - OnKeyUp(prevState.bInfo[0], prevState.bInfo[i]); - } - for(uint32_t i = 0; i < 8; i++) - prevState.bInfo[i] = buf[i]; -}; - -uint8_t KeyboardReportParser::HandleLockingKeys(HID *hid, uint8_t key) { - uint8_t old_keys = kbdLockingKeys.bLeds; - - switch (key) { - case UHS_HID_BOOT_KEY_NUM_LOCK: - kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock; - break; - case UHS_HID_BOOT_KEY_CAPS_LOCK: - kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock; - break; - case UHS_HID_BOOT_KEY_SCROLL_LOCK: - kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock; - break; - } - - if (old_keys != kbdLockingKeys.bLeds && hid) - return (hid->SetReport(0, 0/*hid->GetIface()*/, 2, 0, 1, &kbdLockingKeys.bLeds)); - - return 0; -} - -const uint8_t KeyboardReportParser::numKeys[10] = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; -const uint8_t KeyboardReportParser::symKeysUp[12] = { '_', '+', '{', '}', '|', '~', ':', '"', '~', '<', '>', '?'}; -const uint8_t KeyboardReportParser::symKeysLo[12] = { '-', '=', '[', ']', '\\', ' ', ';', '\'', '`', ',', '.', '/'}; -const uint8_t KeyboardReportParser::padKeys[5] = { '/', '*', '-', '+', 0x13}; -#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) -uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { - uint8_t shift = (mod & 0x22); - - // [a-z] - if (VALUE_WITHIN(key, 0x04, 0x1d)) { - // Upper case letters - if ((kbdLockingKeys.kbdLeds.bmCapsLock == 0 && (mod & 2)) || - (kbdLockingKeys.kbdLeds.bmCapsLock == 1 && (mod & 2) == 0)) - return (key - 4 + 'A'); - - // Lower case letters - else - return (key - 4 + 'a'); - }// Numbers - else if (VALUE_WITHIN(key, 0x1e, 0x27)) { - if (shift) - return ((uint8_t)pgm_read_byte(&getNumKeys()[key - 0x1e])); - else - return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1'); - }// Keypad Numbers - else if(VALUE_WITHIN(key, 0x59, 0x61)) { - if(kbdLockingKeys.kbdLeds.bmNumLock == 1) - return (key - 0x59 + '1'); - } else if(VALUE_WITHIN(key, 0x2d, 0x38)) - return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d])); - else if(VALUE_WITHIN(key, 0x54, 0x58)) - return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]); - else { - switch(key) { - case UHS_HID_BOOT_KEY_SPACE: return (0x20); - case UHS_HID_BOOT_KEY_ENTER: return (0x13); - case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); - case UHS_HID_BOOT_KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0); - } - } - return ( 0); -} - diff --git a/test/libraries/USBHost/src/hidboot.h b/test/libraries/USBHost/src/hidboot.h deleted file mode 100644 index 621ce57a..00000000 --- a/test/libraries/USBHost/src/hidboot.h +++ /dev/null @@ -1,609 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#ifndef HIDBOOT_H_INCLUDED -#define HIDBOOT_H_INCLUDED - -#include -#include "Usb.h" -#include "hid.h" -#include "Arduino.h" - -#define UHS_HID_BOOT_KEY_ZERO 0x27 -#define UHS_HID_BOOT_KEY_ENTER 0x28 -#define UHS_HID_BOOT_KEY_SPACE 0x2c -#define UHS_HID_BOOT_KEY_CAPS_LOCK 0x39 -#define UHS_HID_BOOT_KEY_SCROLL_LOCK 0x47 -#define UHS_HID_BOOT_KEY_NUM_LOCK 0x53 -#define UHS_HID_BOOT_KEY_ZERO2 0x62 -#define UHS_HID_BOOT_KEY_PERIOD 0x63 - -// Don't worry, GCC will optimize the result to a final value. -#define bitsEndpoints(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 2 : 0) | (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) -#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2) -#define epMUL(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 1 : 0) + (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) - -// Already defined in hid.h -// #define HID_MAX_HID_CLASS_DESCRIPTORS 5 - -struct MOUSEINFO { - - struct { - uint8_t bmLeftButton : 1; - uint8_t bmRightButton : 1; - uint8_t bmMiddleButton : 1; - uint8_t bmDummy : 5; - }; - int8_t dX; - int8_t dY; -}; - -class MouseReportParser : public HIDReportParser { - - union { - MOUSEINFO mouseInfo; - uint8_t bInfo[sizeof (MOUSEINFO)]; - } prevState; - -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); - -protected: - - virtual void OnMouseMove(MOUSEINFO *mi) { - }; - - virtual void OnLeftButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnLeftButtonDown(MOUSEINFO *mi) { - }; - - virtual void OnRightButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnRightButtonDown(MOUSEINFO *mi) { - }; - - virtual void OnMiddleButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnMiddleButtonDown(MOUSEINFO *mi) { - }; -}; - -struct MODIFIERKEYS { - uint8_t bmLeftCtrl : 1; - uint8_t bmLeftShift : 1; - uint8_t bmLeftAlt : 1; - uint8_t bmLeftGUI : 1; - uint8_t bmRightCtrl : 1; - uint8_t bmRightShift : 1; - uint8_t bmRightAlt : 1; - uint8_t bmRightGUI : 1; -}; - -struct KBDINFO { - - struct { - uint8_t bmLeftCtrl : 1; - uint8_t bmLeftShift : 1; - uint8_t bmLeftAlt : 1; - uint8_t bmLeftGUI : 1; - uint8_t bmRightCtrl : 1; - uint8_t bmRightShift : 1; - uint8_t bmRightAlt : 1; - uint8_t bmRightGUI : 1; - }; - uint8_t bReserved; - uint8_t Keys[6]; -}; - -struct KBDLEDS { - uint8_t bmNumLock : 1; - uint8_t bmCapsLock : 1; - uint8_t bmScrollLock : 1; - uint8_t bmCompose : 1; - uint8_t bmKana : 1; - uint8_t bmReserved : 3; -}; - -class KeyboardReportParser : public HIDReportParser { - static const uint8_t numKeys[10]; - static const uint8_t symKeysUp[12]; - static const uint8_t symKeysLo[12]; - static const uint8_t padKeys[5]; - -protected: - - union { - KBDINFO kbdInfo; - uint8_t bInfo[sizeof (KBDINFO)]; - } prevState; - - union { - KBDLEDS kbdLeds; - uint8_t bLeds; - } kbdLockingKeys; - - uint8_t OemToAscii(uint8_t mod, uint8_t key); - -public: - - KeyboardReportParser() { - kbdLockingKeys.bLeds = 0; - }; - - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); - -protected: - virtual uint8_t HandleLockingKeys(HID* hid, uint8_t key); - - virtual void OnControlKeysChanged(uint8_t before, uint8_t after) { - }; - - virtual void OnKeyDown(uint8_t mod, uint8_t key) { - }; - - virtual void OnKeyUp(uint8_t mod, uint8_t key) { - }; - - virtual const uint8_t *getNumKeys() { - return numKeys; - }; - - virtual const uint8_t *getSymKeysUp() { - return symKeysUp; - }; - - virtual const uint8_t *getSymKeysLo() { - return symKeysLo; - }; - - virtual const uint8_t *getPadKeys() { - return padKeys; - }; -}; - -template -class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter -{ - EpInfo epInfo[totalEndpoints(BOOT_PROTOCOL)]; - HIDReportParser *pRptParser[epMUL(BOOT_PROTOCOL)]; - - uint32_t bConfNum; // configuration number - uint32_t bIfaceNum; // Interface Number - uint32_t bNumIface; // number of interfaces in the configuration - uint32_t bNumEP; // total number of EP in the configuration - - uint32_t qNextPollTime; // next poll time - uint32_t bPollEnable; // poll enable flag - uint32_t bInterval; // largest interval - - void Initialize(); - - virtual HIDReportParser* GetReportParser(uint32_t id) { - return pRptParser[id]; - }; - -public: - HIDBoot(USBHost *p); - - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs) { - pRptParser[id] = prs; - return true; - }; - - // USBDeviceConfig implementation - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - // UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; - -template -HIDBoot::HIDBoot(USBHost *p) : - HID(p), - qNextPollTime(0), - bPollEnable(false) { - Initialize(); - - for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - pRptParser[i] = NULL; - } - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -template -void HIDBoot::Initialize() { - for(int i = 0; i < totalEndpoints(BOOT_PROTOCOL); i++) { - epInfo[i].epAddr = 0; - epInfo[i].maxPktSize = (i) ? 0 : 8; - epInfo[i].epAttribs = 0; - epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; - } - bNumEP = 1; - bNumIface = 0; - bConfNum = 0; -} - -template -uint32_t HIDBoot::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); - - uint8_t buf[constBufSize]; - uint32_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint32_t len = 0; - //uint16_t cd_len = 0; - - uint32_t num_of_conf; // number of configurations - //uint32_t num_of_intf; // number of interfaces - - // Get memory address of USB device address pool - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("BM Init\r\n"); - //USBTRACE2("totalEndpoints:", (uint8_t) (totalEndpoints(BOOT_PROTOCOL))); - //USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); - - // Check if address has already been assigned to an instance - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - bInterval = 0; - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) { - USBTRACE("epinfo\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(0, 0, /*8*/sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - - if(!rcode) - len = (buf[0] > constBufSize) ? constBufSize : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - - goto FailGetDevDescr; - } - - - // Reset - UHD_BusReset(); - while( Is_uhd_starting_reset() ) {} - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; - - // Assign new address to the device SET_ADDRESS - - rcode = pUsb->setAddr(0, 0, bAddress); - if(rcode) { - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - USBTRACE2("setAddr:", rcode); - return rcode; - } - //delay(2); //per USB 2.0 sect.9.2.6.3 - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(bAddress, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // Restore p->epinfo - p->epinfo = oldep_ptr; - if (rcode) - { - goto FailGetDevDescr; - } - - TRACE_USBHOST(printf("HIDBoot::Init : device address is now %lu\r\n", bAddress);) - - p->lowspeed = false; - - //get pointer to assigned address record - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; - - USBTRACE2("NC:", num_of_conf); - - // GCC will optimize unused stuff away. - if((BOOT_PROTOCOL & (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) == (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) { - USBTRACE("HID_PROTOCOL_KEYBOARD AND MOUSE\r\n"); - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE, - CP_MASK_COMPARE_ALL > confDescrParser(this); - confDescrParser.SetOR(); // Use the OR variant. - for(uint32_t i = 0; i < num_of_conf; i++) { - pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) - break; - } - } else { - // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); - for(uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_KEYBOARD, - CP_MASK_COMPARE_ALL> confDescrParserA(this); - - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); - if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) - break; - } - } - - // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) { - USBTRACE("HID_PROTOCOL_MOUSE\r\n"); - for(uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_MOUSE, - CP_MASK_COMPARE_ALL> confDescrParserB(this); - - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL)))) - break; - - } - } - } - USBTRACE2("bNumEP:", bNumEP); - - if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { - rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - goto Fail; - } - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - //USBTRACE2("setEpInfoEntry returned ", rcode); - USBTRACE2("Cnf:", bConfNum); - - delay(1000); - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - - if(rcode) - goto FailSetConfDescr; - - delay(1000); - - USBTRACE2("bIfaceNum:", bIfaceNum); - USBTRACE2("bNumIface:", bNumIface); - - // Yes, mouse wants SetProtocol and SetIdle too! - for(uint32_t i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - USBTRACE2("\r\nInterface:", i); - rcode = SetProtocol(i, HID_BOOT_PROTOCOL); - if(rcode) goto FailSetProtocol; - USBTRACE2("PROTOCOL SET HID_BOOT rcode:", rcode); - rcode = SetIdle(i, 0, 0); - USBTRACE2("SET_IDLE rcode:", rcode); - // if(rcode) goto FailSetIdle; This can fail. - // Get the RPIPE and just throw it away. - SinkParser sink; - rcode = GetReportDescr(i, (USBReadParser *)&sink); - USBTRACE2("RPIPE rcode:", rcode); - } - - // Get RPIPE and throw it away. - - if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - // Wake keyboard interface by twinkling up to 5 LEDs that are in the spec. - // kana, compose, scroll, caps, num - rcode = 0x20; // Reuse rcode. - while(rcode) { - rcode >>= 1; - // Ignore any error returned, we don't care if LED is not supported - SetReport(0, 0, 2, 0, 1, (uint8_t*)&rcode); // Eventually becomes zero (All off) - delay(25); - } - } - USBTRACE("BM configured\r\n"); - - bPollEnable = true; - return 0; - -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(); - goto Fail; -#endif - - //FailSetDevTblEntry: - //#ifdef DEBUG_USB_HOST - // NotifyFailSetDevTblEntry(); - // goto Fail; - //#endif - - //FailGetConfDescr: - //#ifdef DEBUG_USB_HOST - // NotifyFailGetConfDescr(); - // goto Fail; - //#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(); - goto Fail; -#endif - -FailSetProtocol: -#ifdef DEBUG_USB_HOST - USBTRACE("SetProto:"); - goto Fail; -#endif - - //FailSetIdle: - //#ifdef DEBUG_USB_HOST - // USBTRACE("SetIdle:"); - //#endif - -Fail: -#ifdef DEBUG_USB_HOST - NotifyFail(rcode); -#endif - Release(); - - return rcode; -} - -template -void HIDBoot::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - // If the first configuration satisfies, the others are not considered. - //if(bNumEP > 1 && conf != bConfNum) - if(bNumEP == totalEndpoints(BOOT_PROTOCOL)) - return; - - bConfNum = conf; - bIfaceNum = iface; - - if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { - if(pep->bInterval > bInterval) bInterval = pep->bInterval; - - // Fill in the endpoint info structure - epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; - epInfo[bNumEP].epAttribs = 0; - epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; - bNumEP++; - - } -} - -template -uint32_t HIDBoot::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bConfNum = 0; - bIfaceNum = 0; - bNumEP = 1; - bAddress = 0; - qNextPollTime = 0; - bPollEnable = false; - - return 0; -} - -template -uint32_t HIDBoot::Poll() { - uint32_t rcode = 0; - - if(bPollEnable && ((long)(millis() - qNextPollTime) >= 0L)) { - - // To-do: optimize manually, using the for loop only if needed. - for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - const uint16_t const_buff_len = 16; - uint8_t buf[const_buff_len]; - - USBTRACE3("(hidboot.h) i=", i, 0x81); - USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].epAddr=", epInfo[epInterruptInIndex + i].epAddr, 0x81); - USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].maxPktSize=", epInfo[epInterruptInIndex + i].maxPktSize, 0x81); - uint16_t read = (uint16_t)epInfo[epInterruptInIndex + i].maxPktSize; - UHD_Pipe_Alloc(bAddress, epInfo[epInterruptInIndex + i].epAddr, USB_HOST_PTYPE_BULK, USB_EP_DIR_IN, epInfo[epInterruptInIndex + i].maxPktSize, 0, USB_HOST_NB_BK_1); - rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, (uint8_t*)&read, buf); - // SOME buggy dongles report extra keys (like sleep) using a 2 byte packet on the wrong endpoint. - // Since keyboard and mice must report at least 3 bytes, we ignore the extra data. - if(!rcode && read > 2) { - if(pRptParser[i]) - pRptParser[i]->Parse((HID*)this, 0, (uint8_t)read, buf); -#ifdef DEBUG_USB_HOST - // We really don't care about errors and anomalies unless we are debugging. - } else { - if(rcode != USB_ERRORFLOW) { - USBTRACE3("(hidboot.h) Poll:", rcode, 0x81); - } - if(!rcode && read) { - USBTRACE3("(hidboot.h) Strange read count: ", read, 0x80); - USBTRACE3("(hidboot.h) Interface:", i, 0x80); - } - } - - if(!rcode && read && (UsbDEBUGlvl > 0x7f)) { - for(uint8_t i = 0; i < read; i++) { - PrintHex (buf[i], 0x80); - USBTRACE1(" ", 0x80); - } - if(read) - USBTRACE1("\r\n", 0x80); -#endif - } - - } - qNextPollTime = millis() + bInterval; - } - return rcode; -} - -#endif /* HIDBOOT_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/hidescriptorparser.cpp b/test/libraries/USBHost/src/hidescriptorparser.cpp deleted file mode 100644 index 17e1e35a..00000000 --- a/test/libraries/USBHost/src/hidescriptorparser.cpp +++ /dev/null @@ -1,1599 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "hidescriptorparser.h" - -const char * const ReportDescParserBase::usagePageTitles0[] PROGMEM = { - pstrUsagePageGenericDesktopControls, - pstrUsagePageSimulationControls, - pstrUsagePageVRControls, - pstrUsagePageSportControls, - pstrUsagePageGameControls, - pstrUsagePageGenericDeviceControls, - pstrUsagePageKeyboardKeypad, - pstrUsagePageLEDs, - pstrUsagePageButton, - pstrUsagePageOrdinal, - pstrUsagePageTelephone, - pstrUsagePageConsumer, - pstrUsagePageDigitizer, - pstrUsagePagePID, - pstrUsagePageUnicode -}; - -const char * const ReportDescParserBase::usagePageTitles1[] PROGMEM = { - pstrUsagePageBarCodeScanner, - pstrUsagePageScale, - pstrUsagePageMSRDevices, - pstrUsagePagePointOfSale, - pstrUsagePageCameraControl, - pstrUsagePageArcade -}; -const char * const ReportDescParserBase::genDesktopTitles0[] PROGMEM = { - pstrUsagePointer, - pstrUsageMouse, - pstrUsageJoystick, - pstrUsageGamePad, - pstrUsageKeyboard, - pstrUsageKeypad, - pstrUsageMultiAxisController, - pstrUsageTabletPCSystemControls - -}; -const char * const ReportDescParserBase::genDesktopTitles1[] PROGMEM = { - pstrUsageX, - pstrUsageY, - pstrUsageZ, - pstrUsageRx, - pstrUsageRy, - pstrUsageRz, - pstrUsageSlider, - pstrUsageDial, - pstrUsageWheel, - pstrUsageHatSwitch, - pstrUsageCountedBuffer, - pstrUsageByteCount, - pstrUsageMotionWakeup, - pstrUsageStart, - pstrUsageSelect, - pstrUsagePageReserved, - pstrUsageVx, - pstrUsageVy, - pstrUsageVz, - pstrUsageVbrx, - pstrUsageVbry, - pstrUsageVbrz, - pstrUsageVno, - pstrUsageFeatureNotification, - pstrUsageResolutionMultiplier -}; -const char * const ReportDescParserBase::genDesktopTitles2[] PROGMEM = { - pstrUsageSystemControl, - pstrUsageSystemPowerDown, - pstrUsageSystemSleep, - pstrUsageSystemWakeup, - pstrUsageSystemContextMenu, - pstrUsageSystemMainMenu, - pstrUsageSystemAppMenu, - pstrUsageSystemMenuHelp, - pstrUsageSystemMenuExit, - pstrUsageSystemMenuSelect, - pstrUsageSystemMenuRight, - pstrUsageSystemMenuLeft, - pstrUsageSystemMenuUp, - pstrUsageSystemMenuDown, - pstrUsageSystemColdRestart, - pstrUsageSystemWarmRestart, - pstrUsageDPadUp, - pstrUsageDPadDown, - pstrUsageDPadRight, - pstrUsageDPadLeft -}; -const char * const ReportDescParserBase::genDesktopTitles3[] PROGMEM = { - pstrUsageSystemDock, - pstrUsageSystemUndock, - pstrUsageSystemSetup, - pstrUsageSystemBreak, - pstrUsageSystemDebuggerBreak, - pstrUsageApplicationBreak, - pstrUsageApplicationDebuggerBreak, - pstrUsageSystemSpeakerMute, - pstrUsageSystemHibernate -}; -const char * const ReportDescParserBase::genDesktopTitles4[] PROGMEM = { - pstrUsageSystemDisplayInvert, - pstrUsageSystemDisplayInternal, - pstrUsageSystemDisplayExternal, - pstrUsageSystemDisplayBoth, - pstrUsageSystemDisplayDual, - pstrUsageSystemDisplayToggleIntExt, - pstrUsageSystemDisplaySwapPriSec, - pstrUsageSystemDisplayLCDAutoscale -}; -const char * const ReportDescParserBase::simuTitles0[] PROGMEM = { - pstrUsageFlightSimulationDevice, - pstrUsageAutomobileSimulationDevice, - pstrUsageTankSimulationDevice, - pstrUsageSpaceshipSimulationDevice, - pstrUsageSubmarineSimulationDevice, - pstrUsageSailingSimulationDevice, - pstrUsageMotocicleSimulationDevice, - pstrUsageSportsSimulationDevice, - pstrUsageAirplaneSimulationDevice, - pstrUsageHelicopterSimulationDevice, - pstrUsageMagicCarpetSimulationDevice, - pstrUsageBicycleSimulationDevice -}; -const char * const ReportDescParserBase::simuTitles1[] PROGMEM = { - pstrUsageFlightControlStick, - pstrUsageFlightStick, - pstrUsageCyclicControl, - pstrUsageCyclicTrim, - pstrUsageFlightYoke, - pstrUsageTrackControl -}; -const char * const ReportDescParserBase::simuTitles2[] PROGMEM = { - pstrUsageAileron, - pstrUsageAileronTrim, - pstrUsageAntiTorqueControl, - pstrUsageAutopilotEnable, - pstrUsageChaffRelease, - pstrUsageCollectiveControl, - pstrUsageDiveBrake, - pstrUsageElectronicCountermeasures, - pstrUsageElevator, - pstrUsageElevatorTrim, - pstrUsageRudder, - pstrUsageThrottle, - pstrUsageFlightCommunications, - pstrUsageFlareRelease, - pstrUsageLandingGear, - pstrUsageToeBrake, - pstrUsageTrigger, - pstrUsageWeaponsArm, - pstrUsageWeaponsSelect, - pstrUsageWingFlaps, - pstrUsageAccelerator, - pstrUsageBrake, - pstrUsageClutch, - pstrUsageShifter, - pstrUsageSteering, - pstrUsageTurretDirection, - pstrUsageBarrelElevation, - pstrUsageDivePlane, - pstrUsageBallast, - pstrUsageBicycleCrank, - pstrUsageHandleBars, - pstrUsageFrontBrake, - pstrUsageRearBrake -}; -const char * const ReportDescParserBase::vrTitles0[] PROGMEM = { - pstrUsageBelt, - pstrUsageBodySuit, - pstrUsageFlexor, - pstrUsageGlove, - pstrUsageHeadTracker, - pstrUsageHeadMountedDisplay, - pstrUsageHandTracker, - pstrUsageOculometer, - pstrUsageVest, - pstrUsageAnimatronicDevice -}; -const char * const ReportDescParserBase::vrTitles1[] PROGMEM = { - pstrUsageStereoEnable, - pstrUsageDisplayEnable -}; -const char * const ReportDescParserBase::sportsCtrlTitles0[] PROGMEM = { - pstrUsageBaseballBat, - pstrUsageGolfClub, - pstrUsageRowingMachine, - pstrUsageTreadmill -}; -const char * const ReportDescParserBase::sportsCtrlTitles1[] PROGMEM = { - pstrUsageOar, - pstrUsageSlope, - pstrUsageRate, - pstrUsageStickSpeed, - pstrUsageStickFaceAngle, - pstrUsageStickHeelToe, - pstrUsageStickFollowThough, - pstrUsageStickTempo, - pstrUsageStickType, - pstrUsageStickHeight -}; -const char * const ReportDescParserBase::sportsCtrlTitles2[] PROGMEM = { - pstrUsagePutter, - pstrUsage1Iron, - pstrUsage2Iron, - pstrUsage3Iron, - pstrUsage4Iron, - pstrUsage5Iron, - pstrUsage6Iron, - pstrUsage7Iron, - pstrUsage8Iron, - pstrUsage9Iron, - pstrUsage10Iron, - pstrUsage11Iron, - pstrUsageSandWedge, - pstrUsageLoftWedge, - pstrUsagePowerWedge, - pstrUsage1Wood, - pstrUsage3Wood, - pstrUsage5Wood, - pstrUsage7Wood, - pstrUsage9Wood -}; -const char * const ReportDescParserBase::gameTitles0[] PROGMEM = { - pstrUsage3DGameController, - pstrUsagePinballDevice, - pstrUsageGunDevice -}; -const char * const ReportDescParserBase::gameTitles1[] PROGMEM = { - pstrUsagePointOfView, - pstrUsageTurnRightLeft, - pstrUsagePitchForwardBackward, - pstrUsageRollRightLeft, - pstrUsageMoveRightLeft, - pstrUsageMoveForwardBackward, - pstrUsageMoveUpDown, - pstrUsageLeanRightLeft, - pstrUsageLeanForwardBackward, - pstrUsageHeightOfPOV, - pstrUsageFlipper, - pstrUsageSecondaryFlipper, - pstrUsageBump, - pstrUsageNewGame, - pstrUsageShootBall, - pstrUsagePlayer, - pstrUsageGunBolt, - pstrUsageGunClip, - pstrUsageGunSelector, - pstrUsageGunSingleShot, - pstrUsageGunBurst, - pstrUsageGunAutomatic, - pstrUsageGunSafety, - pstrUsageGamepadFireJump, - pstrUsageGamepadTrigger -}; -const char * const ReportDescParserBase::genDevCtrlTitles[] PROGMEM = { - pstrUsageBatteryStrength, - pstrUsageWirelessChannel, - pstrUsageWirelessID, - pstrUsageDiscoverWirelessControl, - pstrUsageSecurityCodeCharEntered, - pstrUsageSecurityCodeCharErased, - pstrUsageSecurityCodeCleared -}; -const char * const ReportDescParserBase::ledTitles[] PROGMEM = { - pstrUsageNumLock, - pstrUsageCapsLock, - pstrUsageScrollLock, - pstrUsageCompose, - pstrUsageKana, - pstrUsagePower, - pstrUsageShift, - pstrUsageDoNotDisturb, - pstrUsageMute, - pstrUsageToneEnable, - pstrUsageHighCutFilter, - pstrUsageLowCutFilter, - pstrUsageEqualizerEnable, - pstrUsageSoundFieldOn, - pstrUsageSurroundOn, - pstrUsageRepeat, - pstrUsageStereo, - pstrUsageSamplingRateDetect, - pstrUsageSpinning, - pstrUsageCAV, - pstrUsageCLV, - pstrUsageRecordingFormatDetect, - pstrUsageOffHook, - pstrUsageRing, - pstrUsageMessageWaiting, - pstrUsageDataMode, - pstrUsageBatteryOperation, - pstrUsageBatteryOK, - pstrUsageBatteryLow, - pstrUsageSpeaker, - pstrUsageHeadSet, - pstrUsageHold, - pstrUsageMicrophone, - pstrUsageCoverage, - pstrUsageNightMode, - pstrUsageSendCalls, - pstrUsageCallPickup, - pstrUsageConference, - pstrUsageStandBy, - pstrUsageCameraOn, - pstrUsageCameraOff, - pstrUsageOnLine, - pstrUsageOffLine, - pstrUsageBusy, - pstrUsageReady, - pstrUsagePaperOut, - pstrUsagePaperJam, - pstrUsageRemote, - pstrUsageForward, - pstrUsageReverse, - pstrUsageStop, - pstrUsageRewind, - pstrUsageFastForward, - pstrUsagePlay, - pstrUsagePause, - pstrUsageRecord, - pstrUsageError, - pstrUsageSelectedIndicator, - pstrUsageInUseIndicator, - pstrUsageMultiModeIndicator, - pstrUsageIndicatorOn, - pstrUsageIndicatorFlash, - pstrUsageIndicatorSlowBlink, - pstrUsageIndicatorFastBlink, - pstrUsageIndicatorOff, - pstrUsageFlashOnTime, - pstrUsageSlowBlinkOnTime, - pstrUsageSlowBlinkOffTime, - pstrUsageFastBlinkOnTime, - pstrUsageFastBlinkOffTime, - pstrUsageIndicatorColor, - pstrUsageIndicatorRed, - pstrUsageIndicatorGreen, - pstrUsageIndicatorAmber, - pstrUsageGenericIndicator, - pstrUsageSystemSuspend, - pstrUsageExternalPowerConnected -}; -const char * const ReportDescParserBase::telTitles0 [] PROGMEM = { - pstrUsagePhone, - pstrUsageAnsweringMachine, - pstrUsageMessageControls, - pstrUsageHandset, - pstrUsageHeadset, - pstrUsageTelephonyKeyPad, - pstrUsageProgrammableButton -}; -const char * const ReportDescParserBase::telTitles1 [] PROGMEM = { - pstrUsageHookSwitch, - pstrUsageFlash, - pstrUsageFeature, - pstrUsageHold, - pstrUsageRedial, - pstrUsageTransfer, - pstrUsageDrop, - pstrUsagePark, - pstrUsageForwardCalls, - pstrUsageAlternateFunction, - pstrUsageLine, - pstrUsageSpeakerPhone, - pstrUsageConference, - pstrUsageRingEnable, - pstrUsageRingSelect, - pstrUsagePhoneMute, - pstrUsageCallerID, - pstrUsageSend -}; -const char * const ReportDescParserBase::telTitles2 [] PROGMEM = { - pstrUsageSpeedDial, - pstrUsageStoreNumber, - pstrUsageRecallNumber, - pstrUsagePhoneDirectory -}; -const char * const ReportDescParserBase::telTitles3 [] PROGMEM = { - pstrUsageVoiceMail, - pstrUsageScreenCalls, - pstrUsageDoNotDisturb, - pstrUsageMessage, - pstrUsageAnswerOnOff -}; -const char * const ReportDescParserBase::telTitles4 [] PROGMEM = { - pstrUsageInsideDialTone, - pstrUsageOutsideDialTone, - pstrUsageInsideRingTone, - pstrUsageOutsideRingTone, - pstrUsagePriorityRingTone, - pstrUsageInsideRingback, - pstrUsagePriorityRingback, - pstrUsageLineBusyTone, - pstrUsageReorderTone, - pstrUsageCallWaitingTone, - pstrUsageConfirmationTone1, - pstrUsageConfirmationTone2, - pstrUsageTonesOff, - pstrUsageOutsideRingback, - pstrUsageRinger -}; -const char * const ReportDescParserBase::telTitles5 [] PROGMEM = { - pstrUsagePhoneKey0, - pstrUsagePhoneKey1, - pstrUsagePhoneKey2, - pstrUsagePhoneKey3, - pstrUsagePhoneKey4, - pstrUsagePhoneKey5, - pstrUsagePhoneKey6, - pstrUsagePhoneKey7, - pstrUsagePhoneKey8, - pstrUsagePhoneKey9, - pstrUsagePhoneKeyStar, - pstrUsagePhoneKeyPound, - pstrUsagePhoneKeyA, - pstrUsagePhoneKeyB, - pstrUsagePhoneKeyC, - pstrUsagePhoneKeyD -}; -const char * const ReportDescParserBase::consTitles0[] PROGMEM = { - pstrUsageConsumerControl, - pstrUsageNumericKeyPad, - pstrUsageProgrammableButton, - pstrUsageMicrophone, - pstrUsageHeadphone, - pstrUsageGraphicEqualizer -}; -const char * const ReportDescParserBase::consTitles1[] PROGMEM = { - pstrUsagePlus10, - pstrUsagePlus100, - pstrUsageAMPM -}; -const char * const ReportDescParserBase::consTitles2[] PROGMEM = { - pstrUsagePower, - pstrUsageReset, - pstrUsageSleep, - pstrUsageSleepAfter, - pstrUsageSleepMode, - pstrUsageIllumination, - pstrUsageFunctionButtons - -}; -const char * const ReportDescParserBase::consTitles3[] PROGMEM = { - pstrUsageMenu, - pstrUsageMenuPick, - pstrUsageMenuUp, - pstrUsageMenuDown, - pstrUsageMenuLeft, - pstrUsageMenuRight, - pstrUsageMenuEscape, - pstrUsageMenuValueIncrease, - pstrUsageMenuValueDecrease -}; -const char * const ReportDescParserBase::consTitles4[] PROGMEM = { - pstrUsageDataOnScreen, - pstrUsageClosedCaption, - pstrUsageClosedCaptionSelect, - pstrUsageVCRTV, - pstrUsageBroadcastMode, - pstrUsageSnapshot, - pstrUsageStill -}; -const char * const ReportDescParserBase::consTitles5[] PROGMEM = { - pstrUsageSelection, - pstrUsageAssignSelection, - pstrUsageModeStep, - pstrUsageRecallLast, - pstrUsageEnterChannel, - pstrUsageOrderMovie, - pstrUsageChannel, - pstrUsageMediaSelection, - pstrUsageMediaSelectComputer, - pstrUsageMediaSelectTV, - pstrUsageMediaSelectWWW, - pstrUsageMediaSelectDVD, - pstrUsageMediaSelectTelephone, - pstrUsageMediaSelectProgramGuide, - pstrUsageMediaSelectVideoPhone, - pstrUsageMediaSelectGames, - pstrUsageMediaSelectMessages, - pstrUsageMediaSelectCD, - pstrUsageMediaSelectVCR, - pstrUsageMediaSelectTuner, - pstrUsageQuit, - pstrUsageHelp, - pstrUsageMediaSelectTape, - pstrUsageMediaSelectCable, - pstrUsageMediaSelectSatellite, - pstrUsageMediaSelectSecurity, - pstrUsageMediaSelectHome, - pstrUsageMediaSelectCall, - pstrUsageChannelIncrement, - pstrUsageChannelDecrement, - pstrUsageMediaSelectSAP, - pstrUsagePageReserved, - pstrUsageVCRPlus, - pstrUsageOnce, - pstrUsageDaily, - pstrUsageWeekly, - pstrUsageMonthly -}; -const char * const ReportDescParserBase::consTitles6[] PROGMEM = { - pstrUsagePlay, - pstrUsagePause, - pstrUsageRecord, - pstrUsageFastForward, - pstrUsageRewind, - pstrUsageScanNextTrack, - pstrUsageScanPreviousTrack, - pstrUsageStop, - pstrUsageEject, - pstrUsageRandomPlay, - pstrUsageSelectDisk, - pstrUsageEnterDisk, - pstrUsageRepeat, - pstrUsageTracking, - pstrUsageTrackNormal, - pstrUsageSlowTracking, - pstrUsageFrameForward, - pstrUsageFrameBackwards, - pstrUsageMark, - pstrUsageClearMark, - pstrUsageRepeatFromMark, - pstrUsageReturnToMark, - pstrUsageSearchMarkForward, - pstrUsageSearchMarkBackwards, - pstrUsageCounterReset, - pstrUsageShowCounter, - pstrUsageTrackingIncrement, - pstrUsageTrackingDecrement, - pstrUsageStopEject, - pstrUsagePlayPause, - pstrUsagePlaySkip -}; -const char * const ReportDescParserBase::consTitles7[] PROGMEM = { - pstrUsageVolume, - pstrUsageBalance, - pstrUsageMute, - pstrUsageBass, - pstrUsageTreble, - pstrUsageBassBoost, - pstrUsageSurroundMode, - pstrUsageLoudness, - pstrUsageMPX, - pstrUsageVolumeIncrement, - pstrUsageVolumeDecrement -}; -const char * const ReportDescParserBase::consTitles8[] PROGMEM = { - pstrUsageSpeedSelect, - pstrUsagePlaybackSpeed, - pstrUsageStandardPlay, - pstrUsageLongPlay, - pstrUsageExtendedPlay, - pstrUsageSlow -}; -const char * const ReportDescParserBase::consTitles9[] PROGMEM = { - pstrUsageFanEnable, - pstrUsageFanSpeed, - pstrUsageLightEnable, - pstrUsageLightIlluminationLevel, - pstrUsageClimateControlEnable, - pstrUsageRoomTemperature, - pstrUsageSecurityEnable, - pstrUsageFireAlarm, - pstrUsagePoliceAlarm, - pstrUsageProximity, - pstrUsageMotion, - pstrUsageDuresAlarm, - pstrUsageHoldupAlarm, - pstrUsageMedicalAlarm -}; -const char * const ReportDescParserBase::consTitlesA[] PROGMEM = { - pstrUsageBalanceRight, - pstrUsageBalanceLeft, - pstrUsageBassIncrement, - pstrUsageBassDecrement, - pstrUsageTrebleIncrement, - pstrUsageTrebleDecrement -}; -const char * const ReportDescParserBase::consTitlesB[] PROGMEM = { - pstrUsageSpeakerSystem, - pstrUsageChannelLeft, - pstrUsageChannelRight, - pstrUsageChannelCenter, - pstrUsageChannelFront, - pstrUsageChannelCenterFront, - pstrUsageChannelSide, - pstrUsageChannelSurround, - pstrUsageChannelLowFreqEnhancement, - pstrUsageChannelTop, - pstrUsageChannelUnknown -}; -const char * const ReportDescParserBase::consTitlesC[] PROGMEM = { - pstrUsageSubChannel, - pstrUsageSubChannelIncrement, - pstrUsageSubChannelDecrement, - pstrUsageAlternateAudioIncrement, - pstrUsageAlternateAudioDecrement -}; -const char * const ReportDescParserBase::consTitlesD[] PROGMEM = { - pstrUsageApplicationLaunchButtons, - pstrUsageALLaunchButtonConfigTool, - pstrUsageALProgrammableButton, - pstrUsageALConsumerControlConfig, - pstrUsageALWordProcessor, - pstrUsageALTextEditor, - pstrUsageALSpreadsheet, - pstrUsageALGraphicsEditor, - pstrUsageALPresentationApp, - pstrUsageALDatabaseApp, - pstrUsageALEmailReader, - pstrUsageALNewsreader, - pstrUsageALVoicemail, - pstrUsageALContactsAddressBook, - pstrUsageALCalendarSchedule, - pstrUsageALTaskProjectManager, - pstrUsageALLogJournalTimecard, - pstrUsageALCheckbookFinance, - pstrUsageALCalculator, - pstrUsageALAVCapturePlayback, - pstrUsageALLocalMachineBrowser, - pstrUsageALLANWANBrow, - pstrUsageALInternetBrowser, - pstrUsageALRemoteNetISPConnect, - pstrUsageALNetworkConference, - pstrUsageALNetworkChat, - pstrUsageALTelephonyDialer, - pstrUsageALLogon, - pstrUsageALLogoff, - pstrUsageALLogonLogoff, - pstrUsageALTermLockScrSav, - pstrUsageALControlPannel, - pstrUsageALCommandLineProcessorRun, - pstrUsageALProcessTaskManager, - pstrUsageALSelectTaskApplication, - pstrUsageALNextTaskApplication, - pstrUsageALPreviousTaskApplication, - pstrUsageALPreemptiveHaltTaskApp, - pstrUsageALIntegratedHelpCenter, - pstrUsageALDocuments, - pstrUsageALThesaurus, - pstrUsageALDictionary, - pstrUsageALDesktop, - pstrUsageALSpellCheck, - pstrUsageALGrammarCheck, - pstrUsageALWirelessStatus, - pstrUsageALKeyboardLayout, - pstrUsageALVirusProtection, - pstrUsageALEncryption, - pstrUsageALScreenSaver, - pstrUsageALAlarms, - pstrUsageALClock, - pstrUsageALFileBrowser, - pstrUsageALPowerStatus, - pstrUsageALImageBrowser, - pstrUsageALAudioBrowser, - pstrUsageALMovieBrowser, - pstrUsageALDigitalRightsManager, - pstrUsageALDigitalWallet, - pstrUsagePageReserved, - pstrUsageALInstantMessaging, - pstrUsageALOEMFeaturesBrowser, - pstrUsageALOEMHelp, - pstrUsageALOnlineCommunity, - pstrUsageALEntertainmentContentBrow, - pstrUsageALOnlineShoppingBrowser, - pstrUsageALSmartCardInfoHelp, - pstrUsageALMarketMonitorFinBrowser, - pstrUsageALCustomCorpNewsBrowser, - pstrUsageALOnlineActivityBrowser, - pstrUsageALResearchSearchBrowser, - pstrUsageALAudioPlayer -}; -const char * const ReportDescParserBase::consTitlesE[] PROGMEM = { - pstrUsageGenericGUIAppControls, - pstrUsageACNew, - pstrUsageACOpen, - pstrUsageACClose, - pstrUsageACExit, - pstrUsageACMaximize, - pstrUsageACMinimize, - pstrUsageACSave, - pstrUsageACPrint, - pstrUsageACProperties, - pstrUsageACUndo, - pstrUsageACCopy, - pstrUsageACCut, - pstrUsageACPaste, - pstrUsageACSelectAll, - pstrUsageACFind, - pstrUsageACFindAndReplace, - pstrUsageACSearch, - pstrUsageACGoto, - pstrUsageACHome, - pstrUsageACBack, - pstrUsageACForward, - pstrUsageACStop, - pstrUsageACRefresh, - pstrUsageACPreviousLink, - pstrUsageACNextLink, - pstrUsageACBookmarks, - pstrUsageACHistory, - pstrUsageACSubscriptions, - pstrUsageACZoomIn, - pstrUsageACZoomOut, - pstrUsageACZoom, - pstrUsageACFullScreenView, - pstrUsageACNormalView, - pstrUsageACViewToggle, - pstrUsageACScrollUp, - pstrUsageACScrollDown, - pstrUsageACScroll, - pstrUsageACPanLeft, - pstrUsageACPanRight, - pstrUsageACPan, - pstrUsageACNewWindow, - pstrUsageACTileHoriz, - pstrUsageACTileVert, - pstrUsageACFormat, - pstrUsageACEdit, - pstrUsageACBold, - pstrUsageACItalics, - pstrUsageACUnderline, - pstrUsageACStrikethrough, - pstrUsageACSubscript, - pstrUsageACSuperscript, - pstrUsageACAllCaps, - pstrUsageACRotate, - pstrUsageACResize, - pstrUsageACFlipHorizontal, - pstrUsageACFlipVertical, - pstrUsageACMirrorHorizontal, - pstrUsageACMirrorVertical, - pstrUsageACFontSelect, - pstrUsageACFontColor, - pstrUsageACFontSize, - pstrUsageACJustifyLeft, - pstrUsageACJustifyCenterH, - pstrUsageACJustifyRight, - pstrUsageACJustifyBlockH, - pstrUsageACJustifyTop, - pstrUsageACJustifyCenterV, - pstrUsageACJustifyBottom, - pstrUsageACJustifyBlockV, - pstrUsageACIndentDecrease, - pstrUsageACIndentIncrease, - pstrUsageACNumberedList, - pstrUsageACRestartNumbering, - pstrUsageACBulletedList, - pstrUsageACPromote, - pstrUsageACDemote, - pstrUsageACYes, - pstrUsageACNo, - pstrUsageACCancel, - pstrUsageACCatalog, - pstrUsageACBuyChkout, - pstrUsageACAddToCart, - pstrUsageACExpand, - pstrUsageACExpandAll, - pstrUsageACCollapse, - pstrUsageACCollapseAll, - pstrUsageACPrintPreview, - pstrUsageACPasteSpecial, - pstrUsageACInsertMode, - pstrUsageACDelete, - pstrUsageACLock, - pstrUsageACUnlock, - pstrUsageACProtect, - pstrUsageACUnprotect, - pstrUsageACAttachComment, - pstrUsageACDeleteComment, - pstrUsageACViewComment, - pstrUsageACSelectWord, - pstrUsageACSelectSentence, - pstrUsageACSelectParagraph, - pstrUsageACSelectColumn, - pstrUsageACSelectRow, - pstrUsageACSelectTable, - pstrUsageACSelectObject, - pstrUsageACRedoRepeat, - pstrUsageACSort, - pstrUsageACSortAscending, - pstrUsageACSortDescending, - pstrUsageACFilter, - pstrUsageACSetClock, - pstrUsageACViewClock, - pstrUsageACSelectTimeZone, - pstrUsageACEditTimeZone, - pstrUsageACSetAlarm, - pstrUsageACClearAlarm, - pstrUsageACSnoozeAlarm, - pstrUsageACResetAlarm, - pstrUsageACSyncronize, - pstrUsageACSendReceive, - pstrUsageACSendTo, - pstrUsageACReply, - pstrUsageACReplyAll, - pstrUsageACForwardMessage, - pstrUsageACSend, - pstrUsageACAttachFile, - pstrUsageACUpload, - pstrUsageACDownload, - pstrUsageACSetBorders, - pstrUsageACInsertRow, - pstrUsageACInsertColumn, - pstrUsageACInsertFile, - pstrUsageACInsertPicture, - pstrUsageACInsertObject, - pstrUsageACInsertSymbol, - pstrUsageACSaveAndClose, - pstrUsageACRename, - pstrUsageACMerge, - pstrUsageACSplit, - pstrUsageACDistributeHorizontaly, - pstrUsageACDistributeVerticaly -}; -const char * const ReportDescParserBase::digitTitles0[] PROGMEM = { - pstrUsageDigitizer, - pstrUsagePen, - pstrUsageLightPen, - pstrUsageTouchScreen, - pstrUsageTouchPad, - pstrUsageWhiteBoard, - pstrUsageCoordinateMeasuringMachine, - pstrUsage3DDigitizer, - pstrUsageStereoPlotter, - pstrUsageArticulatedArm, - pstrUsageArmature, - pstrUsageMultiplePointDigitizer, - pstrUsageFreeSpaceWand -}; -const char * const ReportDescParserBase::digitTitles1[] PROGMEM = { - pstrUsageStylus, - pstrUsagePuck, - pstrUsageFinger - -}; -const char * const ReportDescParserBase::digitTitles2[] PROGMEM = { - pstrUsageTipPressure, - pstrUsageBarrelPressure, - pstrUsageInRange, - pstrUsageTouch, - pstrUsageUntouch, - pstrUsageTap, - pstrUsageQuality, - pstrUsageDataValid, - pstrUsageTransducerIndex, - pstrUsageTabletFunctionKeys, - pstrUsageProgramChangeKeys, - pstrUsageBatteryStrength, - pstrUsageInvert, - pstrUsageXTilt, - pstrUsageYTilt, - pstrUsageAzimuth, - pstrUsageAltitude, - pstrUsageTwist, - pstrUsageTipSwitch, - pstrUsageSecondaryTipSwitch, - pstrUsageBarrelSwitch, - pstrUsageEraser, - pstrUsageTabletPick -}; -const char * const ReportDescParserBase::aplphanumTitles0[] PROGMEM = { - pstrUsageAlphanumericDisplay, - pstrUsageBitmappedDisplay -}; -const char * const ReportDescParserBase::aplphanumTitles1[] PROGMEM = { - pstrUsageDisplayAttributesReport, - pstrUsageASCIICharacterSet, - pstrUsageDataReadBack, - pstrUsageFontReadBack, - pstrUsageDisplayControlReport, - pstrUsageClearDisplay, - pstrUsageDisplayEnable, - pstrUsageScreenSaverDelay, - pstrUsageScreenSaverEnable, - pstrUsageVerticalScroll, - pstrUsageHorizontalScroll, - pstrUsageCharacterReport, - pstrUsageDisplayData, - pstrUsageDisplayStatus, - pstrUsageStatusNotReady, - pstrUsageStatusReady, - pstrUsageErrorNotALoadableCharacter, - pstrUsageErrorFotDataCanNotBeRead, - pstrUsageCursorPositionReport, - pstrUsageRow, - pstrUsageColumn, - pstrUsageRows, - pstrUsageColumns, - pstrUsageCursorPixelPosition, - pstrUsageCursorMode, - pstrUsageCursorEnable, - pstrUsageCursorBlink, - pstrUsageFontReport, - pstrUsageFontData, - pstrUsageCharacterWidth, - pstrUsageCharacterHeight, - pstrUsageCharacterSpacingHorizontal, - pstrUsageCharacterSpacingVertical, - pstrUsageUnicodeCharset, - pstrUsageFont7Segment, - pstrUsage7SegmentDirectMap, - pstrUsageFont14Segment, - pstrUsage14SegmentDirectMap, - pstrUsageDisplayBrightness, - pstrUsageDisplayContrast, - pstrUsageCharacterAttribute, - pstrUsageAttributeReadback, - pstrUsageAttributeData, - pstrUsageCharAttributeEnhance, - pstrUsageCharAttributeUnderline, - pstrUsageCharAttributeBlink -}; -const char * const ReportDescParserBase::aplphanumTitles2[] PROGMEM = { - pstrUsageBitmapSizeX, - pstrUsageBitmapSizeY, - pstrUsagePageReserved, - pstrUsageBitDepthFormat, - pstrUsageDisplayOrientation, - pstrUsagePaletteReport, - pstrUsagePaletteDataSize, - pstrUsagePaletteDataOffset, - pstrUsagePaletteData, - pstrUsageBlitReport, - pstrUsageBlitRectangleX1, - pstrUsageBlitRectangleY1, - pstrUsageBlitRectangleX2, - pstrUsageBlitRectangleY2, - pstrUsageBlitData, - pstrUsageSoftButton, - pstrUsageSoftButtonID, - pstrUsageSoftButtonSide, - pstrUsageSoftButtonOffset1, - pstrUsageSoftButtonOffset2, - pstrUsageSoftButtonReport -}; -const char * const ReportDescParserBase::medInstrTitles0[] PROGMEM = { - pstrUsageVCRAcquisition, - pstrUsageFreezeThaw, - pstrUsageClipStore, - pstrUsageUpdate, - pstrUsageNext, - pstrUsageSave, - pstrUsagePrint, - pstrUsageMicrophoneEnable -}; -const char * const ReportDescParserBase::medInstrTitles1[] PROGMEM = { - pstrUsageCine, - pstrUsageTransmitPower, - pstrUsageVolume, - pstrUsageFocus, - pstrUsageDepth -}; -const char * const ReportDescParserBase::medInstrTitles2[] PROGMEM = { - pstrUsageSoftStepPrimary, - pstrUsageSoftStepSecondary -}; -const char * const ReportDescParserBase::medInstrTitles3[] PROGMEM = { - pstrUsageZoomSelect, - pstrUsageZoomAdjust, - pstrUsageSpectralDopplerModeSelect, - pstrUsageSpectralDopplerModeAdjust, - pstrUsageColorDopplerModeSelect, - pstrUsageColorDopplerModeAdjust, - pstrUsageMotionModeSelect, - pstrUsageMotionModeAdjust, - pstrUsage2DModeSelect, - pstrUsage2DModeAdjust -}; -const char * const ReportDescParserBase::medInstrTitles4[] PROGMEM = { - pstrUsageSoftControlSelect, - pstrUsageSoftControlAdjust -}; - -void ReportDescParserBase::Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) { - uint32_t cntdn = (uint32_t)len; - uint8_t *p = (uint8_t*)pbuf; - - - totalSize = 0; - - while(cntdn) { - //USB_HOST_SERIAL.println(""); - //PrintHex(offset + len - cntdn); - //USB_HOST_SERIAL.print(":"); - - ParseItem(&p, &cntdn); - - //if (ParseItem(&p, &cntdn)) - // return; - } - //USBTRACE2("Total:", totalSize); -} - -void ReportDescParserBase::PrintValue(uint8_t *p, uint8_t len) { - E_Notify(PSTR("("), 0x80); - for(; len; p++, len--) - PrintHex (*p, 0x80); - E_Notify(PSTR(")"), 0x80); -} - -void ReportDescParserBase::PrintByteValue(uint8_t data) { - E_Notify(PSTR("("), 0x80); - PrintHex (data, 0x80); - E_Notify(PSTR(")"), 0x80); -} - -void ReportDescParserBase::PrintItemTitle(uint8_t prefix) { - switch(prefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_GLOBAL | TAG_GLOBAL_PUSH): - E_Notify(PSTR("\r\nPush"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_POP): - E_Notify(PSTR("\r\nPop"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - E_Notify(PSTR("\r\nUsage Page"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN): - E_Notify(PSTR("\r\nLogical Min"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX): - E_Notify(PSTR("\r\nLogical Max"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN): - E_Notify(PSTR("\r\nPhysical Min"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX): - E_Notify(PSTR("\r\nPhysical Max"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP): - E_Notify(PSTR("\r\nUnit Exp"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_UNIT): - E_Notify(PSTR("\r\nUnit"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - E_Notify(PSTR("\r\nReport Size"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - E_Notify(PSTR("\r\nReport Count"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - E_Notify(PSTR("\r\nReport Id"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - E_Notify(PSTR("\r\nUsage"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - E_Notify(PSTR("\r\nUsage Min"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - E_Notify(PSTR("\r\nUsage Max"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_COLLECTION): - E_Notify(PSTR("\r\nCollection"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION): - E_Notify(PSTR("\r\nEnd Collection"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - E_Notify(PSTR("\r\nInput"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - E_Notify(PSTR("\r\nOutput"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_FEATURE): - E_Notify(PSTR("\r\nFeature"), 0x80); - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) -} - -uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint32_t *pcntdn) { - //uint8_t ret = enErrorSuccess; - //reinterpret_cast<>(varBuffer); - switch(itemParseState) { - case 0: - if(**pp == HID_LONG_ITEM_PREFIX) - USBTRACE("\r\nLONG\r\n"); - else { - uint8_t size = ((**pp) & DATA_SIZE_MASK); - - itemPrefix = (**pp); - itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size); - - PrintItemTitle(itemPrefix); - } - (*pp)++; - (*pcntdn)--; - itemSize--; - itemParseState = 1; - - if(!itemSize) - break; - - if(!pcntdn) - return enErrorIncomplete; - case 1: - //USBTRACE2("\r\niSz:",itemSize); - - theBuffer.valueSize = itemSize; - valParser.Initialize(&theBuffer); - itemParseState = 2; - case 2: - if(!valParser.Parse(pp, pcntdn)) - return enErrorIncomplete; - itemParseState = 3; - case 3: - { - uint8_t data = *((uint8_t*)varBuffer); - - switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if(pfUsage) { - if(theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); - pfUsage(*ui16); - } else - pfUsage(data); - } - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - rptSize = data; - PrintByteValue(data); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - rptCount = data; - PrintByteValue(data); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN): - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN): - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP): - case (TYPE_GLOBAL | TAG_GLOBAL_UNIT): - PrintValue(varBuffer, theBuffer.valueSize); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PUSH): - case (TYPE_GLOBAL | TAG_GLOBAL_POP): - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - SetUsagePage(data); - PrintUsagePage(data); - PrintByteValue(data); - break; - case (TYPE_MAIN | TAG_MAIN_COLLECTION): - case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION): - switch(data) { - case 0x00: - E_Notify(PSTR(" Physical"), 0x80); - break; - case 0x01: - E_Notify(PSTR(" Application"), 0x80); - break; - case 0x02: - E_Notify(PSTR(" Logical"), 0x80); - break; - case 0x03: - E_Notify(PSTR(" Report"), 0x80); - break; - case 0x04: - E_Notify(PSTR(" Named Array"), 0x80); - break; - case 0x05: - E_Notify(PSTR(" Usage Switch"), 0x80); - break; - case 0x06: - E_Notify(PSTR(" Usage Modifier"), 0x80); - break; - default: - E_Notify(PSTR(" Vendor Defined("), 0x80); - PrintHex (data, 0x80); - E_Notify(PSTR(")"), 0x80); - } - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - case (TYPE_MAIN | TAG_MAIN_FEATURE): - totalSize += (uint16_t)rptSize * (uint16_t)rptCount; - rptSize = 0; - rptCount = 0; - E_Notify(PSTR("("), 0x80); - PrintBin (data, 0x80); - E_Notify(PSTR(")"), 0x80); - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) - } - } // switch (itemParseState) - itemParseState = 0; - return enErrorSuccess; -} - -ReportDescParserBase::UsagePageFunc ReportDescParserBase::usagePageFunctions[] /*PROGMEM*/ = { - &ReportDescParserBase::PrintGenericDesktopPageUsage, - &ReportDescParserBase::PrintSimulationControlsPageUsage, - &ReportDescParserBase::PrintVRControlsPageUsage, - &ReportDescParserBase::PrintSportsControlsPageUsage, - &ReportDescParserBase::PrintGameControlsPageUsage, - &ReportDescParserBase::PrintGenericDeviceControlsPageUsage, - NULL, // Keyboard/Keypad - &ReportDescParserBase::PrintLEDPageUsage, - &ReportDescParserBase::PrintButtonPageUsage, - &ReportDescParserBase::PrintOrdinalPageUsage, - &ReportDescParserBase::PrintTelephonyPageUsage, - &ReportDescParserBase::PrintConsumerPageUsage, - &ReportDescParserBase::PrintDigitizerPageUsage, - NULL, // Reserved - NULL, // PID - NULL // Unicode -}; - -void ReportDescParserBase::SetUsagePage(uint16_t page) { - pfUsage = NULL; - - if(VALUE_BETWEEN(page, 0x00, 0x11)) - pfUsage = (usagePageFunctions[page - 1]); - - // Dead code... - // - // pfUsage = (UsagePageFunc)pgm_read_pointer(usagePageFunctions[page - 1]); - //else if (page > 0x7f && page < 0x84) - // E_Notify(pstrUsagePageMonitor); - //else if (page > 0x83 && page < 0x8c) - // E_Notify(pstrUsagePagePower); - //else if (page > 0x8b && page < 0x92) - // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); - //else if (page > 0xfeff && page <= 0xffff) - // E_Notify(pstrUsagePageVendorDefined); - // - else - switch(page) { - case 0x14: - pfUsage = &ReportDescParserBase::PrintAlphanumDisplayPageUsage; - break; - case 0x40: - pfUsage = &ReportDescParserBase::PrintMedicalInstrumentPageUsage; - break; - } -} - -void ReportDescParserBase::PrintUsagePage(uint16_t page) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0, 0x80) - else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1, 0x80) - else if(VALUE_BETWEEN(page, 0x7f, 0x84)) - E_Notify(pstrUsagePageMonitor, 0x80); - else if(VALUE_BETWEEN(page, 0x83, 0x8c)) - E_Notify(pstrUsagePagePower, 0x80); - else if(page > 0xfeff /* && page <= 0xffff */) - E_Notify(pstrUsagePageVendorDefined, 0x80); - else - switch(page) { - case 0x14: - E_Notify(pstrUsagePageAlphaNumericDisplay, 0x80); - break; - case 0x40: - E_Notify(pstrUsagePageMedicalInstruments, 0x80); - break; - default: - E_Notify(pstrUsagePageUndefined, 0x80); - } -} - -void ReportDescParserBase::PrintButtonPageUsage(uint16_t usage) { - E_Notify(pstrSpace, 0x80); - E_Notify(PSTR("Btn"), 0x80); - PrintHex (usage, 0x80); - E_Notify(PSTR("\r\n"), 0x80); - //USB_HOST_SERIAL.print(usage, HEX); -} - -void ReportDescParserBase::PrintOrdinalPageUsage(uint16_t usage) { - E_Notify(pstrSpace, 0x80); - E_Notify(PSTR("Inst"), 0x80); - // Sorry, HEX for now... - PrintHex (usage, 0x80); - E_Notify(PSTR("\r\n"), 0x80); - //USB_HOST_SERIAL.print(usage, DEC); -} - -void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0, 0x80) - else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1, 0x80) - else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2, 0x80) - else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3, 0x80) - else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1, 0x80) - else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0, 0x80) - else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1, 0x80) - else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1, 0x80) - else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2, 0x80) - else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3, 0x80) - else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4, 0x80) - else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1, 0x80) - else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2, 0x80) - else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3, 0x80) - else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4, 0x80) - else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5, 0x80) - else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6, 0x80) - else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7, 0x80) - else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8, 0x80) - else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9, 0x80) - else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA, 0x80) - else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB, 0x80) - else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC, 0x80) - else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD, 0x80) - else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1, 0x80) - else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1, 0x80) - else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - if(usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); - else if(usage == 0x70) - E_Notify(pstrUsageDepthGainCompensation, 0x80); - else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0, 0x80) - else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1, 0x80) - else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2, 0x80) - else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3, 0x80) - else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint32_t *pcntdn) { - //uint8_t ret = enErrorSuccess; - - switch(itemParseState) { - case 0: - if(**pp == HID_LONG_ITEM_PREFIX) - USBTRACE("\r\nLONG\r\n"); - else { - uint8_t size = ((**pp) & DATA_SIZE_MASK); - itemPrefix = (**pp); - itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size); - } - (*pp)++; - (*pcntdn)--; - itemSize--; - itemParseState = 1; - - if(!itemSize) - break; - - if(!pcntdn) - return enErrorIncomplete; - case 1: - theBuffer.valueSize = itemSize; - valParser.Initialize(&theBuffer); - itemParseState = 2; - case 2: - if(!valParser.Parse(pp, pcntdn)) - return enErrorIncomplete; - itemParseState = 3; - case 3: - { - uint8_t data = *((uint8_t*)varBuffer); - - switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if(pfUsage) { - if(theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); - pfUsage(*ui16); - } else - pfUsage(data); - } - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - rptSize = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - rptCount = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - rptId = data; - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - useMin = data; - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - useMax = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - SetUsagePage(data); - break; - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - case (TYPE_MAIN | TAG_MAIN_FEATURE): - rptSize = 0; - rptCount = 0; - useMin = 0; - useMax = 0; - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - OnInputItem(data); - - totalSize += (uint16_t)rptSize * (uint16_t)rptCount; - - rptSize = 0; - rptCount = 0; - useMin = 0; - useMax = 0; - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) - } - } // switch (itemParseState) - itemParseState = 0; - return enErrorSuccess; -} - -void ReportDescParser2::OnInputItem(uint8_t itm) { - uint8_t byte_offset = (totalSize >> 3); // calculate offset to the next unhandled byte i = (int)(totalCount / 8); - uint32_t tmp = (byte_offset << 3); - uint8_t bit_offset = totalSize - tmp; // number of bits in the current byte already handled - uint8_t *p = pBuf + byte_offset; // current byte pointer - - if(bit_offset) - *p >>= bit_offset; - - uint8_t usage = useMin; - - bool print_usemin_usemax = ((useMin < useMax) && ((itm & 3) == 2) && pfUsage) ? true : false; - - uint8_t bits_of_byte = 8; - - // for each field in field array defined by rptCount - for(uint8_t field = 0; field < rptCount; field++, usage++) { - - union { - uint8_t bResult[4]; - uint16_t wResult[2]; - uint32_t dwResult; - } result; - - result.dwResult = 0; - uint8_t mask = 0; - - if(print_usemin_usemax) - pfUsage(usage); - - // bits_left - number of bits in the field(array of fields, depending on Report Count) left to process - // bits_of_byte - number of bits in current byte left to process - // bits_to_copy - number of bits to copy to result buffer - - // for each bit in a field - for(uint8_t bits_left = rptSize, bits_to_copy = 0; bits_left; - bits_left -= bits_to_copy) { - bits_to_copy = (bits_left > bits_of_byte) ? bits_of_byte : bits_left; - - result.dwResult <<= bits_to_copy; // Result buffer is shifted by the number of bits to be copied into it - - uint8_t val = *p; - - val >>= (8 - bits_of_byte); // Shift by the number of bits already processed - - mask = 0; - - for(uint8_t j = bits_to_copy; j; j--) { - mask <<= 1; - mask |= 1; - } - - result.bResult[0] = (result.bResult[0] | (val & mask)); - - bits_of_byte -= bits_to_copy; - - if(bits_of_byte < 1) { - bits_of_byte = 8; - p++; - } - } - PrintByteValue(result.dwResult); - } - E_Notify(PSTR("\r\n"), 0x80); -} - -void UniversalReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - ReportDescParser2 prs(len, buf); - - uint8_t ret = hid->GetReportDescr(0, &prs); - - if(ret) - ErrorMessage (PSTR("GetReportDescr-2"), ret); -} diff --git a/test/libraries/USBHost/src/hidescriptorparser.h b/test/libraries/USBHost/src/hidescriptorparser.h deleted file mode 100644 index 65803df5..00000000 --- a/test/libraries/USBHost/src/hidescriptorparser.h +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(__HIDDESCRIPTORPARSER_H__) -#define __HIDDESCRIPTORPARSER_H__ - -#include "hid.h" - -class ReportDescParserBase : public USBReadParser { -public: - typedef void (*UsagePageFunc)(uint16_t usage); - - static void PrintGenericDesktopPageUsage(uint16_t usage); - static void PrintSimulationControlsPageUsage(uint16_t usage); - static void PrintVRControlsPageUsage(uint16_t usage); - static void PrintSportsControlsPageUsage(uint16_t usage); - static void PrintGameControlsPageUsage(uint16_t usage); - static void PrintGenericDeviceControlsPageUsage(uint16_t usage); - static void PrintLEDPageUsage(uint16_t usage); - static void PrintButtonPageUsage(uint16_t usage); - static void PrintOrdinalPageUsage(uint16_t usage); - static void PrintTelephonyPageUsage(uint16_t usage); - static void PrintConsumerPageUsage(uint16_t usage); - static void PrintDigitizerPageUsage(uint16_t usage); - static void PrintAlphanumDisplayPageUsage(uint16_t usage); - static void PrintMedicalInstrumentPageUsage(uint16_t usage); - - static void PrintValue(uint8_t *p, uint8_t len); - static void PrintByteValue(uint8_t data); - - static void PrintItemTitle(uint8_t prefix); - - static const char * const usagePageTitles0[]; - static const char * const usagePageTitles1[]; - static const char * const genDesktopTitles0[]; - static const char * const genDesktopTitles1[]; - static const char * const genDesktopTitles2[]; - static const char * const genDesktopTitles3[]; - static const char * const genDesktopTitles4[]; - static const char * const simuTitles0[]; - static const char * const simuTitles1[]; - static const char * const simuTitles2[]; - static const char * const vrTitles0[]; - static const char * const vrTitles1[]; - static const char * const sportsCtrlTitles0[]; - static const char * const sportsCtrlTitles1[]; - static const char * const sportsCtrlTitles2[]; - static const char * const gameTitles0[]; - static const char * const gameTitles1[]; - static const char * const genDevCtrlTitles[]; - static const char * const ledTitles[]; - static const char * const telTitles0[]; - static const char * const telTitles1[]; - static const char * const telTitles2[]; - static const char * const telTitles3[]; - static const char * const telTitles4[]; - static const char * const telTitles5[]; - static const char * const consTitles0[]; - static const char * const consTitles1[]; - static const char * const consTitles2[]; - static const char * const consTitles3[]; - static const char * const consTitles4[]; - static const char * const consTitles5[]; - static const char * const consTitles6[]; - static const char * const consTitles7[]; - static const char * const consTitles8[]; - static const char * const consTitles9[]; - static const char * const consTitlesA[]; - static const char * const consTitlesB[]; - static const char * const consTitlesC[]; - static const char * const consTitlesD[]; - static const char * const consTitlesE[]; - static const char * const digitTitles0[]; - static const char * const digitTitles1[]; - static const char * const digitTitles2[]; - static const char * const aplphanumTitles0[]; - static const char * const aplphanumTitles1[]; - static const char * const aplphanumTitles2[]; - static const char * const medInstrTitles0[]; - static const char * const medInstrTitles1[]; - static const char * const medInstrTitles2[]; - static const char * const medInstrTitles3[]; - static const char * const medInstrTitles4[]; - -protected: - static UsagePageFunc usagePageFunctions[]; - - MultiValueBuffer theBuffer; - MultiByteValueParser valParser; - ByteSkipper theSkipper; - uint8_t varBuffer[sizeof (USB_CONFIGURATION_DESCRIPTOR)]; - - uint8_t itemParseState; // Item parser state variable - uint8_t itemSize; // Item size - uint8_t itemPrefix; // Item prefix (first byte) - uint8_t rptSize; // Report Size - uint8_t rptCount; // Report Count - - uint16_t totalSize; // Report size in bits - - virtual uint8_t ParseItem(uint8_t **pp, uint32_t *pcntdn); - - UsagePageFunc pfUsage; - - static void PrintUsagePage(uint16_t page); - void SetUsagePage(uint16_t page); - -public: - - ReportDescParserBase() : - itemParseState(0), - itemSize(0), - itemPrefix(0), - rptSize(0), - rptCount(0), - pfUsage(NULL) { - theBuffer.pValue = varBuffer; - valParser.Initialize(&theBuffer); - theSkipper.Initialize(&theBuffer); - }; - - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset); - - enum { - enErrorSuccess = 0 - , enErrorIncomplete // value or record is partialy read in buffer - , enErrorBufferTooSmall - }; -}; - -class ReportDescParser : public ReportDescParserBase { -}; - -class ReportDescParser2 : public ReportDescParserBase { - uint8_t rptId; // Report ID - uint8_t useMin; // Usage Minimum - uint8_t useMax; // Usage Maximum - uint8_t fieldCount; // Number of field being currently processed - - void OnInputItem(uint8_t itm); // Method which is called every time Input item is found - - uint8_t *pBuf; // Report buffer pointer - uint8_t bLen; // Report length - -protected: - virtual uint8_t ParseItem(uint8_t **pp, uint32_t *pcntdn); - -public: - - ReportDescParser2(uint16_t len, uint8_t *pbuf) : - ReportDescParserBase(), rptId(0), useMin(0), useMax(0), fieldCount(0), pBuf(pbuf), bLen(len) { - }; -}; - -class UniversalReportParser : public HIDReportParser { -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); -}; - -#endif // __HIDDESCRIPTORPARSER_H__ diff --git a/test/libraries/USBHost/src/hiduniversal.cpp b/test/libraries/USBHost/src/hiduniversal.cpp deleted file mode 100644 index ac5309b8..00000000 --- a/test/libraries/USBHost/src/hiduniversal.cpp +++ /dev/null @@ -1,421 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "Arduino.h" -#include "hiduniversal.h" - -HIDUniversal::HIDUniversal(USBHost *p) : -HID(p), -qNextPollTime(0), -pollInterval(0), -bPollEnable(false), -bHasReportId(false) { - Initialize(); - - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -uint16_t HIDUniversal::GetHidClassDescrLen(uint8_t type, uint8_t num) { - for(uint8_t i = 0, n = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { - if(descrInfo[i].bDescrType == type) { - if(n == num) - return descrInfo[i].wDescriptorLength; - n++; - } - } - return 0; -} - -void HIDUniversal::Initialize() { - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - rptParsers[i].rptId = 0; - rptParsers[i].rptParser = NULL; - } - for(uint8_t i = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { - descrInfo[i].bDescrType = 0; - descrInfo[i].wDescriptorLength = 0; - } - for(uint8_t i = 0; i < maxHidInterfaces; i++) { - hidInterfaces[i].bmInterface = 0; - hidInterfaces[i].bmProtocol = 0; - - for(uint8_t j = 0; j < maxEpPerInterface; j++) - hidInterfaces[i].epIndex[j] = 0; - } - for(uint8_t i = 0; i < totalEndpoints; i++) { - epInfo[i].epAddr = 0; - epInfo[i].maxPktSize = (i) ? 0 : 8; - epInfo[i].epAttribs = 0; - epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; - } - bNumEP = 1; - bNumIface = 0; - bConfNum = 0; - pollInterval = 0; - - ZeroMemory(constBuffLen, prevBuf); -} - -uint32_t HIDUniversal::SetReportParser(uint32_t id, HIDReportParser *prs) { - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if(rptParsers[i].rptId == 0 && rptParsers[i].rptParser == NULL) { - rptParsers[i].rptId = id; - rptParsers[i].rptParser = prs; - return true; - } - } - return false; -} - -HIDReportParser* HIDUniversal::GetReportParser(uint32_t id) { - if(!bHasReportId) - return ((rptParsers[0].rptParser) ? rptParsers[0].rptParser : NULL); - - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if(rptParsers[i].rptId == id) - return rptParsers[i].rptParser; - } - return NULL; -} - -uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { - const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); - - uint8_t buf[constBufSize]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - uint8_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint8_t len = 0; - - uint8_t num_of_conf; // number of configurations - //uint8_t num_of_intf; // number of interfaces - - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("HU Init\r\n"); - - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) { - USBTRACE("epinfo\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - - if(!rcode) - len = (buf[0] > constBufSize) ? constBufSize : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - - goto FailGetDevDescr; - } - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device - rcode = pUsb->setAddr(0, 0, bAddress); - - if(rcode) { - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - USBTRACE2("setAddr:", rcode); - return rcode; - } - - //delay(2); //per USB 2.0 sect.9.2.6.3 - - USBTRACE2("Addr:", bAddress); - - p->lowspeed = false; - - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - VID = udd->idVendor; // Can be used by classes that inherits this class to check the VID and PID of the connected device - PID = udd->idProduct; - - num_of_conf = udd->bNumConfigurations; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - - if(rcode) - goto FailSetDevTblEntry; - - USBTRACE2("NC:", num_of_conf); - - for(uint8_t i = 0; i < num_of_conf; i++) { - //HexDumper HexDump; - ConfigDescParser confDescrParser(this); - - //rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump); - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - - if(rcode) - goto FailGetConfDescr; - - if(bNumEP > 1) - break; - } // for - - if(bNumEP < 2) - return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - - USBTRACE2("Cnf:", bConfNum); - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - - if(rcode) - goto FailSetConfDescr; - - for(uint8_t i = 0; i < bNumIface; i++) { - if(hidInterfaces[i].epIndex[epInterruptInIndex] == 0) - continue; - - rcode = SetIdle(hidInterfaces[i].bmInterface, 0, 0); - - if(rcode)/* && rcode != hrSTALL) */ - goto FailSetIdle; - } - - USBTRACE("HU configured\r\n"); - - OnInitSuccessful(); - - bPollEnable = true; - return 0; - -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(); - goto Fail; -#endif - -FailSetDevTblEntry: -#ifdef DEBUG_USB_HOST - NotifyFailSetDevTblEntry(); - goto Fail; -#endif - -FailGetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetConfDescr(); - goto Fail; -#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(); - goto Fail; -#endif - - -FailSetIdle: -#ifdef DEBUG_USB_HOST - USBTRACE("SetIdle:"); -#endif - -#ifdef DEBUG_USB_HOST -Fail: - NotifyFail(rcode); -#endif - Release(); - return rcode; -} - -HIDUniversal::HIDInterface* HIDUniversal::FindInterface(uint8_t iface, uint8_t alt, uint8_t proto) { - for(uint8_t i = 0; i < bNumIface && i < maxHidInterfaces; i++) - if(hidInterfaces[i].bmInterface == iface && hidInterfaces[i].bmAltSet == alt - && hidInterfaces[i].bmProtocol == proto) - return hidInterfaces + i; - return NULL; -} - -void HIDUniversal::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - // If the first configuration satisfies, the others are not concidered. - if(bNumEP > 1 && conf != bConfNum) - return; - - //ErrorMessage(PSTR("\r\nConf.Val"), conf); - //ErrorMessage(PSTR("Iface Num"), iface); - //ErrorMessage(PSTR("Alt.Set"), alt); - - bConfNum = conf; - - uint8_t index = 0; - HIDInterface *piface = FindInterface(iface, alt, proto); - - // Fill in interface structure in case of new interface - if(!piface) { - piface = hidInterfaces + bNumIface; - piface->bmInterface = iface; - piface->bmAltSet = alt; - piface->bmProtocol = proto; - bNumIface++; - } - - if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) - index = epInterruptInIndex; - else - index = epInterruptOutIndex; - - if(index) { - // Fill in the endpoint info structure - epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; - epInfo[bNumEP].epAttribs = 0; - epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; - - // Fill in the endpoint index list - piface->epIndex[index] = bNumEP; //(pep->bEndpointAddress & 0x0F); - - if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints - pollInterval = pep->bInterval; - - bNumEP++; - } - //PrintEndpointDescriptor(pep); -} - -uint32_t HIDUniversal::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bNumEP = 1; - bAddress = 0; - qNextPollTime = 0; - bPollEnable = false; - return 0; -} - -bool HIDUniversal::BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2) { - for(uint8_t i = 0; i < len; i++) - if(buf1[i] != buf2[i]) - return false; - return true; -} - -void HIDUniversal::ZeroMemory(uint8_t len, uint8_t *buf) { - for(uint8_t i = 0; i < len; i++) - buf[i] = 0; -} - -void HIDUniversal::SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest) { - for(uint8_t i = 0; i < len; i++) - dest[i] = src[i]; -} - -uint32_t HIDUniversal::Poll() { - uint32_t rcode = 0; - - if(!bPollEnable) - return 0; - - if((long)(millis() - qNextPollTime) >= 0L) { - qNextPollTime = millis() + pollInterval; - - uint8_t buf[constBuffLen]; - - for(uint8_t i = 0; i < bNumIface; i++) { - uint8_t index = hidInterfaces[i].epIndex[epInterruptInIndex]; - uint16_t read = (uint8_t)epInfo[index].maxPktSize; - - ZeroMemory(constBuffLen, buf); - - uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[index].epAddr, (uint8_t*)&read, buf); - - if(rcode) { - if(rcode != USB_ERRORFLOW/*hrNAK*/) - USBTRACE3("(hiduniversal.h) Poll:", rcode, 0x81); - return rcode; - } - - if(read > constBuffLen) - read = constBuffLen; - - bool identical = BuffersIdentical(read, buf, prevBuf); - - SaveBuffer(read, buf, prevBuf); - - if(identical) - return 0; -#if 0 - Notify(PSTR("\r\nBuf: "), 0x80); - - for(uint8_t i = 0; i < read; i++) { - D_PrintHex (buf[i], 0x80); - Notify(PSTR(" "), 0x80); - } - - Notify(PSTR("\r\n"), 0x80); -#endif - ParseHIDData(this, bHasReportId, (uint8_t)read, buf); - - HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0)); - - if(prs) - prs->Parse(this, bHasReportId, (uint8_t)read, buf); - } - } - return rcode; -} diff --git a/test/libraries/USBHost/src/hiduniversal.h b/test/libraries/USBHost/src/hiduniversal.h deleted file mode 100644 index 9c033f0a..00000000 --- a/test/libraries/USBHost/src/hiduniversal.h +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(__HIDUNIVERSAL_H__) -#define __HIDUNIVERSAL_H__ - -#include "hid.h" -//#include "hidescriptorparser.h" - -class HIDUniversal : public HID { - - struct ReportParser { - uint8_t rptId; - HIDReportParser *rptParser; - } rptParsers[MAX_REPORT_PARSERS]; - - // HID class specific descriptor type and length info obtained from HID descriptor - HID_CLASS_DESCRIPTOR_LEN_AND_TYPE descrInfo[HID_MAX_HID_CLASS_DESCRIPTORS]; - - // Returns HID class specific descriptor length by its type and order number - uint16_t GetHidClassDescrLen(uint8_t type, uint8_t num); - - struct HIDInterface { - struct { - uint8_t bmInterface : 3; - uint8_t bmAltSet : 3; - uint8_t bmProtocol : 2; - }; - uint8_t epIndex[maxEpPerInterface]; - }; - - uint8_t bConfNum; // configuration number - uint8_t bNumIface; // number of interfaces in the configuration - uint8_t bNumEP; // total number of EP in the configuration - uint32_t qNextPollTime; // next poll time - uint8_t pollInterval; - bool bPollEnable; // poll enable flag - - static const uint16_t constBuffLen = 64; // event buffer length - uint8_t prevBuf[constBuffLen]; // previous event buffer - - void Initialize(); - HIDInterface* FindInterface(uint8_t iface, uint8_t alt, uint8_t proto); - - void ZeroMemory(uint8_t len, uint8_t *buf); - bool BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2); - void SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest); - -protected: - EpInfo epInfo[totalEndpoints]; - HIDInterface hidInterfaces[maxHidInterfaces]; - - bool bHasReportId; - - uint16_t PID, VID; // PID and VID of connected device - - // HID implementation - virtual HIDReportParser* GetReportParser(uint32_t id); - - virtual uint32_t OnInitSuccessful() { - return 0; - }; - - virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { - return; - }; - -public: - HIDUniversal(USBHost *p); - - // HID implementation - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs); - - // USBDeviceConfig implementation - virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t isReady() { - return bPollEnable; - }; - - // UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; - -#endif // __HIDUNIVERSAL_H__ diff --git a/test/libraries/USBHost/src/hidusagestr.h b/test/libraries/USBHost/src/hidusagestr.h deleted file mode 100644 index 71e53787..00000000 --- a/test/libraries/USBHost/src/hidusagestr.h +++ /dev/null @@ -1,977 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#if !defined( __HIDUSAGESTR_H__) -#define __HIDUSAGESTR_H__ - -#include "Usb.h" - -const char pstrSpace [] PROGMEM = " "; -const char pstrCRLF [] PROGMEM = "\r\n"; -const char pstrSingleTab [] PROGMEM = "\t"; -const char pstrDoubleTab [] PROGMEM = "\t\t"; -const char pstrTripleTab [] PROGMEM = "\t\t\t"; - -// Usage Page String Titles -const char pstrUsagePageUndefined [] PROGMEM = "Undef"; -const char pstrUsagePageGenericDesktopControls [] PROGMEM = "Gen Desktop Ctrls"; -const char pstrUsagePageSimulationControls [] PROGMEM = "Simu Ctrls"; -const char pstrUsagePageVRControls [] PROGMEM = "VR Ctrls"; -const char pstrUsagePageSportControls [] PROGMEM = "Sport Ctrls"; -const char pstrUsagePageGameControls [] PROGMEM = "Game Ctrls"; -const char pstrUsagePageGenericDeviceControls [] PROGMEM = "Gen Dev Ctrls"; -const char pstrUsagePageKeyboardKeypad [] PROGMEM = "Kbrd/Keypad"; -const char pstrUsagePageLEDs [] PROGMEM = "LEDs"; -const char pstrUsagePageButton [] PROGMEM = "Button"; -const char pstrUsagePageOrdinal [] PROGMEM = "Ordinal"; -const char pstrUsagePageTelephone [] PROGMEM = "Tel"; -const char pstrUsagePageConsumer [] PROGMEM = "Consumer"; -const char pstrUsagePageDigitizer [] PROGMEM = "Digitizer"; -const char pstrUsagePagePID [] PROGMEM = "PID"; -const char pstrUsagePageUnicode [] PROGMEM = "Unicode"; -const char pstrUsagePageAlphaNumericDisplay [] PROGMEM = "Alpha Num Disp"; -const char pstrUsagePageMedicalInstruments [] PROGMEM = "Medical Instr"; -const char pstrUsagePageMonitor [] PROGMEM = "Monitor"; -const char pstrUsagePagePower [] PROGMEM = "Power"; -const char pstrUsagePageBarCodeScanner [] PROGMEM = "Bar Code Scan"; -const char pstrUsagePageScale [] PROGMEM = "Scale"; -const char pstrUsagePageMSRDevices [] PROGMEM = "Magn Stripe Read Dev"; -const char pstrUsagePagePointOfSale [] PROGMEM = "POS"; -const char pstrUsagePageCameraControl [] PROGMEM = "Cam Ctrl"; -const char pstrUsagePageArcade [] PROGMEM = "Arcade"; -const char pstrUsagePageReserved [] PROGMEM = "Reserved"; -const char pstrUsagePageVendorDefined [] PROGMEM = "Vendor Def"; - -// Generic Desktop Controls Page -const char pstrUsagePointer [] PROGMEM = "Pointer"; -const char pstrUsageMouse [] PROGMEM = "Mouse"; -const char pstrUsageJoystick [] PROGMEM = "Joystick"; -const char pstrUsageGamePad [] PROGMEM = "Game Pad"; -const char pstrUsageKeyboard [] PROGMEM = "Kbrd"; -const char pstrUsageKeypad [] PROGMEM = "Keypad"; -const char pstrUsageMultiAxisController [] PROGMEM = "Multi-axis Ctrl"; -const char pstrUsageTabletPCSystemControls [] PROGMEM = "Tablet PC Sys Ctrls"; -const char pstrUsageX [] PROGMEM = "X"; -const char pstrUsageY [] PROGMEM = "Y"; -const char pstrUsageZ [] PROGMEM = "Z"; -const char pstrUsageRx [] PROGMEM = "Rx"; -const char pstrUsageRy [] PROGMEM = "Ry"; -const char pstrUsageRz [] PROGMEM = "Rz"; -const char pstrUsageSlider [] PROGMEM = "Slider"; -const char pstrUsageDial [] PROGMEM = "Dial"; -const char pstrUsageWheel [] PROGMEM = "Wheel"; -const char pstrUsageHatSwitch [] PROGMEM = "Hat Switch"; -const char pstrUsageCountedBuffer [] PROGMEM = "Counted Buf"; -const char pstrUsageByteCount [] PROGMEM = "Byte Count"; -const char pstrUsageMotionWakeup [] PROGMEM = "Motion Wakeup"; -const char pstrUsageStart [] PROGMEM = "Start"; -const char pstrUsageSelect [] PROGMEM = "Sel"; -const char pstrUsageVx [] PROGMEM = "Vx"; -const char pstrUsageVy [] PROGMEM = "Vy"; -const char pstrUsageVz [] PROGMEM = "Vz"; -const char pstrUsageVbrx [] PROGMEM = "Vbrx"; -const char pstrUsageVbry [] PROGMEM = "Vbry"; -const char pstrUsageVbrz [] PROGMEM = "Vbrz"; -const char pstrUsageVno [] PROGMEM = "Vno"; -const char pstrUsageFeatureNotification [] PROGMEM = "Feature Notif"; -const char pstrUsageResolutionMultiplier [] PROGMEM = "Res Mult"; -const char pstrUsageSystemControl [] PROGMEM = "Sys Ctrl"; -const char pstrUsageSystemPowerDown [] PROGMEM = "Sys Pwr Down"; -const char pstrUsageSystemSleep [] PROGMEM = "Sys Sleep"; -const char pstrUsageSystemWakeup [] PROGMEM = "Sys Wakeup"; -const char pstrUsageSystemContextMenu [] PROGMEM = "Sys Context Menu"; -const char pstrUsageSystemMainMenu [] PROGMEM = "Sys Main Menu"; -const char pstrUsageSystemAppMenu [] PROGMEM = "Sys App Menu"; -const char pstrUsageSystemMenuHelp [] PROGMEM = "Sys Menu Help"; -const char pstrUsageSystemMenuExit [] PROGMEM = "Sys Menu Exit"; -const char pstrUsageSystemMenuSelect [] PROGMEM = "Sys Menu Select"; -const char pstrUsageSystemMenuRight [] PROGMEM = "Sys Menu Right"; -const char pstrUsageSystemMenuLeft [] PROGMEM = "Sys Menu Left"; -const char pstrUsageSystemMenuUp [] PROGMEM = "Sys Menu Up"; -const char pstrUsageSystemMenuDown [] PROGMEM = "Sys Menu Down"; -const char pstrUsageSystemColdRestart [] PROGMEM = "Sys Cold Restart"; -const char pstrUsageSystemWarmRestart [] PROGMEM = "Sys Warm Restart"; -const char pstrUsageDPadUp [] PROGMEM = "D-pad Up"; -const char pstrUsageDPadDown [] PROGMEM = "D-pad Down"; -const char pstrUsageDPadRight [] PROGMEM = "D-pad Right"; -const char pstrUsageDPadLeft [] PROGMEM = "D-pad Left"; -const char pstrUsageSystemDock [] PROGMEM = "Sys Dock"; -const char pstrUsageSystemUndock [] PROGMEM = "Sys Undock"; -const char pstrUsageSystemSetup [] PROGMEM = "Sys Setup"; -const char pstrUsageSystemBreak [] PROGMEM = "Sys Break"; -const char pstrUsageSystemDebuggerBreak [] PROGMEM = "Sys Dbg Brk"; -const char pstrUsageApplicationBreak [] PROGMEM = "App Break"; -const char pstrUsageApplicationDebuggerBreak [] PROGMEM = "App Dbg Brk"; -const char pstrUsageSystemSpeakerMute [] PROGMEM = "Sys Spk Mute"; -const char pstrUsageSystemHibernate [] PROGMEM = "Sys Hiber"; -const char pstrUsageSystemDisplayInvert [] PROGMEM = "Sys Disp Inv"; -const char pstrUsageSystemDisplayInternal [] PROGMEM = "Sys Disp Int"; -const char pstrUsageSystemDisplayExternal [] PROGMEM = "Sys Disp Ext"; -const char pstrUsageSystemDisplayBoth [] PROGMEM = "Sys Disp Both"; -const char pstrUsageSystemDisplayDual [] PROGMEM = "Sys Disp Dual"; -const char pstrUsageSystemDisplayToggleIntExt [] PROGMEM = "Sys Disp Tgl Int/Ext"; -const char pstrUsageSystemDisplaySwapPriSec [] PROGMEM = "Sys Disp Swap Pri/Sec"; -const char pstrUsageSystemDisplayLCDAutoscale [] PROGMEM = "Sys Disp LCD Autoscale"; - -// Simulation Controls Page -const char pstrUsageFlightSimulationDevice [] PROGMEM = "Flight Simu Dev"; -const char pstrUsageAutomobileSimulationDevice [] PROGMEM = "Auto Simu Dev"; -const char pstrUsageTankSimulationDevice [] PROGMEM = "Tank Simu Dev"; -const char pstrUsageSpaceshipSimulationDevice [] PROGMEM = "Space Simu Dev"; -const char pstrUsageSubmarineSimulationDevice [] PROGMEM = "Subm Simu Dev"; -const char pstrUsageSailingSimulationDevice [] PROGMEM = "Sail Simu Dev"; -const char pstrUsageMotocicleSimulationDevice [] PROGMEM = "Moto Simu Dev"; -const char pstrUsageSportsSimulationDevice [] PROGMEM = "Sport Simu Dev"; -const char pstrUsageAirplaneSimulationDevice [] PROGMEM = "Airp Simu Dev"; -const char pstrUsageHelicopterSimulationDevice [] PROGMEM = "Heli Simu Dev"; -const char pstrUsageMagicCarpetSimulationDevice [] PROGMEM = "Magic Carpet Simu Dev"; -const char pstrUsageBicycleSimulationDevice [] PROGMEM = "Bike Simu Dev"; -const char pstrUsageFlightControlStick [] PROGMEM = "Flight Ctrl Stick"; -const char pstrUsageFlightStick [] PROGMEM = "Flight Stick"; -const char pstrUsageCyclicControl [] PROGMEM = "Cyclic Ctrl"; -const char pstrUsageCyclicTrim [] PROGMEM = "Cyclic Trim"; -const char pstrUsageFlightYoke [] PROGMEM = "Flight Yoke"; -const char pstrUsageTrackControl [] PROGMEM = "Track Ctrl"; -const char pstrUsageAileron [] PROGMEM = "Aileron"; -const char pstrUsageAileronTrim [] PROGMEM = "Aileron Trim"; -const char pstrUsageAntiTorqueControl [] PROGMEM = "Anti-Torque Ctrl"; -const char pstrUsageAutopilotEnable [] PROGMEM = "Autopilot Enable"; -const char pstrUsageChaffRelease [] PROGMEM = "Chaff Release"; -const char pstrUsageCollectiveControl [] PROGMEM = "Collective Ctrl"; -const char pstrUsageDiveBrake [] PROGMEM = "Dive Brake"; -const char pstrUsageElectronicCountermeasures [] PROGMEM = "El Countermeasures"; -const char pstrUsageElevator [] PROGMEM = "Elevator"; -const char pstrUsageElevatorTrim [] PROGMEM = "Elevator Trim"; -const char pstrUsageRudder [] PROGMEM = "Rudder"; -const char pstrUsageThrottle [] PROGMEM = "Throttle"; -const char pstrUsageFlightCommunications [] PROGMEM = "Flight Comm"; -const char pstrUsageFlareRelease [] PROGMEM = "Flare Release"; -const char pstrUsageLandingGear [] PROGMEM = "Landing Gear"; -const char pstrUsageToeBrake [] PROGMEM = "Toe Brake"; -const char pstrUsageTrigger [] PROGMEM = "Trigger"; -const char pstrUsageWeaponsArm [] PROGMEM = "Weapons Arm"; -const char pstrUsageWeaponsSelect [] PROGMEM = "Weapons Sel"; -const char pstrUsageWingFlaps [] PROGMEM = "Wing Flaps"; -const char pstrUsageAccelerator [] PROGMEM = "Accel"; -const char pstrUsageBrake [] PROGMEM = "Brake"; -const char pstrUsageClutch [] PROGMEM = "Clutch"; -const char pstrUsageShifter [] PROGMEM = "Shifter"; -const char pstrUsageSteering [] PROGMEM = "Steering"; -const char pstrUsageTurretDirection [] PROGMEM = "Turret Dir"; -const char pstrUsageBarrelElevation [] PROGMEM = "Barrel Ele"; -const char pstrUsageDivePlane [] PROGMEM = "Dive Plane"; -const char pstrUsageBallast [] PROGMEM = "Ballast"; -const char pstrUsageBicycleCrank [] PROGMEM = "Bicycle Crank"; -const char pstrUsageHandleBars [] PROGMEM = "Handle Bars"; -const char pstrUsageFrontBrake [] PROGMEM = "Front Brake"; -const char pstrUsageRearBrake [] PROGMEM = "Rear Brake"; - -// VR Controls Page -const char pstrUsageBelt [] PROGMEM = "Belt"; -const char pstrUsageBodySuit [] PROGMEM = "Body Suit"; -const char pstrUsageFlexor [] PROGMEM = "Flexor"; -const char pstrUsageGlove [] PROGMEM = "Glove"; -const char pstrUsageHeadTracker [] PROGMEM = "Head Track"; -const char pstrUsageHeadMountedDisplay [] PROGMEM = "Head Disp"; -const char pstrUsageHandTracker [] PROGMEM = "Hand Track"; -const char pstrUsageOculometer [] PROGMEM = "Oculometer"; -const char pstrUsageVest [] PROGMEM = "Vest"; -const char pstrUsageAnimatronicDevice [] PROGMEM = "Animat Dev"; -const char pstrUsageStereoEnable [] PROGMEM = "Stereo Enbl"; -const char pstrUsageDisplayEnable [] PROGMEM = "Display Enbl"; - -// Sport Controls Page -const char pstrUsageBaseballBat [] PROGMEM = "Baseball Bat"; -const char pstrUsageGolfClub [] PROGMEM = "Golf Club"; -const char pstrUsageRowingMachine [] PROGMEM = "Rowing Mach"; -const char pstrUsageTreadmill [] PROGMEM = "Treadmill"; -const char pstrUsageOar [] PROGMEM = "Oar"; -const char pstrUsageSlope [] PROGMEM = "Slope"; -const char pstrUsageRate [] PROGMEM = "Rate"; -const char pstrUsageStickSpeed [] PROGMEM = "Stick Speed"; -const char pstrUsageStickFaceAngle [] PROGMEM = "Stick Face Ang"; -const char pstrUsageStickHeelToe [] PROGMEM = "Stick Heel/Toe"; -const char pstrUsageStickFollowThough [] PROGMEM = "Stick Flw Thru"; -const char pstrUsageStickTempo [] PROGMEM = "Stick Tempo"; -const char pstrUsageStickType [] PROGMEM = "Stick Type"; -const char pstrUsageStickHeight [] PROGMEM = "Stick Hght"; -const char pstrUsagePutter [] PROGMEM = "Putter"; -const char pstrUsage1Iron [] PROGMEM = "1 Iron"; -const char pstrUsage2Iron [] PROGMEM = "2 Iron"; -const char pstrUsage3Iron [] PROGMEM = "3 Iron"; -const char pstrUsage4Iron [] PROGMEM = "4 Iron"; -const char pstrUsage5Iron [] PROGMEM = "5 Iron"; -const char pstrUsage6Iron [] PROGMEM = "6 Iron"; -const char pstrUsage7Iron [] PROGMEM = "7 Iron"; -const char pstrUsage8Iron [] PROGMEM = "8 Iron"; -const char pstrUsage9Iron [] PROGMEM = "9 Iron"; -const char pstrUsage10Iron [] PROGMEM = "10 Iron"; -const char pstrUsage11Iron [] PROGMEM = "11 Iron"; -const char pstrUsageSandWedge [] PROGMEM = "Sand Wedge"; -const char pstrUsageLoftWedge [] PROGMEM = "Loft Wedge"; -const char pstrUsagePowerWedge [] PROGMEM = "Pwr Wedge"; -const char pstrUsage1Wood [] PROGMEM = "1 Wood"; -const char pstrUsage3Wood [] PROGMEM = "3 Wood"; -const char pstrUsage5Wood [] PROGMEM = "5 Wood"; -const char pstrUsage7Wood [] PROGMEM = "7 Wood"; -const char pstrUsage9Wood [] PROGMEM = "9 Wood"; - -// Game Controls Page -const char pstrUsage3DGameController [] PROGMEM = "3D Game Ctrl"; -const char pstrUsagePinballDevice [] PROGMEM = "Pinball Dev"; -const char pstrUsageGunDevice [] PROGMEM = "Gun Dev"; -const char pstrUsagePointOfView [] PROGMEM = "POV"; -const char pstrUsageTurnRightLeft [] PROGMEM = "Turn Right Left"; -const char pstrUsagePitchForwardBackward [] PROGMEM = "Pitch Fwd/Back"; -const char pstrUsageRollRightLeft [] PROGMEM = "Roll Right/Left"; -const char pstrUsageMoveRightLeft [] PROGMEM = "Move Right/Left"; -const char pstrUsageMoveForwardBackward [] PROGMEM = "Move Fwd/Back"; -const char pstrUsageMoveUpDown [] PROGMEM = "Move Up/Down"; -const char pstrUsageLeanRightLeft [] PROGMEM = "Lean Right/Left"; -const char pstrUsageLeanForwardBackward [] PROGMEM = "Lean Fwd/Back"; -const char pstrUsageHeightOfPOV [] PROGMEM = "Height of POV"; -const char pstrUsageFlipper [] PROGMEM = "Flipper"; -const char pstrUsageSecondaryFlipper [] PROGMEM = "Second Flipper"; -const char pstrUsageBump [] PROGMEM = "Bump"; -const char pstrUsageNewGame [] PROGMEM = "New Game"; -const char pstrUsageShootBall [] PROGMEM = "Shoot Ball"; -const char pstrUsagePlayer [] PROGMEM = "Player"; -const char pstrUsageGunBolt [] PROGMEM = "Gun Bolt"; -const char pstrUsageGunClip [] PROGMEM = "Gun Clip"; -const char pstrUsageGunSelector [] PROGMEM = "Gun Sel"; -const char pstrUsageGunSingleShot [] PROGMEM = "Gun Sngl Shot"; -const char pstrUsageGunBurst [] PROGMEM = "Gun Burst"; -const char pstrUsageGunAutomatic [] PROGMEM = "Gun Auto"; -const char pstrUsageGunSafety [] PROGMEM = "Gun Safety"; -const char pstrUsageGamepadFireJump [] PROGMEM = "Gamepad Fire/Jump"; -const char pstrUsageGamepadTrigger [] PROGMEM = "Gamepad Trig"; - -// Generic Device Controls Page -const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength"; -const char pstrUsageWirelessChannel [] PROGMEM = "Wireless Ch"; -const char pstrUsageWirelessID [] PROGMEM = "Wireless ID"; -const char pstrUsageDiscoverWirelessControl [] PROGMEM = "Discover Wireless Ctrl"; -const char pstrUsageSecurityCodeCharEntered [] PROGMEM = "Sec Code Char Entrd"; -const char pstrUsageSecurityCodeCharErased [] PROGMEM = "Sec Code Char Erased"; -const char pstrUsageSecurityCodeCleared [] PROGMEM = "Sec Code Cleared"; - -// LED Page -const char pstrUsageNumLock [] PROGMEM = "Num Lock"; -const char pstrUsageCapsLock [] PROGMEM = "Caps Lock"; -const char pstrUsageScrollLock [] PROGMEM = "Scroll Lock"; -const char pstrUsageCompose [] PROGMEM = "Compose"; -const char pstrUsageKana [] PROGMEM = "Kana"; -const char pstrUsagePower [] PROGMEM = "Pwr"; -const char pstrUsageShift [] PROGMEM = "Shift"; -const char pstrUsageDoNotDisturb [] PROGMEM = "DND"; -const char pstrUsageMute [] PROGMEM = "Mute"; -const char pstrUsageToneEnable [] PROGMEM = "Tone Enbl"; -const char pstrUsageHighCutFilter [] PROGMEM = "High Cut Fltr"; -const char pstrUsageLowCutFilter [] PROGMEM = "Low Cut Fltr"; -const char pstrUsageEqualizerEnable [] PROGMEM = "Eq Enbl"; -const char pstrUsageSoundFieldOn [] PROGMEM = "Sound Field On"; -const char pstrUsageSurroundOn [] PROGMEM = "Surround On"; -const char pstrUsageRepeat [] PROGMEM = "Repeat"; -const char pstrUsageStereo [] PROGMEM = "Stereo"; -const char pstrUsageSamplingRateDetect [] PROGMEM = "Smpl Rate Detect"; -const char pstrUsageSpinning [] PROGMEM = "Spinning"; -const char pstrUsageCAV [] PROGMEM = "CAV"; -const char pstrUsageCLV [] PROGMEM = "CLV"; -const char pstrUsageRecordingFormatDetect [] PROGMEM = "Rec Format Detect"; -const char pstrUsageOffHook [] PROGMEM = "Off Hook"; -const char pstrUsageRing [] PROGMEM = "Ring"; -const char pstrUsageMessageWaiting [] PROGMEM = "Msg Wait"; -const char pstrUsageDataMode [] PROGMEM = "Data Mode"; -const char pstrUsageBatteryOperation [] PROGMEM = "Bat Op"; -const char pstrUsageBatteryOK [] PROGMEM = "Bat OK"; -const char pstrUsageBatteryLow [] PROGMEM = "Bat Low"; -const char pstrUsageSpeaker [] PROGMEM = "Speaker"; -const char pstrUsageHeadSet [] PROGMEM = "Head Set"; -const char pstrUsageHold [] PROGMEM = "Hold"; -const char pstrUsageMicrophone [] PROGMEM = "Mic"; -const char pstrUsageCoverage [] PROGMEM = "Coverage"; -const char pstrUsageNightMode [] PROGMEM = "Night Mode"; -const char pstrUsageSendCalls [] PROGMEM = "Send Calls"; -const char pstrUsageCallPickup [] PROGMEM = "Call Pickup"; -const char pstrUsageConference [] PROGMEM = "Conf"; -const char pstrUsageStandBy [] PROGMEM = "Stand-by"; -const char pstrUsageCameraOn [] PROGMEM = "Cam On"; -const char pstrUsageCameraOff [] PROGMEM = "Cam Off"; -const char pstrUsageOnLine [] PROGMEM = "On-Line"; -const char pstrUsageOffLine [] PROGMEM = "Off-Line"; -const char pstrUsageBusy [] PROGMEM = "Busy"; -const char pstrUsageReady [] PROGMEM = "Ready"; -const char pstrUsagePaperOut [] PROGMEM = "Paper Out"; -const char pstrUsagePaperJam [] PROGMEM = "Paper Jam"; -const char pstrUsageRemote [] PROGMEM = "Remote"; -const char pstrUsageForward [] PROGMEM = "Fwd"; -const char pstrUsageReverse [] PROGMEM = "Rev"; -const char pstrUsageStop [] PROGMEM = "Stop"; -const char pstrUsageRewind [] PROGMEM = "Rewind"; -const char pstrUsageFastForward [] PROGMEM = "Fast Fwd"; -const char pstrUsagePlay [] PROGMEM = "Play"; -const char pstrUsagePause [] PROGMEM = "Pause"; -const char pstrUsageRecord [] PROGMEM = "Rec"; -const char pstrUsageError [] PROGMEM = "Error"; -const char pstrUsageSelectedIndicator [] PROGMEM = "Usage Sel Ind"; -const char pstrUsageInUseIndicator [] PROGMEM = "Usage In Use Ind"; -const char pstrUsageMultiModeIndicator [] PROGMEM = "Usage Multi Mode Ind"; -const char pstrUsageIndicatorOn [] PROGMEM = "Ind On"; -const char pstrUsageIndicatorFlash [] PROGMEM = "Ind Flash"; -const char pstrUsageIndicatorSlowBlink [] PROGMEM = "Ind Slow Blk"; -const char pstrUsageIndicatorFastBlink [] PROGMEM = "Ind Fast Blk"; -const char pstrUsageIndicatorOff [] PROGMEM = "Ind Off"; -const char pstrUsageFlashOnTime [] PROGMEM = "Flash On Time"; -const char pstrUsageSlowBlinkOnTime [] PROGMEM = "Slow Blk On Time"; -const char pstrUsageSlowBlinkOffTime [] PROGMEM = "Slow Blk Off Time"; -const char pstrUsageFastBlinkOnTime [] PROGMEM = "Fast Blk On Time"; -const char pstrUsageFastBlinkOffTime [] PROGMEM = "Fast Blk Off Time"; -const char pstrUsageIndicatorColor [] PROGMEM = "Usage Ind Color"; -const char pstrUsageIndicatorRed [] PROGMEM = "Ind Red"; -const char pstrUsageIndicatorGreen [] PROGMEM = "Ind Green"; -const char pstrUsageIndicatorAmber [] PROGMEM = "Ind Amber"; -const char pstrUsageGenericIndicator [] PROGMEM = "Gen Ind"; -const char pstrUsageSystemSuspend [] PROGMEM = "Sys Suspend"; -const char pstrUsageExternalPowerConnected [] PROGMEM = "Ext Pwr Conn"; - -// Telephony Usage Page -const char pstrUsagePhone [] PROGMEM = "Phone"; -const char pstrUsageAnsweringMachine [] PROGMEM = "Answ Mach"; -const char pstrUsageMessageControls [] PROGMEM = "Msg Ctrls"; -const char pstrUsageHandset [] PROGMEM = "Handset"; -const char pstrUsageHeadset [] PROGMEM = "Headset"; -const char pstrUsageTelephonyKeyPad [] PROGMEM = "Tel Key Pad"; -const char pstrUsageProgrammableButton [] PROGMEM = "Prog Button"; -const char pstrUsageHookSwitch [] PROGMEM = "Hook Sw"; -const char pstrUsageFlash [] PROGMEM = "Flash"; -const char pstrUsageFeature [] PROGMEM = "Feature"; -//const char pstrUsageHold [] PROGMEM = "Hold"; -const char pstrUsageRedial [] PROGMEM = "Redial"; -const char pstrUsageTransfer [] PROGMEM = "Transfer"; -const char pstrUsageDrop [] PROGMEM = "Drop"; -const char pstrUsagePark [] PROGMEM = "Park"; -const char pstrUsageForwardCalls [] PROGMEM = "Fwd Calls"; -const char pstrUsageAlternateFunction [] PROGMEM = "Alt Func"; -const char pstrUsageLine [] PROGMEM = "Line"; -const char pstrUsageSpeakerPhone [] PROGMEM = "Spk Phone"; -//const char pstrUsageConference [] PROGMEM = "Conference"; -const char pstrUsageRingEnable [] PROGMEM = "Ring Enbl"; -const char pstrUsageRingSelect [] PROGMEM = "Ring Sel"; -const char pstrUsagePhoneMute [] PROGMEM = "Phone Mute"; -const char pstrUsageCallerID [] PROGMEM = "Caller ID"; -const char pstrUsageSend [] PROGMEM = "Send"; -const char pstrUsageSpeedDial [] PROGMEM = "Speed Dial"; -const char pstrUsageStoreNumber [] PROGMEM = "Store Num"; -const char pstrUsageRecallNumber [] PROGMEM = "Recall Num"; -const char pstrUsagePhoneDirectory [] PROGMEM = "Phone Dir"; -const char pstrUsageVoiceMail [] PROGMEM = "Voice Mail"; -const char pstrUsageScreenCalls [] PROGMEM = "Screen Calls"; -//const char pstrUsageDoNotDisturb [] PROGMEM = "Do Not Disturb"; -const char pstrUsageMessage [] PROGMEM = "Msg"; -const char pstrUsageAnswerOnOff [] PROGMEM = "Answer On/Off"; -const char pstrUsageInsideDialTone [] PROGMEM = "Inside Dial Tone"; -const char pstrUsageOutsideDialTone [] PROGMEM = "Outside Dial Tone"; -const char pstrUsageInsideRingTone [] PROGMEM = "Inside Ring Tone"; -const char pstrUsageOutsideRingTone [] PROGMEM = "Outside Ring Tone"; -const char pstrUsagePriorityRingTone [] PROGMEM = "Prior Ring Tone"; -const char pstrUsageInsideRingback [] PROGMEM = "Inside Ringback"; -const char pstrUsagePriorityRingback [] PROGMEM = "Priority Ringback"; -const char pstrUsageLineBusyTone [] PROGMEM = "Ln Busy Tone"; -const char pstrUsageReorderTone [] PROGMEM = "Reorder Tone"; -const char pstrUsageCallWaitingTone [] PROGMEM = "Call Wait Tone"; -const char pstrUsageConfirmationTone1 [] PROGMEM = "Cnfrm Tone1"; -const char pstrUsageConfirmationTone2 [] PROGMEM = "Cnfrm Tone2"; -const char pstrUsageTonesOff [] PROGMEM = "Tones Off"; -const char pstrUsageOutsideRingback [] PROGMEM = "Outside Ringback"; -const char pstrUsageRinger [] PROGMEM = "Ringer"; -const char pstrUsagePhoneKey0 [] PROGMEM = "0"; -const char pstrUsagePhoneKey1 [] PROGMEM = "1"; -const char pstrUsagePhoneKey2 [] PROGMEM = "2"; -const char pstrUsagePhoneKey3 [] PROGMEM = "3"; -const char pstrUsagePhoneKey4 [] PROGMEM = "4"; -const char pstrUsagePhoneKey5 [] PROGMEM = "5"; -const char pstrUsagePhoneKey6 [] PROGMEM = "6"; -const char pstrUsagePhoneKey7 [] PROGMEM = "7"; -const char pstrUsagePhoneKey8 [] PROGMEM = "8"; -const char pstrUsagePhoneKey9 [] PROGMEM = "9"; -const char pstrUsagePhoneKeyStar [] PROGMEM = "*"; -const char pstrUsagePhoneKeyPound [] PROGMEM = "#"; -const char pstrUsagePhoneKeyA [] PROGMEM = "A"; -const char pstrUsagePhoneKeyB [] PROGMEM = "B"; -const char pstrUsagePhoneKeyC [] PROGMEM = "C"; -const char pstrUsagePhoneKeyD [] PROGMEM = "D"; - -// Consumer Usage Page -const char pstrUsageConsumerControl [] PROGMEM = "Consumer Ctrl"; -const char pstrUsageNumericKeyPad [] PROGMEM = "Num Key Pad"; -//const char pstrUsageProgrammableButton [] PROGMEM = "Prog Btn"; -//const char pstrUsageMicrophone [] PROGMEM = "Mic"; -const char pstrUsageHeadphone [] PROGMEM = "Headphone"; -const char pstrUsageGraphicEqualizer [] PROGMEM = "Graph Eq"; -const char pstrUsagePlus10 [] PROGMEM = "+10"; -const char pstrUsagePlus100 [] PROGMEM = "+100"; -const char pstrUsageAMPM [] PROGMEM = "AM/PM"; -//const char pstrUsagePower [] PROGMEM = "Pwr"; -const char pstrUsageReset [] PROGMEM = "Reset"; -const char pstrUsageSleep [] PROGMEM = "Sleep"; -const char pstrUsageSleepAfter [] PROGMEM = "Sleep After"; -const char pstrUsageSleepMode [] PROGMEM = "Sleep Mode"; -const char pstrUsageIllumination [] PROGMEM = "Illumin"; -const char pstrUsageFunctionButtons [] PROGMEM = "Func Btns"; -const char pstrUsageMenu [] PROGMEM = "Menu"; -const char pstrUsageMenuPick [] PROGMEM = "Menu Pick"; -const char pstrUsageMenuUp [] PROGMEM = "Menu Up"; -const char pstrUsageMenuDown [] PROGMEM = "Menu Down"; -const char pstrUsageMenuLeft [] PROGMEM = "Menu Left"; -const char pstrUsageMenuRight [] PROGMEM = "Menu Right"; -const char pstrUsageMenuEscape [] PROGMEM = "Menu Esc"; -const char pstrUsageMenuValueIncrease [] PROGMEM = "Menu Val Inc"; -const char pstrUsageMenuValueDecrease [] PROGMEM = "Menu Val Dec"; -const char pstrUsageDataOnScreen [] PROGMEM = "Data On Scr"; -const char pstrUsageClosedCaption [] PROGMEM = "Closed Cptn"; -const char pstrUsageClosedCaptionSelect [] PROGMEM = "Closed Cptn Sel"; -const char pstrUsageVCRTV [] PROGMEM = "VCR/TV"; -const char pstrUsageBroadcastMode [] PROGMEM = "Brdcast Mode"; -const char pstrUsageSnapshot [] PROGMEM = "Snapshot"; -const char pstrUsageStill [] PROGMEM = "Still"; -const char pstrUsageSelection [] PROGMEM = "Sel"; -const char pstrUsageAssignSelection [] PROGMEM = "Assign Sel"; -const char pstrUsageModeStep [] PROGMEM = "Mode Step"; -const char pstrUsageRecallLast [] PROGMEM = "Recall Last"; -const char pstrUsageEnterChannel [] PROGMEM = "Entr Channel"; -const char pstrUsageOrderMovie [] PROGMEM = "Ord Movie"; -const char pstrUsageChannel [] PROGMEM = "Channel"; -const char pstrUsageMediaSelection [] PROGMEM = "Med Sel"; -const char pstrUsageMediaSelectComputer [] PROGMEM = "Med Sel Comp"; -const char pstrUsageMediaSelectTV [] PROGMEM = "Med Sel TV"; -const char pstrUsageMediaSelectWWW [] PROGMEM = "Med Sel WWW"; -const char pstrUsageMediaSelectDVD [] PROGMEM = "Med Sel DVD"; -const char pstrUsageMediaSelectTelephone [] PROGMEM = "Med Sel Tel"; -const char pstrUsageMediaSelectProgramGuide [] PROGMEM = "Med Sel PG"; -const char pstrUsageMediaSelectVideoPhone [] PROGMEM = "Med Sel Vid"; -const char pstrUsageMediaSelectGames [] PROGMEM = "Med Sel Games"; -const char pstrUsageMediaSelectMessages [] PROGMEM = "Med Sel Msg"; -const char pstrUsageMediaSelectCD [] PROGMEM = "Med Sel CD"; -const char pstrUsageMediaSelectVCR [] PROGMEM = "Med Sel VCR"; -const char pstrUsageMediaSelectTuner [] PROGMEM = "Med Sel Tuner"; -const char pstrUsageQuit [] PROGMEM = "Quit"; -const char pstrUsageHelp [] PROGMEM = "Help"; -const char pstrUsageMediaSelectTape [] PROGMEM = "Med Sel Tape"; -const char pstrUsageMediaSelectCable [] PROGMEM = "Med Sel Cbl"; -const char pstrUsageMediaSelectSatellite [] PROGMEM = "Med Sel Sat"; -const char pstrUsageMediaSelectSecurity [] PROGMEM = "Med Sel Secur"; -const char pstrUsageMediaSelectHome [] PROGMEM = "Med Sel Home"; -const char pstrUsageMediaSelectCall [] PROGMEM = "Med Sel Call"; -const char pstrUsageChannelIncrement [] PROGMEM = "Ch Inc"; -const char pstrUsageChannelDecrement [] PROGMEM = "Ch Dec"; -const char pstrUsageMediaSelectSAP [] PROGMEM = "Med Sel SAP"; -const char pstrUsageVCRPlus [] PROGMEM = "VCR+"; -const char pstrUsageOnce [] PROGMEM = "Once"; -const char pstrUsageDaily [] PROGMEM = "Daily"; -const char pstrUsageWeekly [] PROGMEM = "Weekly"; -const char pstrUsageMonthly [] PROGMEM = "Monthly"; -//const char pstrUsagePlay [] PROGMEM = "Play"; -//const char pstrUsagePause [] PROGMEM = "Pause"; -//const char pstrUsageRecord [] PROGMEM = "Rec"; -//const char pstrUsageFastForward [] PROGMEM = "FF"; -//const char pstrUsageRewind [] PROGMEM = "Rewind"; -const char pstrUsageScanNextTrack [] PROGMEM = "Next Track"; -const char pstrUsageScanPreviousTrack [] PROGMEM = "Prev Track"; -//const char pstrUsageStop [] PROGMEM = "Stop"; -const char pstrUsageEject [] PROGMEM = "Eject"; -const char pstrUsageRandomPlay [] PROGMEM = "Random"; -const char pstrUsageSelectDisk [] PROGMEM = "Sel Disk"; -const char pstrUsageEnterDisk [] PROGMEM = "Ent Disk"; -//const char pstrUsageRepeat [] PROGMEM = "Repeat"; -const char pstrUsageTracking [] PROGMEM = "Tracking"; -const char pstrUsageTrackNormal [] PROGMEM = "Trk Norm"; -const char pstrUsageSlowTracking [] PROGMEM = "Slow Trk"; -const char pstrUsageFrameForward [] PROGMEM = "Frm Fwd"; -const char pstrUsageFrameBackwards [] PROGMEM = "Frm Back"; -const char pstrUsageMark [] PROGMEM = "Mark"; -const char pstrUsageClearMark [] PROGMEM = "Clr Mark"; -const char pstrUsageRepeatFromMark [] PROGMEM = "Rpt Mark"; -const char pstrUsageReturnToMark [] PROGMEM = "Ret to Mark"; -const char pstrUsageSearchMarkForward [] PROGMEM = "Search Mark Fwd"; -const char pstrUsageSearchMarkBackwards [] PROGMEM = "Search Mark Back"; -const char pstrUsageCounterReset [] PROGMEM = "Counter Reset"; -const char pstrUsageShowCounter [] PROGMEM = "Show Counter"; -const char pstrUsageTrackingIncrement [] PROGMEM = "Track Inc"; -const char pstrUsageTrackingDecrement [] PROGMEM = "Track Dec"; -const char pstrUsageStopEject [] PROGMEM = "Stop/Eject"; -const char pstrUsagePlayPause [] PROGMEM = "Play/Pause"; -const char pstrUsagePlaySkip [] PROGMEM = "Play/Skip"; -const char pstrUsageVolume [] PROGMEM = "Vol"; -const char pstrUsageBalance [] PROGMEM = "Balance"; -//const char pstrUsageMute [] PROGMEM = "Mute"; -const char pstrUsageBass [] PROGMEM = "Bass"; -const char pstrUsageTreble [] PROGMEM = "Treble"; -const char pstrUsageBassBoost [] PROGMEM = "Bass Boost"; -const char pstrUsageSurroundMode [] PROGMEM = "Surround"; -const char pstrUsageLoudness [] PROGMEM = "Loud"; -const char pstrUsageMPX [] PROGMEM = "MPX"; -const char pstrUsageVolumeIncrement [] PROGMEM = "Vol Inc"; -const char pstrUsageVolumeDecrement [] PROGMEM = "Vol Dec"; -const char pstrUsageSpeedSelect [] PROGMEM = "Speed"; -const char pstrUsagePlaybackSpeed [] PROGMEM = "Play Speed"; -const char pstrUsageStandardPlay [] PROGMEM = "Std Play"; -const char pstrUsageLongPlay [] PROGMEM = "Long Play"; -const char pstrUsageExtendedPlay [] PROGMEM = "Ext Play"; -const char pstrUsageSlow [] PROGMEM = "Slow"; -const char pstrUsageFanEnable [] PROGMEM = "Fan Enbl"; -const char pstrUsageFanSpeed [] PROGMEM = "Fan Speed"; -const char pstrUsageLightEnable [] PROGMEM = "Light Enbl"; -const char pstrUsageLightIlluminationLevel [] PROGMEM = "Light Illum Lev"; -const char pstrUsageClimateControlEnable [] PROGMEM = "Climate Enbl"; -const char pstrUsageRoomTemperature [] PROGMEM = "Room Temp"; -const char pstrUsageSecurityEnable [] PROGMEM = "Secur Enbl"; -const char pstrUsageFireAlarm [] PROGMEM = "Fire Alm"; -const char pstrUsagePoliceAlarm [] PROGMEM = "Police Alm"; -const char pstrUsageProximity [] PROGMEM = "Prox"; -const char pstrUsageMotion [] PROGMEM = "Motion"; -const char pstrUsageDuresAlarm [] PROGMEM = "Dures Alm"; -const char pstrUsageHoldupAlarm [] PROGMEM = "Holdup Alm"; -const char pstrUsageMedicalAlarm [] PROGMEM = "Med Alm"; -const char pstrUsageBalanceRight [] PROGMEM = "Balance Right"; -const char pstrUsageBalanceLeft [] PROGMEM = "Balance Left"; -const char pstrUsageBassIncrement [] PROGMEM = "Bass Inc"; -const char pstrUsageBassDecrement [] PROGMEM = "Bass Dec"; -const char pstrUsageTrebleIncrement [] PROGMEM = "Treble Inc"; -const char pstrUsageTrebleDecrement [] PROGMEM = "Treble Dec"; -const char pstrUsageSpeakerSystem [] PROGMEM = "Spk Sys"; -const char pstrUsageChannelLeft [] PROGMEM = "Ch Left"; -const char pstrUsageChannelRight [] PROGMEM = "Ch Right"; -const char pstrUsageChannelCenter [] PROGMEM = "Ch Center"; -const char pstrUsageChannelFront [] PROGMEM = "Ch Front"; -const char pstrUsageChannelCenterFront [] PROGMEM = "Ch Cntr Front"; -const char pstrUsageChannelSide [] PROGMEM = "Ch Side"; -const char pstrUsageChannelSurround [] PROGMEM = "Ch Surround"; -const char pstrUsageChannelLowFreqEnhancement [] PROGMEM = "Ch Low Freq Enh"; -const char pstrUsageChannelTop [] PROGMEM = "Ch Top"; -const char pstrUsageChannelUnknown [] PROGMEM = "Ch Unk"; -const char pstrUsageSubChannel [] PROGMEM = "Sub-ch"; -const char pstrUsageSubChannelIncrement [] PROGMEM = "Sub-ch Inc"; -const char pstrUsageSubChannelDecrement [] PROGMEM = "Sub-ch Dec"; -const char pstrUsageAlternateAudioIncrement [] PROGMEM = "Alt Aud Inc"; -const char pstrUsageAlternateAudioDecrement [] PROGMEM = "Alt Aud Dec"; -const char pstrUsageApplicationLaunchButtons [] PROGMEM = "App Launch Btns"; -const char pstrUsageALLaunchButtonConfigTool [] PROGMEM = "AL Launch Conf Tl"; -const char pstrUsageALProgrammableButton [] PROGMEM = "AL Pgm Btn"; -const char pstrUsageALConsumerControlConfig [] PROGMEM = "AL Cons Ctrl Cfg"; -const char pstrUsageALWordProcessor [] PROGMEM = "AL Word Proc"; -const char pstrUsageALTextEditor [] PROGMEM = "AL Txt Edtr"; -const char pstrUsageALSpreadsheet [] PROGMEM = "AL Sprdsheet"; -const char pstrUsageALGraphicsEditor [] PROGMEM = "AL Graph Edtr"; -const char pstrUsageALPresentationApp [] PROGMEM = "AL Present App"; -const char pstrUsageALDatabaseApp [] PROGMEM = "AL DB App"; -const char pstrUsageALEmailReader [] PROGMEM = "AL E-mail Rdr"; -const char pstrUsageALNewsreader [] PROGMEM = "AL Newsrdr"; -const char pstrUsageALVoicemail [] PROGMEM = "AL Voicemail"; -const char pstrUsageALContactsAddressBook [] PROGMEM = "AL Addr Book"; -const char pstrUsageALCalendarSchedule [] PROGMEM = "AL Clndr/Schdlr"; -const char pstrUsageALTaskProjectManager [] PROGMEM = "AL Task/Prj Mgr"; -const char pstrUsageALLogJournalTimecard [] PROGMEM = "AL Log/Jrnl/Tmcrd"; -const char pstrUsageALCheckbookFinance [] PROGMEM = "AL Chckbook/Fin"; -const char pstrUsageALCalculator [] PROGMEM = "AL Calc"; -const char pstrUsageALAVCapturePlayback [] PROGMEM = "AL A/V Capt/Play"; -const char pstrUsageALLocalMachineBrowser [] PROGMEM = "AL Loc Mach Brow"; -const char pstrUsageALLANWANBrow [] PROGMEM = "AL LAN/WAN Brow"; -const char pstrUsageALInternetBrowser [] PROGMEM = "AL I-net Brow"; -const char pstrUsageALRemoteNetISPConnect [] PROGMEM = "AL Rem Net Con"; -const char pstrUsageALNetworkConference [] PROGMEM = "AL Net Conf"; -const char pstrUsageALNetworkChat [] PROGMEM = "AL Net Chat"; -const char pstrUsageALTelephonyDialer [] PROGMEM = "AL Tel/Dial"; -const char pstrUsageALLogon [] PROGMEM = "AL Logon"; -const char pstrUsageALLogoff [] PROGMEM = "AL Logoff"; -const char pstrUsageALLogonLogoff [] PROGMEM = "AL Logon/Logoff"; -const char pstrUsageALTermLockScrSav [] PROGMEM = "AL Term Lock/Scr Sav"; -const char pstrUsageALControlPannel [] PROGMEM = "AL Ctrl Pan"; -const char pstrUsageALCommandLineProcessorRun [] PROGMEM = "AL Cmd/Run"; -const char pstrUsageALProcessTaskManager [] PROGMEM = "AL Task Mgr"; -const char pstrUsageALSelectTaskApplication [] PROGMEM = "AL Sel App"; -const char pstrUsageALNextTaskApplication [] PROGMEM = "AL Next App"; -const char pstrUsageALPreviousTaskApplication [] PROGMEM = "AL Prev App"; -const char pstrUsageALPreemptiveHaltTaskApp [] PROGMEM = "AL Prmpt Halt App"; -const char pstrUsageALIntegratedHelpCenter [] PROGMEM = "AL Hlp Cntr"; -const char pstrUsageALDocuments [] PROGMEM = "AL Docs"; -const char pstrUsageALThesaurus [] PROGMEM = "AL Thsrs"; -const char pstrUsageALDictionary [] PROGMEM = "AL Dict"; -const char pstrUsageALDesktop [] PROGMEM = "AL Desktop"; -const char pstrUsageALSpellCheck [] PROGMEM = "AL Spell Chk"; -const char pstrUsageALGrammarCheck [] PROGMEM = "AL Gram Chk"; -const char pstrUsageALWirelessStatus [] PROGMEM = "AL Wireless Sts"; -const char pstrUsageALKeyboardLayout [] PROGMEM = "AL Kbd Layout"; -const char pstrUsageALVirusProtection [] PROGMEM = "AL Vir Protect"; -const char pstrUsageALEncryption [] PROGMEM = "AL Encrypt"; -const char pstrUsageALScreenSaver [] PROGMEM = "AL Scr Sav"; -const char pstrUsageALAlarms [] PROGMEM = "AL Alarms"; -const char pstrUsageALClock [] PROGMEM = "AL Clock"; -const char pstrUsageALFileBrowser [] PROGMEM = "AL File Brow"; -const char pstrUsageALPowerStatus [] PROGMEM = "AL Pwr Sts"; -const char pstrUsageALImageBrowser [] PROGMEM = "AL Img Brow"; -const char pstrUsageALAudioBrowser [] PROGMEM = "AL Aud Brow"; -const char pstrUsageALMovieBrowser [] PROGMEM = "AL Mov Brow"; -const char pstrUsageALDigitalRightsManager [] PROGMEM = "AL Dig Rights Mgr"; -const char pstrUsageALDigitalWallet [] PROGMEM = "AL Dig Wallet"; -const char pstrUsageALInstantMessaging [] PROGMEM = "AL Inst Msg"; -const char pstrUsageALOEMFeaturesBrowser [] PROGMEM = "AL OEM Tips Brow"; -const char pstrUsageALOEMHelp [] PROGMEM = "AL OEM Hlp"; -const char pstrUsageALOnlineCommunity [] PROGMEM = "AL Online Com"; -const char pstrUsageALEntertainmentContentBrow [] PROGMEM = "AL Ent Cont Brow"; -const char pstrUsageALOnlineShoppingBrowser [] PROGMEM = "AL Online Shop Brow"; -const char pstrUsageALSmartCardInfoHelp [] PROGMEM = "AL SmartCard Inf"; -const char pstrUsageALMarketMonitorFinBrowser [] PROGMEM = "AL Market Brow"; -const char pstrUsageALCustomCorpNewsBrowser [] PROGMEM = "AL Cust Corp News Brow"; -const char pstrUsageALOnlineActivityBrowser [] PROGMEM = "AL Online Act Brow"; -const char pstrUsageALResearchSearchBrowser [] PROGMEM = "AL Search Brow"; -const char pstrUsageALAudioPlayer [] PROGMEM = "AL Aud Player"; -const char pstrUsageGenericGUIAppControls [] PROGMEM = "Gen GUI App Ctrl"; -const char pstrUsageACNew [] PROGMEM = "AC New"; -const char pstrUsageACOpen [] PROGMEM = "AC Open"; -const char pstrUsageACClose [] PROGMEM = "AC Close"; -const char pstrUsageACExit [] PROGMEM = "AC Exit"; -const char pstrUsageACMaximize [] PROGMEM = "AC Max"; -const char pstrUsageACMinimize [] PROGMEM = "AC Min"; -const char pstrUsageACSave [] PROGMEM = "AC Save"; -const char pstrUsageACPrint [] PROGMEM = "AC Print"; -const char pstrUsageACProperties [] PROGMEM = "AC Prop"; -const char pstrUsageACUndo [] PROGMEM = "AC Undo"; -const char pstrUsageACCopy [] PROGMEM = "AC Copy"; -const char pstrUsageACCut [] PROGMEM = "AC Cut"; -const char pstrUsageACPaste [] PROGMEM = "AC Paste"; -const char pstrUsageACSelectAll [] PROGMEM = "AC Sel All"; -const char pstrUsageACFind [] PROGMEM = "AC Find"; -const char pstrUsageACFindAndReplace [] PROGMEM = "AC Find/Replace"; -const char pstrUsageACSearch [] PROGMEM = "AC Search"; -const char pstrUsageACGoto [] PROGMEM = "AC Goto"; -const char pstrUsageACHome [] PROGMEM = "AC Home"; -const char pstrUsageACBack [] PROGMEM = "AC Back"; -const char pstrUsageACForward [] PROGMEM = "AC Fwd"; -const char pstrUsageACStop [] PROGMEM = "AC Stop"; -const char pstrUsageACRefresh [] PROGMEM = "AC Refresh"; -const char pstrUsageACPreviousLink [] PROGMEM = "AC Prev Link"; -const char pstrUsageACNextLink [] PROGMEM = "AC Next Link"; -const char pstrUsageACBookmarks [] PROGMEM = "AC Bkmarks"; -const char pstrUsageACHistory [] PROGMEM = "AC Hist"; -const char pstrUsageACSubscriptions [] PROGMEM = "AC Subscr"; -const char pstrUsageACZoomIn [] PROGMEM = "AC Zoom In"; -const char pstrUsageACZoomOut [] PROGMEM = "AC Zoom Out"; -const char pstrUsageACZoom [] PROGMEM = "AC Zoom"; -const char pstrUsageACFullScreenView [] PROGMEM = "AC Full Scr"; -const char pstrUsageACNormalView [] PROGMEM = "AC Norm View"; -const char pstrUsageACViewToggle [] PROGMEM = "AC View Tgl"; -const char pstrUsageACScrollUp [] PROGMEM = "AC Scroll Up"; -const char pstrUsageACScrollDown [] PROGMEM = "AC Scroll Down"; -const char pstrUsageACScroll [] PROGMEM = "AC Scroll"; -const char pstrUsageACPanLeft [] PROGMEM = "AC Pan Left"; -const char pstrUsageACPanRight [] PROGMEM = "AC Pan Right"; -const char pstrUsageACPan [] PROGMEM = "AC Pan"; -const char pstrUsageACNewWindow [] PROGMEM = "AC New Wnd"; -const char pstrUsageACTileHoriz [] PROGMEM = "AC Tile Horiz"; -const char pstrUsageACTileVert [] PROGMEM = "AC Tile Vert"; -const char pstrUsageACFormat [] PROGMEM = "AC Frmt"; -const char pstrUsageACEdit [] PROGMEM = "AC Edit"; -const char pstrUsageACBold [] PROGMEM = "AC Bold"; -const char pstrUsageACItalics [] PROGMEM = "AC Ital"; -const char pstrUsageACUnderline [] PROGMEM = "AC Under"; -const char pstrUsageACStrikethrough [] PROGMEM = "AC Strike"; -const char pstrUsageACSubscript [] PROGMEM = "AC Sub"; -const char pstrUsageACSuperscript [] PROGMEM = "AC Super"; -const char pstrUsageACAllCaps [] PROGMEM = "AC All Caps"; -const char pstrUsageACRotate [] PROGMEM = "AC Rotate"; -const char pstrUsageACResize [] PROGMEM = "AC Resize"; -const char pstrUsageACFlipHorizontal [] PROGMEM = "AC Flp H"; -const char pstrUsageACFlipVertical [] PROGMEM = "AC Flp V"; -const char pstrUsageACMirrorHorizontal [] PROGMEM = "AC Mir H"; -const char pstrUsageACMirrorVertical [] PROGMEM = "AC Mir V"; -const char pstrUsageACFontSelect [] PROGMEM = "AC Fnt Sel"; -const char pstrUsageACFontColor [] PROGMEM = "AC Fnt Clr"; -const char pstrUsageACFontSize [] PROGMEM = "AC Fnt Size"; -const char pstrUsageACJustifyLeft [] PROGMEM = "AC Just Left"; -const char pstrUsageACJustifyCenterH [] PROGMEM = "AC Just Cent H"; -const char pstrUsageACJustifyRight [] PROGMEM = "AC Just Right"; -const char pstrUsageACJustifyBlockH [] PROGMEM = "AC Just Block H"; -const char pstrUsageACJustifyTop [] PROGMEM = "AC Just Top"; -const char pstrUsageACJustifyCenterV [] PROGMEM = "AC Just Cent V"; -const char pstrUsageACJustifyBottom [] PROGMEM = "AC Just Bot"; -const char pstrUsageACJustifyBlockV [] PROGMEM = "AC Just Block V"; -const char pstrUsageACIndentDecrease [] PROGMEM = "AC Indent Dec"; -const char pstrUsageACIndentIncrease [] PROGMEM = "AC Indent Inc"; -const char pstrUsageACNumberedList [] PROGMEM = "AC Num List"; -const char pstrUsageACRestartNumbering [] PROGMEM = "AC Res Num"; -const char pstrUsageACBulletedList [] PROGMEM = "AC Blt List"; -const char pstrUsageACPromote [] PROGMEM = "AC Promote"; -const char pstrUsageACDemote [] PROGMEM = "AC Demote"; -const char pstrUsageACYes [] PROGMEM = "AC Yes"; -const char pstrUsageACNo [] PROGMEM = "AC No"; -const char pstrUsageACCancel [] PROGMEM = "AC Cancel"; -const char pstrUsageACCatalog [] PROGMEM = "AC Ctlg"; -const char pstrUsageACBuyChkout [] PROGMEM = "AC Buy"; -const char pstrUsageACAddToCart [] PROGMEM = "AC Add2Cart"; -const char pstrUsageACExpand [] PROGMEM = "AC Xpnd"; -const char pstrUsageACExpandAll [] PROGMEM = "AC Xpand All"; -const char pstrUsageACCollapse [] PROGMEM = "AC Collapse"; -const char pstrUsageACCollapseAll [] PROGMEM = "AC Collapse All"; -const char pstrUsageACPrintPreview [] PROGMEM = "AC Prn Prevw"; -const char pstrUsageACPasteSpecial [] PROGMEM = "AC Paste Spec"; -const char pstrUsageACInsertMode [] PROGMEM = "AC Ins Mode"; -const char pstrUsageACDelete [] PROGMEM = "AC Del"; -const char pstrUsageACLock [] PROGMEM = "AC Lock"; -const char pstrUsageACUnlock [] PROGMEM = "AC Unlock"; -const char pstrUsageACProtect [] PROGMEM = "AC Prot"; -const char pstrUsageACUnprotect [] PROGMEM = "AC Unprot"; -const char pstrUsageACAttachComment [] PROGMEM = "AC Attach Cmnt"; -const char pstrUsageACDeleteComment [] PROGMEM = "AC Del Cmnt"; -const char pstrUsageACViewComment [] PROGMEM = "AC View Cmnt"; -const char pstrUsageACSelectWord [] PROGMEM = "AC Sel Word"; -const char pstrUsageACSelectSentence [] PROGMEM = "AC Sel Sntc"; -const char pstrUsageACSelectParagraph [] PROGMEM = "AC Sel Para"; -const char pstrUsageACSelectColumn [] PROGMEM = "AC Sel Col"; -const char pstrUsageACSelectRow [] PROGMEM = "AC Sel Row"; -const char pstrUsageACSelectTable [] PROGMEM = "AC Sel Tbl"; -const char pstrUsageACSelectObject [] PROGMEM = "AC Sel Obj"; -const char pstrUsageACRedoRepeat [] PROGMEM = "AC Redo"; -const char pstrUsageACSort [] PROGMEM = "AC Sort"; -const char pstrUsageACSortAscending [] PROGMEM = "AC Sort Asc"; -const char pstrUsageACSortDescending [] PROGMEM = "AC Sort Desc"; -const char pstrUsageACFilter [] PROGMEM = "AC Filt"; -const char pstrUsageACSetClock [] PROGMEM = "AC Set Clk"; -const char pstrUsageACViewClock [] PROGMEM = "AC View Clk"; -const char pstrUsageACSelectTimeZone [] PROGMEM = "AC Sel Time Z"; -const char pstrUsageACEditTimeZone [] PROGMEM = "AC Edt Time Z"; -const char pstrUsageACSetAlarm [] PROGMEM = "AC Set Alm"; -const char pstrUsageACClearAlarm [] PROGMEM = "AC Clr Alm"; -const char pstrUsageACSnoozeAlarm [] PROGMEM = "AC Snz Alm"; -const char pstrUsageACResetAlarm [] PROGMEM = "AC Rst Alm"; -const char pstrUsageACSyncronize [] PROGMEM = "AC Sync"; -const char pstrUsageACSendReceive [] PROGMEM = "AC Snd/Rcv"; -const char pstrUsageACSendTo [] PROGMEM = "AC Snd To"; -const char pstrUsageACReply [] PROGMEM = "AC Reply"; -const char pstrUsageACReplyAll [] PROGMEM = "AC Reply All"; -const char pstrUsageACForwardMessage [] PROGMEM = "AC Fwd Msg"; -const char pstrUsageACSend [] PROGMEM = "AC Snd"; -const char pstrUsageACAttachFile [] PROGMEM = "AC Att File"; -const char pstrUsageACUpload [] PROGMEM = "AC Upld"; -const char pstrUsageACDownload [] PROGMEM = "AC Dnld"; -const char pstrUsageACSetBorders [] PROGMEM = "AC Set Brd"; -const char pstrUsageACInsertRow [] PROGMEM = "AC Ins Row"; -const char pstrUsageACInsertColumn [] PROGMEM = "AC Ins Col"; -const char pstrUsageACInsertFile [] PROGMEM = "AC Ins File"; -const char pstrUsageACInsertPicture [] PROGMEM = "AC Ins Pic"; -const char pstrUsageACInsertObject [] PROGMEM = "AC Ins Obj"; -const char pstrUsageACInsertSymbol [] PROGMEM = "AC Ins Sym"; -const char pstrUsageACSaveAndClose [] PROGMEM = "AC Sav&Cls"; -const char pstrUsageACRename [] PROGMEM = "AC Rename"; -const char pstrUsageACMerge [] PROGMEM = "AC Merge"; -const char pstrUsageACSplit [] PROGMEM = "AC Split"; -const char pstrUsageACDistributeHorizontaly [] PROGMEM = "AC Dist Hor"; -const char pstrUsageACDistributeVerticaly [] PROGMEM = "AC Dist Ver"; - -// Digitaizers -const char pstrUsageDigitizer [] PROGMEM = "Digitizer"; -const char pstrUsagePen [] PROGMEM = "Pen"; -const char pstrUsageLightPen [] PROGMEM = "Light Pen"; -const char pstrUsageTouchScreen [] PROGMEM = "Touch Scr"; -const char pstrUsageTouchPad [] PROGMEM = "Touch Pad"; -const char pstrUsageWhiteBoard [] PROGMEM = "White Brd"; -const char pstrUsageCoordinateMeasuringMachine [] PROGMEM = "Coord Meas Mach"; -const char pstrUsage3DDigitizer [] PROGMEM = "3D Dgtz"; -const char pstrUsageStereoPlotter [] PROGMEM = "Stereo Plot"; -const char pstrUsageArticulatedArm [] PROGMEM = "Art Arm"; -const char pstrUsageArmature [] PROGMEM = "Armature"; -const char pstrUsageMultiplePointDigitizer [] PROGMEM = "Multi Point Dgtz"; -const char pstrUsageFreeSpaceWand [] PROGMEM = "Free Space Wand"; -const char pstrUsageStylus [] PROGMEM = "Stylus"; -const char pstrUsagePuck [] PROGMEM = "Puck"; -const char pstrUsageFinger [] PROGMEM = "Finger"; -const char pstrUsageTipPressure [] PROGMEM = "Tip Press"; -const char pstrUsageBarrelPressure [] PROGMEM = "Brl Press"; -const char pstrUsageInRange [] PROGMEM = "In Range"; -const char pstrUsageTouch [] PROGMEM = "Touch"; -const char pstrUsageUntouch [] PROGMEM = "Untouch"; -const char pstrUsageTap [] PROGMEM = "Tap"; -const char pstrUsageQuality [] PROGMEM = "Qlty"; -const char pstrUsageDataValid [] PROGMEM = "Data Valid"; -const char pstrUsageTransducerIndex [] PROGMEM = "Transducer Ind"; -const char pstrUsageTabletFunctionKeys [] PROGMEM = "Tabl Func Keys"; -const char pstrUsageProgramChangeKeys [] PROGMEM = "Pgm Chng Keys"; -//const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength"; -const char pstrUsageInvert [] PROGMEM = "Invert"; -const char pstrUsageXTilt [] PROGMEM = "X Tilt"; -const char pstrUsageYTilt [] PROGMEM = "Y Tilt"; -const char pstrUsageAzimuth [] PROGMEM = "Azimuth"; -const char pstrUsageAltitude [] PROGMEM = "Altitude"; -const char pstrUsageTwist [] PROGMEM = "Twist"; -const char pstrUsageTipSwitch [] PROGMEM = "Tip Sw"; -const char pstrUsageSecondaryTipSwitch [] PROGMEM = "Scnd Tip Sw"; -const char pstrUsageBarrelSwitch [] PROGMEM = "Brl Sw"; -const char pstrUsageEraser [] PROGMEM = "Eraser"; -const char pstrUsageTabletPick [] PROGMEM = "Tbl Pick"; - -// Alphanumeric Display Page -const char pstrUsageAlphanumericDisplay [] PROGMEM = "Alphanum Disp"; -const char pstrUsageBitmappedDisplay [] PROGMEM = "Bmp Disp"; -const char pstrUsageDisplayAttributesReport [] PROGMEM = "Disp Attr Rpt"; -const char pstrUsageASCIICharacterSet [] PROGMEM = "ASCII chset"; -const char pstrUsageDataReadBack [] PROGMEM = "Data Rd Back"; -const char pstrUsageFontReadBack [] PROGMEM = "Fnt Rd Back"; -const char pstrUsageDisplayControlReport [] PROGMEM = "Disp Ctrl Rpt"; -const char pstrUsageClearDisplay [] PROGMEM = "Clr Disp"; -//const char pstrUsageDisplayEnable [] PROGMEM = "Disp Enbl"; -const char pstrUsageScreenSaverDelay [] PROGMEM = "Scr Sav Delay"; -const char pstrUsageScreenSaverEnable [] PROGMEM = "Scr Sav Enbl"; -const char pstrUsageVerticalScroll [] PROGMEM = "V Scroll"; -const char pstrUsageHorizontalScroll [] PROGMEM = "H Scroll"; -const char pstrUsageCharacterReport [] PROGMEM = "Char Rpt"; -const char pstrUsageDisplayData [] PROGMEM = "Disp Data"; -const char pstrUsageDisplayStatus [] PROGMEM = "Disp Stat"; -const char pstrUsageStatusNotReady [] PROGMEM = "Stat !Ready"; -const char pstrUsageStatusReady [] PROGMEM = "Stat Ready"; -const char pstrUsageErrorNotALoadableCharacter [] PROGMEM = "Err Not Ld Char"; -const char pstrUsageErrorFotDataCanNotBeRead [] PROGMEM = "Fnt Data Rd Err"; -const char pstrUsageCursorPositionReport [] PROGMEM = "Cur Pos Rpt"; -const char pstrUsageRow [] PROGMEM = "Row"; -const char pstrUsageColumn [] PROGMEM = "Col"; -const char pstrUsageRows [] PROGMEM = "Rows"; -const char pstrUsageColumns [] PROGMEM = "Cols"; -const char pstrUsageCursorPixelPosition [] PROGMEM = "Cur Pix Pos"; -const char pstrUsageCursorMode [] PROGMEM = "Cur Mode"; -const char pstrUsageCursorEnable [] PROGMEM = "Cur Enbl"; -const char pstrUsageCursorBlink [] PROGMEM = "Cur Blnk"; -const char pstrUsageFontReport [] PROGMEM = "Fnt Rpt"; -const char pstrUsageFontData [] PROGMEM = "Fnt Data"; -const char pstrUsageCharacterWidth [] PROGMEM = "Char Wdth"; -const char pstrUsageCharacterHeight [] PROGMEM = "Char Hght"; -const char pstrUsageCharacterSpacingHorizontal [] PROGMEM = "Char Space H"; -const char pstrUsageCharacterSpacingVertical [] PROGMEM = "Char Space V"; -const char pstrUsageUnicodeCharset [] PROGMEM = "Unicode Char"; -const char pstrUsageFont7Segment [] PROGMEM = "Fnt 7-seg"; -const char pstrUsage7SegmentDirectMap [] PROGMEM = "7-seg map"; -const char pstrUsageFont14Segment [] PROGMEM = "Fnt 14-seg"; -const char pstrUsage14SegmentDirectMap [] PROGMEM = "14-seg map"; -const char pstrUsageDisplayBrightness [] PROGMEM = "Disp Bright"; -const char pstrUsageDisplayContrast [] PROGMEM = "Disp Cntrst"; -const char pstrUsageCharacterAttribute [] PROGMEM = "Char Attr"; -const char pstrUsageAttributeReadback [] PROGMEM = "Attr Readbk"; -const char pstrUsageAttributeData [] PROGMEM = "Attr Data"; -const char pstrUsageCharAttributeEnhance [] PROGMEM = "Char Attr Enh"; -const char pstrUsageCharAttributeUnderline [] PROGMEM = "Char Attr Undl"; -const char pstrUsageCharAttributeBlink [] PROGMEM = "Char Attr Blnk"; -const char pstrUsageBitmapSizeX [] PROGMEM = "Bmp Size X"; -const char pstrUsageBitmapSizeY [] PROGMEM = "Bmp Size Y"; -const char pstrUsageBitDepthFormat [] PROGMEM = "Bit Dpth Fmt"; -const char pstrUsageDisplayOrientation [] PROGMEM = "Disp Ornt"; -const char pstrUsagePaletteReport [] PROGMEM = "Pal Rpt"; -const char pstrUsagePaletteDataSize [] PROGMEM = "Pal Data Size"; -const char pstrUsagePaletteDataOffset [] PROGMEM = "Pal Data Off"; -const char pstrUsagePaletteData [] PROGMEM = "Pal Data"; -const char pstrUsageBlitReport [] PROGMEM = "Blit Rpt"; -const char pstrUsageBlitRectangleX1 [] PROGMEM = "Blit Rect X1"; -const char pstrUsageBlitRectangleY1 [] PROGMEM = "Blit Rect Y1"; -const char pstrUsageBlitRectangleX2 [] PROGMEM = "Blit Rect X2"; -const char pstrUsageBlitRectangleY2 [] PROGMEM = "Blit Rect Y2"; -const char pstrUsageBlitData [] PROGMEM = "Blit Data"; -const char pstrUsageSoftButton [] PROGMEM = "Soft Btn"; -const char pstrUsageSoftButtonID [] PROGMEM = "Soft Btn ID"; -const char pstrUsageSoftButtonSide [] PROGMEM = "Soft Btn Side"; -const char pstrUsageSoftButtonOffset1 [] PROGMEM = "Soft Btn Off1"; -const char pstrUsageSoftButtonOffset2 [] PROGMEM = "Soft Btn Off2"; -const char pstrUsageSoftButtonReport [] PROGMEM = "Soft Btn Rpt"; - -// Medical Instrument Page -const char pstrUsageMedicalUltrasound [] PROGMEM = "Med Ultrasnd"; -const char pstrUsageVCRAcquisition [] PROGMEM = "VCR/Acq"; -const char pstrUsageFreezeThaw [] PROGMEM = "Freeze"; -const char pstrUsageClipStore [] PROGMEM = "Clip Store"; -const char pstrUsageUpdate [] PROGMEM = "Update"; -const char pstrUsageNext [] PROGMEM = "Next"; -const char pstrUsageSave [] PROGMEM = "Save"; -const char pstrUsagePrint [] PROGMEM = "Print"; -const char pstrUsageMicrophoneEnable [] PROGMEM = "Mic Enbl"; -const char pstrUsageCine [] PROGMEM = "Cine"; -const char pstrUsageTransmitPower [] PROGMEM = "Trans Pwr"; -//const char pstrUsageVolume [] PROGMEM = "Vol"; -const char pstrUsageFocus [] PROGMEM = "Focus"; -const char pstrUsageDepth [] PROGMEM = "Depth"; -const char pstrUsageSoftStepPrimary [] PROGMEM = "Soft Stp-Pri"; -const char pstrUsageSoftStepSecondary [] PROGMEM = "Soft Stp-Sec"; -const char pstrUsageDepthGainCompensation [] PROGMEM = "Dpth Gain Comp"; -const char pstrUsageZoomSelect [] PROGMEM = "Zoom Sel"; -const char pstrUsageZoomAdjust [] PROGMEM = "Zoom Adj"; -const char pstrUsageSpectralDopplerModeSelect [] PROGMEM = "Spec Dop Mode Sel"; -const char pstrUsageSpectralDopplerModeAdjust [] PROGMEM = "Spec Dop Mode Adj"; -const char pstrUsageColorDopplerModeSelect [] PROGMEM = "Color Dop Mode Sel"; -const char pstrUsageColorDopplerModeAdjust [] PROGMEM = "Color Dop Mode Adj"; -const char pstrUsageMotionModeSelect [] PROGMEM = "Motion Mode Sel"; -const char pstrUsageMotionModeAdjust [] PROGMEM = "Motion Mode Adj"; -const char pstrUsage2DModeSelect [] PROGMEM = "2D Mode Sel"; -const char pstrUsage2DModeAdjust [] PROGMEM = "2D Mode Adj"; -const char pstrUsageSoftControlSelect [] PROGMEM = "Soft Ctrl Sel"; -const char pstrUsageSoftControlAdjust [] PROGMEM = "Soft Ctrl Adj"; - -//extern const char *usagePageTitles0[15]; -//const char *usagePageTitles1[]; -//const char *genDesktopTitles0[]; -//const char *genDesktopTitles1[]; -//const char *genDesktopTitles2[]; -//const char *genDesktopTitles3[]; -//const char *genDesktopTitles4[]; -//const char *simuTitles0[]; -//const char *simuTitles1[]; -//const char *simuTitles2[]; -//const char *vrTitles0[]; -//const char *vrTitles1[]; -//const char *sportsCtrlTitles0[]; -//const char *sportsCtrlTitles1[]; -//const char *sportsCtrlTitles2[]; -//const char *gameTitles0[]; -//const char *gameTitles1[]; -//const char *genDevCtrlTitles[]; -//const char *ledTitles[]; -//const char *telTitles0[]; -//const char *telTitles1[]; -//const char *telTitles2[]; -//const char *telTitles3[]; -//const char *telTitles4[]; -//const char *telTitles5[]; -//const char *consTitles0[]; -//const char *consTitles1[]; -//const char *consTitles2[]; -//const char *consTitles3[]; -//const char *consTitles4[]; -//const char *consTitles5[]; -//const char *consTitles6[]; -//const char *consTitles7[]; -//const char *consTitles8[]; -//const char *consTitles9[]; -//const char *consTitlesA[]; -//const char *consTitlesB[]; -//const char *consTitlesC[]; -//const char *consTitlesD[]; -//const char *consTitlesE[]; -//const char *digitTitles0[]; -//const char *digitTitles1[]; -//const char *digitTitles2[]; -//const char *aplphanumTitles0[]; -//const char *aplphanumTitles1[]; -//const char *aplphanumTitles2[]; -//const char *medInstrTitles0[]; -//const char *medInstrTitles1[]; -//const char *medInstrTitles2[]; -//const char *medInstrTitles3[]; -//const char *medInstrTitles4[]; - -#endif //__HIDUSAGESTR_H__ diff --git a/test/libraries/USBHost/src/macros.h b/test/libraries/USBHost/src/macros.h deleted file mode 100644 index 5df3faff..00000000 --- a/test/libraries/USBHost/src/macros.h +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(MACROS_H) -#error "Never include macros.h directly; include Usb.h instead" -#else -#define MACROS_H - -//////////////////////////////////////////////////////////////////////////////// -// HANDY MACROS -//////////////////////////////////////////////////////////////////////////////// - -#define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) -#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) -#define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)/*pgm_read_pointer*/(wa), el) -#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el); - -#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) -#ifndef __BYTE_GRABBING_DEFINED__ -#define __BYTE_GRABBING_DEFINED__ 1 -#ifdef BROKEN_OPTIMIZER_LITTLE_ENDIAN -// Note: Use this if your compiler generates horrible assembler! -#define BGRAB0(__usi__) (((uint8_t *)&(__usi__))[0]) -#define BGRAB1(__usi__) (((uint8_t *)&(__usi__))[1]) -#define BGRAB2(__usi__) (((uint8_t *)&(__usi__))[2]) -#define BGRAB3(__usi__) (((uint8_t *)&(__usi__))[3]) -#define BGRAB4(__usi__) (((uint8_t *)&(__usi__))[4]) -#define BGRAB5(__usi__) (((uint8_t *)&(__usi__))[5]) -#define BGRAB6(__usi__) (((uint8_t *)&(__usi__))[6]) -#define BGRAB7(__usi__) (((uint8_t *)&(__usi__))[7]) -#else -// Note: The cast alone to uint8_t is actually enough. -// GCC throws out the "& 0xff", and the size is no different. -// Some compilers need it. -#define BGRAB0(__usi__) ((uint8_t)((__usi__) & 0xff )) -#define BGRAB1(__usi__) ((uint8_t)(((__usi__) >> 8) & 0xff)) -#define BGRAB2(__usi__) ((uint8_t)(((__usi__) >> 16) & 0xff)) -#define BGRAB3(__usi__) ((uint8_t)(((__usi__) >> 24) & 0xff)) -#define BGRAB4(__usi__) ((uint8_t)(((__usi__) >> 32) & 0xff)) -#define BGRAB5(__usi__) ((uint8_t)(((__usi__) >> 40) & 0xff)) -#define BGRAB6(__usi__) ((uint8_t)(((__usi__) >> 48) & 0xff)) -#define BGRAB7(__usi__) ((uint8_t)(((__usi__) >> 56) & 0xff)) -#endif -#define BOVER1(__usi__) ((uint16_t)(__usi__) << 8) -#define BOVER2(__usi__) ((uint32_t)(__usi__) << 16) -#define BOVER3(__usi__) ((uint32_t)(__usi__) << 24) -#define BOVER4(__usi__) ((uint64_t)(__usi__) << 32) -#define BOVER5(__usi__) ((uint64_t)(__usi__) << 40) -#define BOVER6(__usi__) ((uint64_t)(__usi__) << 48) -#define BOVER7(__usi__) ((uint64_t)(__usi__) << 56) - -// These are the smallest and fastest ways I have found so far in pure C/C++. -#define BMAKE16(__usc1__,__usc0__) ((uint16_t)((uint16_t)(__usc0__) | (uint16_t)BOVER1(__usc1__))) -#define BMAKE32(__usc3__,__usc2__,__usc1__,__usc0__) ((uint32_t)((uint32_t)(__usc0__) | (uint32_t)BOVER1(__usc1__) | (uint32_t)BOVER2(__usc2__) | (uint32_t)BOVER3(__usc3__))) -#define BMAKE64(__usc7__,__usc6__,__usc5__,__usc4__,__usc3__,__usc2__,__usc1__,__usc0__) ((uint64_t)((uint64_t)__usc0__ | (uint64_t)BOVER1(__usc1__) | (uint64_t)BOVER2(__usc2__) | (uint64_t)BOVER3(__usc3__) | (uint64_t)BOVER4(__usc4__) | (uint64_t)BOVER5(__usc5__) | (uint64_t)BOVER6(__usc6__) | (uint64_t)BOVER1(__usc7__))) -#endif - -/* - * Debug macros: Strings are stored in progmem (flash) instead of RAM. - */ -#define USBTRACE(s) (Notify(PSTR(s), 0x80)) -#define USBTRACE1(s,l) (Notify(PSTR(s), l)) -#define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80)) -#define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l)) - - -#endif /* MACROS_H */ - diff --git a/test/libraries/USBHost/src/message.cpp b/test/libraries/USBHost/src/message.cpp deleted file mode 100644 index bdcdd183..00000000 --- a/test/libraries/USBHost/src/message.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "Usb.h" -// 0x80 is the default (i.e. trace) to turn off set this global to something lower. -// this allows for 126 other debugging levels. -// TO-DO: Allow assignment to a different serial port by software -int UsbDEBUGlvl = 0x80; - -void E_Notifyc(char c, int lvl) { - if(UsbDEBUGlvl < lvl) return; -#if defined(ARDUINO) && ARDUINO >=100 - USB_HOST_SERIAL.print(c); -#else - USB_HOST_SERIAL.print(c, BYTE); -#endif - //USB_HOST_SERIAL.flush(); -} - -void E_Notify(char const * msg, int lvl) { - if(UsbDEBUGlvl < lvl) return; - if(!msg) return; - char c; - - while((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl); -} - -void E_NotifyStr(char const * msg, int lvl) { - if(UsbDEBUGlvl < lvl) return; - if(!msg) return; - char c; - - while((c = *msg++)) E_Notifyc(c, lvl); -} - -void E_Notify(uint8_t b, int lvl) { - if(UsbDEBUGlvl < lvl) return; -#if defined(ARDUINO) && ARDUINO >=100 - USB_HOST_SERIAL.print(b); -#else - USB_HOST_SERIAL.print(b, DEC); -#endif - //USB_HOST_SERIAL.flush(); -} - -void E_Notify(double d, int lvl) { - if(UsbDEBUGlvl < lvl) return; - USB_HOST_SERIAL.print(d); - //USB_HOST_SERIAL.flush(); -} - -#ifdef DEBUG_USB_HOST - -void NotifyFailGetDevDescr(void) { - Notify(PSTR("\r\ngetDevDescr "), 0x80); -} - -void NotifyFailSetDevTblEntry(void) { - Notify(PSTR("\r\nsetDevTblEn "), 0x80); -} - -void NotifyFailGetConfDescr(void) { - Notify(PSTR("\r\ngetConf "), 0x80); -} - -void NotifyFailSetConfDescr(void) { - Notify(PSTR("\r\nsetConf "), 0x80); -} - -void NotifyFailGetDevDescr(uint8_t reason) { - NotifyFailGetDevDescr(); - NotifyFail(reason); -} - -void NotifyFailSetDevTblEntry(uint8_t reason) { - NotifyFailSetDevTblEntry(); - NotifyFail(reason); - -} - -void NotifyFailGetConfDescr(uint8_t reason) { - NotifyFailGetConfDescr(); - NotifyFail(reason); -} - -void NotifyFailSetConfDescr(uint8_t reason) { - NotifyFailSetConfDescr(); - NotifyFail(reason); -} - -void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID) { - Notify(PSTR("\r\nUnknown Device Connected - VID: "), 0x80); - D_PrintHex (VID, 0x80); - Notify(PSTR(" PID: "), 0x80); - D_PrintHex (PID, 0x80); -} - -void NotifyFail(uint8_t rcode) { - D_PrintHex (rcode, 0x80); - Notify(PSTR("\r\n"), 0x80); -} -#endif diff --git a/test/libraries/USBHost/src/message.h b/test/libraries/USBHost/src/message.h deleted file mode 100644 index c26628e7..00000000 --- a/test/libraries/USBHost/src/message.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__MESSAGE_H__) -#error "Never include message.h directly; include Usb.h instead" -#else -#define __MESSAGE_H__ - -extern int UsbDEBUGlvl; - -void E_Notify(char const * msg, int lvl); -void E_Notify(uint8_t b, int lvl); -void E_NotifyStr(char const * msg, int lvl); -void E_Notifyc(char c, int lvl); - -#ifdef DEBUG_USB_HOST -#define Notify E_Notify -#define NotifyStr E_NotifyStr -#define Notifyc E_Notifyc -void NotifyFailGetDevDescr(uint8_t reason); -void NotifyFailSetDevTblEntry(uint8_t reason); -void NotifyFailGetConfDescr(uint8_t reason); -void NotifyFailSetConfDescr(uint8_t reason); -void NotifyFailGetDevDescr(void); -void NotifyFailSetDevTblEntry(void); -void NotifyFailGetConfDescr(void); -void NotifyFailSetConfDescr(void); -void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID); -void NotifyFail(uint8_t rcode); -#else -#define Notify(...) ((void)0) -#define NotifyStr(...) ((void)0) -#define Notifyc(...) ((void)0) -#define NotifyFailGetDevDescr(...) ((void)0) -#define NotifyFailSetDevTblEntry(...) ((void)0) -#define NotifyFailGetConfDescr(...) ((void)0) -#define NotifyFailGetDevDescr(...) ((void)0) -#define NotifyFailSetDevTblEntry(...) ((void)0) -#define NotifyFailGetConfDescr(...) ((void)0) -#define NotifyFailSetConfDescr(...) ((void)0) -#define NotifyFailUnknownDevice(...) ((void)0) -#define NotifyFail(...) ((void)0) -#endif - -template -void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) { -#ifdef DEBUG_USB_HOST - Notify(msg, level); - Notify(PSTR(": "), level); - D_PrintHex (rcode, level); - Notify(PSTR("\r\n"), level); -#endif -} - -template -void ErrorMessage(char const * msg, ERROR_TYPE rcode = 0) { -#ifdef DEBUG_USB_HOST - Notify(msg, 0x80); - Notify(PSTR(": "), 0x80); - D_PrintHex (rcode, 0x80); - Notify(PSTR("\r\n"), 0x80); -#endif -} - -#endif // __MESSAGE_H__ diff --git a/test/libraries/USBHost/src/parsetools.cpp b/test/libraries/USBHost/src/parsetools.cpp deleted file mode 100644 index 00ca9e64..00000000 --- a/test/libraries/USBHost/src/parsetools.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#include "Usb.h" - -bool MultiByteValueParser::Parse(uint8_t **pp, uint32_t *pcntdn) { - if(!pBuf) { - Notify(PSTR("Buffer pointer is NULL!\r\n"), 0x80); - return false; - } - for (; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++) - pBuf[valueSize - countDown] = (**pp); - - if(countDown) - return false; - - countDown = valueSize; - return true; -} - -bool PTPListParser::Parse(uint8_t **pp, uint32_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me) { - switch(nStage) { - case 0: - pBuf->valueSize = lenSize; - theParser.Initialize(pBuf); - nStage = 1; - - case 1: - if(!theParser.Parse(pp, pcntdn)) - return false; - - arLen = 0; - arLen = (pBuf->valueSize >= 4) ? *((uint32_t*)pBuf->pValue) : (uint32_t)(*((uint16_t*)pBuf->pValue)); - arLenCntdn = arLen; - nStage = 2; - - case 2: - pBuf->valueSize = valSize; - theParser.Initialize(pBuf); - nStage = 3; - - case 3: - for(; arLenCntdn; arLenCntdn--) { - if(!theParser.Parse(pp, pcntdn)) - return false; - - if(pf) - pf(pBuf, (arLen - arLenCntdn), me); - } - - nStage = 0; - } - return true; -} diff --git a/test/libraries/USBHost/src/parsetools.h b/test/libraries/USBHost/src/parsetools.h deleted file mode 100644 index d4633589..00000000 --- a/test/libraries/USBHost/src/parsetools.h +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(__PARSETOOLS_H__) -#error "Never include parsetools.h directly; include Usb.h instead" -#else -#define __PARSETOOLS_H__ - -#include -//#include "Arduino.h" - -struct MultiValueBuffer { - uint8_t valueSize; - void *pValue; -}; - -class MultiByteValueParser { - uint8_t *pBuf; - uint32_t countDown; - uint32_t valueSize; - -public: - - MultiByteValueParser() : pBuf(NULL), countDown(0), valueSize(0) { - }; - - const uint8_t* GetBuffer() { - return pBuf; - }; - - void Initialize(MultiValueBuffer * const pbuf) { - pBuf = (uint8_t*)pbuf->pValue; - countDown = valueSize = pbuf->valueSize; - }; - - bool Parse(uint8_t **pp, uint32_t *pcntdn); -}; - -class ByteSkipper { - uint8_t *pBuf; - uint32_t nStage; - uint32_t countDown; - -public: - - ByteSkipper() : pBuf(NULL), nStage(0), countDown(0) { - }; - - void Initialize(MultiValueBuffer *pbuf) { - pBuf = (uint8_t*)pbuf->pValue; - countDown = 0; - }; - - bool Skip(uint8_t **pp, uint32_t *pcntdn, uint32_t bytes_to_skip) { - switch(nStage) { - case 0: - countDown = bytes_to_skip; - nStage++; - case 1: - for(; countDown && (*pcntdn); countDown--, (*pp)++, (*pcntdn)--); - - if(!countDown) - nStage = 0; - }; - return (!countDown); - }; -}; - -// Pointer to a callback function triggered for each element of PTP array when used with PTPArrayParser -typedef void (*PTP_ARRAY_EL_FUNC)(const MultiValueBuffer * const p, uint32_t count, const void *me); - -class PTPListParser { -public: - - enum ParseMode { - modeArray, modeRange/*, modeEnum*/ - }; - -private: - uint32_t nStage; - uint32_t enStage; - - uint32_t arLen; - uint32_t arLenCntdn; - - uint32_t lenSize; // size of the array length field in bytes - uint32_t valSize; // size of the array element in bytes - - MultiValueBuffer *pBuf; - - // The only parser for both size and array element parsing - MultiByteValueParser theParser; - - uint32_t /*ParseMode*/ prsMode; - -public: - - PTPListParser() : - nStage(0), - enStage(0), - arLen(0), - arLenCntdn(0), - lenSize(0), - valSize(0), - pBuf(NULL), - prsMode(modeArray) { - }; - - void Initialize(const uint32_t len_size, const uint32_t val_size, MultiValueBuffer * const p, const uint32_t mode = modeArray) { - pBuf = p; - lenSize = len_size; - valSize = val_size; - prsMode = mode; - - if(prsMode == modeRange) { - arLenCntdn = arLen = 3; - nStage = 2; - } else { - arLenCntdn = arLen = 0; - nStage = 0; - } - enStage = 0; - theParser.Initialize(p); - }; - - bool Parse(uint8_t **pp, uint32_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me = NULL); -}; - -#endif // __PARSETOOLS_H__ diff --git a/test/libraries/USBHost/src/printhex.h b/test/libraries/USBHost/src/printhex.h deleted file mode 100644 index 369d7e1f..00000000 --- a/test/libraries/USBHost/src/printhex.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(__PRINTHEX_H__) -#error "Never include printhex.h directly; include Usb.h instead" -#else -#define __PRINTHEX_H__ - -void E_Notifyc(char c, int lvl); - -template -void PrintHex(T val, int lvl) { - int num_nibbles = sizeof (T) * 2; - - do { - char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); - if(v > 57) v += 7; - E_Notifyc(v, lvl); - } while(--num_nibbles); -} - -template -void PrintBin(T val, int lvl) { - for(T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1) - if(val & mask) - E_Notifyc('1', lvl); - else - E_Notifyc('0', lvl); -} - -template -void SerialPrintHex(T val) { - int num_nibbles = sizeof (T) * 2; - - do { - char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); - if(v > 57) v += 7; - USB_HOST_SERIAL.print(v); - } while(--num_nibbles); -} - -template -void PrintHex2(Print *prn, T val) { - T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2)); - - while(mask > 1) { - if(val < mask) - prn->print("0"); - - mask >>= 4; - } - prn->print((T)val, HEX); -} - -template void D_PrintHex(T val, int lvl) { -#ifdef DEBUG_USB_HOST - PrintHex (val, lvl); -#endif -} - -template -void D_PrintBin(T val, int lvl) { -#ifdef DEBUG_USB_HOST - PrintBin (val, lvl); -#endif -} - - - -#endif // __PRINTHEX_H__ diff --git a/test/libraries/USBHost/src/sink_parser.h b/test/libraries/USBHost/src/sink_parser.h deleted file mode 100644 index a23637d2..00000000 --- a/test/libraries/USBHost/src/sink_parser.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__SINK_PARSER_H__) -#error "Never include hexdump.h directly; include Usb.h instead" -#else -#define __SINK_PARSER_H__ - -extern int UsbDEBUGlvl; - -// This parser does absolutely nothing with the data, just swallows it. - -template -class SinkParser : public BASE_CLASS { -public: - - SinkParser() { - }; - - void Initialize() { - }; - - void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { - }; -}; - - -#endif // __HEXDUMP_H__ diff --git a/test/libraries/USBHost/src/usb_ch9.h b/test/libraries/USBHost/src/usb_ch9.h deleted file mode 100644 index 09dd94b9..00000000 --- a/test/libraries/USBHost/src/usb_ch9.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(_ch9_h_) -#error "Never include usb_ch9.h directly; include Usb.h instead" -#else - -/* USB chapter 9 structures */ -#define _ch9_h_ - -#include - -/* Misc.USB constants */ -#define DEV_DESCR_LEN 18 //device descriptor length -#define CONF_DESCR_LEN 9 //configuration descriptor length -#define INTR_DESCR_LEN 9 //interface descriptor length -#define EP_DESCR_LEN 7 //endpoint descriptor length - -/* Standard Device Requests */ - -#define USB_REQUEST_GET_STATUS 0 // Standard Device Request - GET STATUS -#define USB_REQUEST_CLEAR_FEATURE 1 // Standard Device Request - CLEAR FEATURE -#define USB_REQUEST_SET_FEATURE 3 // Standard Device Request - SET FEATURE -#define USB_REQUEST_SET_ADDRESS 5 // Standard Device Request - SET ADDRESS -#define USB_REQUEST_GET_DESCRIPTOR 6 // Standard Device Request - GET DESCRIPTOR -#define USB_REQUEST_SET_DESCRIPTOR 7 // Standard Device Request - SET DESCRIPTOR -#define USB_REQUEST_GET_CONFIGURATION 8 // Standard Device Request - GET CONFIGURATION -#define USB_REQUEST_SET_CONFIGURATION 9 // Standard Device Request - SET CONFIGURATION -#define USB_REQUEST_GET_INTERFACE 10 // Standard Device Request - GET INTERFACE -#define USB_REQUEST_SET_INTERFACE 11 // Standard Device Request - SET INTERFACE -#define USB_REQUEST_SYNCH_FRAME 12 // Standard Device Request - SYNCH FRAME - -#define USB_FEATURE_ENDPOINT_HALT 0 // CLEAR/SET FEATURE - Endpoint Halt -#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // CLEAR/SET FEATURE - Device remote wake-up -#define USB_FEATURE_TEST_MODE 2 // CLEAR/SET FEATURE - Test mode - -/* Setup Data Constants */ - -#define USB_SETUP_HOST_TO_DEVICE 0x00 // Device Request bmRequestType transfer direction - host to device transfer -#define USB_SETUP_DEVICE_TO_HOST 0x80 // Device Request bmRequestType transfer direction - device to host transfer -#define USB_SETUP_TYPE_STANDARD 0x00 // Device Request bmRequestType type - standard -#define USB_SETUP_TYPE_CLASS 0x20 // Device Request bmRequestType type - class -#define USB_SETUP_TYPE_VENDOR 0x40 // Device Request bmRequestType type - vendor -#define USB_SETUP_RECIPIENT_DEVICE 0x00 // Device Request bmRequestType recipient - device -#define USB_SETUP_RECIPIENT_INTERFACE 0x01 // Device Request bmRequestType recipient - interface -#define USB_SETUP_RECIPIENT_ENDPOINT 0x02 // Device Request bmRequestType recipient - endpoint -#define USB_SETUP_RECIPIENT_OTHER 0x03 // Device Request bmRequestType recipient - other - -/* USB descriptors */ - -#define USB_DESCRIPTOR_DEVICE 0x01 // bDescriptorType for a Device Descriptor. -#define USB_DESCRIPTOR_CONFIGURATION 0x02 // bDescriptorType for a Configuration Descriptor. -#define USB_DESCRIPTOR_STRING 0x03 // bDescriptorType for a String Descriptor. -#define USB_DESCRIPTOR_INTERFACE 0x04 // bDescriptorType for an Interface Descriptor. -#define USB_DESCRIPTOR_ENDPOINT 0x05 // bDescriptorType for an Endpoint Descriptor. -#define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // bDescriptorType for a Device Qualifier. -#define USB_DESCRIPTOR_OTHER_SPEED 0x07 // bDescriptorType for a Other Speed Configuration. -#define USB_DESCRIPTOR_INTERFACE_POWER 0x08 // bDescriptorType for Interface Power. -#define USB_DESCRIPTOR_OTG 0x09 // bDescriptorType for an OTG Descriptor. - -#define HID_DESCRIPTOR_HID 0x21 - - - -/* OTG SET FEATURE Constants */ -#define OTG_FEATURE_B_HNP_ENABLE 3 // SET FEATURE OTG - Enable B device to perform HNP -#define OTG_FEATURE_A_HNP_SUPPORT 4 // SET FEATURE OTG - A device supports HNP -#define OTG_FEATURE_A_ALT_HNP_SUPPORT 5 // SET FEATURE OTG - Another port on the A device supports HNP - -/* USB Endpoint Transfer Types */ -#define USB_TRANSFER_TYPE_CONTROL 0x00 // Endpoint is a control endpoint. -#define USB_TRANSFER_TYPE_ISOCHRONOUS 0x01 // Endpoint is an isochronous endpoint. -#define USB_TRANSFER_TYPE_BULK 0x02 // Endpoint is a bulk endpoint. -#define USB_TRANSFER_TYPE_INTERRUPT 0x03 // Endpoint is an interrupt endpoint. -#define bmUSB_TRANSFER_TYPE 0x03 // bit mask to separate transfer type from ISO attributes - - -/* Standard Feature Selectors for CLEAR_FEATURE Requests */ -#define USB_FEATURE_ENDPOINT_STALL 0 // Endpoint recipient -#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // Device recipient -#define USB_FEATURE_TEST_MODE 2 // Device recipient - -_Pragma("pack(1)") - -/* descriptor data structures */ - -/* Device descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE). - uint16_t bcdUSB; // USB Spec Release Number (BCD). - uint8_t bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bDeviceSubClass; // Subclass code (assigned by the USB-IF). - uint8_t bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bMaxPacketSize0; // Maximum packet size for endpoint 0. - uint16_t idVendor; // Vendor ID (assigned by the USB-IF). - uint16_t idProduct; // Product ID (assigned by the manufacturer). - uint16_t bcdDevice; // Device release number (BCD). - uint8_t iManufacturer; // Index of String Descriptor describing the manufacturer. - uint8_t iProduct; // Index of String Descriptor describing the product. - uint8_t iSerialNumber; // Index of String Descriptor with the device's serial number. - uint8_t bNumConfigurations; // Number of possible configurations. -} USB_DEVICE_DESCRIPTOR; - -/* Configuration descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION). - uint16_t wTotalLength; // Total length of all descriptors for this configuration. - uint8_t bNumInterfaces; // Number of interfaces in this configuration. - uint8_t bConfigurationValue; // Value of this configuration (1 based). - uint8_t iConfiguration; // Index of String Descriptor describing the configuration. - uint8_t bmAttributes; // Configuration characteristics. - uint8_t bMaxPower; // Maximum power consumed by this configuration. -} USB_CONFIGURATION_DESCRIPTOR; - -/* Interface descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). - uint8_t bInterfaceNumber; // Number of this interface (0 based). - uint8_t bAlternateSetting; // Value of this alternate interface setting. - uint8_t bNumEndpoints; // Number of endpoints in this interface. - uint8_t bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bInterfaceSubClass; // Subclass code (assigned by the USB-IF). - uint8_t bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t iInterface; // Index of String Descriptor describing the interface. -} USB_INTERFACE_DESCRIPTOR; - -/* Endpoint descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). - uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). - uint8_t bmAttributes; // Endpoint transfer type. - uint16_t wMaxPacketSize; // Maximum packet size. - uint8_t bInterval; // Polling interval in frames. -} USB_ENDPOINT_DESCRIPTOR; - - -/* HID descriptor */ -typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bcdHID; // HID class specification release - uint8_t bCountryCode; - uint8_t bNumDescriptors; // Number of additional class specific descriptors - uint8_t bDescrType; // Type of class descriptor - uint16_t wDescriptorLength; // Total size of the Report descriptor -} USB_HID_DESCRIPTOR; - -typedef struct { - uint8_t bDescrType; // Type of class descriptor - uint16_t wDescriptorLength; // Total size of the Report descriptor -} HID_CLASS_DESCRIPTOR_LEN_AND_TYPE; - -_Pragma("pack()") - -#endif // _ch9_h_ - diff --git a/test/libraries/USBHost/src/usbhub.cpp b/test/libraries/USBHost/src/usbhub.cpp deleted file mode 100644 index 55d5bc1f..00000000 --- a/test/libraries/USBHost/src/usbhub.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#include "usbhub.h" -#include "delay.h" - -bool USBHub::bResetInitiated = false; - -USBHub::USBHub(USBHost *p) : -pUsb(p), -bAddress(0), -bNbrPorts(0), -//bInitState(0), -qNextPollTime(0), -bPollEnable(false) { - epInfo[0].epAddr = 0; - epInfo[0].maxPktSize = 8; - epInfo[0].epAttribs = 0; - epInfo[0].bmNakPower = USB_NAK_MAX_POWER; - - epInfo[1].epAddr = 1; - epInfo[1].maxPktSize = 8; //kludge - epInfo[1].epAttribs = 0; - epInfo[1].bmNakPower = USB_NAK_NOWAIT; - - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -uint32_t USBHub::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - uint8_t buf[32]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - HubDescriptor* hd = reinterpret_cast(buf); - USB_CONFIGURATION_DESCRIPTOR * ucd = reinterpret_cast(buf); - uint32_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint32_t len = 0; - uint32_t cd_len = 0; - - //USBTRACE("\r\nHub Init Start "); - //D_PrintHex (bInitState, 0x80); - - AddressPool &addrPool = pUsb->GetAddressPool(); - - //switch (bInitState) { - // case 0: - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - - p->lowspeed = false; - - if(!rcode) - len = (buf[0] > 32) ? 32 : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - return rcode; - } - - // Extract device class from device descriptor - // If device class is not a hub return - if(udd->bDeviceClass != 0x09) - return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device - rcode = pUsb->setAddr(0, 0, bAddress); - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - addrPool.FreeAddress(bAddress); - bAddress = 0; - return rcode; - } - - //USBTRACE2("\r\nHub address: ", bAddress ); - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 2, epInfo); - - if(rcode) - goto FailSetDevTblEntry; - - // bInitState = 1; - - // case 1: - // Get hub descriptor - rcode = GetHubDescriptor(0, 8, buf); - - if(rcode) - goto FailGetHubDescr; - - // Save number of ports for future use - bNbrPorts = hd->bNbrPorts; - - // bInitState = 2; - - // case 2: - // Read configuration Descriptor in Order To Obtain Proper Configuration Value - rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf); - - if(!rcode) { - cd_len = ucd->wTotalLength; - rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf); - } - if(rcode) - goto FailGetConfDescr; - - // The following code is of no practical use in real life applications. - // It only intended for the usb protocol sniffer to properly parse hub-class requests. - { - uint8_t buf2[24]; - - rcode = pUsb->getConfDescr(bAddress, 0, buf[0], 0, buf2); - - if(rcode) - goto FailGetConfDescr; - } - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, buf[5]); - - if(rcode) - goto FailSetConfDescr; - - // bInitState = 3; - - // case 3: - // Power on all ports - for(uint32_t j = 1; j <= bNbrPorts; j++) - SetPortFeature(HUB_FEATURE_PORT_POWER, j, 0); //HubPortPowerOn(j); - - pUsb->SetHubPreMask(); - bPollEnable = true; - // bInitState = 0; - //} - //bInitState = 0; - //USBTRACE("...OK\r\n"); - return 0; - - // Oleg, No debugging?? -- xxxajk -FailGetDevDescr: - goto Fail; - -FailSetDevTblEntry: - goto Fail; - -FailGetHubDescr: - goto Fail; - -FailGetConfDescr: - goto Fail; - -FailSetConfDescr: - goto Fail; - -Fail: - USBTRACE("...FAIL\r\n"); - return rcode; -} - -uint32_t USBHub::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - if(bAddress == 0x41) - pUsb->SetHubPreMask(); - - bAddress = 0; - bNbrPorts = 0; - qNextPollTime = 0; - bPollEnable = false; - return 0; -} - -uint32_t USBHub::Poll() { - uint32_t rcode = 0; - - if(!bPollEnable) - return 0; - - if(((long)(millis() - qNextPollTime) >= 0L)) { - rcode = CheckHubStatus(); - qNextPollTime = millis() + 100; - } - return rcode; -} - -uint32_t USBHub::CheckHubStatus() { - uint32_t rcode; - uint8_t buf[8]; - uint32_t read = 1; - - rcode = pUsb->inTransfer(bAddress, 1, (uint8_t*)&read, buf); - - if(rcode) - return rcode; - - //if (buf[0] & 0x01) // Hub Status Change - //{ - // pUsb->PrintHubStatus(addr); - // rcode = GetHubStatus(1, 0, 1, 4, buf); - // if (rcode) - // { - // USB_HOST_SERIAL.print("GetHubStatus Error"); - // USB_HOST_SERIAL.println(rcode, HEX); - // return rcode; - // } - //} - for(uint32_t port = 1, mask = 0x02; port < 8; mask <<= 1, port++) { - if(buf[0] & mask) { - HubEvent evt; - evt.bmEvent = 0; - - rcode = GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) - continue; - - rcode = PortStatusChange(port, evt); - - if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) - return 0; - - if(rcode) - return rcode; - } - } // for - - for(uint32_t port = 1; port <= bNbrPorts; port++) { - HubEvent evt; - evt.bmEvent = 0; - - rcode = GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) - continue; - - if((evt.bmStatus & bmHUB_PORT_STATE_CHECK_DISABLED) != bmHUB_PORT_STATE_DISABLED) - continue; - - // Emulate connection event for the port - evt.bmChange |= bmHUB_PORT_STATUS_C_PORT_CONNECTION; - - rcode = PortStatusChange(port, evt); - - if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) - return 0; - - if(rcode) - return rcode; - } // for - return 0; -} - -void USBHub::ResetHubPort(uint32_t port) { - HubEvent evt; - evt.bmEvent = 0; - uint8_t rcode; - - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0); - - - for(int i = 0; i < 3; i++) { - rcode = GetPortStatus(port, 4, evt.evtBuff); - if(rcode) break; // Some kind of error, bail. - if(evt.bmEvent == bmHUB_PORT_EVENT_RESET_COMPLETE || evt.bmEvent == bmHUB_PORT_EVENT_LS_RESET_COMPLETE) { - break; - } - delay(100); // simulate polling. - } - ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - delay(20); -} - -uint32_t USBHub::PortStatusChange(uint32_t port, HubEvent &evt) { - switch(evt.bmEvent) { - // Device connected event - case bmHUB_PORT_EVENT_CONNECT: - case bmHUB_PORT_EVENT_LS_CONNECT: - if(bResetInitiated) - return 0; - - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0); - bResetInitiated = true; - return HUB_ERROR_PORT_HAS_BEEN_RESET; - - // Device disconnected event - case bmHUB_PORT_EVENT_DISCONNECT: - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - bResetInitiated = false; - - UsbDeviceAddress a; - a.devAddress = 0; - a.bmHub = 0; - a.bmParent = bAddress; - a.bmAddress = port; - pUsb->ReleaseDevice(a.devAddress); - return 0; - - // Reset complete event - case bmHUB_PORT_EVENT_RESET_COMPLETE: - case bmHUB_PORT_EVENT_LS_RESET_COMPLETE: - ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - - delay(20); - - a.devAddress = bAddress; - - pUsb->Configuring(a.bmAddress, port, (evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED)); - bResetInitiated = false; - break; - - } // switch (evt.bmEvent) - return 0; -} - -void PrintHubPortStatus(USBHub *hubptr, uint32_t addr, uint32_t port, uint32_t print_changes) { - uint8_t rcode = 0; - HubEvent evt; - - rcode = hubptr->GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) { - USB_HOST_SERIAL.println("ERROR!"); - return; - } - USB_HOST_SERIAL.print("\r\nPort "); - USB_HOST_SERIAL.println(port, DEC); - - USB_HOST_SERIAL.println("Status"); - USB_HOST_SERIAL.print("CONNECTION:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_CONNECTION) > 0, DEC); - USB_HOST_SERIAL.print("ENABLE:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_ENABLE) > 0, DEC); - USB_HOST_SERIAL.print("SUSPEND:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_SUSPEND) > 0, DEC); - USB_HOST_SERIAL.print("OVER_CURRENT:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_OVER_CURRENT) > 0, DEC); - USB_HOST_SERIAL.print("RESET:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_RESET) > 0, DEC); - USB_HOST_SERIAL.print("POWER:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_POWER) > 0, DEC); - USB_HOST_SERIAL.print("LOW_SPEED:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED) > 0, DEC); - USB_HOST_SERIAL.print("HIGH_SPEED:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_HIGH_SPEED) > 0, DEC); - USB_HOST_SERIAL.print("TEST:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_TEST) > 0, DEC); - USB_HOST_SERIAL.print("INDICATOR:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_INDICATOR) > 0, DEC); - - if(!print_changes) - return; - - USB_HOST_SERIAL.println("\r\nChange"); - USB_HOST_SERIAL.print("CONNECTION:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_CONNECTION) > 0, DEC); - USB_HOST_SERIAL.print("ENABLE:\t\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_ENABLE) > 0, DEC); - USB_HOST_SERIAL.print("SUSPEND:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_SUSPEND) > 0, DEC); - USB_HOST_SERIAL.print("OVER_CURRENT:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT) > 0, DEC); - USB_HOST_SERIAL.print("RESET:\t\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_RESET) > 0, DEC); -} diff --git a/test/libraries/USBHost/src/usbhub.h b/test/libraries/USBHost/src/usbhub.h deleted file mode 100644 index 6a80a123..00000000 --- a/test/libraries/USBHost/src/usbhub.h +++ /dev/null @@ -1,252 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(__USBHUB_H__) -#define __USBHUB_H__ - -#include "Usb.h" - -#define USB_DESCRIPTOR_HUB 0x09 // Hub descriptor type - -// Hub Requests -#define bmREQ_CLEAR_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_CLEAR_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_CLEAR_TT_BUFFER USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_GET_HUB_DESCRIPTOR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_GET_HUB_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_GET_PORT_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_RESET_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_SET_HUB_DESCRIPTOR USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_SET_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_SET_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_GET_TT_STATE USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_STOP_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER - -// Hub Class Requests -#define HUB_REQUEST_CLEAR_TT_BUFFER 8 -#define HUB_REQUEST_RESET_TT 9 -#define HUB_REQUEST_GET_TT_STATE 10 -#define HUB_REQUEST_STOP_TT 11 - -// Hub Features -#define HUB_FEATURE_C_HUB_LOCAL_POWER 0 -#define HUB_FEATURE_C_HUB_OVER_CURRENT 1 -#define HUB_FEATURE_PORT_CONNECTION 0 -#define HUB_FEATURE_PORT_ENABLE 1 -#define HUB_FEATURE_PORT_SUSPEND 2 -#define HUB_FEATURE_PORT_OVER_CURRENT 3 -#define HUB_FEATURE_PORT_RESET 4 -#define HUB_FEATURE_PORT_POWER 8 -#define HUB_FEATURE_PORT_LOW_SPEED 9 -#define HUB_FEATURE_C_PORT_CONNECTION 16 -#define HUB_FEATURE_C_PORT_ENABLE 17 -#define HUB_FEATURE_C_PORT_SUSPEND 18 -#define HUB_FEATURE_C_PORT_OVER_CURRENT 19 -#define HUB_FEATURE_C_PORT_RESET 20 -#define HUB_FEATURE_PORT_TEST 21 -#define HUB_FEATURE_PORT_INDICATOR 22 - -// Hub Port Test Modes -#define HUB_PORT_TEST_MODE_J 1 -#define HUB_PORT_TEST_MODE_K 2 -#define HUB_PORT_TEST_MODE_SE0_NAK 3 -#define HUB_PORT_TEST_MODE_PACKET 4 -#define HUB_PORT_TEST_MODE_FORCE_ENABLE 5 - -// Hub Port Indicator Color -#define HUB_PORT_INDICATOR_AUTO 0 -#define HUB_PORT_INDICATOR_AMBER 1 -#define HUB_PORT_INDICATOR_GREEN 2 -#define HUB_PORT_INDICATOR_OFF 3 - -// Hub Port Status Bitmasks -#define bmHUB_PORT_STATUS_PORT_CONNECTION 0x0001 -#define bmHUB_PORT_STATUS_PORT_ENABLE 0x0002 -#define bmHUB_PORT_STATUS_PORT_SUSPEND 0x0004 -#define bmHUB_PORT_STATUS_PORT_OVER_CURRENT 0x0008 -#define bmHUB_PORT_STATUS_PORT_RESET 0x0010 -#define bmHUB_PORT_STATUS_PORT_POWER 0x0100 -#define bmHUB_PORT_STATUS_PORT_LOW_SPEED 0x0200 -#define bmHUB_PORT_STATUS_PORT_HIGH_SPEED 0x0400 -#define bmHUB_PORT_STATUS_PORT_TEST 0x0800 -#define bmHUB_PORT_STATUS_PORT_INDICATOR 0x1000 - -// Hub Port Status Change Bitmasks (used one byte instead of two) -#define bmHUB_PORT_STATUS_C_PORT_CONNECTION 0x0001 -#define bmHUB_PORT_STATUS_C_PORT_ENABLE 0x0002 -#define bmHUB_PORT_STATUS_C_PORT_SUSPEND 0x0004 -#define bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT 0x0008 -#define bmHUB_PORT_STATUS_C_PORT_RESET 0x0010 - -// Hub Status Bitmasks (used one byte instead of two) -#define bmHUB_STATUS_LOCAL_POWER_SOURCE 0x01 -#define bmHUB_STATUS_OVER_CURRENT 0x12 - -// Hub Status Change Bitmasks (used one byte instead of two) -#define bmHUB_STATUS_C_LOCAL_POWER_SOURCE 0x01 -#define bmHUB_STATUS_C_OVER_CURRENT 0x12 - - -// Hub Port Configuring Substates -#define USB_STATE_HUB_PORT_CONFIGURING 0xb0 -#define USB_STATE_HUB_PORT_POWERED_OFF 0xb1 -#define USB_STATE_HUB_PORT_WAIT_FOR_POWER_GOOD 0xb2 -#define USB_STATE_HUB_PORT_DISCONNECTED 0xb3 -#define USB_STATE_HUB_PORT_DISABLED 0xb4 -#define USB_STATE_HUB_PORT_RESETTING 0xb5 -#define USB_STATE_HUB_PORT_ENABLED 0xb6 - -// Additional Error Codes -#define HUB_ERROR_PORT_HAS_BEEN_RESET 0xb1 - -// The bit mask to check for all necessary state bits -#define bmHUB_PORT_STATUS_ALL_MAIN ((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE | bmHUB_PORT_STATUS_C_PORT_SUSPEND | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND) - -// Bit mask to check for DISABLED state in HubEvent::bmStatus field -#define bmHUB_PORT_STATE_CHECK_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND) - -// Hub Port States -#define bmHUB_PORT_STATE_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION) - -// Hub Port Events -#define bmHUB_PORT_EVENT_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION) -#define bmHUB_PORT_EVENT_DISCONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER) -#define bmHUB_PORT_EVENT_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION) - -#define bmHUB_PORT_EVENT_LS_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) -#define bmHUB_PORT_EVENT_LS_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) -#define bmHUB_PORT_EVENT_LS_PORT_ENABLED (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) - -struct HubDescriptor { - uint32_t bDescLength; // descriptor length - uint32_t bDescriptorType; // descriptor type - uint32_t bNbrPorts; // number of ports a hub equiped with - - struct { - uint32_t LogPwrSwitchMode : 2; - uint32_t CompoundDevice : 1; - uint32_t OverCurrentProtectMode : 2; - uint32_t TTThinkTime : 2; - uint32_t PortIndicatorsSupported : 1; - uint32_t Reserved : 24; - } __attribute__((packed)); - - uint32_t bPwrOn2PwrGood; - uint32_t bHubContrCurrent; -} __attribute__((packed)); - -struct HubEvent { - - union { - - struct { - uint32_t bmStatus; // port status bits - uint32_t bmChange; // port status change bits - } __attribute__((packed)); - uint32_t bmEvent; - uint8_t evtBuff[4]; - }; -} __attribute__((packed)); - -class USBHub : USBDeviceConfig { - static bool bResetInitiated; // True when reset is triggered - - USBHost *pUsb; // USB class instance pointer - - EpInfo epInfo[2]; // interrupt endpoint info structure - - uint32_t bAddress; // address - uint32_t bNbrPorts; // number of ports - // uint8_t bInitState; // initialization state variable - uint32_t qNextPollTime; // next poll time - uint32_t bPollEnable; // poll enable flag - - uint32_t CheckHubStatus(); - uint32_t PortStatusChange(uint32_t port, HubEvent &evt); - -public: - USBHub(USBHost *p); - - uint32_t ClearHubFeature(uint32_t fid); - uint32_t ClearPortFeature(uint32_t fid, uint32_t port, uint32_t sel = 0); - uint32_t GetHubDescriptor(uint32_t index, uint32_t nbytes, uint8_t *dataptr); - uint32_t GetHubStatus(uint32_t nbytes, uint8_t* dataptr); - uint32_t GetPortStatus(uint32_t port, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetHubDescriptor(uint32_t port, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetHubFeature(uint32_t fid); - uint32_t SetPortFeature(uint32_t fid, uint32_t port, uint32_t sel = 0); - - void PrintHubStatus(); - - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - virtual void ResetHubPort(uint32_t port); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t DEVCLASSOK(uint32_t klass) { - return (klass == 0x09); - } - -}; - -// Clear Hub Feature - -inline uint32_t USBHub::ClearHubFeature(uint32_t fid) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_HUB_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); -} -// Clear Port Feature - -inline uint32_t USBHub::ClearPortFeature(uint32_t fid, uint32_t port, uint32_t sel) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_PORT_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, ((0x0000 | port) | (sel << 8)), 0, 0, NULL, NULL)); -} -// Get Hub Descriptor - -inline uint32_t USBHub::GetHubDescriptor(uint32_t index, uint32_t nbytes, uint8_t *dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_DESCRIPTOR, USB_REQUEST_GET_DESCRIPTOR, index, 0x29, 0, nbytes, nbytes, dataptr, NULL)); -} -// Get Hub Status - -inline uint32_t USBHub::GetHubStatus(uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_STATUS, USB_REQUEST_GET_STATUS, 0, 0, 0x0000, nbytes, nbytes, dataptr, NULL)); -} -// Get Port Status - -inline uint32_t USBHub::GetPortStatus(uint32_t port, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_PORT_STATUS, USB_REQUEST_GET_STATUS, 0, 0, port, nbytes, nbytes, dataptr, NULL)); -} -// Set Hub Descriptor - -inline uint32_t USBHub::SetHubDescriptor(uint32_t port, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_DESCRIPTOR, USB_REQUEST_SET_DESCRIPTOR, 0, 0, port, nbytes, nbytes, dataptr, NULL)); -} -// Set Hub Feature - -inline uint32_t USBHub::SetHubFeature(uint32_t fid) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); -} -// Set Port Feature - -inline uint32_t USBHub::SetPortFeature(uint32_t fid, uint32_t port, uint32_t sel) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_PORT_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, (((0x0000 | sel) << 8) | port), 0, 0, NULL, NULL)); -} - -void PrintHubPortStatus(USBHost *usbptr, uint32_t addr, uint32_t port, uint32_t print_changes = false); - -#endif // __USBHUB_H__ diff --git a/test/libraries/testlib1/testlib1.h b/test/libraries/testlib1/testlib1.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib2/testlib2.h b/test/libraries/testlib2/testlib2.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib3/testlib3.h b/test/libraries/testlib3/testlib3.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib4/testlib4.h b/test/libraries/testlib4/testlib4.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/wronglib/library.properties b/test/libraries/wronglib/library.properties deleted file mode 100644 index b235c667..00000000 --- a/test/libraries/wronglib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=wronglib -version=1.0 -author=Arduino -maintainer=Arduino -sentence=sentence -paragraph=paragraph -url=url -architectures=* -category=Other diff --git a/test/libraries/wronglib/src/.gitkeep b/test/libraries/wronglib/src/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/wronglib/utility/.gitkeep b/test/libraries/wronglib/utility/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go deleted file mode 100644 index 1908d4de..00000000 --- a/test/libraries_loader_test.go +++ /dev/null @@ -1,292 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "sort" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func TestLoadLibrariesAVR(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - FQBN: "arduino:avr:leonardo", - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesFolders - require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) - - libraries := ctx.Libraries - require.Equal(t, 24, len(libraries)) - - sort.Sort(ByLibraryName(libraries)) - - idx := 0 - - require.Equal(t, "ANewLibrary-master", libraries[idx].Name) - - idx++ - require.Equal(t, "Adafruit_PN532", libraries[idx].Name) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libraries[idx].Folder) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libraries[idx].SrcFolder) - require.Equal(t, 1, len(libraries[idx].Archs)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, libraries[idx].Archs[0]) - require.False(t, libraries[idx].IsLegacy) - - idx++ - require.Equal(t, "Audio", libraries[idx].Name) - - idx++ - require.Equal(t, "Balanduino", libraries[idx].Name) - require.True(t, libraries[idx].IsLegacy) - - idx++ - bridgeLib := libraries[idx] - require.Equal(t, "Bridge", bridgeLib.Name) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge"), bridgeLib.Folder) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge/src"), bridgeLib.SrcFolder) - require.Equal(t, 1, len(bridgeLib.Archs)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Archs[0]) - require.Equal(t, "Arduino", bridgeLib.Author) - require.Equal(t, "Arduino ", bridgeLib.Maintainer) - - idx++ - require.Equal(t, "CapacitiveSensor", libraries[idx].Name) - idx++ - require.Equal(t, "EEPROM", libraries[idx].Name) - idx++ - require.Equal(t, "Ethernet", libraries[idx].Name) - idx++ - require.Equal(t, "FakeAudio", libraries[idx].Name) - idx++ - require.Equal(t, "FastLED", libraries[idx].Name) - idx++ - require.Equal(t, "HID", libraries[idx].Name) - idx++ - require.Equal(t, "IRremote", libraries[idx].Name) - idx++ - require.Equal(t, "Robot_IR_Remote", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "ShouldNotRecurseWithOldLibs", libraries[idx].Name) - idx++ - require.Equal(t, "SoftwareSerial", libraries[idx].Name) - idx++ - require.Equal(t, "USBHost", libraries[idx].Name) - idx++ - require.Equal(t, "Wire", libraries[idx].Name) - - headerToLibraries := ctx.HeaderToLibraries - require.Equal(t, 2, len(headerToLibraries["Audio.h"])) - require.Equal(t, "Audio", headerToLibraries["Audio.h"][0].Name) - require.Equal(t, "FakeAudio", headerToLibraries["Audio.h"][1].Name) - require.Equal(t, 1, len(headerToLibraries["FakeAudio.h"])) - require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) - require.Equal(t, 1, len(headerToLibraries["Adafruit_PN532.h"])) - require.Equal(t, "Adafruit_PN532", headerToLibraries["Adafruit_PN532.h"][0].Name) - - require.Equal(t, 2, len(headerToLibraries["IRremote.h"])) - - libraries = headerToLibraries["IRremote.h"] - sort.Sort(ByLibraryName(libraries)) - - require.Equal(t, "IRremote", libraries[0].Name) - require.Equal(t, "Robot_IR_Remote", libraries[1].Name) -} - -func TestLoadLibrariesSAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - FQBN: "arduino:sam:arduino_due_x_dbg", - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesFolders - require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "sam", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) - - libraries := ctx.Libraries - require.Equal(t, 22, len(libraries)) - - sort.Sort(ByLibraryName(libraries)) - - idx := 0 - require.Equal(t, "ANewLibrary-master", libraries[idx].Name) - idx++ - require.Equal(t, "Adafruit_PN532", libraries[idx].Name) - idx++ - require.Equal(t, "Audio", libraries[idx].Name) - idx++ - require.Equal(t, "Balanduino", libraries[idx].Name) - idx++ - require.Equal(t, "Bridge", libraries[idx].Name) - idx++ - require.Equal(t, "CapacitiveSensor", libraries[idx].Name) - idx++ - require.Equal(t, "Ethernet", libraries[idx].Name) - idx++ - require.Equal(t, "FakeAudio", libraries[idx].Name) - idx++ - require.Equal(t, "FastLED", libraries[idx].Name) - idx++ - require.Equal(t, "HID", libraries[idx].Name) - idx++ - require.Equal(t, "IRremote", libraries[idx].Name) - idx++ - require.Equal(t, "Robot_IR_Remote", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "ShouldNotRecurseWithOldLibs", libraries[idx].Name) - idx++ - require.Equal(t, "USBHost", libraries[idx].Name) - idx++ - require.Equal(t, "Wire", libraries[idx].Name) - - headerToLibraries := ctx.HeaderToLibraries - - require.Equal(t, 2, len(headerToLibraries["Audio.h"])) - libraries = headerToLibraries["Audio.h"] - sort.Sort(ByLibraryName(libraries)) - require.Equal(t, "Audio", libraries[0].Name) - require.Equal(t, "FakeAudio", libraries[1].Name) - - require.Equal(t, 1, len(headerToLibraries["FakeAudio.h"])) - require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) - require.Equal(t, 2, len(headerToLibraries["IRremote.h"])) - require.Equal(t, "Robot_IR_Remote", headerToLibraries["IRremote.h"][0].Name) - require.Equal(t, "IRremote", headerToLibraries["IRremote.h"][1].Name) -} - -func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")}, - FQBN: "arduino:avr:leonardo", - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesFolders - require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) -} - -func TestLoadLibrariesMyAVRPlatform(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")}, - FQBN: "my_avr_platform:avr:custom_yun", - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesFolders - require.Equal(t, 4, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries")), librariesFolders[2]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[3]) -} diff --git a/test/load_previous_build_options_map_test.go b/test/load_previous_build_options_map_test.go deleted file mode 100644 index 55984804..00000000 --- a/test/load_previous_build_options_map_test.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" -) - -func TestLoadPreviousBuildOptionsMap(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - err := utils.WriteFile(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE), "test") - NoError(t, err) - - command := builder.LoadPreviousBuildOptionsMap{} - err = command.Run(ctx) - NoError(t, err) - - require.Equal(t, "test", ctx.BuildOptionsJsonPrevious) -} - -func TestLoadPreviousBuildOptionsMapMissingFile(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - command := builder.LoadPreviousBuildOptionsMap{} - err := command.Run(ctx) - NoError(t, err) - - require.Empty(t, ctx.BuildOptionsJsonPrevious) -} diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go deleted file mode 100644 index 05fbf80f..00000000 --- a/test/load_vid_pid_specific_properties_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" -) - -func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:micro", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "0x0037", buildProperties["pid.0"]) - require.Equal(t, "\"Genuino Micro\"", buildProperties["vid.4.build.usb_product"]) - require.Equal(t, "0x8037", buildProperties["build.pid"]) -} - -func TestLoadVIDPIDSpecificProperties(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:micro", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - ctx.USBVidPid = "0x2341_0x0237" - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "0x0037", buildProperties["pid.0"]) - require.Equal(t, "\"Genuino Micro\"", buildProperties["vid.4.build.usb_product"]) - require.Equal(t, "0x2341", buildProperties["build.vid"]) - require.Equal(t, "0x8237", buildProperties["build.pid"]) -} diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go deleted file mode 100644 index 5d6776cf..00000000 --- a/test/merge_sketch_with_bootloader_test.go +++ /dev/null @@ -1,207 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" -) - -func TestMergeSketchWithBootloader(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch", "sketch.ino.hex"), fakeSketchHex) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch", "sketch.ino.with_bootloader.hex")) - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:107E0000112484B714BE81FFF0D085E080938100F7\n")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":0400000300007E007B\n:00000001FF\n")) -} - -func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch.ino.hex"), fakeSketchHex) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch.ino.with_bootloader.hex")) - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:107E0000112484B714BE81FFF0D085E080938100F7\n")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":0400000300007E007B\n:00000001FF\n")) -} - -func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - delete(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) - delete(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_FILE) - - command := &builder.MergeSketchWithBootloader{} - err := command.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.with_bootloader.hex")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) -} - -func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch", "sketch.ino.hex"), fakeSketchHex) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch", "sketch.ino.with_bootloader.hex")) - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:020000023000CC")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":040000033000E000E9\n:00000001FF\n")) -} diff --git a/test/platform_keys_rewrite_loader_test.go b/test/platform_keys_rewrite_loader_test.go deleted file mode 100644 index 914f5f75..00000000 --- a/test/platform_keys_rewrite_loader_test.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "path/filepath" - "testing" -) - -func TestLoadPlatformKeysRewrite(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware"}, - } - - commands := []types.Command{ - &builder.PlatformKeysRewriteLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - platformKeysRewrite := ctx.PlatformKeyRewrites - - require.Equal(t, 13, len(platformKeysRewrite.Rewrites)) - require.Equal(t, constants.BUILD_PROPERTIES_COMPILER_PATH, platformKeysRewrite.Rewrites[0].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platformKeysRewrite.Rewrites[0].OldValue) - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platformKeysRewrite.Rewrites[0].NewValue) - - require.Equal(t, "tools.avrdude.cmd.path", platformKeysRewrite.Rewrites[1].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/avrdude", platformKeysRewrite.Rewrites[1].OldValue) - require.Equal(t, "{path}/bin/avrdude", platformKeysRewrite.Rewrites[1].NewValue) - - require.Equal(t, constants.BUILD_PROPERTIES_COMPILER_PATH, platformKeysRewrite.Rewrites[3].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/", platformKeysRewrite.Rewrites[3].OldValue) - require.Equal(t, "{runtime.tools.arm-none-eabi-gcc.path}/bin/", platformKeysRewrite.Rewrites[3].NewValue) - - require.Equal(t, "recipe.c.combine.pattern", platformKeysRewrite.Rewrites[5].Key) - require.Equal(t, "\"{compiler.path}{compiler.c.elf.cmd}\" {compiler.c.elf.flags} -mcpu={build.mcu} \"-T{build.variant.path}/{build.ldscript}\" \"-Wl,-Map,{build.path}/{build.project_name}.map\" {compiler.c.elf.extra_flags} -o \"{build.path}/{build.project_name}.elf\" \"-L{build.path}\" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group \"{build.path}/syscalls_sam3.c.o\" {object_files} \"{build.variant.path}/{build.variant_system_lib}\" \"{build.path}/{archive_file}\" -Wl,--end-group -lm -gcc", platformKeysRewrite.Rewrites[5].OldValue) - require.Equal(t, "\"{compiler.path}{compiler.c.elf.cmd}\" {compiler.c.elf.flags} -mcpu={build.mcu} \"-T{build.variant.path}/{build.ldscript}\" \"-Wl,-Map,{build.path}/{build.project_name}.map\" {compiler.c.elf.extra_flags} -o \"{build.path}/{build.project_name}.elf\" \"-L{build.path}\" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group \"{build.path}/core/syscalls_sam3.c.o\" {object_files} \"{build.variant.path}/{build.variant_system_lib}\" \"{build.path}/{archive_file}\" -Wl,--end-group -lm -gcc", platformKeysRewrite.Rewrites[5].NewValue) -} diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go deleted file mode 100644 index 04d5481a..00000000 --- a/test/prototypes_adder_test.go +++ /dev/null @@ -1,951 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" -) - -func TestPrototypesAdderBridgeExample(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - ctx.DebugLevel = 10 - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 33 "+quotedSketchLocation+"\nvoid setup();\n#line 46 "+quotedSketchLocation+"\nvoid loop();\n#line 62 "+quotedSketchLocation+"\nvoid process(BridgeClient client);\n#line 82 "+quotedSketchLocation+"\nvoid digitalCommand(BridgeClient client);\n#line 109 "+quotedSketchLocation+"\nvoid analogCommand(BridgeClient client);\n#line 149 "+quotedSketchLocation+"\nvoid modeCommand(BridgeClient client);\n#line 33 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithIfDef(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch2", "SketchWithIfDef.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderBaladuino(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch3", "Baladuino.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch3", "Baladuino.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch4", "CharWithEscapedDoubleQuote.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch4", "CharWithEscapedDoubleQuote.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch5", "IncludeBetweenMultilineComment.ino"), - FQBN: "arduino:sam:arduino_due_x_dbg", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch5", "IncludeBetweenMultilineComment.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderLineContinuations(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch6", "/LineContinuations.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch6", "LineContinuations.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderStringWithComment(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch7", "StringWithComment.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch7", "StringWithComment.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithStruct(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch8", "SketchWithStruct.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch8", "SketchWithStruct.preprocessed.txt"), ctx) - obtained := strings.Replace(ctx.Source, "\r\n", "\n", -1) - // ctags based preprocessing removes the space after "dostuff", but this is still OK - // TODO: remove this exception when moving to a more powerful parser - preprocessed = strings.Replace(preprocessed, "void dostuff (A_NEW_TYPE * bar);", "void dostuff(A_NEW_TYPE * bar);", 1) - obtained = strings.Replace(obtained, "void dostuff (A_NEW_TYPE * bar);", "void dostuff(A_NEW_TYPE * bar);", 1) - require.Equal(t, preprocessed, obtained) -} - -func TestPrototypesAdderSketchWithConfig(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_config", "sketch_with_config.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 13 "+quotedSketchLocation+"\nvoid setup();\n#line 17 "+quotedSketchLocation+"\nvoid loop();\n#line 13 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch_with_config", "sketch_with_config.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_no_functions_two_files", "main.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_no_functions_two_files", "main.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchNoFunctions(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_no_functions", "main.ino"), - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - sketchLocation := filepath.Join("sketch_no_functions", "main.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_default_args", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 4 "+quotedSketchLocation+"\nvoid setup();\n#line 7 "+quotedSketchLocation+"\nvoid loop();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_inline_function", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - - expected := "#line 1 " + quotedSketchLocation + "\nvoid setup();\n#line 2 " + quotedSketchLocation + "\nvoid loop();\n#line 4 " + quotedSketchLocation + "\nshort unsigned int testInt();\n#line 8 " + quotedSketchLocation + "\nstatic int8_t testInline();\n#line 12 " + quotedSketchLocation + "\n__attribute__((always_inline)) uint8_t testAttribute();\n#line 1 " + quotedSketchLocation + "\n" - obtained := ctx.PrototypesSection - // ctags based preprocessing removes "inline" but this is still OK - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "static inline int8_t testInline();", "static int8_t testInline();", -1) - obtained = strings.Replace(obtained, "static inline int8_t testInline();", "static int8_t testInline();", -1) - // ctags based preprocessing removes "__attribute__ ....." but this is still OK - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "__attribute__((always_inline)) uint8_t testAttribute();", "uint8_t testAttribute();", -1) - obtained = strings.Replace(obtained, "__attribute__((always_inline)) uint8_t testAttribute();", "uint8_t testAttribute();", -1) - require.Equal(t, expected, obtained) -} - -func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_function_signature_inside_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 1 "+quotedSketchLocation+"\nvoid setup();\n#line 3 "+quotedSketchLocation+"\nvoid loop();\n#line 15 "+quotedSketchLocation+"\nint8_t adalight();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_usbcon", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - OtherLibrariesFolders: []string{"libraries"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 5 "+quotedSketchLocation+"\nvoid ciao();\n#line 10 "+quotedSketchLocation+"\nvoid setup();\n#line 15 "+quotedSketchLocation+"\nvoid loop();\n#line 5 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithTypename(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_typename", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - LibrariesFolders: []string{"libraries", "downloaded_libraries"}, - ToolsFolders: []string{"downloaded_tools"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - expected := "#line 6 " + quotedSketchLocation + "\nvoid setup();\n#line 10 " + quotedSketchLocation + "\nvoid loop();\n#line 12 " + quotedSketchLocation + "\ntypename Foo::Bar func();\n#line 6 " + quotedSketchLocation + "\n" - obtained := ctx.PrototypesSection - // ctags based preprocessing ignores line with typename - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "#line 12 "+quotedSketchLocation+"\ntypename Foo::Bar func();\n", "", -1) - obtained = strings.Replace(obtained, "#line 12 "+quotedSketchLocation+"\ntypename Foo::Bar func();\n", "", -1) - require.Equal(t, expected, obtained) -} - -func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:yun", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 5 "+quotedSketchLocation+"\nvoid elseBranch();\n#line 9 "+quotedSketchLocation+"\nvoid f1();\n#line 10 "+quotedSketchLocation+"\nvoid f2();\n#line 12 "+quotedSketchLocation+"\nvoid setup();\n#line 14 "+quotedSketchLocation+"\nvoid loop();\n#line 5 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - expectedSource := LoadAndInterpolate(t, filepath.Join("sketch_with_ifdef", "sketch.preprocessed.txt"), ctx) - require.Equal(t, expectedSource, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:sam:arduino_due_x_dbg", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 2 "+quotedSketchLocation+"\nvoid ifBranch();\n#line 9 "+quotedSketchLocation+"\nvoid f1();\n#line 10 "+quotedSketchLocation+"\nvoid f2();\n#line 12 "+quotedSketchLocation+"\nvoid setup();\n#line 14 "+quotedSketchLocation+"\nvoid loop();\n#line 2 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - expectedSource := LoadAndInterpolate(t, filepath.Join("sketch_with_ifdef", "sketch.preprocessed.SAM.txt"), ctx) - require.Equal(t, expectedSource, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithConst(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_const", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 1 "+quotedSketchLocation+"\nvoid setup();\n#line 2 "+quotedSketchLocation+"\nvoid loop();\n#line 4 "+quotedSketchLocation+"\nconst __FlashStringHelper* test();\n#line 6 "+quotedSketchLocation+"\nconst int test3();\n#line 8 "+quotedSketchLocation+"\nvolatile __FlashStringHelper* test2();\n#line 10 "+quotedSketchLocation+"\nvolatile int test4();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithDosEol(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("eol_processing", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - // only requires no error as result -} - -func TestPrototypesAdderSketchWithSubstringFunctionMember(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := filepath.Join("sketch_with_class_and_method_substring", "sketch_with_class_and_method_substring.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Contains(t, ctx.Source, "class Foo {\nint blooper(int x) { return x+1; }\n};\n\nFoo foo;\n\n#line 7 "+quotedSketchLocation+"\nvoid setup();") -} diff --git a/test/read_file_and_store_in_context_test.go b/test/read_file_and_store_in_context_test.go deleted file mode 100644 index b33ff47c..00000000 --- a/test/read_file_and_store_in_context_test.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "testing" -) - -func TestReadFileAndStoreInContext(t *testing.T) { - file, err := ioutil.TempFile("", "test") - NoError(t, err) - defer os.RemoveAll(file.Name()) - - utils.WriteFile(file.Name(), "test test\nciao") - - ctx := &types.Context{} - - command := &builder.ReadFileAndStoreInContext{FileToRead: file.Name(), Target: &ctx.SourceGccMinusE} - err = command.Run(ctx) - NoError(t, err) - - require.Equal(t, "test test\nciao", ctx.SourceGccMinusE) -} diff --git a/test/recipe_runner_test.go b/test/recipe_runner_test.go deleted file mode 100644 index 2ebb7a37..00000000 --- a/test/recipe_runner_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" - "github.com/stretchr/testify/require" -) - -// TODO -// I can't find a command I can run on linux, mac and windows -// and that allows to test if the recipe is actually run -// So this test is pretty useless -func TestRecipeRunner(t *testing.T) { - ctx := &types.Context{} - buildProperties := make(properties.Map) - ctx.BuildProperties = buildProperties - - buildProperties["recipe.hooks.prebuild.1.pattern"] = "echo" - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } -} - -func TestRecipesComposition(t *testing.T) { - require.Equal(t, "recipe.hooks.core.postbuild", constants.HOOKS_CORE_POSTBUILD) - require.Equal(t, "recipe.hooks.postbuild", constants.HOOKS_POSTBUILD) - require.Equal(t, "recipe.hooks.linking.prelink", constants.HOOKS_LINKING_PRELINK) - require.Equal(t, "recipe.hooks.objcopy.preobjcopy", constants.HOOKS_OBJCOPY_PREOBJCOPY) -} diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go deleted file mode 100644 index 76829e0f..00000000 --- a/test/rewrite_hardware_keys_test.go +++ /dev/null @@ -1,108 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestRewriteHardwareKeys(t *testing.T) { - ctx := &types.Context{} - - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - aPackage := &types.Package{PackageId: "dummy"} - packages.Packages["dummy"] = aPackage - aPackage.Platforms = make(map[string]*types.Platform) - - platform := &types.Platform{PlatformId: "dummy"} - aPackage.Platforms["dummy"] = platform - platform.Properties = make(map[string]string) - platform.Properties[constants.PLATFORM_NAME] = "A test platform" - platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH] = "{runtime.ide.path}/hardware/tools/avr/bin/" - - ctx.Hardware = packages - - rewrite := types.PlatforKeyRewrite{Key: constants.BUILD_PROPERTIES_COMPILER_PATH, OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} - platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} - ctx.PlatformKeyRewrites = platformKeysRewrite - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH]) -} - -func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { - ctx := &types.Context{} - - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - aPackage := &types.Package{PackageId: "dummy"} - packages.Packages["dummy"] = aPackage - aPackage.Platforms = make(map[string]*types.Platform) - - platform := &types.Platform{PlatformId: "dummy"} - aPackage.Platforms["dummy"] = platform - platform.Properties = make(map[string]string) - platform.Properties[constants.PLATFORM_NAME] = "A test platform" - platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH] = "{runtime.ide.path}/hardware/tools/avr/bin/" - platform.Properties[constants.REWRITING] = constants.REWRITING_DISABLED - - ctx.Hardware = packages - - rewrite := types.PlatforKeyRewrite{Key: constants.BUILD_PROPERTIES_COMPILER_PATH, OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} - platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} - - ctx.PlatformKeyRewrites = platformKeysRewrite - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH]) -} diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go deleted file mode 100644 index c8d39a91..00000000 --- a/test/setup_build_properties_test.go +++ /dev/null @@ -1,237 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" -) - -func TestSetupBuildProperties(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.ToolsLoader{}, - &builder.TargetBoardResolver{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) - - require.Equal(t, "uno", buildProperties[constants.ID]) - require.Equal(t, "Arduino/Genuino Uno", buildProperties["name"]) - require.Equal(t, "0x2341", buildProperties["vid.0"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - - require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) - require.Equal(t, "10600", buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION]) - require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS]) - - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) - require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) - - require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH]) - - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST)) -} - -func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", - - CustomBuildProperties: []string{"name=fake name", "tools.avrdude.config.path=non existent path with space and a ="}, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.ToolsLoader{}, - &builder.TargetBoardResolver{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - &builder.SetCustomBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) - - require.Equal(t, "uno", buildProperties[constants.ID]) - require.Equal(t, "fake name", buildProperties["name"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "non existent path with space and a =", buildProperties["tools.avrdude.config.path"]) -} - -func TestSetupBuildPropertiesUserHardware(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.ToolsLoader{}, - &builder.TargetBoardResolver{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) - - require.Equal(t, "custom_yun", buildProperties[constants.ID]) - require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_FILE]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr")), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform")), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) -} - -func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) - - require.Equal(t, "custom_yun", buildProperties[constants.ID]) - require.Equal(t, "Arduino Yún", buildProperties["name"]) - require.Equal(t, "0x2341", buildProperties["vid.0"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - - require.Equal(t, Abs(t, "user_hardware/my_avr_platform/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, "user_hardware/my_avr_platform"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) - require.Equal(t, "10600", buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION]) - require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS]) - - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) - require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) - - require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH]) - - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST)) -} diff --git a/test/sketch1/doc.txt b/test/sketch1/doc.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/header.h b/test/sketch1/header.h deleted file mode 100644 index 2e24536f..00000000 --- a/test/sketch1/header.h +++ /dev/null @@ -1 +0,0 @@ -#define TRUE FALSE \ No newline at end of file diff --git a/test/sketch1/merged_sketch.txt b/test/sketch1/merged_sketch.txt deleted file mode 100644 index 4654de32..00000000 --- a/test/sketch1/merged_sketch.txt +++ /dev/null @@ -1,16 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - -} -#line 1 {{QuoteCppString (index .sketch.OtherSketchFiles 0).Name}} - -#line 1 {{QuoteCppString (index .sketch.OtherSketchFiles 1).Name}} -String hello() { - return "world"; -} diff --git a/test/sketch1/old.pde b/test/sketch1/old.pde deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/other.ino b/test/sketch1/other.ino deleted file mode 100644 index c426196c..00000000 --- a/test/sketch1/other.ino +++ /dev/null @@ -1,3 +0,0 @@ -String hello() { - return "world"; -} \ No newline at end of file diff --git a/test/sketch1/s_file.S b/test/sketch1/s_file.S deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/sketch.ino b/test/sketch1/sketch.ino deleted file mode 100644 index 0d5e0f5c..00000000 --- a/test/sketch1/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch1/src/helper.h b/test/sketch1/src/helper.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch10/sketch.ino b/test/sketch10/sketch.ino deleted file mode 100644 index 28c88524..00000000 --- a/test/sketch10/sketch.ino +++ /dev/null @@ -1,5 +0,0 @@ -#include -#include - -void setup() {} -void loop() {} diff --git a/test/sketch11/sketch_fastleds.ino b/test/sketch11/sketch_fastleds.ino deleted file mode 100644 index eba4f526..00000000 --- a/test/sketch11/sketch_fastleds.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include "FastLED.h" - -#define DATA_PIN 7 -#define CLK_PIN 6 -#define LED_TYPE APA102 -#define COLOR_ORDER GRB -#define NUM_LEDS 79 -CRGB leds[NUM_LEDS]; - -#define BRIGHTNESS 96 -#define FRAMES_PER_SECOND 120 -void setup() { - - FastLED.addLeds(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); -} - -void loop() { - -} - -typedef void (*SimplePatternList[])(); -//SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm }; -SimplePatternList gPatterns = {sinelon}; - -void sinelon() -{ -} \ No newline at end of file diff --git a/test/sketch12/sketch12.ino b/test/sketch12/sketch12.ino deleted file mode 100644 index ec00136a..00000000 --- a/test/sketch12/sketch12.ino +++ /dev/null @@ -1,16 +0,0 @@ -// See: https://github.com/arduino/arduino-builder/issues/68 - -// The following avoid duplicate definitions of min and max -#undef min -#undef max - -#include - -void setup() { - test(); -} - -void loop() {} - -void test() {} - diff --git a/test/sketch2/SketchWithIfDef.ino b/test/sketch2/SketchWithIfDef.ino deleted file mode 100644 index ddd7f3d4..00000000 --- a/test/sketch2/SketchWithIfDef.ino +++ /dev/null @@ -1,50 +0,0 @@ -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - -#if DISABLED -#include -#endif - -#ifdef DISABLED -#include "empty_1.h" -#endif - -#include "empty_2.h" - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -#if DISABLED -void shouldNotBePrototyped() { - -} -#endif - -#if DEBUG -void debug() { - -} -#endif - -#ifdef UNDEFINED -void undefinedFunction() { -} -#endif - -#ifdef DISABLED -void disabledIsDefined() { -} -#endif - -int useMyType(MyType type) { - -} diff --git a/test/sketch2/SketchWithIfDef.preprocessed.txt b/test/sketch2/SketchWithIfDef.preprocessed.txt deleted file mode 100644 index e0380e17..00000000 --- a/test/sketch2/SketchWithIfDef.preprocessed.txt +++ /dev/null @@ -1,65 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - -#if DISABLED -#include -#endif - -#ifdef DISABLED -#include "empty_1.h" -#endif - -#include "empty_2.h" - -#line 16 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 21 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 33 {{QuoteCppString .sketch.MainFile.Name}} -void debug(); -#line 44 {{QuoteCppString .sketch.MainFile.Name}} -void disabledIsDefined(); -#line 48 {{QuoteCppString .sketch.MainFile.Name}} -int useMyType(MyType type); -#line 16 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -#if DISABLED -void shouldNotBePrototyped() { - -} -#endif - -#if DEBUG -void debug() { - -} -#endif - -#ifdef UNDEFINED -void undefinedFunction() { -} -#endif - -#ifdef DISABLED -void disabledIsDefined() { -} -#endif - -int useMyType(MyType type) { - -} - diff --git a/test/sketch2/SketchWithIfDef.resolved.directives.txt b/test/sketch2/SketchWithIfDef.resolved.directives.txt deleted file mode 100644 index c01a6fe3..00000000 --- a/test/sketch2/SketchWithIfDef.resolved.directives.txt +++ /dev/null @@ -1,55 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - - - - - - -#include "empty_1.h" - - -#include "empty_2.h" - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - - - - - - - - -void debug() { - -} - - - - - - - - -void disabledIsDefined() { -} - - -int useMyType(MyType type) { - -} - - diff --git a/test/sketch2/empty_1.h b/test/sketch2/empty_1.h deleted file mode 100644 index 2741ec6f..00000000 --- a/test/sketch2/empty_1.h +++ /dev/null @@ -1,4 +0,0 @@ -#define world - -void two() { -} \ No newline at end of file diff --git a/test/sketch2/empty_2.h b/test/sketch2/empty_2.h deleted file mode 100644 index 11f2de2c..00000000 --- a/test/sketch2/empty_2.h +++ /dev/null @@ -1,4 +0,0 @@ -#define hello - -void one(MyType arg){ -} \ No newline at end of file diff --git a/test/sketch3/Baladuino.ino b/test/sketch3/Baladuino.ino deleted file mode 100644 index a208fafd..00000000 --- a/test/sketch3/Baladuino.ino +++ /dev/null @@ -1,303 +0,0 @@ -/* - * The code is released under the GNU General Public License. - * Developed by Kristian Lauszus, TKJ Electronics 2013 - * This is the algorithm for the Balanduino balancing robot. - * It can be controlled by either an Android app or a Processing application via Bluetooth. - * The Android app can be found at the following link: https://github.com/TKJElectronics/BalanduinoAndroidApp - * The Processing application can be found here: https://github.com/TKJElectronics/BalanduinoProcessingApp - * It can also be controlled by a PS3, Wii or a Xbox controller - * For details, see: http://balanduino.net/ - */ - -/* Use this to enable and disable the different options */ -#define ENABLE_TOOLS -#define ENABLE_SPP -#define ENABLE_PS3 -#define ENABLE_WII -#define ENABLE_XBOX -#define ENABLE_ADK - -#include "Balanduino.h" -#include // Official Arduino Wire library -#include // Some dongles can have a hub inside - -#ifdef ENABLE_ADK -#include -#endif - -// These are all open source libraries written by Kristian Lauszus, TKJ Electronics -// The USB libraries are located at the following link: https://github.com/felis/USB_Host_Shield_2.0 -#include // Kalman filter library - see: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it/ - -#ifdef ENABLE_XBOX -#include -#endif -#ifdef ENABLE_SPP -#include -#endif -#ifdef ENABLE_PS3 -#include -#endif -#ifdef ENABLE_WII -#include -#endif - -// Create the Kalman library instance -Kalman kalman; // See https://github.com/TKJElectronics/KalmanFilter for source code - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) || defined(ENABLE_XBOX) || defined(ENABLE_ADK) -#define ENABLE_USB -USB Usb; // This will take care of all USB communication -#endif - -#ifdef ENABLE_ADK -// Implementation for the Android Open Accessory Protocol. Simply connect your phone to get redirected to the Play Store -ADK adk(&Usb, "TKJ Electronics", // Manufacturer Name - "Balanduino", // Model Name - "Android App for Balanduino", // Description - user visible string - "0.5.0", // Version of the Android app - "https://play.google.com/store/apps/details?id=com.tkjelectronics.balanduino", // URL - web page to visit if no installed apps support the accessory - "1234"); // Serial Number - this is not used -#endif - -#ifdef ENABLE_XBOX -XBOXRECV Xbox(&Usb); // You have to connect a Xbox wireless receiver to the Arduino to control it with a wireless Xbox controller -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) -USBHub Hub(&Usb); // Some dongles have a hub inside -BTD Btd(&Usb); // This is the main Bluetooth library, it will take care of all the USB and HCI communication with the Bluetooth dongle -#endif - -#ifdef ENABLE_SPP -SPP SerialBT(&Btd, "Balanduino", "0000"); // The SPP (Serial Port Protocol) emulates a virtual Serial port, which is supported by most computers and mobile phones -#endif - -#ifdef ENABLE_PS3 -PS3BT PS3(&Btd); // The PS3 library supports all three official controllers: the Dualshock 3, Navigation and Move controller -#endif - -#ifdef ENABLE_WII -WII Wii(&Btd); // The Wii library can communicate with Wiimotes and the Nunchuck and Motion Plus extension and finally the Wii U Pro Controller -//WII Wii(&Btd,PAIR); // You will have to pair with your Wiimote first by creating the instance like this and the press 1+2 on the Wiimote -// or press sync if you are using a Wii U Pro Controller -// Or you can simply send "CW;" to the robot to start the pairing sequence -// This can also be done using the Android or Processing application -#endif - -void setup() { - /* Initialize UART */ - Serial.begin(115200); - - /* Read the PID values, target angle and other saved values in the EEPROM */ - if (!checkInitializationFlags()) - readEEPROMValues(); // Only read the EEPROM values if they have not been restored - - /* Setup encoders */ - pinMode(leftEncoder1, INPUT); - pinMode(leftEncoder2, INPUT); - pinMode(rightEncoder1, INPUT); - pinMode(rightEncoder2, INPUT); - attachInterrupt(0, leftEncoder, CHANGE); - attachInterrupt(1, rightEncoder, CHANGE); - - /* Enable the motor drivers */ - pinMode(leftEnable, OUTPUT); - pinMode(rightEnable, OUTPUT); - digitalWrite(leftEnable, HIGH); - digitalWrite(rightEnable, HIGH); - - /* Setup motor pins to output */ - sbi(pwmPortDirection, leftPWM); - sbi(leftPortDirection, leftA); - sbi(leftPortDirection, leftB); - sbi(pwmPortDirection, rightPWM); - sbi(rightPortDirection, rightA); - sbi(rightPortDirection, rightB); - - /* Set PWM frequency to 20kHz - see the datasheet http://www.atmel.com/Images/doc8272.pdf page 128-135 */ - // Set up PWM, Phase and Frequency Correct on pin 18 (OC1A) & pin 17 (OC1B) with ICR1 as TOP using Timer1 - TCCR1B = _BV(WGM13) | _BV(CS10); // Set PWM Phase and Frequency Correct with ICR1 as TOP and no prescaling - ICR1 = PWMVALUE; // ICR1 is the TOP value - this is set so the frequency is equal to 20kHz - - /* Enable PWM on pin 18 (OC1A) & pin 17 (OC1B) */ - // Clear OC1A/OC1B on compare match when up-counting - // Set OC1A/OC1B on compare match when downcounting - TCCR1A = _BV(COM1A1) | _BV(COM1B1); - setPWM(leftPWM, 0); // Turn off PWM on both pins - setPWM(rightPWM, 0); - - /* Setup buzzer pin */ - pinMode(buzzer, OUTPUT); - -#ifdef ENABLE_USB - if (Usb.Init() == -1) { // Check if USB Host is working - Serial.print(F("OSC did not start")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } -#endif - - /* Attach onInit function */ - // This is used to set the LEDs according to the voltage level and vibrate the controller to indicate the new connection -#ifdef ENABLE_PS3 - PS3.attachOnInit(onInit); -#endif -#ifdef ENABLE_WII - Wii.attachOnInit(onInit); -#endif -#ifdef ENABLE_XBOX - Xbox.attachOnInit(onInit); -#endif - - /* Setup IMU */ - Wire.begin(); - - while (i2cRead(0x75, i2cBuffer, 1)); - if (i2cBuffer[0] != 0x68) { // Read "WHO_AM_I" register - Serial.print(F("Error reading sensor")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } - - i2cBuffer[0] = 19; // Set the sample rate to 400Hz - 8kHz/(19+1) = 400Hz - i2cBuffer[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling - i2cBuffer[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s - i2cBuffer[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g - while (i2cWrite(0x19, i2cBuffer, 4, false)); // Write to all four registers at once - while (i2cWrite(0x6B, 0x09, true)); // PLL with X axis gyroscope reference, disable temperature sensor and disable sleep mode - - delay(100); // Wait for the sensor to get ready - - /* Set Kalman and gyro starting angle */ - while (i2cRead(0x3D, i2cBuffer, 4)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - kalman.setAngle(accAngle); // Set starting angle - pitch = accAngle; - gyroAngle = accAngle; - - /* Find gyro zero value */ - calibrateGyro(); - - pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN is defined in pins_arduino.h in the hardware add-on - - /* Beep to indicate that it is now ready */ - digitalWrite(buzzer, HIGH); - delay(100); - digitalWrite(buzzer, LOW); - - /* Setup timing */ - kalmanTimer = micros(); - pidTimer = kalmanTimer; - encoderTimer = kalmanTimer; - imuTimer = millis(); - reportTimer = imuTimer; - ledTimer = imuTimer; - blinkTimer = imuTimer; -} - -void loop() { -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Calculate pitch */ - while (i2cRead(0x3D, i2cBuffer, 8)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - gyroX = ((i2cBuffer[6] << 8) | i2cBuffer[7]); - - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - uint32_t timer = micros(); - // This fixes the 0-360 transition problem when the accelerometer angle jumps between 0 and 360 degrees - if ((accAngle < 90 && pitch > 270) || (accAngle > 270 && pitch < 90)) { - kalman.setAngle(accAngle); - pitch = accAngle; - gyroAngle = accAngle; - } else { - gyroRate = ((double)gyroX - gyroXzero) / 131.0; // Convert to deg/s - double dt = (double)(timer - kalmanTimer) / 1000000.0; - gyroAngle += gyroRate * dt; // Gyro angle is only used for debugging - if (gyroAngle < 0 || gyroAngle > 360) - gyroAngle = pitch; // Reset the gyro angle when it has drifted too much - pitch = kalman.getAngle(accAngle, gyroRate, dt); // Calculate the angle using a Kalman filter - } - kalmanTimer = timer; - //Serial.print(accAngle);Serial.print('\t');Serial.print(gyroAngle);Serial.print('\t');Serial.println(pitch); - -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Drive motors */ - timer = micros(); - // If the robot is laying down, it has to be put in a vertical position before it starts balancing - // If it's already balancing it has to be ±45 degrees before it stops trying to balance - if ((layingDown && (pitch < cfg.targetAngle - 10 || pitch > cfg.targetAngle + 10)) || (!layingDown && (pitch < cfg.targetAngle - 45 || pitch > cfg.targetAngle + 45))) { - layingDown = true; // The robot is in a unsolvable position, so turn off both motors and wait until it's vertical again - stopAndReset(); - } else { - layingDown = false; // It's no longer laying down - updatePID(cfg.targetAngle, targetOffset, turningOffset, (double)(timer - pidTimer) / 1000000.0); - } - pidTimer = timer; - - /* Update encoders */ - timer = micros(); - if (timer - encoderTimer >= 100000) { // Update encoder values every 100ms - encoderTimer = timer; - int32_t wheelPosition = getWheelsPosition(); - wheelVelocity = wheelPosition - lastWheelPosition; - lastWheelPosition = wheelPosition; - //Serial.print(wheelPosition);Serial.print('\t');Serial.print(targetPosition);Serial.print('\t');Serial.println(wheelVelocity); - if (abs(wheelVelocity) <= 40 && !stopped) { // Set new targetPosition if braking - targetPosition = wheelPosition; - stopped = true; - } - - batteryCounter++; - if (batteryCounter > 10) { // Measure battery every 1s - batteryCounter = 0; - batteryVoltage = (double)analogRead(VBAT) / 63.050847458; // VBAT is connected to analog input 5 which is not broken out. This is then connected to a 47k-12k voltage divider - 1023.0/(3.3/(12.0/(12.0+47.0))) = 63.050847458 - if (batteryVoltage < 10.2 && batteryVoltage > 5) // Equal to 3.4V per cell - don't turn on if it's below 5V, this means that no battery is connected - digitalWrite(buzzer, HIGH); - else - digitalWrite(buzzer, LOW); - } - } - - /* Read the Bluetooth dongle and send PID and IMU values */ -#ifdef ENABLE_USB - readUsb(); -#endif -#ifdef ENABLE_TOOLS - checkSerialData(); -#endif -#if defined(ENABLE_TOOLS) || defined(ENABLE_SPP) - printValues(); -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) - if (Btd.isReady()) { - timer = millis(); - if ((Btd.watingForConnection && timer - blinkTimer > 1000) || (!Btd.watingForConnection && timer - blinkTimer > 100)) { - blinkTimer = timer; - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // Used to blink the built in LED, starts blinking faster upon an incoming Bluetooth request - } - } else if (ledState) { // The LED is on - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // This will turn it off - } -#endif -} \ No newline at end of file diff --git a/test/sketch3/Baladuino.preprocessed.txt b/test/sketch3/Baladuino.preprocessed.txt deleted file mode 100644 index 989b6b9b..00000000 --- a/test/sketch3/Baladuino.preprocessed.txt +++ /dev/null @@ -1,311 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -/* - * The code is released under the GNU General Public License. - * Developed by Kristian Lauszus, TKJ Electronics 2013 - * This is the algorithm for the Balanduino balancing robot. - * It can be controlled by either an Android app or a Processing application via Bluetooth. - * The Android app can be found at the following link: https://github.com/TKJElectronics/BalanduinoAndroidApp - * The Processing application can be found here: https://github.com/TKJElectronics/BalanduinoProcessingApp - * It can also be controlled by a PS3, Wii or a Xbox controller - * For details, see: http://balanduino.net/ - */ - -/* Use this to enable and disable the different options */ -#define ENABLE_TOOLS -#define ENABLE_SPP -#define ENABLE_PS3 -#define ENABLE_WII -#define ENABLE_XBOX -#define ENABLE_ADK - -#include "Balanduino.h" -#include // Official Arduino Wire library -#include // Some dongles can have a hub inside - -#ifdef ENABLE_ADK -#include -#endif - -// These are all open source libraries written by Kristian Lauszus, TKJ Electronics -// The USB libraries are located at the following link: https://github.com/felis/USB_Host_Shield_2.0 -#include // Kalman filter library - see: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it/ - -#ifdef ENABLE_XBOX -#include -#endif -#ifdef ENABLE_SPP -#include -#endif -#ifdef ENABLE_PS3 -#include -#endif -#ifdef ENABLE_WII -#include -#endif - -// Create the Kalman library instance -Kalman kalman; // See https://github.com/TKJElectronics/KalmanFilter for source code - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) || defined(ENABLE_XBOX) || defined(ENABLE_ADK) -#define ENABLE_USB -USB Usb; // This will take care of all USB communication -#endif - -#ifdef ENABLE_ADK -// Implementation for the Android Open Accessory Protocol. Simply connect your phone to get redirected to the Play Store -ADK adk(&Usb, "TKJ Electronics", // Manufacturer Name - "Balanduino", // Model Name - "Android App for Balanduino", // Description - user visible string - "0.5.0", // Version of the Android app - "https://play.google.com/store/apps/details?id=com.tkjelectronics.balanduino", // URL - web page to visit if no installed apps support the accessory - "1234"); // Serial Number - this is not used -#endif - -#ifdef ENABLE_XBOX -XBOXRECV Xbox(&Usb); // You have to connect a Xbox wireless receiver to the Arduino to control it with a wireless Xbox controller -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) -USBHub Hub(&Usb); // Some dongles have a hub inside -BTD Btd(&Usb); // This is the main Bluetooth library, it will take care of all the USB and HCI communication with the Bluetooth dongle -#endif - -#ifdef ENABLE_SPP -SPP SerialBT(&Btd, "Balanduino", "0000"); // The SPP (Serial Port Protocol) emulates a virtual Serial port, which is supported by most computers and mobile phones -#endif - -#ifdef ENABLE_PS3 -PS3BT PS3(&Btd); // The PS3 library supports all three official controllers: the Dualshock 3, Navigation and Move controller -#endif - -#ifdef ENABLE_WII -WII Wii(&Btd); // The Wii library can communicate with Wiimotes and the Nunchuck and Motion Plus extension and finally the Wii U Pro Controller -//WII Wii(&Btd,PAIR); // You will have to pair with your Wiimote first by creating the instance like this and the press 1+2 on the Wiimote -// or press sync if you are using a Wii U Pro Controller -// Or you can simply send "CW;" to the robot to start the pairing sequence -// This can also be done using the Android or Processing application -#endif - -#line 88 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 204 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 88 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - /* Initialize UART */ - Serial.begin(115200); - - /* Read the PID values, target angle and other saved values in the EEPROM */ - if (!checkInitializationFlags()) - readEEPROMValues(); // Only read the EEPROM values if they have not been restored - - /* Setup encoders */ - pinMode(leftEncoder1, INPUT); - pinMode(leftEncoder2, INPUT); - pinMode(rightEncoder1, INPUT); - pinMode(rightEncoder2, INPUT); - attachInterrupt(0, leftEncoder, CHANGE); - attachInterrupt(1, rightEncoder, CHANGE); - - /* Enable the motor drivers */ - pinMode(leftEnable, OUTPUT); - pinMode(rightEnable, OUTPUT); - digitalWrite(leftEnable, HIGH); - digitalWrite(rightEnable, HIGH); - - /* Setup motor pins to output */ - sbi(pwmPortDirection, leftPWM); - sbi(leftPortDirection, leftA); - sbi(leftPortDirection, leftB); - sbi(pwmPortDirection, rightPWM); - sbi(rightPortDirection, rightA); - sbi(rightPortDirection, rightB); - - /* Set PWM frequency to 20kHz - see the datasheet http://www.atmel.com/Images/doc8272.pdf page 128-135 */ - // Set up PWM, Phase and Frequency Correct on pin 18 (OC1A) & pin 17 (OC1B) with ICR1 as TOP using Timer1 - TCCR1B = _BV(WGM13) | _BV(CS10); // Set PWM Phase and Frequency Correct with ICR1 as TOP and no prescaling - ICR1 = PWMVALUE; // ICR1 is the TOP value - this is set so the frequency is equal to 20kHz - - /* Enable PWM on pin 18 (OC1A) & pin 17 (OC1B) */ - // Clear OC1A/OC1B on compare match when up-counting - // Set OC1A/OC1B on compare match when downcounting - TCCR1A = _BV(COM1A1) | _BV(COM1B1); - setPWM(leftPWM, 0); // Turn off PWM on both pins - setPWM(rightPWM, 0); - - /* Setup buzzer pin */ - pinMode(buzzer, OUTPUT); - -#ifdef ENABLE_USB - if (Usb.Init() == -1) { // Check if USB Host is working - Serial.print(F("OSC did not start")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } -#endif - - /* Attach onInit function */ - // This is used to set the LEDs according to the voltage level and vibrate the controller to indicate the new connection -#ifdef ENABLE_PS3 - PS3.attachOnInit(onInit); -#endif -#ifdef ENABLE_WII - Wii.attachOnInit(onInit); -#endif -#ifdef ENABLE_XBOX - Xbox.attachOnInit(onInit); -#endif - - /* Setup IMU */ - Wire.begin(); - - while (i2cRead(0x75, i2cBuffer, 1)); - if (i2cBuffer[0] != 0x68) { // Read "WHO_AM_I" register - Serial.print(F("Error reading sensor")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } - - i2cBuffer[0] = 19; // Set the sample rate to 400Hz - 8kHz/(19+1) = 400Hz - i2cBuffer[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling - i2cBuffer[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s - i2cBuffer[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g - while (i2cWrite(0x19, i2cBuffer, 4, false)); // Write to all four registers at once - while (i2cWrite(0x6B, 0x09, true)); // PLL with X axis gyroscope reference, disable temperature sensor and disable sleep mode - - delay(100); // Wait for the sensor to get ready - - /* Set Kalman and gyro starting angle */ - while (i2cRead(0x3D, i2cBuffer, 4)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - kalman.setAngle(accAngle); // Set starting angle - pitch = accAngle; - gyroAngle = accAngle; - - /* Find gyro zero value */ - calibrateGyro(); - - pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN is defined in pins_arduino.h in the hardware add-on - - /* Beep to indicate that it is now ready */ - digitalWrite(buzzer, HIGH); - delay(100); - digitalWrite(buzzer, LOW); - - /* Setup timing */ - kalmanTimer = micros(); - pidTimer = kalmanTimer; - encoderTimer = kalmanTimer; - imuTimer = millis(); - reportTimer = imuTimer; - ledTimer = imuTimer; - blinkTimer = imuTimer; -} - -void loop() { -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Calculate pitch */ - while (i2cRead(0x3D, i2cBuffer, 8)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - gyroX = ((i2cBuffer[6] << 8) | i2cBuffer[7]); - - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - uint32_t timer = micros(); - // This fixes the 0-360 transition problem when the accelerometer angle jumps between 0 and 360 degrees - if ((accAngle < 90 && pitch > 270) || (accAngle > 270 && pitch < 90)) { - kalman.setAngle(accAngle); - pitch = accAngle; - gyroAngle = accAngle; - } else { - gyroRate = ((double)gyroX - gyroXzero) / 131.0; // Convert to deg/s - double dt = (double)(timer - kalmanTimer) / 1000000.0; - gyroAngle += gyroRate * dt; // Gyro angle is only used for debugging - if (gyroAngle < 0 || gyroAngle > 360) - gyroAngle = pitch; // Reset the gyro angle when it has drifted too much - pitch = kalman.getAngle(accAngle, gyroRate, dt); // Calculate the angle using a Kalman filter - } - kalmanTimer = timer; - //Serial.print(accAngle);Serial.print('\t');Serial.print(gyroAngle);Serial.print('\t');Serial.println(pitch); - -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Drive motors */ - timer = micros(); - // If the robot is laying down, it has to be put in a vertical position before it starts balancing - // If it's already balancing it has to be ±45 degrees before it stops trying to balance - if ((layingDown && (pitch < cfg.targetAngle - 10 || pitch > cfg.targetAngle + 10)) || (!layingDown && (pitch < cfg.targetAngle - 45 || pitch > cfg.targetAngle + 45))) { - layingDown = true; // The robot is in a unsolvable position, so turn off both motors and wait until it's vertical again - stopAndReset(); - } else { - layingDown = false; // It's no longer laying down - updatePID(cfg.targetAngle, targetOffset, turningOffset, (double)(timer - pidTimer) / 1000000.0); - } - pidTimer = timer; - - /* Update encoders */ - timer = micros(); - if (timer - encoderTimer >= 100000) { // Update encoder values every 100ms - encoderTimer = timer; - int32_t wheelPosition = getWheelsPosition(); - wheelVelocity = wheelPosition - lastWheelPosition; - lastWheelPosition = wheelPosition; - //Serial.print(wheelPosition);Serial.print('\t');Serial.print(targetPosition);Serial.print('\t');Serial.println(wheelVelocity); - if (abs(wheelVelocity) <= 40 && !stopped) { // Set new targetPosition if braking - targetPosition = wheelPosition; - stopped = true; - } - - batteryCounter++; - if (batteryCounter > 10) { // Measure battery every 1s - batteryCounter = 0; - batteryVoltage = (double)analogRead(VBAT) / 63.050847458; // VBAT is connected to analog input 5 which is not broken out. This is then connected to a 47k-12k voltage divider - 1023.0/(3.3/(12.0/(12.0+47.0))) = 63.050847458 - if (batteryVoltage < 10.2 && batteryVoltage > 5) // Equal to 3.4V per cell - don't turn on if it's below 5V, this means that no battery is connected - digitalWrite(buzzer, HIGH); - else - digitalWrite(buzzer, LOW); - } - } - - /* Read the Bluetooth dongle and send PID and IMU values */ -#ifdef ENABLE_USB - readUsb(); -#endif -#ifdef ENABLE_TOOLS - checkSerialData(); -#endif -#if defined(ENABLE_TOOLS) || defined(ENABLE_SPP) - printValues(); -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) - if (Btd.isReady()) { - timer = millis(); - if ((Btd.watingForConnection && timer - blinkTimer > 1000) || (!Btd.watingForConnection && timer - blinkTimer > 100)) { - blinkTimer = timer; - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // Used to blink the built in LED, starts blinking faster upon an incoming Bluetooth request - } - } else if (ledState) { // The LED is on - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // This will turn it off - } -#endif -} diff --git a/test/sketch4/CharWithEscapedDoubleQuote.ino b/test/sketch4/CharWithEscapedDoubleQuote.ino deleted file mode 100644 index 35c1d6ee..00000000 --- a/test/sketch4/CharWithEscapedDoubleQuote.ino +++ /dev/null @@ -1,338 +0,0 @@ -#include // required to send and receive AT commands from the GPRS Shield -#include // required for I2C communication with the RTC - -// pin numbers for RTC -#define DS3231_I2C_ADDRESS 104 // 0x68 // Address for RTC -#define DS3231_TIME_CAL_ADDR 0 // 0x00 -#define DS3231_ALARM1_ADDR 7 // 0x07 -#define DS3231_ALARM2_ADDR 11 // 0x0B -#define DS3231_CONTROL_ADDR 14 // 0x0E -#define DS3231_STATUS_ADDR 15 // 0x0F -//#define DS3231_AGING_OFFSET_ADDR 16 // 0x10 -#define DS3231_TEMPERATURE_ADDR 17 // 0x11 - -// Declarations for GPRS shield -SoftwareSerial GPRS( 7, 8 ); // A softwareSerial line is defined for the GPRS Shield -byte buffer[ 64 ]; // Buffer is used to transfer data from the GPRS line to the serial line -int count = 0, e = 0, count2 = 0, t = 0, q; -char temp, lastCaller[13] = "blank"; -boolean callIncoming = false, done; - -// Declarations for RTC -byte time[ 7 ]; // second, minute, hour, dow, day, month, year -byte time_A1[ 5 ]; // second_A1, minute_A1, hour_A1, day_A1, DY/DT -byte time_A2[ 4 ]; // minute_A2, hour_A2, day_A2, DY/DT -byte received[1]; // used to catch bytes sent from the clock -float temperature; // clock temperature is updated every 64 s - -// Declarations for RemoteCallLogger -char telescopeNames[6][4]; - -/* -Code Exclusively for GPRS shield: -*/ - -// -// Default set of instructions for GPRS Shield power control -// - -void setPowerStateTo( int newState ) -{ - if( newState != 1 && newState != 0 ) { // tests for an invalid state. In this case no change is made to powerstate - Serial.print( "Error: Invalid powerstate. Current powerstate = " ); - Serial.print( getPowerState() ); - Serial.print( "\n" ); - } - else { - if( newState == getPowerState() ) { // if the requested powerstate is already in effect, no action is taken - Serial.print( "Powerstate = " ); - Serial.print( newState ); - Serial.print( " remains unchanged.\n" ); - } - else { - powerUpOrDown(); // This is the only case where the powerstate is changed - Serial.print( "Powerstate changed from " ); - Serial.print( 1 - newState ); - Serial.print( " to " ); - Serial.print( newState ); - Serial.print( "\n" ); - } - } - delay( 5000 ); // for startup -} - -int getPowerState() // returns 0 if GPRS Shield is off, and 1 if GPRS Shield is on. This corresponds to the constant HIGH LOW enumeration -{ - int ret; - if ( digitalRead(18) == 0 && digitalRead(19) == 0 ) // tests pins 18 and 19 for activity. See ExFoundImportantPins sketch to find out why - ret = 1; - else - ret = 0; - - return ret; -} - -void powerUpOrDown() // toggle the power of the shield -{ - pinMode( 9, OUTPUT ); - digitalWrite( 9, LOW ); - delay( 1000 ); - digitalWrite( 9, HIGH ); - delay( 2000 ); - digitalWrite( 9, LOW ); - delay( 3000 ); -} - -// -// End of default power control -// - -void clearBufferArray() // gives each element in the buffer array a null value -{ - for( int i = 0; i < count; i++ ) - buffer[ i ] = NULL; -} - -void makeMissedCall( char num[] ) -{ - int i; - char in[ 18 ] = "ATD"; - for( i = 3; i <= 14; i++ ) // AT command string containing telephone number is prepared - in[ i ] = num[ i - 3] ; - in[ 15 ] = ';'; - in[ 16 ] = '\r'; - in[ 17 ] = '\0'; - GPRS.write( in ); // AT command requesting call is sent - delay( 10000 ); // enough time is given for GSM connection, and at least one ring. - GPRS.write( "ATH\r\0" ); // AT command requesting hangup is sent - delay( 1000 ); -} - -void sendTextMessage( char number[], char messg[] ) -{ - char temp[ 27 ] = "AT + CMGS = \""; - for( q = 0; q < 12; q++ ) // for-loop is used to prepare the AT command string containing the telephone number - temp[ q + 13 ] = number[ q ]; - temp[ 25 ] = '\"'; - temp[ 26 ] = '\0'; - - GPRS.println( "AT+CMGF=1\r" ); // AT command requesting SMS in text mode is sent - delay( 1000 ); - GPRS.println( temp ); // AT command containing telephone number is sent - delay( 1000 ); - GPRS.println( messg ); //the content of the message - delay( 1000 ); - GPRS.println( (char) 26 ); //the ASCII code of the ctrl+z is 26. This character indicates the end of the message. - delay( 1000 ); -} - -void analise(byte incoming[], int length) // this function receives and analyses all text sent from the GPRS Shield to the serial line. It stores the cell number of the last caller. -{ - e = 0; // Counter that represents a letter in the buffer - done = false; // Boolean that prevents unneccessary loop revolutions - while( e < length && !done){ // while e does not surpass the last letter index of the buffer... - temp = char( incoming[e] ); // store the character at index e in a temporary char - switch( temp ){ // inspect temp - case 'R': - { - if( length > e + 3 && !callIncoming ) { // This case responds to "RING" - if(char( incoming[e + 1] ) == 'I' - && char( incoming[e + 2] ) == 'N' - && char( incoming[e + 3] ) == 'G'){ - GPRS.write("AT+CLCC\r"); // call information is requested - delay(500); // time is given for processing - GPRS.write("ATH\r"); // GPRS shield hangs up - callIncoming = true; // this ensures that a number cannot be stored in any other case than a missed call - done = true; // prevents the further operation of this while loop - } - } - } - break; - case '+': - { - if(char( buffer[ e + 1]) == '2' && length > e + 11 && callIncoming){ // this case responds to "+2", but only if the buffer contains enough characters for a valid cell number - for(t = 0; t < 12; t++) // and only if the callIncoming boolean had been triggered by a previous instance of this function - lastCaller[t] = char( buffer[ e + t ]); // the number of this caller is stored in lastCaller - lastCaller[12] = '\0'; - callIncoming = false; // now we are ready for the next call - done = true; // prevents the further operation of this while loop - } - } - break; - case 'l': - Serial.println(lastCaller); // an easy way to test this function. Simply type "l" to see the value of lastCaller (default "blank") - break; - } - e++; // buffer index is incremented - } -} - -/* -End of GPRS Shield code -*/ - - -/* -Code exclusively for RTC -*/ - -byte decToBcd( byte b ) // converts a byte from a decimal format to a binary-coded decimal -{ - return ( b / 10 << 4 ) + b % 10; -} - -boolean getBit( byte addr, int pos ) // returns a single bit from a determined location in the RTC register -{ - byte temp = getByte( addr ); - return boolean( (temp >> pos) & B00000001 ); -} - -void setBit( byte addr, int pos, boolean newBit ) // ensures that a single bit from a determined location in the RTC register is a determined value -{ - boolean oldBit = getBit( addr, pos ); // bits' current state is retrieved - byte temp = received[ 0 ]; // complete byte is retrieved. it is still left in received from the previous command - if ( oldBit != newBit ) // change is only made if the bit isnt already the correct value - { - if( newBit ) // if newBit is 1, then old bit must be 0, thus we must add an amount - temp += (B00000001 << pos); // 2 to the power of the bit position is added to the byte - else - temp -= (B00000001 << pos); // 2 to the power of the bit position is subtracted from the byte - } - setByte( addr, temp ); // the register is updated with the new byte -} - -byte getByte( byte addr ) // returns a single byte from the given address in the RTC register -{ - byte temp; - if( getBytes( addr, 1) ) // If one byte was read from the address: - temp = received[ 0 ]; // get that byte - else temp = -1; // -1 is returned as an error - return temp; -} - -boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address -{ // ^ returns false if reading failed - boolean wireWorked = false; - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to read from the given address - Wire.endTransmission(); // We want to receive, so we stop transmitting - Wire.requestFrom( DS3231_I2C_ADDRESS, amount ); // we request the given amount of bytes from the RTC - if( Wire.available() ){ - received[amount]; // prepare the array for the amount of incoming bytes - for( int i = 0; i < amount; i++){ - received[ i ] = Wire.read(); // we read the given amount of bytes - } - wireWorked = true; // everything went as planned - } - return wireWorked; -} - -void setByte( byte addr, byte newByte ) // writes a given byte to a given address in the RTCs register. convenient -{ - setBytes( addr, &newByte, 1); // call the setBytes function with the default amount = 1 -} - -void setBytes( byte addr, byte newBytes[], int amount ) // writes a given amount of bytes in a sequence starting from a given address -{ - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to start writing from the given address - for( int i = 0; i < amount; i++ ) - Wire.write( newBytes[ i ] ); // we write each byte in sequence - Wire.endTransmission(); // we're done here -} - -void getTime() // reads the current time from the register and updates the byte array containing the current time -{ - if( getBytes( DS3231_TIME_CAL_ADDR, 7) ) // if 7 bytes were read in from the time address: - { - for(int i = 0; i < 7; i++) // place each byte in it's place - time[ i ] = received[ i ]; - // The following conversions convert the values from binary-coded decimal format to regular binary: - time[ 0 ] = ( ( time[ 0 ] & B01110000 ) >> 4 ) * 10 + ( time[ 0 ] & B00001111 ); // second - time[ 1 ] = ( ( time[ 1 ] & B01110000 ) >> 4 ) * 10 + ( time[ 1 ] & B00001111 ); // minute - time[ 2 ] = ( ( time[ 2 ] & B00110000 ) >> 4 ) * 10 + ( time[ 2 ] & B00001111 ); // hour - time[ 4 ] = ( ( time[ 4 ] & B00110000 ) >> 4 ) * 10 + ( time[ 4 ] & B00001111 ); // day of month - time[ 5 ] = ( ( time[ 5 ] & B00010000 ) >> 4 ) * 10 + ( time[ 5 ] & B00001111 ); // month - time[ 6 ] = ( ( time[ 6 ] & B11110000 ) >> 4 ) * 10 + ( time[ 6 ] & B00001111 ); // year - } -} - -void setTime( byte newTime[ 7 ] ) // sets the time in the RTC register to the given values -{ - for(int i = 0; i < 7; i++) - newTime[i] = decToBcd(newTime[i]); // the time consists of 7 bytes, each which must be converted to binary-coded decimal - setBytes( DS3231_TIME_CAL_ADDR, newTime, 7 ); // bytes are sent to be written -} - -void getRTCTemperature() // reads the temperature from the register and updates the global temperature float -{ - //temp registers (11h-12h) get updated automatically every 64s - if( getBytes( DS3231_TEMPERATURE_ADDR, 2 ) ) // if 2 bytes were read from the temperature addresss - { - temperature = ( received[ 0 ] & B01111111 ); // assign the integer part of the integer - temperature += ( ( received[ 1 ] >> 6 ) * 0.25 ); // assign the fractional part of the temperature - } -} - -void gprsListen() -{ - if( GPRS.available() ) { // If the GPRS Shield is transmitting data to the Stalker... - while( GPRS.available() ) { // While there is still data left... - buffer[ count++ ] = GPRS.read(); // get the next byte of data - if ( count == 64 ) // we only handle a maximum of 64 bytes of data at a time - break; - } - Serial.write( buffer, count ); // Send the data to the serial line - analise( buffer, count ); - clearBufferArray(); // clear the buffer - count = 0; // reset counter - } - if (Serial.available()) // if the Stalker is transmitting data.... - GPRS.write(Serial.read()); // send the data to the GPRS Shield. -} - -void printTime() // updates time, and prints it in a convenient format -{ - getTime(); - Serial.print( int( time[ 3 ] ) ); // dow - Serial.print( ' ' ); - Serial.print( int( time[ 2 ] ) ); // hour - Serial.print( ':' ); - Serial.print( int( time[ 1 ] ) ); // minute - Serial.print( ':' ); - Serial.print( int( time[ 0 ] ) ); // second - Serial.print( ' ' ); - Serial.print( int( time[ 4 ] ) ); // day - Serial.print( '/' ); - Serial.print( int( time[ 5 ] ) ); // month - Serial.print( "/20" ); - Serial.print( int( time[ 6 ] ) ); // year - Serial.println(); -} - -/* -End of RTC code -*/ - -void setup() -{ - // GPRS Shield startup code - GPRS.begin( 9600 ); - delay(1000); - setPowerStateTo(1); - delay(1000); - - // RTC Startup code - Wire.begin(); - delay(1000); - - Serial.begin(9600); - delay(1000); - -} - -void loop() -{ - gprsListen(); // GPRS Shield listener. Todo: replace w interrupt - getTime(); // Updates the time. Todo: replace w interrupt -} diff --git a/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt b/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt deleted file mode 100644 index 62fa1ac6..00000000 --- a/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt +++ /dev/null @@ -1,385 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include // required to send and receive AT commands from the GPRS Shield -#include // required for I2C communication with the RTC - -// pin numbers for RTC -#define DS3231_I2C_ADDRESS 104 // 0x68 // Address for RTC -#define DS3231_TIME_CAL_ADDR 0 // 0x00 -#define DS3231_ALARM1_ADDR 7 // 0x07 -#define DS3231_ALARM2_ADDR 11 // 0x0B -#define DS3231_CONTROL_ADDR 14 // 0x0E -#define DS3231_STATUS_ADDR 15 // 0x0F -//#define DS3231_AGING_OFFSET_ADDR 16 // 0x10 -#define DS3231_TEMPERATURE_ADDR 17 // 0x11 - -// Declarations for GPRS shield -SoftwareSerial GPRS( 7, 8 ); // A softwareSerial line is defined for the GPRS Shield -byte buffer[ 64 ]; // Buffer is used to transfer data from the GPRS line to the serial line -int count = 0, e = 0, count2 = 0, t = 0, q; -char temp, lastCaller[13] = "blank"; -boolean callIncoming = false, done; - -// Declarations for RTC -byte time[ 7 ]; // second, minute, hour, dow, day, month, year -byte time_A1[ 5 ]; // second_A1, minute_A1, hour_A1, day_A1, DY/DT -byte time_A2[ 4 ]; // minute_A2, hour_A2, day_A2, DY/DT -byte received[1]; // used to catch bytes sent from the clock -float temperature; // clock temperature is updated every 64 s - -// Declarations for RemoteCallLogger -char telescopeNames[6][4]; - -/* -Code Exclusively for GPRS shield: -*/ - -// -// Default set of instructions for GPRS Shield power control -// - -#line 39 {{QuoteCppString .sketch.MainFile.Name}} -void setPowerStateTo( int newState ); -#line 64 {{QuoteCppString .sketch.MainFile.Name}} -int getPowerState(); -#line 75 {{QuoteCppString .sketch.MainFile.Name}} -void powerUpOrDown(); -#line 90 {{QuoteCppString .sketch.MainFile.Name}} -void clearBufferArray(); -#line 96 {{QuoteCppString .sketch.MainFile.Name}} -void makeMissedCall( char num[] ); -#line 111 {{QuoteCppString .sketch.MainFile.Name}} -void sendTextMessage( char number[], char messg[] ); -#line 129 {{QuoteCppString .sketch.MainFile.Name}} -void analise(byte incoming[], int length); -#line 179 {{QuoteCppString .sketch.MainFile.Name}} -byte decToBcd( byte b ); -#line 184 {{QuoteCppString .sketch.MainFile.Name}} -boolean getBit( byte addr, int pos ); -#line 190 {{QuoteCppString .sketch.MainFile.Name}} -void setBit( byte addr, int pos, boolean newBit ); -#line 204 {{QuoteCppString .sketch.MainFile.Name}} -byte getByte( byte addr ); -#line 213 {{QuoteCppString .sketch.MainFile.Name}} -boolean getBytes( byte addr, int amount ); -#line 230 {{QuoteCppString .sketch.MainFile.Name}} -void setByte( byte addr, byte newByte ); -#line 235 {{QuoteCppString .sketch.MainFile.Name}} -void setBytes( byte addr, byte newBytes[], int amount ); -#line 244 {{QuoteCppString .sketch.MainFile.Name}} -void getTime(); -#line 260 {{QuoteCppString .sketch.MainFile.Name}} -void setTime( byte newTime[ 7 ] ); -#line 267 {{QuoteCppString .sketch.MainFile.Name}} -void getRTCTemperature(); -#line 277 {{QuoteCppString .sketch.MainFile.Name}} -void gprsListen(); -#line 294 {{QuoteCppString .sketch.MainFile.Name}} -void printTime(); -#line 317 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 334 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 39 {{QuoteCppString .sketch.MainFile.Name}} -void setPowerStateTo( int newState ) -{ - if( newState != 1 && newState != 0 ) { // tests for an invalid state. In this case no change is made to powerstate - Serial.print( "Error: Invalid powerstate. Current powerstate = " ); - Serial.print( getPowerState() ); - Serial.print( "\n" ); - } - else { - if( newState == getPowerState() ) { // if the requested powerstate is already in effect, no action is taken - Serial.print( "Powerstate = " ); - Serial.print( newState ); - Serial.print( " remains unchanged.\n" ); - } - else { - powerUpOrDown(); // This is the only case where the powerstate is changed - Serial.print( "Powerstate changed from " ); - Serial.print( 1 - newState ); - Serial.print( " to " ); - Serial.print( newState ); - Serial.print( "\n" ); - } - } - delay( 5000 ); // for startup -} - -int getPowerState() // returns 0 if GPRS Shield is off, and 1 if GPRS Shield is on. This corresponds to the constant HIGH LOW enumeration -{ - int ret; - if ( digitalRead(18) == 0 && digitalRead(19) == 0 ) // tests pins 18 and 19 for activity. See ExFoundImportantPins sketch to find out why - ret = 1; - else - ret = 0; - - return ret; -} - -void powerUpOrDown() // toggle the power of the shield -{ - pinMode( 9, OUTPUT ); - digitalWrite( 9, LOW ); - delay( 1000 ); - digitalWrite( 9, HIGH ); - delay( 2000 ); - digitalWrite( 9, LOW ); - delay( 3000 ); -} - -// -// End of default power control -// - -void clearBufferArray() // gives each element in the buffer array a null value -{ - for( int i = 0; i < count; i++ ) - buffer[ i ] = NULL; -} - -void makeMissedCall( char num[] ) -{ - int i; - char in[ 18 ] = "ATD"; - for( i = 3; i <= 14; i++ ) // AT command string containing telephone number is prepared - in[ i ] = num[ i - 3] ; - in[ 15 ] = ';'; - in[ 16 ] = '\r'; - in[ 17 ] = '\0'; - GPRS.write( in ); // AT command requesting call is sent - delay( 10000 ); // enough time is given for GSM connection, and at least one ring. - GPRS.write( "ATH\r\0" ); // AT command requesting hangup is sent - delay( 1000 ); -} - -void sendTextMessage( char number[], char messg[] ) -{ - char temp[ 27 ] = "AT + CMGS = \""; - for( q = 0; q < 12; q++ ) // for-loop is used to prepare the AT command string containing the telephone number - temp[ q + 13 ] = number[ q ]; - temp[ 25 ] = '\"'; - temp[ 26 ] = '\0'; - - GPRS.println( "AT+CMGF=1\r" ); // AT command requesting SMS in text mode is sent - delay( 1000 ); - GPRS.println( temp ); // AT command containing telephone number is sent - delay( 1000 ); - GPRS.println( messg ); //the content of the message - delay( 1000 ); - GPRS.println( (char) 26 ); //the ASCII code of the ctrl+z is 26. This character indicates the end of the message. - delay( 1000 ); -} - -void analise(byte incoming[], int length) // this function receives and analyses all text sent from the GPRS Shield to the serial line. It stores the cell number of the last caller. -{ - e = 0; // Counter that represents a letter in the buffer - done = false; // Boolean that prevents unneccessary loop revolutions - while( e < length && !done){ // while e does not surpass the last letter index of the buffer... - temp = char( incoming[e] ); // store the character at index e in a temporary char - switch( temp ){ // inspect temp - case 'R': - { - if( length > e + 3 && !callIncoming ) { // This case responds to "RING" - if(char( incoming[e + 1] ) == 'I' - && char( incoming[e + 2] ) == 'N' - && char( incoming[e + 3] ) == 'G'){ - GPRS.write("AT+CLCC\r"); // call information is requested - delay(500); // time is given for processing - GPRS.write("ATH\r"); // GPRS shield hangs up - callIncoming = true; // this ensures that a number cannot be stored in any other case than a missed call - done = true; // prevents the further operation of this while loop - } - } - } - break; - case '+': - { - if(char( buffer[ e + 1]) == '2' && length > e + 11 && callIncoming){ // this case responds to "+2", but only if the buffer contains enough characters for a valid cell number - for(t = 0; t < 12; t++) // and only if the callIncoming boolean had been triggered by a previous instance of this function - lastCaller[t] = char( buffer[ e + t ]); // the number of this caller is stored in lastCaller - lastCaller[12] = '\0'; - callIncoming = false; // now we are ready for the next call - done = true; // prevents the further operation of this while loop - } - } - break; - case 'l': - Serial.println(lastCaller); // an easy way to test this function. Simply type "l" to see the value of lastCaller (default "blank") - break; - } - e++; // buffer index is incremented - } -} - -/* -End of GPRS Shield code -*/ - - -/* -Code exclusively for RTC -*/ - -byte decToBcd( byte b ) // converts a byte from a decimal format to a binary-coded decimal -{ - return ( b / 10 << 4 ) + b % 10; -} - -boolean getBit( byte addr, int pos ) // returns a single bit from a determined location in the RTC register -{ - byte temp = getByte( addr ); - return boolean( (temp >> pos) & B00000001 ); -} - -void setBit( byte addr, int pos, boolean newBit ) // ensures that a single bit from a determined location in the RTC register is a determined value -{ - boolean oldBit = getBit( addr, pos ); // bits' current state is retrieved - byte temp = received[ 0 ]; // complete byte is retrieved. it is still left in received from the previous command - if ( oldBit != newBit ) // change is only made if the bit isnt already the correct value - { - if( newBit ) // if newBit is 1, then old bit must be 0, thus we must add an amount - temp += (B00000001 << pos); // 2 to the power of the bit position is added to the byte - else - temp -= (B00000001 << pos); // 2 to the power of the bit position is subtracted from the byte - } - setByte( addr, temp ); // the register is updated with the new byte -} - -byte getByte( byte addr ) // returns a single byte from the given address in the RTC register -{ - byte temp; - if( getBytes( addr, 1) ) // If one byte was read from the address: - temp = received[ 0 ]; // get that byte - else temp = -1; // -1 is returned as an error - return temp; -} - -boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address -{ // ^ returns false if reading failed - boolean wireWorked = false; - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to read from the given address - Wire.endTransmission(); // We want to receive, so we stop transmitting - Wire.requestFrom( DS3231_I2C_ADDRESS, amount ); // we request the given amount of bytes from the RTC - if( Wire.available() ){ - received[amount]; // prepare the array for the amount of incoming bytes - for( int i = 0; i < amount; i++){ - received[ i ] = Wire.read(); // we read the given amount of bytes - } - wireWorked = true; // everything went as planned - } - return wireWorked; -} - -void setByte( byte addr, byte newByte ) // writes a given byte to a given address in the RTCs register. convenient -{ - setBytes( addr, &newByte, 1); // call the setBytes function with the default amount = 1 -} - -void setBytes( byte addr, byte newBytes[], int amount ) // writes a given amount of bytes in a sequence starting from a given address -{ - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to start writing from the given address - for( int i = 0; i < amount; i++ ) - Wire.write( newBytes[ i ] ); // we write each byte in sequence - Wire.endTransmission(); // we're done here -} - -void getTime() // reads the current time from the register and updates the byte array containing the current time -{ - if( getBytes( DS3231_TIME_CAL_ADDR, 7) ) // if 7 bytes were read in from the time address: - { - for(int i = 0; i < 7; i++) // place each byte in it's place - time[ i ] = received[ i ]; - // The following conversions convert the values from binary-coded decimal format to regular binary: - time[ 0 ] = ( ( time[ 0 ] & B01110000 ) >> 4 ) * 10 + ( time[ 0 ] & B00001111 ); // second - time[ 1 ] = ( ( time[ 1 ] & B01110000 ) >> 4 ) * 10 + ( time[ 1 ] & B00001111 ); // minute - time[ 2 ] = ( ( time[ 2 ] & B00110000 ) >> 4 ) * 10 + ( time[ 2 ] & B00001111 ); // hour - time[ 4 ] = ( ( time[ 4 ] & B00110000 ) >> 4 ) * 10 + ( time[ 4 ] & B00001111 ); // day of month - time[ 5 ] = ( ( time[ 5 ] & B00010000 ) >> 4 ) * 10 + ( time[ 5 ] & B00001111 ); // month - time[ 6 ] = ( ( time[ 6 ] & B11110000 ) >> 4 ) * 10 + ( time[ 6 ] & B00001111 ); // year - } -} - -void setTime( byte newTime[ 7 ] ) // sets the time in the RTC register to the given values -{ - for(int i = 0; i < 7; i++) - newTime[i] = decToBcd(newTime[i]); // the time consists of 7 bytes, each which must be converted to binary-coded decimal - setBytes( DS3231_TIME_CAL_ADDR, newTime, 7 ); // bytes are sent to be written -} - -void getRTCTemperature() // reads the temperature from the register and updates the global temperature float -{ - //temp registers (11h-12h) get updated automatically every 64s - if( getBytes( DS3231_TEMPERATURE_ADDR, 2 ) ) // if 2 bytes were read from the temperature addresss - { - temperature = ( received[ 0 ] & B01111111 ); // assign the integer part of the integer - temperature += ( ( received[ 1 ] >> 6 ) * 0.25 ); // assign the fractional part of the temperature - } -} - -void gprsListen() -{ - if( GPRS.available() ) { // If the GPRS Shield is transmitting data to the Stalker... - while( GPRS.available() ) { // While there is still data left... - buffer[ count++ ] = GPRS.read(); // get the next byte of data - if ( count == 64 ) // we only handle a maximum of 64 bytes of data at a time - break; - } - Serial.write( buffer, count ); // Send the data to the serial line - analise( buffer, count ); - clearBufferArray(); // clear the buffer - count = 0; // reset counter - } - if (Serial.available()) // if the Stalker is transmitting data.... - GPRS.write(Serial.read()); // send the data to the GPRS Shield. -} - -void printTime() // updates time, and prints it in a convenient format -{ - getTime(); - Serial.print( int( time[ 3 ] ) ); // dow - Serial.print( ' ' ); - Serial.print( int( time[ 2 ] ) ); // hour - Serial.print( ':' ); - Serial.print( int( time[ 1 ] ) ); // minute - Serial.print( ':' ); - Serial.print( int( time[ 0 ] ) ); // second - Serial.print( ' ' ); - Serial.print( int( time[ 4 ] ) ); // day - Serial.print( '/' ); - Serial.print( int( time[ 5 ] ) ); // month - Serial.print( "/20" ); - Serial.print( int( time[ 6 ] ) ); // year - Serial.println(); -} - -/* -End of RTC code -*/ - -void setup() -{ - // GPRS Shield startup code - GPRS.begin( 9600 ); - delay(1000); - setPowerStateTo(1); - delay(1000); - - // RTC Startup code - Wire.begin(); - delay(1000); - - Serial.begin(9600); - delay(1000); - -} - -void loop() -{ - gprsListen(); // GPRS Shield listener. Todo: replace w interrupt - getTime(); // Updates the time. Todo: replace w interrupt -} - diff --git a/test/sketch5/IncludeBetweenMultilineComment.ino b/test/sketch5/IncludeBetweenMultilineComment.ino deleted file mode 100644 index 65909275..00000000 --- a/test/sketch5/IncludeBetweenMultilineComment.ino +++ /dev/null @@ -1,15 +0,0 @@ -#include -/* -#include -*/ -CapacitiveSensor cs_13_8 = CapacitiveSensor(13,8); -void setup() -{ - Serial.begin(9600); -} -void loop() -{ - long total1 = cs_13_8.capacitiveSensor(30); - Serial.println(total1); - delay(100); -} diff --git a/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt b/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt deleted file mode 100644 index a19528dc..00000000 --- a/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt +++ /dev/null @@ -1,24 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include -/* -#include -*/ -CapacitiveSensor cs_13_8 = CapacitiveSensor(13,8); -#line 6 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 6 {{QuoteCppString .sketch.MainFile.Name}} -void setup() -{ - Serial.begin(9600); -} -void loop() -{ - long total1 = cs_13_8.capacitiveSensor(30); - Serial.println(total1); - delay(100); -} - diff --git a/test/sketch6/LineContinuations.ino b/test/sketch6/LineContinuations.ino deleted file mode 100644 index 8611603e..00000000 --- a/test/sketch6/LineContinuations.ino +++ /dev/null @@ -1,34 +0,0 @@ -const char *foo = "\ -hello \ -world\n"; - -//" delete this comment line and the IDE parser will crash - -void setup() -{ -} - -void loop() -{ -} -/* -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -*/ diff --git a/test/sketch6/LineContinuations.preprocessed.txt b/test/sketch6/LineContinuations.preprocessed.txt deleted file mode 100644 index 1d584583..00000000 --- a/test/sketch6/LineContinuations.preprocessed.txt +++ /dev/null @@ -1,43 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -const char *foo = "\ -hello \ -world\n"; - -//" delete this comment line and the IDE parser will crash - -#line 7 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 11 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 7 {{QuoteCppString .sketch.MainFile.Name}} -void setup() -{ -} - -void loop() -{ -} -/* -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -*/ - diff --git a/test/sketch7/StringWithComment.ino b/test/sketch7/StringWithComment.ino deleted file mode 100644 index 88b94e1d..00000000 --- a/test/sketch7/StringWithComment.ino +++ /dev/null @@ -1,13 +0,0 @@ -void setup() { - // put your setup code here, to run once: - // "comment with a double quote - /* \" other comment with double quote */ - Serial.println("Accept: */*"); - Serial.println("Accept: \" */*"); - Serial.println("Accept: \\"); // */*"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} \ No newline at end of file diff --git a/test/sketch7/StringWithComment.preprocessed.txt b/test/sketch7/StringWithComment.preprocessed.txt deleted file mode 100644 index f4432fcd..00000000 --- a/test/sketch7/StringWithComment.preprocessed.txt +++ /dev/null @@ -1,21 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - // put your setup code here, to run once: - // "comment with a double quote - /* \" other comment with double quote */ - Serial.println("Accept: */*"); - Serial.println("Accept: \" */*"); - Serial.println("Accept: \\"); // */*"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/test/sketch8/SketchWithStruct.ino b/test/sketch8/SketchWithStruct.ino deleted file mode 100644 index 05f277da..00000000 --- a/test/sketch8/SketchWithStruct.ino +++ /dev/null @@ -1,22 +0,0 @@ -/* START CODE */ - -struct A_NEW_TYPE { - int a = 10; - int b; - int c; -} foo; - -void setup() { - -} - -void loop() { - dostuff(&foo); -} - -void dostuff (A_NEW_TYPE * bar) -{ - Serial.print("bar.a: "); - Serial.print(bar->a); -} -/* END CODE */ \ No newline at end of file diff --git a/test/sketch8/SketchWithStruct.preprocessed.txt b/test/sketch8/SketchWithStruct.preprocessed.txt deleted file mode 100644 index 35302e16..00000000 --- a/test/sketch8/SketchWithStruct.preprocessed.txt +++ /dev/null @@ -1,32 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -/* START CODE */ - -struct A_NEW_TYPE { - int a = 10; - int b; - int c; -} foo; - -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 17 {{QuoteCppString .sketch.MainFile.Name}} -void dostuff (A_NEW_TYPE * bar); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - dostuff(&foo); -} - -void dostuff (A_NEW_TYPE * bar) -{ - Serial.print("bar.a: "); - Serial.print(bar->a); -} -/* END CODE */ diff --git a/test/sketch9/sketch.ino b/test/sketch9/sketch.ino deleted file mode 100644 index 105b1014..00000000 --- a/test/sketch9/sketch.ino +++ /dev/null @@ -1,6 +0,0 @@ -#include -#include -#include - -void setup() {} -void loop() {} \ No newline at end of file diff --git a/test/sketch_class_function/sketch_class_function.ino b/test/sketch_class_function/sketch_class_function.ino deleted file mode 100644 index 45250090..00000000 --- a/test/sketch_class_function/sketch_class_function.ino +++ /dev/null @@ -1,8 +0,0 @@ -class test { - void asdf() {} -}; -void setup() { - asdf(); -} -void loop() {} -void asdf() {} \ No newline at end of file diff --git a/test/sketch_loader_test.go b/test/sketch_loader_test.go deleted file mode 100644 index b524457c..00000000 --- a/test/sketch_loader_test.go +++ /dev/null @@ -1,177 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func TestLoadSketchWithFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "sketch1", - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketchNonExistentPath(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "asdasd78128123981723981273asdasd", - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketch(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name, "sketch.ino") - - require.Equal(t, 2, len(sketch.OtherSketchFiles)) - require.Contains(t, sketch.OtherSketchFiles[0].Name, "old.pde") - require.Contains(t, sketch.OtherSketchFiles[1].Name, "other.ino") - - require.Equal(t, 3, len(sketch.AdditionalFiles)) - require.Contains(t, sketch.AdditionalFiles[0].Name, "header.h") - require.Contains(t, sketch.AdditionalFiles[1].Name, "s_file.S") - require.Contains(t, sketch.AdditionalFiles[2].Name, "helper.h") -} - -func TestFailToLoadSketchFromFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "./sketch1", - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketchFromFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: "sketch_with_subfolders", - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name, "sketch_with_subfolders.ino") - - require.Equal(t, 0, len(sketch.OtherSketchFiles)) - - require.Equal(t, 4, len(sketch.AdditionalFiles)) - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[0].Name), "sketch_with_subfolders/src/subfolder/other.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[1].Name), "sketch_with_subfolders/src/subfolder/other.h") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[2].Name), "sketch_with_subfolders/subfolder/dont_load_me.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[3].Name), "sketch_with_subfolders/subfolder/other.h") -} - -func TestLoadSketchWithBackup(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch_with_backup_files", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name, "sketch.ino") - - require.Equal(t, 0, len(sketch.AdditionalFiles)) - require.Equal(t, 0, len(sketch.OtherSketchFiles)) -} - -func TestLoadSketchWithMacOSXGarbage(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch_with_macosx_garbage", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name, "sketch.ino") - - require.Equal(t, 0, len(sketch.AdditionalFiles)) - require.Equal(t, 0, len(sketch.OtherSketchFiles)) -} diff --git a/test/sketch_no_functions/main.ino b/test/sketch_no_functions/main.ino deleted file mode 100644 index b11f61cc..00000000 --- a/test/sketch_no_functions/main.ino +++ /dev/null @@ -1,8 +0,0 @@ -/* - -Test sketch - - - -*/ - diff --git a/test/sketch_no_functions_two_files/main.ino b/test/sketch_no_functions_two_files/main.ino deleted file mode 100644 index b11f61cc..00000000 --- a/test/sketch_no_functions_two_files/main.ino +++ /dev/null @@ -1,8 +0,0 @@ -/* - -Test sketch - - - -*/ - diff --git a/test/sketch_no_functions_two_files/partb.ino b/test/sketch_no_functions_two_files/partb.ino deleted file mode 100644 index 0e272748..00000000 --- a/test/sketch_no_functions_two_files/partb.ino +++ /dev/null @@ -1,4 +0,0 @@ -#include - -int a = 0; -int b = 0; \ No newline at end of file diff --git a/test/sketch_source_merger_test.go b/test/sketch_source_merger_test.go deleted file mode 100644 index 8708db7b..00000000 --- a/test/sketch_source_merger_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "path/filepath" - "strings" - "testing" -) - -func TestMergeSketch(t *testing.T) { - ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - &builder.SketchSourceMerger{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - source := ctx.Source - - expected_source := LoadAndInterpolate(t, filepath.Join("sketch1", "merged_sketch.txt"), ctx) - require.Equal(t, expected_source, strings.Replace(source, "\r\n", "\n", -1)) -} diff --git a/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino b/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino deleted file mode 100644 index 106c39f2..00000000 --- a/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -#include - -#if !defined(SPI_HAS_TRANSACTION) || !SPI_HAS_TRANSACTION -#error "Where is my SPI_HAS_TRANSACTION!?!?" -#endif - -void setup() {} -void loop() {} diff --git a/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino b/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino deleted file mode 100644 index 68092faa..00000000 --- a/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino +++ /dev/null @@ -1,9 +0,0 @@ -#include -#include - -#if !defined(SPI_HAS_TRANSACTION) || !SPI_HAS_TRANSACTION -#error "Where is my SPI_HAS_TRANSACTION!?!?" -#endif - -void setup() {} -void loop() {} diff --git a/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino b/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino deleted file mode 100644 index 515d9fe5..00000000 --- a/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino +++ /dev/null @@ -1,14 +0,0 @@ -// Arduino.h should not be automatically included by the Arduino -// preprocessor before the explicit include line in this sketch. - -#if defined(HIGH) -#error Arduino.h seems to be automatically included -#endif - - # include - -void setup() { -} - -void loop() { -} diff --git a/test/sketch_usbhost/sketch_usbhost.ino b/test/sketch_usbhost/sketch_usbhost.ino deleted file mode 100644 index 47d6ccd6..00000000 --- a/test/sketch_usbhost/sketch_usbhost.ino +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_backup_files/backup/sketch.ino b/test/sketch_with_backup_files/backup/sketch.ino deleted file mode 100644 index 86875cfc..00000000 --- a/test/sketch_with_backup_files/backup/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -broken diff --git a/test/sketch_with_backup_files/sketch.ino b/test/sketch_with_backup_files/sketch.ino deleted file mode 100644 index 0d5e0f5c..00000000 --- a/test/sketch_with_backup_files/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_class/sketch.ino b/test/sketch_with_class/sketch.ino deleted file mode 100644 index 97f31071..00000000 --- a/test/sketch_with_class/sketch.ino +++ /dev/null @@ -1,19 +0,0 @@ -class Rectangle { - int width, height; - public: - void set_values (int,int); - int area() {return width*height;} -}; - -void Rectangle::set_values (int x, int y) { - width = x; - height = y; -} - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino b/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino deleted file mode 100644 index d933816a..00000000 --- a/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino +++ /dev/null @@ -1,13 +0,0 @@ -class Foo { -int blooper(int x) { return x+1; } -}; - -Foo foo; - -void setup() { - foo.setup(); -} - -void loop() { - foo.loop(); -} diff --git a/test/sketch_with_config/config.h b/test/sketch_with_config/config.h deleted file mode 100644 index 2998979d..00000000 --- a/test/sketch_with_config/config.h +++ /dev/null @@ -1 +0,0 @@ -#define DEBUG \ No newline at end of file diff --git a/test/sketch_with_config/sketch_with_config.ino b/test/sketch_with_config/sketch_with_config.ino deleted file mode 100644 index 08390371..00000000 --- a/test/sketch_with_config/sketch_with_config.ino +++ /dev/null @@ -1,19 +0,0 @@ -#include "config.h" - -#ifdef DEBUG -#include "src/includes/de bug.h" -#endif - -#ifdef UNDEF -#error -#endif - -#include - -void setup() { - -} - -void loop() { - -} diff --git a/test/sketch_with_config/sketch_with_config.preprocessed.txt b/test/sketch_with_config/sketch_with_config.preprocessed.txt deleted file mode 100644 index 2d56efd3..00000000 --- a/test/sketch_with_config/sketch_with_config.preprocessed.txt +++ /dev/null @@ -1,28 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include "config.h" - -#ifdef DEBUG -#include "src/includes/de bug.h" -#endif - -#ifdef UNDEF -#error -#endif - -#include - -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 17 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - -} - diff --git a/test/sketch_with_config/src/includes/de bug.cpp b/test/sketch_with_config/src/includes/de bug.cpp deleted file mode 100644 index e4d29505..00000000 --- a/test/sketch_with_config/src/includes/de bug.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#pragma debug - -void debug() { - //add debug code -} \ No newline at end of file diff --git a/test/sketch_with_config/src/includes/de bug.h b/test/sketch_with_config/src/includes/de bug.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch_with_const/sketch.ino b/test/sketch_with_const/sketch.ino deleted file mode 100644 index f4f52ca0..00000000 --- a/test/sketch_with_const/sketch.ino +++ /dev/null @@ -1,10 +0,0 @@ -void setup() {} -void loop() {} - -const __FlashStringHelper* test() {} - -const int test3() {} - -volatile __FlashStringHelper* test2() {} - -volatile int test4() {} diff --git a/test/sketch_with_default_args/sketch.ino b/test/sketch_with_default_args/sketch.ino deleted file mode 100644 index 6a5ee7cc..00000000 --- a/test/sketch_with_default_args/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -void test(int x = 1) { -} - -void setup() { -} - -void loop() { -} \ No newline at end of file diff --git a/test/sketch_with_dependend_libraries/sketch.ino b/test/sketch_with_dependend_libraries/sketch.ino deleted file mode 100644 index ad070592..00000000 --- a/test/sketch_with_dependend_libraries/sketch.ino +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/sketch_with_enum_class/sketch_with_enum_class.ino b/test/sketch_with_enum_class/sketch_with_enum_class.ino deleted file mode 100644 index 54c3dfbb..00000000 --- a/test/sketch_with_enum_class/sketch_with_enum_class.ino +++ /dev/null @@ -1,19 +0,0 @@ -void test() { - test2(); -} - -enum class MyEnum -{ - AValue = 0, - AnotherValue = 1 -}; - -void test2() { -} - -void setup() { -} - -void loop() { -} - diff --git a/test/sketch_with_externC/sketch_with_externC.ino b/test/sketch_with_externC/sketch_with_externC.ino deleted file mode 100644 index 8e6c53ea..00000000 --- a/test/sketch_with_externC/sketch_with_externC.ino +++ /dev/null @@ -1,11 +0,0 @@ -void setup() { - // put your setup code here, to run once: - test(); -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -extern "C" void test() {} \ No newline at end of file diff --git a/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino b/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino deleted file mode 100644 index e911a4b0..00000000 --- a/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino +++ /dev/null @@ -1,34 +0,0 @@ -void setup() { - // put your setup code here, to run once: - } - - void loop() { - // put your main code here, to run repeatedly: - test2(); - test4(); - test6(); - test7(); - test10(); - } - - extern "C" { - void test2() {} - } - - extern "C" - { - void test4() {} - } - - extern "C" - - { - void test6() {} - } - - // this function should not have C linkage - void test7() {} - - extern "C" void test10() { - - }; \ No newline at end of file diff --git a/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino b/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino deleted file mode 100644 index eb83500c..00000000 --- a/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino +++ /dev/null @@ -1,19 +0,0 @@ -template< uint16_t nBuffSize > - class Foo{ - public: - - template< uint16_t N > - Foo &operator +=( const Foo &ref ){ - //... - return *this; - } -}; - -Foo<64> a; -Foo<32> b; - -void setup(){ - a += b; -} - -void loop(){} diff --git a/test/sketch_with_function_pointer/CallbackBug.h b/test/sketch_with_function_pointer/CallbackBug.h deleted file mode 100644 index cc8ee18b..00000000 --- a/test/sketch_with_function_pointer/CallbackBug.h +++ /dev/null @@ -1,5 +0,0 @@ -class Task { - public: - Task(void (*aCallback)()) {}; -}; - diff --git a/test/sketch_with_function_pointer/sketch.ino b/test/sketch_with_function_pointer/sketch.ino deleted file mode 100644 index aa50e6e0..00000000 --- a/test/sketch_with_function_pointer/sketch.ino +++ /dev/null @@ -1,5 +0,0 @@ -#include "CallbackBug.h" -Task t1(&t1Callback); -void t1Callback() {} -void setup() {} -void loop() {} diff --git a/test/sketch_with_function_signature_inside_ifdef/sketch.ino b/test/sketch_with_function_signature_inside_ifdef/sketch.ino deleted file mode 100644 index 809f2b5a..00000000 --- a/test/sketch_with_function_signature_inside_ifdef/sketch.ino +++ /dev/null @@ -1,20 +0,0 @@ -void setup() {} - -void loop() { - // Visualize leds via Adalight - int8_t newData = adalight(); - -} - - -//#define ADALIGHT_USE_TEMPLATE - -#ifdef ADALIGHT_USE_TEMPLATE -int16_t adalight() -#else -int8_t adalight() -#endif -{ - // Flag if the leds got a new frame that should be updated - return 0; -} diff --git a/test/sketch_with_ifdef/sketch.ino b/test/sketch_with_ifdef/sketch.ino deleted file mode 100644 index 3d3e2f49..00000000 --- a/test/sketch_with_ifdef/sketch.ino +++ /dev/null @@ -1,15 +0,0 @@ -#if __SAM3X8E__ -void ifBranch() { -} -#else -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} \ No newline at end of file diff --git a/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt b/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt deleted file mode 100644 index 2eb36912..00000000 --- a/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt +++ /dev/null @@ -1,29 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#if __SAM3X8E__ -#line 2 {{QuoteCppString .sketch.MainFile.Name}} -void ifBranch(); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void f1(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void f2(); -#line 12 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 14 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 2 {{QuoteCppString .sketch.MainFile.Name}} -void ifBranch() { -} -#else -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} diff --git a/test/sketch_with_ifdef/sketch.preprocessed.txt b/test/sketch_with_ifdef/sketch.preprocessed.txt deleted file mode 100644 index 31c86758..00000000 --- a/test/sketch_with_ifdef/sketch.preprocessed.txt +++ /dev/null @@ -1,29 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#if __SAM3X8E__ -void ifBranch() { -} -#else -#line 5 {{QuoteCppString .sketch.MainFile.Name}} -void elseBranch(); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void f1(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void f2(); -#line 12 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 14 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 5 {{QuoteCppString .sketch.MainFile.Name}} -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} diff --git a/test/sketch_with_inline_function/sketch.ino b/test/sketch_with_inline_function/sketch.ino deleted file mode 100644 index f0a25e69..00000000 --- a/test/sketch_with_inline_function/sketch.ino +++ /dev/null @@ -1,14 +0,0 @@ -void setup() {} -void loop() {} - -short unsigned int testInt(){ - -} - -static inline int8_t testInline(){ - -} - -__attribute__((always_inline)) uint8_t testAttribute() { - -} diff --git a/test/sketch_with_macosx_garbage/.#sketch.ino b/test/sketch_with_macosx_garbage/.#sketch.ino deleted file mode 100644 index 71048175..00000000 --- a/test/sketch_with_macosx_garbage/.#sketch.ino +++ /dev/null @@ -1,2 +0,0 @@ -void setup() -void loop) } \ No newline at end of file diff --git a/test/sketch_with_macosx_garbage/sketch.ino b/test/sketch_with_macosx_garbage/sketch.ino deleted file mode 100644 index 4f069e3b..00000000 --- a/test/sketch_with_macosx_garbage/sketch.ino +++ /dev/null @@ -1,2 +0,0 @@ -void setup() {} -void loop() {} \ No newline at end of file diff --git a/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino b/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino deleted file mode 100644 index 85f7fb6d..00000000 --- a/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino +++ /dev/null @@ -1,53 +0,0 @@ -void setup() { - myctagstestfunc(1,2,3,4); - test(); - test3(); - test5(1,2,3); - test7(); - test8(); - test9(42, 42); - test10(0,0,0); -} - -void myctagstestfunc(int a, -int b, -int c, -int d) { } - -void loop() {} - -void -test() {} - -void -// comment -test3() {} - -void -test5(int a, - int b, - int c) -{ - -} - -void /* comment */ -test7() {} - -void -/* -multi -line -comment -*/ -test8() {} - - void - /* comment */ - test9(int a, - int b) {} - -void test10(int a, // this - int b, // doesn't - int c // work - ) {} \ No newline at end of file diff --git a/test/sketch_with_multiline_template/sketch_with_multiline_template.ino b/test/sketch_with_multiline_template/sketch_with_multiline_template.ino deleted file mode 100644 index a3ddecdf..00000000 --- a/test/sketch_with_multiline_template/sketch_with_multiline_template.ino +++ /dev/null @@ -1,10 +0,0 @@ -template< typename T > -T func(T t){ - return t * t; -} - -void setup() { - func( 12.34f ); -} - -void loop() {} diff --git a/test/sketch_with_namespace/sketch.ino b/test/sketch_with_namespace/sketch.ino deleted file mode 100644 index 178ba312..00000000 --- a/test/sketch_with_namespace/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -namespace Test { - int value() { - return 42; - } - int ciao = 24; -} -void setup() {} -void loop() {} diff --git a/test/sketch_with_old_lib/sketch.ino b/test/sketch_with_old_lib/sketch.ino deleted file mode 100644 index 8be27087..00000000 --- a/test/sketch_with_old_lib/sketch.ino +++ /dev/null @@ -1,9 +0,0 @@ -#include "ShouldNotRecurseWithOldLibs.h" - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_static_asserts/sketch_with_static_asserts.ino b/test/sketch_with_static_asserts/sketch_with_static_asserts.ino deleted file mode 100644 index 4b5500dd..00000000 --- a/test/sketch_with_static_asserts/sketch_with_static_asserts.ino +++ /dev/null @@ -1,16 +0,0 @@ -// https://github.com/arduino/arduino-builder/issues/68 - -const int a = 10; -const int b = 20; - -static_assert(a < b, "bar"); - -void setup() { - test(); -} - -void loop() { -} - -void test() { -} diff --git a/test/sketch_with_subfolders/sketch_with_subfolders.ino b/test/sketch_with_subfolders/sketch_with_subfolders.ino deleted file mode 100644 index 24a58577..00000000 --- a/test/sketch_with_subfolders/sketch_with_subfolders.ino +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include "subfolder/other.h" -#include "src/subfolder/other.h" - -MyClass myClass; - -void setup() { - myClass.init ( &Serial ); -} - -void loop() { -} diff --git a/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino b/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino deleted file mode 100644 index 1d32675e..00000000 --- a/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino +++ /dev/null @@ -1 +0,0 @@ -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/src/subfolder/other.cpp b/test/sketch_with_subfolders/src/subfolder/other.cpp deleted file mode 100644 index ea74d5a0..00000000 --- a/test/sketch_with_subfolders/src/subfolder/other.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include // Arduino 1.0 -#include - -#include "other.h" - -MyClass::MyClass() { -} - -void MyClass::init ( Stream *stream ) { - controllerStream = stream; -} diff --git a/test/sketch_with_subfolders/src/subfolder/other.h b/test/sketch_with_subfolders/src/subfolder/other.h deleted file mode 100644 index d56bdcdd..00000000 --- a/test/sketch_with_subfolders/src/subfolder/other.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef other__h -#define other__h -#include - -class MyClass { - public: - MyClass(); - void init ( Stream *controllerStream ); - - private: - Stream *controllerStream; -}; -#endif diff --git a/test/sketch_with_subfolders/subfolder/dont_load_me.cpp b/test/sketch_with_subfolders/subfolder/dont_load_me.cpp deleted file mode 100644 index 46b07018..00000000 --- a/test/sketch_with_subfolders/subfolder/dont_load_me.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/subfolder/dont_load_me.ino b/test/sketch_with_subfolders/subfolder/dont_load_me.ino deleted file mode 100644 index 46b07018..00000000 --- a/test/sketch_with_subfolders/subfolder/dont_load_me.ino +++ /dev/null @@ -1,2 +0,0 @@ -#include -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/subfolder/other.h b/test/sketch_with_subfolders/subfolder/other.h deleted file mode 100644 index 13a2014b..00000000 --- a/test/sketch_with_subfolders/subfolder/other.h +++ /dev/null @@ -1,2 +0,0 @@ -// This file *is* included from the main sketch, even though it is -// outside of the src/ directory. diff --git a/test/sketch_with_templates_and_shift/template_and_shift.cpp b/test/sketch_with_templates_and_shift/template_and_shift.cpp deleted file mode 100644 index f4f1ece8..00000000 --- a/test/sketch_with_templates_and_shift/template_and_shift.cpp +++ /dev/null @@ -1,19 +0,0 @@ -template<> class FastPin<0> : public _ARMPIN<0, 10, 1 << 10, 0> {};; - -template<> class FastPin<0> : public _ARMPIN<0, 10, 1 < 10, 0> {};; - -template class OtherType> class NestedTemplateClass -{ - OtherType f; -}; - -void printGyro() -{ -} - -template class c {}; -c< 8 > bVar; -c< 1<<8 > aVar; - -template func( c< 1< & aParam) { -} diff --git a/test/sketch_with_typename/sketch.ino b/test/sketch_with_typename/sketch.ino deleted file mode 100644 index 0fdc8167..00000000 --- a/test/sketch_with_typename/sketch.ino +++ /dev/null @@ -1,14 +0,0 @@ -template< typename T > - struct Foo{ - typedef T Bar; -}; - -void setup() { - func(); -} - -void loop() {} - -typename Foo::Bar func(){ - -} diff --git a/test/sketch_with_usbcon/sketch.ino b/test/sketch_with_usbcon/sketch.ino deleted file mode 100644 index 1fa15390..00000000 --- a/test/sketch_with_usbcon/sketch.ino +++ /dev/null @@ -1,18 +0,0 @@ -#if !defined(USBCON) -#error "Where's my USBCON?" -#endif -#if defined(USBCON) -void ciao() { - -} -#endif - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} \ No newline at end of file diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go deleted file mode 100644 index ebd593c2..00000000 --- a/test/store_build_options_map_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "testing" -) - -func TestStoreBuildOptionsMap(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{"hardware"}, - ToolsFolders: []string{"tools"}, - BuiltInLibrariesFolders: []string{"built-in libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: "sketchLocation", - FQBN: "fqbn", - ArduinoAPIVersion: "ideVersion", - CustomBuildProperties: []string{"custom=prop"}, - Verbose: true, - DebugLevel: 5, - } - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - commands := []types.Command{ - &builder.CreateBuildOptionsMap{}, - &builder.StoreBuildOptionsMap{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - _, err := os.Stat(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE)) - NoError(t, err) - - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE)) - NoError(t, err) - - require.Equal(t, "{\n"+ - " \"additionalFiles\": \"\",\n"+ - " \"builtInLibrariesFolders\": \"built-in libraries\",\n"+ - " \"customBuildProperties\": \"custom=prop\",\n"+ - " \"fqbn\": \"fqbn\",\n"+ - " \"hardwareFolders\": \"hardware\",\n"+ - " \"otherLibrariesFolders\": \"libraries\",\n"+ - " \"runtime.ide.version\": \"ideVersion\",\n"+ - " \"sketchLocation\": \"sketchLocation\",\n"+ - " \"toolsFolders\": \"tools\"\n"+ - "}", string(bytes)) -} diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go deleted file mode 100644 index 49e0abea..00000000 --- a/test/target_board_resolver_test.go +++ /dev/null @@ -1,193 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "path/filepath" - "testing" -) - -func TestTargetBoardResolverUno(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - FQBN: "arduino:avr:uno", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "uno", targetBoard.BoardId) - require.Equal(t, "atmega328p", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) -} - -func TestTargetBoardResolverDue(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - FQBN: "arduino:sam:arduino_due_x", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "sam", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "arduino_due_x", targetBoard.BoardId) - require.Equal(t, "cortex-m3", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) -} - -func TestTargetBoardResolverMega1280(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - FQBN: "arduino:avr:mega:cpu=atmega1280", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardId) - require.Equal(t, "atmega1280", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) -} - -func TestTargetBoardResolverMega2560(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - FQBN: "arduino:avr:mega:cpu=atmega2560", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardId) - require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) -} - -func TestTargetBoardResolverCustomYun(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - FQBN: "my_avr_platform:avr:custom_yun", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "custom_yun", targetBoard.BoardId) - require.Equal(t, "atmega32u4", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_YUN", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) -} - -func TestTargetBoardResolverCustomCore(t *testing.T) { - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - FQBN: "watterott:avr:attiny841:core=spencekonde,info=info", - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "watterott", targetPackage.PackageId) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) - targetBoard := ctx.TargetBoard - require.Equal(t, "attiny841", targetBoard.BoardId) - require.Equal(t, "tiny841", ctx.BuildCore) - require.Equal(t, "tiny14", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_VARIANT]) -} diff --git a/test/tools_builtin/avr/builtin_tools_versions.txt b/test/tools_builtin/avr/builtin_tools_versions.txt deleted file mode 100644 index a071f413..00000000 --- a/test/tools_builtin/avr/builtin_tools_versions.txt +++ /dev/null @@ -1,2 +0,0 @@ -arduino.avrdude=6.0.1-arduino5 -arduino.avr-gcc=4.8.1-arduino5 diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go deleted file mode 100644 index 926bca37..00000000 --- a/test/tools_loader_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "sort" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -type ByToolIDAndVersion []*types.Tool - -func (s ByToolIDAndVersion) Len() int { - return len(s) -} -func (s ByToolIDAndVersion) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByToolIDAndVersion) Less(i, j int) bool { - if s[i].Name == s[j].Name { - return s[i].Version < s[j].Version - } - return s[i].Name < s[j].Name -} - -func TestLoadTools(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - ToolsFolders: []string{"downloaded_tools", "tools_builtin"}, - } - - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) - - tools := ctx.Tools - require.Equal(t, 7, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, "arduino-preprocessor", tools[idx].Name) - require.Equal(t, "0.1.5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/arduino-preprocessor/0.1.5"), tools[idx].Folder) - idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) - idx++ - require.Equal(t, "avr-gcc", tools[idx].Name) - require.Equal(t, "4.8.1-arduino5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) - idx++ - require.Equal(t, "avrdude", tools[idx].Name) - require.Equal(t, "6.0.1-arduino5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) - idx++ - require.Equal(t, "bossac", tools[idx].Name) - require.Equal(t, "1.5-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) - idx++ - require.Equal(t, "bossac", tools[idx].Name) - require.Equal(t, "1.6.1-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) - idx++ - require.Equal(t, "ctags", tools[idx].Name) - require.Equal(t, "5.8-arduino11", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) -} - -func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - ToolsFolders: []string{"downloaded_board_manager_stuff"}, - } - - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) - - tools := ctx.Tools - require.Equal(t, 3, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, "CMSIS", tools[idx].Name) - require.Equal(t, "4.0.0-atmel", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) - idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) - idx++ - require.Equal(t, "openocd", tools[idx].Name) - require.Equal(t, "0.9.0-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) -} - -func TestLoadLotsOfTools(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - ToolsFolders: []string{"downloaded_tools", "tools_builtin", "downloaded_board_manager_stuff"}, - } - - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) - - tools := ctx.Tools - require.Equal(t, 9, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, "CMSIS", tools[idx].Name) - require.Equal(t, "4.0.0-atmel", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) - idx++ - require.Equal(t, "arduino-preprocessor", tools[idx].Name) - require.Equal(t, "0.1.5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/arduino-preprocessor/0.1.5"), tools[idx].Folder) - idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) - idx++ - require.Equal(t, "avr-gcc", tools[idx].Name) - require.Equal(t, "4.8.1-arduino5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) - idx++ - require.Equal(t, "avrdude", tools[idx].Name) - require.Equal(t, "6.0.1-arduino5", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) - idx++ - require.Equal(t, "bossac", tools[idx].Name) - require.Equal(t, "1.5-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) - idx++ - require.Equal(t, "bossac", tools[idx].Name) - require.Equal(t, "1.6.1-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) - idx++ - require.Equal(t, "ctags", tools[idx].Name) - require.Equal(t, "5.8-arduino11", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) - idx++ - require.Equal(t, "openocd", tools[idx].Name) - require.Equal(t, "0.9.0-arduino", tools[idx].Version) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) -} diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go deleted file mode 100644 index b604d6e0..00000000 --- a/test/try_build_of_problematic_sketch_test.go +++ /dev/null @@ -1,263 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "os" - "path/filepath" - "testing" -) - -func TestTryBuild001(t *testing.T) { - tryBuild(t, "sketch_with_inline_function", "sketch.ino") -} - -func TestTryBuild002(t *testing.T) { - tryBuild(t, "sketch_with_function_signature_inside_ifdef", "sketch.ino") -} - -func TestTryBuild003(t *testing.T) { - tryPreprocess(t, "sketch_no_functions", "main.ino") -} - -func TestTryBuild004(t *testing.T) { - tryBuild(t, "sketch_with_const", "sketch.ino") -} - -func TestTryBuild005(t *testing.T) { - tryBuild(t, "sketch_with_old_lib", "sketch.ino") -} - -func TestTryBuild006(t *testing.T) { - tryBuild(t, "sketch_with_macosx_garbage", "sketch.ino") -} - -func TestTryBuild007(t *testing.T) { - tryBuild(t, "sketch_with_config", "sketch_with_config.ino") -} - -// XXX: Failing sketch, typename not supported -//func TestTryBuild008(t *testing.T) { -// tryBuild(t, "sketch_with_typename", "sketch.ino") -//} - -func TestTryBuild009(t *testing.T) { - tryBuild(t, "sketch_with_usbcon", "sketch.ino") -} - -func TestTryBuild010(t *testing.T) { - tryBuild(t, "sketch_with_namespace", "sketch.ino") -} - -func TestTryBuild011(t *testing.T) { - tryBuild(t, "sketch_with_inline_function", "sketch.ino") -} - -func TestTryBuild012(t *testing.T) { - tryBuild(t, "sketch_with_default_args", "sketch.ino") -} - -func TestTryBuild013(t *testing.T) { - tryBuild(t, "sketch_with_class", "sketch.ino") -} - -func TestTryBuild014(t *testing.T) { - tryBuild(t, "sketch_with_backup_files", "sketch.ino") -} - -func TestTryBuild015(t *testing.T) { - tryBuild(t, "sketch_with_subfolders") -} - -// This is a sketch that fails to build on purpose -//func TestTryBuild016(t *testing.T) { -// tryBuild(t, "sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet", "sketch.ino") -//} - -func TestTryBuild017(t *testing.T) { - tryPreprocess(t, "sketch_no_functions_two_files", "main.ino") -} - -func TestTryBuild018(t *testing.T) { - tryBuild(t, "sketch_that_checks_if_SPI_has_transactions", "sketch.ino") -} - -func TestTryBuild019(t *testing.T) { - tryBuild(t, "sketch_with_ifdef", "sketch.ino") -} - -func TestTryBuild020(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.OtherLibrariesFolders = []string{"dependent_libraries", "libraries"} - tryPreprocessWithContext(t, ctx, "sketch_with_dependend_libraries", "sketch.ino") -} - -func TestTryBuild021(t *testing.T) { - tryBuild(t, "sketch_with_function_pointer", "sketch.ino") -} - -func TestTryBuild022(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" - tryBuildWithContext(t, ctx, "sketch_usbhost", "sketch_usbhost.ino") -} - -func TestTryBuild023(t *testing.T) { - tryBuild(t, "sketch1", "sketch.ino") -} - -func TestTryBuild024(t *testing.T) { - tryBuild(t, "sketch2", "SketchWithIfDef.ino") -} - -// The library for this sketch is missing -//func TestTryBuild025(t *testing.T) { -// tryBuild(t, "sketch3", "Baladuino.ino") -//} - -func TestTryBuild026(t *testing.T) { - tryBuild(t, "sketch4", "CharWithEscapedDoubleQuote.ino") -} - -func TestTryBuild027(t *testing.T) { - tryBuild(t, "sketch5", "IncludeBetweenMultilineComment.ino") -} - -func TestTryBuild028(t *testing.T) { - tryBuild(t, "sketch6", "LineContinuations.ino") -} - -func TestTryBuild029(t *testing.T) { - tryBuild(t, "sketch7", "StringWithComment.ino") -} - -func TestTryBuild030(t *testing.T) { - tryBuild(t, "sketch8", "SketchWithStruct.ino") -} - -func TestTryBuild031(t *testing.T) { - tryBuild(t, "sketch9", "sketch.ino") -} - -func TestTryBuild032(t *testing.T) { - tryBuild(t, "sketch10", "sketch.ino") -} - -func TestTryBuild033(t *testing.T) { - tryBuild(t, "sketch_that_includes_arduino_h", "sketch_that_includes_arduino_h.ino") -} - -func TestTryBuild034(t *testing.T) { - tryBuild(t, "sketch_with_static_asserts", "sketch_with_static_asserts.ino") -} - -func TestTryBuild035(t *testing.T) { - tryBuild(t, "sketch_with_enum_class", "sketch_with_enum_class.ino") -} - -func TestTryBuild036(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" - tryBuildWithContext(t, ctx, "sketch11", "sketch_fastleds.ino") -} - -func TestTryBuild037(t *testing.T) { - tryBuild(t, "sketch_with_externC", "sketch_with_externC.ino") -} - -func TestTryBuild038(t *testing.T) { - tryBuild(t, "sketch_with_multiline_prototypes", "sketch_with_multiline_prototypes.ino") -} - -func TestTryBuild039(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" - tryBuildWithContext(t, ctx, "sketch12", "sketch12.ino") -} - -func TestTryBuild040(t *testing.T) { - tryBuild(t, "sketch_with_externC_multiline", "sketch_with_externC_multiline.ino") -} - -func TestTryBuild041(t *testing.T) { - tryBuild(t, "sketch_with_multiline_template", "sketch_with_multiline_template.ino") -} - -func TestTryBuild042(t *testing.T) { - tryBuild(t, "sketch_with_fake_function_pointer", "sketch_with_fake_function_pointer.ino") -} - -func makeDefaultContext(t *testing.T) *types.Context { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - ToolsFolders: []string{"downloaded_tools", "downloaded_board_manager_stuff"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10607", - Verbose: true, - DebugPreprocessor: true, - } - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - return ctx -} - -func tryBuild(t *testing.T, sketchPath ...string) { - ctx := makeDefaultContext(t) - tryBuildWithContext(t, ctx, sketchPath...) -} - -func tryBuildWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := filepath.Join(sketchPath...) - ctx.SketchLocation = sketchLocation - - err := builder.RunBuilder(ctx) - NoError(t, err, "Build error for "+sketchLocation) -} - -func tryPreprocess(t *testing.T, sketchPath ...string) { - ctx := makeDefaultContext(t) - tryPreprocessWithContext(t, ctx, sketchPath...) -} - -func tryPreprocessWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := filepath.Join(sketchPath...) - ctx.SketchLocation = sketchLocation - - err := builder.RunPreprocess(ctx) - NoError(t, err, "Build error for "+sketchLocation) -} diff --git a/test/unique_string_queue_test.go b/test/unique_string_queue_test.go deleted file mode 100644 index e6e92bb4..00000000 --- a/test/unique_string_queue_test.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestUniqueStringQueue(t *testing.T) { - queue := types.UniqueStringQueue{} - queue.Push("hello") - queue.Push("world") - queue.Push("hello") - queue.Push("world") - - require.Equal(t, "hello", queue.Pop()) - require.Equal(t, "world", queue.Pop()) - require.True(t, queue.Empty()) -} diff --git a/test/unquote_test.go b/test/unquote_test.go deleted file mode 100644 index 88233424..00000000 --- a/test/unquote_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/gohasissues" - "github.com/stretchr/testify/require" - "testing" -) - -func TestStrConvUnquote(t *testing.T) { - s, err := gohasissues.Unquote("ciao") - NoError(t, err) - require.Equal(t, "ciao", s) - - s, err = gohasissues.Unquote("arduino:avr:uno") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) - - s, err = gohasissues.Unquote("\"arduino:avr:uno\"") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) - - s, err = gohasissues.Unquote("'arduino:avr:uno'") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) -} diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go deleted file mode 100644 index 83847dee..00000000 --- a/test/unused_compiled_libraries_remover_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "testing" -) - -func TestUnusedCompiledLibrariesRemover(t *testing.T) { - temp, err := ioutil.TempDir("", "test") - NoError(t, err) - defer os.RemoveAll(temp) - - NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755))) - NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755))) - NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644))) - - ctx := &types.Context{} - ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*types.Library{&types.Library{Name: "Bridge"}} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err = cmd.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(temp, "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "Bridge")) - NoError(t, err) - _, err = os.Stat(filepath.Join(temp, "dummy_file")) - NoError(t, err) -} - -func TestUnusedCompiledLibrariesRemoverLibDoesNotExist(t *testing.T) { - ctx := &types.Context{} - ctx.LibrariesBuildPath = filepath.Join(os.TempDir(), "test") - ctx.ImportedLibraries = []*types.Library{&types.Library{Name: "Bridge"}} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err := cmd.Run(ctx) - NoError(t, err) -} - -func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { - temp, err := ioutil.TempDir("", "test") - NoError(t, err) - defer os.RemoveAll(temp) - - NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755))) - NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755))) - NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644))) - - ctx := &types.Context{} - ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*types.Library{} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err = cmd.Run(ctx) - NoError(t, err) - - _, err = os.Stat(filepath.Join(temp, "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "Bridge")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "dummy_file")) - NoError(t, err) -} diff --git a/test/user_hardware/arduino/avr/.gitkeep b/test/user_hardware/arduino/avr/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/user_hardware/my_avr_platform/avr/boards.txt b/test/user_hardware/my_avr_platform/avr/boards.txt deleted file mode 100644 index 6b98abf5..00000000 --- a/test/user_hardware/my_avr_platform/avr/boards.txt +++ /dev/null @@ -1,85 +0,0 @@ -custom_yun.name=Arduino Yún -custom_yun.upload.via_ssh=true - -custom_yun.build.core=arduino:arduino -custom_yun.bootloader.tool=arduino:avrdude -custom_yun.upload.tool=arduino:avrdude - -custom_yun.vid.0=0x2341 -custom_yun.pid.0=0x0041 -custom_yun.vid.1=0x2341 -custom_yun.pid.1=0x8041 -custom_yun.upload.protocol=avr109 -custom_yun.upload.maximum_size=28672 -custom_yun.upload.maximum_data_size=2560 -custom_yun.upload.speed=57600 -custom_yun.upload.disable_flushing=true -custom_yun.upload.use_1200bps_touch=true -custom_yun.upload.wait_for_upload_port=true - -custom_yun.bootloader.low_fuses=0xff -custom_yun.bootloader.high_fuses=0xd8 -custom_yun.bootloader.extended_fuses=0xfb -custom_yun.bootloader.file=caterina/Caterina-custom_yun.hex -custom_yun.bootloader.unlock_bits=0x3F -custom_yun.bootloader.lock_bits=0x2F - -custom_yun.build.mcu=atmega32u4 -custom_yun.build.f_cpu=16000000L -custom_yun.build.vid=0x2341 -custom_yun.build.pid=0x8041 -custom_yun.build.usb_product="Arduino My" -custom_yun.build.board=AVR_YUN -custom_yun.build.variant=arduino:yun -custom_yun.build.extra_flags={build.usb_flags} - -mymega.name=Arduino Mega or Mega 2560 - -mymega.vid.0=0x2341 -mymega.pid.0=0x0010 -mymega.vid.1=0x2341 -mymega.pid.1=0x0042 -mymega.vid.2=0x2A03 -mymega.pid.2=0x0010 -mymega.vid.3=0x2A03 -mymega.pid.3=0x0042 - -mymega.upload.tool=avrdude -mymega.upload.maximum_data_size=8192 - -mymega.bootloader.tool=avrdude -mymega.bootloader.low_fuses=0xFF -mymega.bootloader.unlock_bits=0x3F -mymega.bootloader.lock_bits=0x0F - -mymega.build.f_cpu=16000000L -mymega.build.core=arduino -mymega.build.variant=mega - -mymega.menu.cpu.atmega2560=ATmega2560 (Mega 2560) - -mymega.menu.cpu.atmega2560.upload.protocol=wiring -mymega.menu.cpu.atmega2560.upload.maximum_size=253952 -mymega.menu.cpu.atmega2560.upload.speed=115200 - -mymega.menu.cpu.atmega2560.bootloader._folder=stk500v2 -mymega.menu.cpu.atmega2560.bootloader.high_fuses=0xD8 -mymega.menu.cpu.atmega2560.bootloader.extended_fuses=0xFD -mymega.menu.cpu.atmega2560.bootloader.file={bootloader._folder}/stk500boot_v2_mega2560.hex - -mymega.menu.cpu.atmega2560.build.mcu=atmega2560 -mymega.menu.cpu.atmega2560.build.board=AVR_MEGA2560 - -mymega.menu.cpu.atmega1280=ATmega1280 - -mymega.menu.cpu.atmega1280.upload.protocol=arduino -mymega.menu.cpu.atmega1280.upload.maximum_size=126976 -mymega.menu.cpu.atmega1280.upload.speed=57600 - -mymega.menu.cpu.atmega1280.bootloader._folder=atmega -mymega.menu.cpu.atmega1280.bootloader.high_fuses=0xDA -mymega.menu.cpu.atmega1280.bootloader.extended_fuses=0xF5 -mymega.menu.cpu.atmega1280.bootloader.file={bootloader._folder}/ATmegaBOOT_168_atmega1280.hex - -mymega.menu.cpu.atmega1280.build.mcu=atmega1280 -mymega.menu.cpu.atmega1280.build.board=AVR_MEGA diff --git a/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex b/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex deleted file mode 100644 index c52e690a..00000000 --- a/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex +++ /dev/null @@ -1,469 +0,0 @@ -:020000023000CC -:10E000000D9489F10D94B2F10D94B2F10D94B2F129 -:10E010000D94B2F10D94B2F10D94B2F10D94B2F1F0 -:10E020000D94B2F10D94B2F10D94B2F10D94B2F1E0 -:10E030000D94B2F10D94B2F10D94B2F10D94B2F1D0 -:10E040000D94B2F10D94B2F10D94B2F10D94B2F1C0 -:10E050000D94B2F10D94B2F10D94B2F10D94B2F1B0 -:10E060000D94B2F10D94B2F10D94B2F10D94B2F1A0 -:10E070000D94B2F10D94B2F10D94B2F10D94B2F190 -:10E080000D94B2F10D94B2F10D94B2F10D94B2F180 -:10E090000D94B2F10D94B2F10D94B2F10D94B2F170 -:10E0A0000D94B2F10D94B2F10D94B2F10D94B2F160 -:10E0B0000D94B2F10D94B2F10D94B2F10D94B2F150 -:10E0C0000D94B2F10D94B2F10D94B2F10D94B2F140 -:10E0D0000D94B2F10D94B2F10D94B2F10D94B2F130 -:10E0E0000D94B2F141546D656761323536300041AF -:10E0F000726475696E6F206578706C6F72657220DE -:10E1000073746B3530305632206279204D4C530099 -:10E11000426F6F746C6F616465723E004875683F52 -:10E1200000436F6D70696C6564206F6E203D200048 -:10E130004350552054797065202020203D20005FF9 -:10E140005F4156525F415243485F5F3D2000415658 -:10E1500052204C696243205665723D20004743437C -:10E160002056657273696F6E203D20004350552024 -:10E1700049442020202020203D20004C6F7720663D -:10E18000757365202020203D20004869676820665F -:10E190007573652020203D200045787420667573D6 -:10E1A00065202020203D20004C6F636B2066757336 -:10E1B000652020203D20004D617220203720323024 -:10E1C000313300312E362E3800342E332E350056A2 -:10E1D00023202020414444522020206F7020636F70 -:10E1E00064652020202020696E73747275637469E1 -:10E1F0006F6E2061646472202020496E74657272B3 -:10E20000757074006E6F20766563746F7200726A49 -:10E210006D702020006A6D70200057686174207056 -:10E220006F72743A00506F7274206E6F7420737541 -:10E2300070706F72746564004D7573742062652030 -:10E2400061206C6574746572002000577269747483 -:10E25000696E672045450052656164696E672045B7 -:10E26000450045452065727220636E743D00504F35 -:10E27000525400303D5A65726F2061646472003FF1 -:10E280003D43505520737461747300403D454550C3 -:10E29000524F4D207465737400423D426C696E6B41 -:10E2A000204C454400453D44756D70204545505215 -:10E2B0004F4D00463D44756D7020464C415348001B -:10E2C000483D48656C70004C3D4C69737420492F83 -:10E2D0004F20506F72747300513D51756974005234 -:10E2E0003D44756D702052414D00563D73686F7707 -:10E2F00020696E7465727275707420566563746FF0 -:10E30000727300593D506F727420626C696E6B00BD -:10E310002A0011241FBECFEFD1E2DEBFCDBF01E046 -:10E320000CBF12E0A0E0B2E0EEE1FDEF03E00BBFB6 -:10E3300002C007900D92A030B107D9F712E0A0E01B -:10E34000B2E001C01D92AE30B107E1F70F9460F367 -:10E350000D948DFE01E20EBF0FEF0DBF11241FBE05 -:10E360000D9460F30D9400F020E030E040ED57E0B4 -:10E3700005C0FA013197F1F72F5F3F4F2817390792 -:10E38000C0F308959C01260F311DC901A0E0B0E043 -:10E390002F5F3F4FABBFFC018791882361F08093D3 -:10E3A000C6008091C00086FFFCCF8091C0008064D1 -:10E3B0008093C000EACF08958DE08093C6008091DD -:10E3C000C00086FFFCCF8091C00080648093C000B5 -:10E3D0008AE08093C6008091C00086FFFCCF8091C8 -:10E3E000C00080648093C00008950F94C2F10F9420 -:10E3F000DCF10895FC019081992359F09093C600B7 -:10E400008091C00086FFFCCF8091C0008064809323 -:10E41000C0003196992379F70895282F982F929567 -:10E420009F70892F805D8A3308F0895F8093C600D2 -:10E430008091C00086FFFCCF8091C00080648093F3 -:10E44000C000822F8F70982F905D9A3308F0995FEB -:10E450009093C6008091C00086FFFCCF8091C000E1 -:10E4600080648093C00008959C01FB01853691056E -:10E470001CF46330710594F0C90164E670E00F94F8 -:10E480002EFE605D7F4F6093C6008091C00086FFC6 -:10E49000FCCF8091C00080648093C0002B30310598 -:10E4A00014F43297B4F0C90164E670E00F942EFEC4 -:10E4B0006AE070E00F942EFE605D7F4F6093C600AF -:10E4C0008091C00086FFFCCF8091C0008064809363 -:10E4D000C000C9016AE070E00F942EFEC0968093E0 -:10E4E000C6008091C00086FFFCCF8091C000806490 -:10E4F0008093C00008951F93182F8EE692EE60E07F -:10E500000F94C2F11093C6008091C00086FFFCCF2B -:10E510008091C00080648093C0000F94DCF11F9153 -:10E5200008952F923F924F925F926F927F928F92B7 -:10E530009F92AF92BF92CF92DF92EF92FF920F9392 -:10E540001F93DF93CF93CDB7DEB762970FB6F894E2 -:10E55000DEBF0FBECDBF382E622ECA01DB015C01CB -:10E560006D01772420E2222E2E010894411C511CBB -:10E570008BC081E0A81680E0B80681E0C80680E084 -:10E58000D80628F0C601AA27BB270F940DF2BB2797 -:10E59000AD2D9C2D8B2D0F940DF28A2D0F940DF225 -:10E5A0002092C6008091C00086FFFCCF8091C00001 -:10E5B00080648093C0009DE29093C6008091C0006B -:10E5C00086FFFCCF8091C00080648093C0002092C1 -:10E5D000C6008091C00086FFFCCF8091C00080649F -:10E5E0008093C00019828601750188249924A1E0D6 -:10E5F0003A1651F03A1620F0B2E03B1661F409C029 -:10E600000BBFF701779007C0C7010F9477FE782EF4 -:10E6100002C0F7017080872D0F940DF22092C60082 -:10E620008091C00086FFFCCF8091C0008064809301 -:10E63000C000872D8052F401EF70F0708F3520F408 -:10E64000E40DF51D708204C0E40DF51D8EE280839B -:10E650000894E11CF11C011D111D0894811C911CE2 -:10E6600090E18916910409F0C2CF80E190E0A0E02A -:10E67000B0E0A80EB91ECA1EDB1E198AC2010F9493 -:10E68000FAF10F94DCF16A94662009F072CF629679 -:10E690000FB6F894DEBF0FBECDBFCF91DF911F91B3 -:10E6A0000F91FF90EF90DF90CF90BF90AF909F9031 -:10E6B0008F907F906F905F904F903F902F90089534 -:10E6C0002F923F924F925F926F927F928F929F9282 -:10E6D000AF92BF92CF92DF92EF92FF920F931F9370 -:10E6E000DF93CF93CDB7DEB7CD53D1400FB6F894BB -:10E6F000DEBF0FBECDBF01E20EBF0FEF0DBF94B75F -:10E70000F894A89514BE80916000886180936000A1 -:10E7100010926000789493FF05C0E0910002F091A0 -:10E7200001021995279A2F9A8091C00082608093E8 -:10E73000C00080E18093C40088E18093C1000000A4 -:10E74000EE24FF24870144E0A42EB12CCC24DD2448 -:10E7500024C0C5010197F1F70894E11CF11C011DCB -:10E76000111D21E2E2162EE4F20620E0020720E06D -:10E77000120718F031E0C32ED12CC801B70127ECE5 -:10E780003BE140E050E00F9441FE611571058105C9 -:10E79000910519F485B1805885B98091C00087FD35 -:10E7A00003C0C114D104A9F2A6014F5F5F4FC25E3E -:10E7B000DE4F59834883CE51D140C25EDE4F8881FF -:10E7C0009981CE51D140019711F00D9410FEC05D9A -:10E7D000DE4F19821882C053D14060E0C15DDE4F28 -:10E7E0001882CF52D14088249924C35DDE4F19820C -:10E7F0001882CD52D140C05EDE4F188219821A8233 -:10E800001B82C052D140CE5CDE4F188219821A8220 -:10E810001B82C253D140EE24FF2487010BBFF701B6 -:10E8200007911691C45CDE4F19830883CC53D14005 -:10E830000D940BFEC25EDE4F28813981CE51D1404E -:10E840002130310509F52091C600C25EDE4F1982E4 -:10E850001882CE51D14022C02F5F3F4F4F4F5F4FA4 -:10E86000213082E138078AE7480780E0580780F0C6 -:10E87000C45CDE4FE881F981CC53D140EF5FFF4F9C -:10E8800019F0EE27FF27099420E030E040E050E047 -:10E890008091C00087FFE0CF2091C600C35DDE4FAE -:10E8A00048815981CD52D1404F5F5F4FC35DDE4FEC -:10E8B00059834883CD52D140213209F063C64A3092 -:10E8C000510508F05FC60894811C911C53E0851621 -:10E8D000910409F059C600E010E018C081E280936D -:10E8E000C6008091C00086FFFCCF8091C00080648C -:10E8F0008093C0002F5F3F4F2931310579F70F9486 -:10E90000DCF10F5F1F4F0530110519F020E030E0FA -:10E91000E5CF10920A0210920B0210920C02109294 -:10E920000D02109206021092070210920802109235 -:10E930000902109202021092030210920402109235 -:10E9400005028FEE90EE60E00F94F5F180E191EE1C -:10E9500060E00F94C2F18091C00087FFFCCF9091DE -:10E96000C600903608F09F759032B8F09093C600BC -:10E970008091C00086FFFCCF8091C00080648093AE -:10E98000C000A0E2A093C6008091C00086FFFCCF2B -:10E990008091C00080648093C000983409F4D7C18E -:10E9A0009934B8F4923409F459C1933458F490333B -:10E9B00019F1903308F4E3C59F33A1F1903409F0C5 -:10E9C000DEC5BDC0953409F470C1963409F0D7C5D1 -:10E9D00098C1923509F42BC2933538F49C3409F46C -:10E9E000F5C1913509F0CBC518C2963509F445C279 -:10E9F000993509F0C4C567C483E792EE62E00F94CD -:10EA0000F5F110920602109207021092080210927D -:10EA1000090210920A0210920B0210920C0210923C -:10EA20000D0213C18FE792EE62E00F94F5F18FEEC5 -:10EA300090EE60E00F94F5F181E291EE60E00F94CA -:10EA4000C2F187EB91EE60E00F94F5F180E391EE77 -:10EA500060E00F94C2F184EE90EE60E00F94F5F167 -:10EA60008FE391EE60E00F94C2F186E090E061E008 -:10EA700070E00F9434F20F94DCF18DE591EE60E0DC -:10EA80000F94C2F189EC91EE60E00F94F5F18EE401 -:10EA900091EE60E00F94C2F183EC91EE60E00F9490 -:10EAA000F5F18CE691EE60E00F94C2F18EE10F94E7 -:10EAB0000DF288E90F940DF281E00F940DF20F949E -:10EAC000DCF18BE791EE60E00F94C2F119E0E0E039 -:10EAD000F0E010935700E4918E2F0F940DF20F94F5 -:10EAE000DCF18AE891EE60E00F94C2F1E3E0F0E03F -:10EAF00010935700E4918E2F0F940DF20F94DCF1D8 -:10EB000089E991EE60E00F94C2F1E2E0F0E0109349 -:10EB10005700E4918E2F0F940DF20F94DCF188EAE8 -:10EB200091EE60E00F94C2F1E1E0F0E01093570045 -:10EB30001491812F0F940DF20F94DCF107CF8BE825 -:10EB400092EE62E00F94F5F18BE492EE60E00F94A8 -:10EB5000F5F10F94DCF100E010E019C0C8016F2D51 -:10EB60000F947FFEFF2031F489E492EE60E00F9471 -:10EB7000C2F10BC0F092C6008091C00086FFFCCFAE -:10EB80008091C00080648093C0000F5F1F4FC80158 -:10EB900081519F41A0E0B0E0ABBFFC01F790BAE229 -:10EBA000FB1621F0E2E000301E07C1F60F94DCF105 -:10EBB0000F94DCF187E592EE60E00F94F5F10F948D -:10EBC000DCF1CC24DD2400E010E01EC0C8010F946D -:10EBD00077FEF82E882331F489E492EE60E00F94FA -:10EBE000C2F10BC08093C6008091C00086FFFCCFAD -:10EBF0008091C00080648093C000FE1419F00894D6 -:10EC0000C11CD11C0F5F1F4FC80181519F41A0E063 -:10EC1000B0E0ABBFFC01E790FAE2EF1621F022E092 -:10EC20000030120799F60F94DCF10F94DCF182E6C4 -:10EC300092EE60E00F94C2F1C60161E070E00F94C3 -:10EC400034F20F94DCF10F94DCF110920202109276 -:10EC50000302109204021092050278CE89E992EE26 -:10EC600062E00F94F5F1279A2F9A16C02F9880E052 -:10EC700090E0E0EDF7E03197F1F7019684369105E9 -:10EC8000C1F72F9A80E090E0E0EDF7E03197F1F7DF -:10EC9000019684369105C1F78091C00087FFE6CFC9 -:10ECA0008091C00087FFFCCF64C485EA92EE62E0E9 -:10ECB0000F94F5F140910202509103026091040219 -:10ECC0007091050281E020E10F9491F2809102029F -:10ECD00090910302A0910402B091050280509F4FD1 -:10ECE000AF4FBF4F8093020290930302A0930402A0 -:10ECF000B093050280509041A040B04008F426CE69 -:10ED0000A4CF83EB92EE62E00F94F5F140910602FE -:10ED100050910702609108027091090280E020E1A1 -:10ED20000F9491F28091060290910702A09108023F -:10ED3000B091090280509F4FAF4FBF4F80930602A2 -:10ED400090930702A0930802B0930902FFCD80ECD4 -:10ED500092EE62E00F94F5F183E792EE60E00F949B -:10ED6000F5F18FE792EE60E00F94F5F18BE892EE0B -:10ED700060E00F94F5F189E992EE60E00F94F5F10F -:10ED800085EA92EE60E00F94F5F183EB92EE60E09D -:10ED90000F94F5F180EC92EE60E00F94F5F187ECC2 -:10EDA00092EE60E00F94F5F188ED92EE60E00F9442 -:10EDB000F5F18FED92EE60E00F94F5F18AEE92EEB0 -:10EDC00060E00F94F5F183E093EEBDCD87EC92EE19 -:10EDD00062E00F94F5F181E40F947BF282E40F94EA -:10EDE0007BF283E40F947BF284E40F947BF285E45E -:10EDF0000F947BF286E40F947BF287E40F947BF20E -:10EE000088E40F947BF28AE40F947BF28BE40F94F6 -:10EE10007BF28CE40F947BF299CD88ED92EE62E068 -:10EE20000F94F5F1772473948824992409C48FED05 -:10EE300092EE62E00F94F5F140910A0250910B02BC -:10EE400060910C0270910D0282E020E10F9491F22A -:10EE500080910A0290910B02A0910C02B0910D02D8 -:10EE600080509F4FAF4FBF4F80930A0290930B0289 -:10EE7000A0930C02B0930D0269CD8AEE92EE62E08F -:10EE80000F94F5F184EE90EE60E00F94F5F18FECC5 -:10EE900091EE60E00F94F5F1662477244301CC5D98 -:10EEA000DE4F19821882C452D140D401C301B695F5 -:10EEB000A79597958795CA5DDE4F88839983AA8326 -:10EEC000BB83C652D140CC5DDE4FA881B981C4520C -:10EED000D1401196CC5DDE4FB983A883C452D14096 -:10EEE000CD0162E070E00F9434F2B0E2B093C6005E -:10EEF0008091C00086FFFCCF8091C0008064809329 -:10EF0000C000EDE2E093C6008091C00086FFFCCF18 -:10EF10008091C00080648093C000F0E2F093C6004E -:10EF20008091C00086FFFCCF8091C00080648093F8 -:10EF3000C000CA5DDE4FE880F9800A811B81C6529D -:10EF4000D140BB27A12F902F8F2D0F940DF2CA5DBA -:10EF5000DE4F8881C652D1400F940DF2B0E2FB2EF5 -:10EF6000F092C6008091C00086FFFCCF8091C00067 -:10EF700080648093C0000DE30093C6008091C000C0 -:10EF800086FFFCCF8091C00080648093C00010E2B7 -:10EF90001093C6008091C00086FFFCCF8091C00016 -:10EFA00080648093C0008BBEF3012791C65DDE4F65 -:10EFB0002883CA52D140A22EBB24CC24DD2408943D -:10EFC000611C711C811C911C8BBEF3018791282E42 -:10EFD0003324442455240894611C711C811C911C09 -:10EFE0008BBEF3013791C55DDE4F3883CB52D140E4 -:10EFF0000894611C711C811C911C8BBEF30147910C -:10F00000C45DDE4F4883CC52D140ADEFEA2EAFEF66 -:10F01000FA2EAFEF0A2FAFEF1A2F6E0C7F1C801E57 -:10F02000911E142D032DF22CEE24EA0CFB1C0C1D5A -:10F030001D1D0F940DF220E22093C6008091C000A8 -:10F0400086FFFCCF8091C00080648093C000C65DC5 -:10F05000DE4F8881CA52D1400F940DF230E23093D6 -:10F06000C6008091C00086FFFCCF8091C000806404 -:10F070008093C000C45DDE4F8881CC52D1400F9494 -:10F080000DF240E24093C6008091C00086FFFCCFA5 -:10F090008091C00080648093C000C55DDE4F888190 -:10F0A000CB52D1400F940DF250E25093C6008091A4 -:10F0B000C00086FFFCCF8091C00080648093C000B8 -:10F0C0008FEFE8168FEFF80680E0080780E018075A -:10F0D00031F484E092EE60E00F94C2F1DFC0D80119 -:10F0E000C7018070907CA070B0708050904CA040A0 -:10F0F000B040D1F52FEF3FE340E050E0E222F322B1 -:10F1000004231523CA5DDE4FA880B980CA80DB8046 -:10F11000C652D140AE0CBF1CC01ED11EAA0CBB1CD7 -:10F12000CC1CDD1C8EE092EE60E00F94C2F1BB2798 -:10F13000A12F902F8F2D0F940DF28E2D0F940DF285 -:10F1400030E23093C6008091C00086FFFCCF8091F2 -:10F15000C00080648093C0004EE34093C60080915D -:10F16000C00086FFFCCF87C08EE09EEFA0E0B0E03D -:10F17000E822F9220A231B239CE0E91694E9F90608 -:10F1800090E0090790E0190709F088C0C45DDE4FE0 -:10F19000A881CC52D140EA2EFF2400E010E0102FCD -:10F1A0000F2DFE2CEE24C55DDE4FB881CB52D14031 -:10F1B000EB0EF11C011D111DD601C501817090706F -:10F1C000A070B070DC0199278827E80EF91E0A1F8D -:10F1D0001B1F20EF30E040E050E0A222B322C42207 -:10F1E000D52241E1AA0CBB1CCC1CDD1C4A95D1F7F1 -:10F1F000EA0CFB1C0C1D1D1D81E090E0A0E0B0E0BE -:10F20000282239224A225B2235E1220C331C441C7D -:10F21000551C3A95D1F7E20CF31C041D151D57013E -:10F220006801AA0CBB1CCC1CDD1C85E192EE60E0E1 -:10F230000F94C2F1C801AA27BB270F940DF2BB2778 -:10F24000A12F902F8F2D0F940DF28E2D0F940DF274 -:10F2500090E29093C6008091C00086FFFCCF809121 -:10F26000C00080648093C000AEE3A093C60080918C -:10F27000C00086FFFCCF8091C00080648093C000F6 -:10F28000C601AA27BB270F940DF2BB27AD2D9C2DDD -:10F290008B2D0F940DF28A2D0F940DF20F94DCF14B -:10F2A000CC5DDE4FE881F981C452D140F99709F471 -:10F2B0004DCBF4E0EF2EF12C012D112D6E0C7F1CA7 -:10F2C000801E911EF2CD83E093EE62E00F94F5F183 -:10F2D0008AE192EE60E00F94C2F18091C00087FF56 -:10F2E000FCCF1091C6001F751093C6008091C0001E -:10F2F00086FFFCCF8091C00080648093C0000F9493 -:10F30000DCF1812F81548A3108F036C1163409F4BA -:10F3100095C0173490F4133409F44EC0143430F40B -:10F320001134F1F0123409F01DC130C0143409F465 -:10F3300059C0153409F016C16BC01A3409F4C4C0A1 -:10F340001B3438F4173409F48FC0183409F00AC19B -:10F35000A1C01B3409F4D2C01C3409F003C1E8C0B9 -:10F360008FEF81B90DC082B1809582B980E090E0C5 -:10F37000E0EDF7E03197F1F70196883C9105C1F790 -:10F380008091C00087FFEFCF12B8EFC08FEF84B934 -:10F390000DC085B1809585B980E090E0E0EDF7E0A3 -:10F3A0003197F1F70196883C9105C1F78091C00033 -:10F3B00087FFEFCF15B8D9C08FEF87B90DC088B1DF -:10F3C000809588B980E090E0E0EDF7E03197F1F7C3 -:10F3D0000196883C9105C1F78091C00087FFEFCF6F -:10F3E00018B8C3C08FEF8AB90DC08BB180958BB9A7 -:10F3F00080E090E0E0EDF7E03197F1F70196883C8E -:10F400009105C1F78091C00087FFEFCF1BB8ADC059 -:10F410008FEF8DB90DC08EB180958EB980E090E0F0 -:10F42000E0EDF7E03197F1F70196883C9105C1F7DF -:10F430008091C00087FFEFCF1EB897C08FEF80BBD1 -:10F440000DC081B3809581BB80E090E0E0EDF7E0F6 -:10F450003197F1F70196883C9105C1F78091C00082 -:10F4600087FFEFCF11BA81C08FEF83BB0DC084B38C -:10F47000809584BB80E090E0E0EDF7E03197F1F714 -:10F480000196883C9105C1F78091C00087FFEFCFBE -:10F4900014BA6BC08FEF809301010FC080910201FD -:10F4A00080958093020180E090E0E0EDF7E03197F5 -:10F4B000F1F70196883C9105C1F78091C00087FF64 -:10F4C000EDCF1092020151C08FEF809304010FC065 -:10F4D0008091050180958093050180E090E0E0ED4A -:10F4E000F7E03197F1F70196883C9105C1F78091DB -:10F4F000C00087FFEDCF1092050137C08FEF8093DA -:10F5000007010FC08091080180958093080180E079 -:10F5100090E0E0EDF7E03197F1F70196883C910536 -:10F52000C1F78091C00087FFEDCF109208011DC088 -:10F530008FEF80930A010FC080910B01809580931B -:10F540000B0180E090E0E0EDF7E03197F1F70196F4 -:10F55000883C9105C1F78091C00087FFEDCF1092E4 -:10F560000B0103C085E292EEEEC98091C00087FFD7 -:10F57000FCCF8091C600EAC988E392EEE4C98CE131 -:10F5800091EEE1C988249924933011F1943028F444 -:10F59000913089F09230B8F408C0953061F195301F -:10F5A000F0F0963009F048C043C02B3109F042C951 -:10F5B00091E06BE13FC96227C15DDE4F2883CF52E6 -:10F5C000D14092E037C9B22FA0E0622793E032C960 -:10F5D000822F90E0A82BB92B622794E02BC92E3004 -:10F5E00009F039C3622795E0C05DDE4F19821882A9 -:10F5F000C053D1401FC9E1E0F0E0EC0FFD1FC05D3A -:10F60000DE4F08811981C053D140E00FF11F2083E4 -:10F610000F5F1F4FC05DDE4F19830883C053D14079 -:10F6200062270A171B0709F005C9D80196E002C92D -:10F63000261709F010C303C0973009F0FBC87724E0 -:10F640009981933109F412C19431C8F4963009F4C8 -:10F65000D8C0973050F4923009F406C1933009F4C1 -:10F660006DC0913009F059C253C0913109F477C08F -:10F67000923108F0BBC0903109F04FC2F5C098310B -:10F6800009F487C0993150F4953109F4EFC09531F0 -:10F6900008F4C6C1963109F040C2C2C19A3109F4DA -:10F6A0006CC09A3108F491C09B3109F45BC09D3164 -:10F6B00009F033C29D81903359F48F81882311F46E -:10F6C0009EE11CC0813011F091E018C098E916C08D -:10F6D000892F807591F0903539F4E0E0F0E089E011 -:10F6E0008093570094910AC0983539F4E3E0F0E034 -:10F6F00089E080935700949101C090E01A821B82A8 -:10F700008D818C831D829E831F8227E030E009C299 -:10F710001A8288E08B8381E48C8386E58D8382E581 -:10F720008E8389E48F8383E5888780E589878FE5E9 -:10F730008A8782E38B872BE030E0F3C18A818139AD -:10F7400041F0823941F0803911F48FE005C080E04A -:10F7500003C082E001C08AE01A828B8344C0772410 -:10F76000739482C08D81882311F48EE12CC0813086 -:10F7700011F081E028C088E926C01A82E1E0F0E0BB -:10F7800089E08093570084918B831C8224E030E0D1 -:10F79000C8C18B81803589F48C81883039F4E2E0EE -:10F7A000F0E089E08093570084910DC0E0E0F0E044 -:10F7B00089E080935700849106C0E3E0F0E089E09F -:10F7C0008093570084911A82DFCF8D81836C99E0FA -:10F7D000E1E0F0E0082E90935700E89507B600FCB2 -:10F7E000FDCF1A821B8223E030E09BC180EC8A832C -:10F7F000CE5CDE4F188219821A821B82C253D1401E -:10F800008EC18A8190E0A0E0B0E0582F44273327D2 -:10F8100022278B8190E0A0E0B0E0DC0199278827C7 -:10F82000282B392B4A2B5B2B8D8190E0A0E0B0E098 -:10F83000282B392B4A2B5B2B8C8190E0A0E0B0E089 -:10F84000BA2FA92F982F8827282B392B4A2B5B2BCF -:10F85000220F331F441F551FC05EDE4F288339839C -:10F860004A835B83C052D1401A8259C13A81C95C34 -:10F87000DE4F3883C753D140CA5CDE4F1882C6536F -:10F88000D1408B81C82EDD24CA5CDE4F488159816E -:10F89000C653D140C42AD52A933109F082C0CE5C28 -:10F8A000DE4F88819981AA81BB81C253D1408050AB -:10F8B000904CA340B04030F583E0CE5CDE4FE88052 -:10F8C000F9800A811B81C253D140F70100935B008C -:10F8D00080935700E89507B600FCFDCFCE5CDE4F65 -:10F8E000088119812A813B81C253D14000501F4FAA -:10F8F0002F4F3F4FCE5CDE4F088319832A833B8313 -:10F90000C253D140C05EDE4F488159816A817B81FC -:10F91000C052D140DE011B9631E08C9111962C91A2 -:10F9200011971296C75CDE4F2883C953D140C85C3B -:10F93000DE4F1882C853D14090E0C85CDE4FE881AA -:10F94000F981C853D1408E2B9F2B0C01FA01609393 -:10F950005B0030935700E89511244E5F5F4F6F4F67 -:10F960007F4F0EEFE02E0FEFF02ECE0CDF1CC114F8 -:10F97000D10499F685E0C05EDE4F088119812A81A5 -:10F980003B81C052D140F80120935B008093570027 -:10F99000E89507B600FCFDCF81E180935700E8951C -:10F9A00035C0C05EDE4F88819981AA81BB81C0527B -:10F9B000D140B695A795979587957C018601ABE0D8 -:10F9C000AA2EB12CAC0EBD1E0BC0D5016D915D01F0 -:10F9D000C7010F947FFE0894E11CF11C01501040F8 -:10F9E0000115110591F7A60160E070E0440F551F65 -:10F9F000661F771FC05EDE4FE880F9800A811B8199 -:10FA0000C052D1404E0D5F1D601F711F1A82C05E33 -:10FA1000DE4F488359836A837B83C052D1407FC0C5 -:10FA2000FA80C55CDE4FF882CB53D140C65CDE4F16 -:10FA30001882CA53D1408B81C82EDD24C65CDE4FAC -:10FA400008811981CA53D140C02AD12A1A828981DA -:10FA5000BE016D5F7F4F843121F59601C05EDE4FA0 -:10FA6000E880F9800A811B81C052D1400BBFF701A9 -:10FA700087919691DB018C9311969C936E5F7F4FDB -:10FA8000D801C7010296A11DB11DC05EDE4F88835B -:10FA90009983AA83BB83C052D14022503040F1F6F3 -:10FAA00036C0C05EDE4F288139814A815B81C052F9 -:10FAB000D1400894C108D108760100E010E0089414 -:10FAC000C11CD11C0894E11CF11C011D111DE20E8A -:10FAD000F31E041F151F21BDBB27A52F942F832FB5 -:10FAE00082BD2F5F3F4F4F4F5F4FF89A80B5DB01CC -:10FAF0008D93BD012E153F054007510761F7C05E8C -:10FB0000DE4F288339834A835B83C052D1409601FC -:10FB10002D5F3F4FFB01108204C080EC8A8322E0FE -:10FB200030E08BE18093C6008091C00086FFFCCF5F -:10FB30008091C00080648093C000C15DDE4FF88179 -:10FB4000CF52D140F093C6008091C00086FFFCCF19 -:10FB50008091C00080648093C000432F3093C60022 -:10FB60008091C00086FFFCCF8091C00080648093AC -:10FB7000C000922F2093C6008091C00086FFFCCF6A -:10FB80008091C00080648093C0008EE08093C600A6 -:10FB90008091C00086FFFCCF8091C000806480937C -:10FBA000C00065E1C15DDE4FE880CF52D1406E25D7 -:10FBB00069276427FE01319610C090819093C6009A -:10FBC0008091C00086FFFCCF31968091C000806498 -:10FBD0008093C0006927215030402115310569F715 -:10FBE0006093C6008091C00086FFFCCF8091C0006A -:10FBF00080648093C00085B1805885B9772081F4F6 -:10FC0000C15DDE4F0881CF52D1400F5FC15DDE4F35 -:10FC10000883CF52D14090E0A0E0B0E00D941AF4F8 -:10FC200027982F9880E090E020ED37E0F901319798 -:10FC3000F1F7019684369105C9F700008091C00064 -:10FC40008D7F8093C00081E180935700E895EE2777 -:10FC5000FF270994FFCF90E00D941AF497FB092E2B -:10FC600007260AD077FD04D02ED006D000201AF443 -:10FC7000709561957F4F0895F6F7909581959F4F08 -:10FC80000895A1E21A2EAA1BBB1BFD010DC0AA1FDD -:10FC9000BB1FEE1FFF1FA217B307E407F50720F0F5 -:10FCA000A21BB30BE40BF50B661F771F881F991F70 -:10FCB0001A9469F760957095809590959B01AC01B9 -:10FCC000BD01CF010895AA1BBB1B51E107C0AA1FAC -:10FCD000BB1FA617B70710F0A61BB70B881F991FED -:10FCE0005A95A9F780959095BC01CD010895F99991 -:10FCF000FECF92BD81BDF89A992780B50895262F31 -:10FD0000F999FECF1FBA92BD81BD20BD0FB6F89400 -:0EFD1000FA9AF99A0FBE01960895F894FFCF63 -:040000033000E000E9 -:00000001FF diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp b/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp deleted file mode 100644 index af14e07b..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "SPI.h" - -SPIClass SPI; - -uint8_t SPIClass::initialized = 0; -uint8_t SPIClass::interruptMode = 0; -uint8_t SPIClass::interruptMask = 0; -uint8_t SPIClass::interruptSave = 0; -#ifdef SPI_TRANSACTION_MISMATCH_LED -uint8_t SPIClass::inTransactionFlag = 0; -#endif - -void SPIClass::begin() -{ - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - if (!initialized) { - // Set SS to high so a connected chip will be "deselected" by default - uint8_t port = digitalPinToPort(SS); - uint8_t bit = digitalPinToBitMask(SS); - volatile uint8_t *reg = portModeRegister(port); - - // if the SS pin is not already configured as an output - // then set it high (to enable the internal pull-up resistor) - if(!(*reg & bit)){ - digitalWrite(SS, HIGH); - } - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); - } - initialized++; // reference count - SREG = sreg; -} - -void SPIClass::end() { - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - // Decrease the reference counter - if (initialized) - initialized--; - // If there are no more references disable SPI - if (!initialized) { - SPCR &= ~_BV(SPE); - interruptMode = 0; - #ifdef SPI_TRANSACTION_MISMATCH_LED - inTransactionFlag = 0; - #endif - } - SREG = sreg; -} - -// mapping of interrupt numbers to bits within SPI_AVR_EIMSK -#if defined(__AVR_ATmega32U4__) - #define SPI_INT0_MASK (1< - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include - -// SPI_HAS_TRANSACTION means SPI has beginTransaction(), endTransaction(), -// usingInterrupt(), and SPISetting(clock, bitOrder, dataMode) -#define SPI_HAS_TRANSACTION 1 - -// SPI_HAS_NOTUSINGINTERRUPT means that SPI has notUsingInterrupt() method -#define SPI_HAS_NOTUSINGINTERRUPT 1 - -// SPI_ATOMIC_VERSION means that SPI has atomicity fixes and what version. -// This way when there is a bug fix you can check this define to alert users -// of your code if it uses better version of this library. -// This also implies everything that SPI_HAS_TRANSACTION as documented above is -// available too. -#define SPI_ATOMIC_VERSION 1 - -// Uncomment this line to add detection of mismatched begin/end transactions. -// A mismatch occurs if other libraries fail to use SPI.endTransaction() for -// each SPI.beginTransaction(). Connect an LED to this pin. The LED will turn -// on if any mismatch is ever detected. -//#define SPI_TRANSACTION_MISMATCH_LED 5 - -#ifndef LSBFIRST -#define LSBFIRST 0 -#endif -#ifndef MSBFIRST -#define MSBFIRST 1 -#endif - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -// define SPI_AVR_EIMSK for AVR boards with external interrupt pins -#if defined(EIMSK) - #define SPI_AVR_EIMSK EIMSK -#elif defined(GICR) - #define SPI_AVR_EIMSK GICR -#elif defined(GIMSK) - #define SPI_AVR_EIMSK GIMSK -#endif - -class SPISettings { -public: - SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - if (__builtin_constant_p(clock)) { - init_AlwaysInline(clock, bitOrder, dataMode); - } else { - init_MightInline(clock, bitOrder, dataMode); - } - } - SPISettings() { - init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); - } -private: - void init_MightInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - init_AlwaysInline(clock, bitOrder, dataMode); - } - void init_AlwaysInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) - __attribute__((__always_inline__)) { - // Clock settings are defined as follows. Note that this shows SPI2X - // inverted, so the bits form increasing numbers. Also note that - // fosc/64 appears twice - // SPR1 SPR0 ~SPI2X Freq - // 0 0 0 fosc/2 - // 0 0 1 fosc/4 - // 0 1 0 fosc/8 - // 0 1 1 fosc/16 - // 1 0 0 fosc/32 - // 1 0 1 fosc/64 - // 1 1 0 fosc/64 - // 1 1 1 fosc/128 - - // We find the fastest clock that is less than or equal to the - // given clock rate. The clock divider that results in clock_setting - // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the - // slowest (128 == 2 ^^ 7, so clock_div = 6). - uint8_t clockDiv; - - // When the clock is known at compiletime, use this if-then-else - // cascade, which the compiler knows how to completely optimize - // away. When clock is not known, use a loop instead, which generates - // shorter code. - if (__builtin_constant_p(clock)) { - if (clock >= F_CPU / 2) { - clockDiv = 0; - } else if (clock >= F_CPU / 4) { - clockDiv = 1; - } else if (clock >= F_CPU / 8) { - clockDiv = 2; - } else if (clock >= F_CPU / 16) { - clockDiv = 3; - } else if (clock >= F_CPU / 32) { - clockDiv = 4; - } else if (clock >= F_CPU / 64) { - clockDiv = 5; - } else { - clockDiv = 6; - } - } else { - uint32_t clockSetting = F_CPU / 2; - clockDiv = 0; - while (clockDiv < 6 && clock < clockSetting) { - clockSetting /= 2; - clockDiv++; - } - } - - // Compensate for the duplicate fosc/64 - if (clockDiv == 6) - clockDiv = 7; - - // Invert the SPI2X bit - clockDiv ^= 0x1; - - // Pack into the SPISettings class - spcr = _BV(SPE) | _BV(MSTR) | ((bitOrder == LSBFIRST) ? _BV(DORD) : 0) | - (dataMode & SPI_MODE_MASK) | ((clockDiv >> 1) & SPI_CLOCK_MASK); - spsr = clockDiv & SPI_2XCLOCK_MASK; - } - uint8_t spcr; - uint8_t spsr; - friend class SPIClass; -}; - - -class SPIClass { -public: - // Initialize the SPI library - static void begin(); - - // If SPI is used from within an interrupt, this function registers - // that interrupt with the SPI library, so beginTransaction() can - // prevent conflicts. The input interruptNumber is the number used - // with attachInterrupt. If SPI is used from a different interrupt - // (eg, a timer), interruptNumber should be 255. - static void usingInterrupt(uint8_t interruptNumber); - // And this does the opposite. - static void notUsingInterrupt(uint8_t interruptNumber); - // Note: the usingInterrupt and notUsingInterrupt functions should - // not to be called from ISR context or inside a transaction. - // For details see: - // https://github.com/arduino/Arduino/pull/2381 - // https://github.com/arduino/Arduino/pull/2449 - - // Before using SPI.transfer() or asserting chip select pins, - // this function is used to gain exclusive access to the SPI bus - // and configure the correct settings. - inline static void beginTransaction(SPISettings settings) { - if (interruptMode > 0) { - uint8_t sreg = SREG; - noInterrupts(); - - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - interruptSave = SPI_AVR_EIMSK; - SPI_AVR_EIMSK &= ~interruptMask; - SREG = sreg; - } else - #endif - { - interruptSave = sreg; - } - } - - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 1; - #endif - - SPCR = settings.spcr; - SPSR = settings.spsr; - } - - // Write to the SPI bus (MOSI pin) and also receive (MISO pin) - inline static uint8_t transfer(uint8_t data) { - SPDR = data; - /* - * The following NOP introduces a small delay that can prevent the wait - * loop form iterating when running at the maximum speed. This gives - * about 10% more speed, even if it seems counter-intuitive. At lower - * speeds it is unnoticed. - */ - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; // wait - return SPDR; - } - inline static uint16_t transfer16(uint16_t data) { - union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; - in.val = data; - if (!(SPCR & _BV(DORD))) { - SPDR = in.msb; - asm volatile("nop"); // See transfer(uint8_t) function - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - } else { - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - SPDR = in.msb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - } - return out.val; - } - inline static void transfer(void *buf, size_t count) { - if (count == 0) return; - uint8_t *p = (uint8_t *)buf; - SPDR = *p; - while (--count > 0) { - uint8_t out = *(p + 1); - while (!(SPSR & _BV(SPIF))) ; - uint8_t in = SPDR; - SPDR = out; - *p++ = in; - } - while (!(SPSR & _BV(SPIF))) ; - *p = SPDR; - } - // After performing a group of transfers and releasing the chip select - // signal, this function allows others to access the SPI bus - inline static void endTransaction(void) { - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (!inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 0; - #endif - - if (interruptMode > 0) { - #ifdef SPI_AVR_EIMSK - uint8_t sreg = SREG; - #endif - noInterrupts(); - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - SPI_AVR_EIMSK = interruptSave; - SREG = sreg; - } else - #endif - { - SREG = interruptSave; - } - } - } - - // Disable the SPI bus - static void end(); - - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setBitOrder(uint8_t bitOrder) { - if (bitOrder == LSBFIRST) SPCR |= _BV(DORD); - else SPCR &= ~(_BV(DORD)); - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setDataMode(uint8_t dataMode) { - SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode; - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setClockDivider(uint8_t clockDiv) { - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK); - } - // These undocumented functions should not be used. SPI.transfer() - // polls the hardware flag which is automatically cleared as the - // AVR responds to SPI's interrupt - inline static void attachInterrupt() { SPCR |= _BV(SPIE); } - inline static void detachInterrupt() { SPCR &= ~_BV(SPIE); } - -private: - static uint8_t initialized; - static uint8_t interruptMode; // 0=none, 1=mask, 2=global - static uint8_t interruptMask; // which interrupts to mask - static uint8_t interruptSave; // temp storage, to restore state - #ifdef SPI_TRANSACTION_MISMATCH_LED - static uint8_t inTransactionFlag; - #endif -}; - -extern SPIClass SPI; - -#endif diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino b/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino deleted file mode 100644 index 8104fcbc..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino +++ /dev/null @@ -1,143 +0,0 @@ -/* - SCP1000 Barometric Pressure Sensor Display - - Shows the output of a Barometric Pressure Sensor on a - Uses the SPI library. For details on the sensor, see: - http://www.sparkfun.com/commerce/product_info.php?products_id=8161 - http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ - - This sketch adapted from Nathan Seidle's SCP1000 example for PIC: - http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip - - Circuit: - SCP1000 sensor attached to pins 6, 7, 10 - 13: - DRDY: pin 6 - CSB: pin 7 - MOSI: pin 11 - MISO: pin 12 - SCK: pin 13 - - created 31 July 2010 - modified 14 August 2010 - by Tom Igoe - */ - -// the sensor communicates using SPI, so include the library: -#include - -//Sensor's memory register addresses: -const int PRESSURE = 0x1F; //3 most significant bits of pressure -const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure -const int TEMPERATURE = 0x21; //16 bit temperature reading -const byte READ = 0b11111100; // SCP1000's read command -const byte WRITE = 0b00000010; // SCP1000's write command - -// pins used for the connection with the sensor -// the other you need are controlled by the SPI library): -const int dataReadyPin = 6; -const int chipSelectPin = 7; - -void setup() { - Serial.begin(9600); - - // start the SPI library: - SPI.begin(); - - // initalize the data ready and chip select pins: - pinMode(dataReadyPin, INPUT); - pinMode(chipSelectPin, OUTPUT); - - //Configure SCP1000 for low noise configuration: - writeRegister(0x02, 0x2D); - writeRegister(0x01, 0x03); - writeRegister(0x03, 0x02); - // give the sensor time to set up: - delay(100); -} - -void loop() { - //Select High Resolution Mode - writeRegister(0x03, 0x0A); - - // don't do anything until the data ready pin is high: - if (digitalRead(dataReadyPin) == HIGH) { - //Read the temperature data - int tempData = readRegister(0x21, 2); - - // convert the temperature to celsius and display it: - float realTemp = (float)tempData / 20.0; - Serial.print("Temp[C]="); - Serial.print(realTemp); - - - //Read the pressure data highest 3 bits: - byte pressure_data_high = readRegister(0x1F, 1); - pressure_data_high &= 0b00000111; //you only needs bits 2 to 0 - - //Read the pressure data lower 16 bits: - unsigned int pressure_data_low = readRegister(0x20, 2); - //combine the two parts into one 19-bit number: - long pressure = ((pressure_data_high << 16) | pressure_data_low) / 4; - - // display the temperature: - Serial.println("\tPressure [Pa]=" + String(pressure)); - } -} - -//Read from or write to register from the SCP1000: -unsigned int readRegister(byte thisRegister, int bytesToRead ) { - byte inByte = 0; // incoming byte from the SPI - unsigned int result = 0; // result to return - Serial.print(thisRegister, BIN); - Serial.print("\t"); - // SCP1000 expects the register name in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the address and the command into one byte - byte dataToSend = thisRegister & READ; - Serial.println(thisRegister, BIN); - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - // send the device the register you want to read: - SPI.transfer(dataToSend); - // send a value of 0 to read the first byte returned: - result = SPI.transfer(0x00); - // decrement the number of bytes left to read: - bytesToRead--; - // if you still have another byte to read: - if (bytesToRead > 0) { - // shift the first byte left, then get the second byte: - result = result << 8; - inByte = SPI.transfer(0x00); - // combine the byte you just got with the previous one: - result = result | inByte; - // decrement the number of bytes left to read: - bytesToRead--; - } - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); - // return the result: - return(result); -} - - -//Sends a write command to SCP1000 - -void writeRegister(byte thisRegister, byte thisValue) { - - // SCP1000 expects the register address in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the register address and the command into one byte: - byte dataToSend = thisRegister | WRITE; - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - - SPI.transfer(dataToSend); //Send register location - SPI.transfer(thisValue); //Send value to record into register - - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); -} - diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino b/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino deleted file mode 100644 index b135a74f..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Digital Pot Control - - This example controls an Analog Devices AD5206 digital potentiometer. - The AD5206 has 6 potentiometer channels. Each channel's pins are labeled - A - connect this to voltage - W - this is the pot's wiper, which changes when you set it - B - connect this to ground. - - The AD5206 is SPI-compatible,and to command it, you send two bytes, - one with the channel number (0 - 5) and one with the resistance value for the - channel (0 - 255). - - The circuit: - * All A pins of AD5206 connected to +5V - * All B pins of AD5206 connected to ground - * An LED and a 220-ohm resisor in series connected from each W pin to ground - * CS - to digital pin 10 (SS pin) - * SDI - to digital pin 11 (MOSI pin) - * CLK - to digital pin 13 (SCK pin) - - created 10 Aug 2010 - by Tom Igoe - - Thanks to Heather Dewey-Hagborg for the original tutorial, 2005 - -*/ - - -// inslude the SPI library: -#include - - -// set pin 10 as the slave select for the digital pot: -const int slaveSelectPin = 10; - -void setup() { - // set the slaveSelectPin as an output: - pinMode (slaveSelectPin, OUTPUT); - // initialize SPI: - SPI.begin(); -} - -void loop() { - // go through the six channels of the digital pot: - for (int channel = 0; channel < 6; channel++) { - // change the resistance on this channel from min to max: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, level); - delay(10); - } - // wait a second at the top: - delay(100); - // change the resistance on this channel from max to min: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, 255 - level); - delay(10); - } - } - -} - -void digitalPotWrite(int address, int value) { - // take the SS pin low to select the chip: - digitalWrite(slaveSelectPin, LOW); - // send in the address and value via SPI: - SPI.transfer(address); - SPI.transfer(value); - // take the SS pin high to de-select the chip: - digitalWrite(slaveSelectPin, HIGH); -} diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt b/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt deleted file mode 100644 index fa761658..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SPI KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 -transfer KEYWORD2 -setBitOrder KEYWORD2 -setDataMode KEYWORD2 -setClockDivider KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -SPI_CLOCK_DIV4 LITERAL1 -SPI_CLOCK_DIV16 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_CLOCK_DIV128 LITERAL1 -SPI_CLOCK_DIV2 LITERAL1 -SPI_CLOCK_DIV8 LITERAL1 -SPI_CLOCK_DIV32 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_MODE0 LITERAL1 -SPI_MODE1 LITERAL1 -SPI_MODE2 LITERAL1 -SPI_MODE3 LITERAL1 \ No newline at end of file diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties b/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties deleted file mode 100644 index 07af8696..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=SPI -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE. -paragraph= -url=http://arduino.cc/en/Reference/SPI -architectures=avr -types=Arduino - diff --git a/test/user_hardware/my_avr_platform/avr/platform.txt b/test/user_hardware/my_avr_platform/avr/platform.txt deleted file mode 100644 index cc0be0a0..00000000 --- a/test/user_hardware/my_avr_platform/avr/platform.txt +++ /dev/null @@ -1,9 +0,0 @@ - -# Arduino AVR Core and platform. -# ------------------------------ - -# For more info: -# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification - -name=My AVR Boards -version=9.9.9 \ No newline at end of file diff --git a/test/user_hardware/my_avr_platform/platform.txt b/test/user_hardware/my_avr_platform/platform.txt deleted file mode 100644 index 4c1664e5..00000000 --- a/test/user_hardware/my_avr_platform/platform.txt +++ /dev/null @@ -1 +0,0 @@ -example=hello world diff --git a/test/user_hardware/my_symlinked_avr_platform b/test/user_hardware/my_symlinked_avr_platform deleted file mode 120000 index 8f67ba7e..00000000 --- a/test/user_hardware/my_symlinked_avr_platform +++ /dev/null @@ -1 +0,0 @@ -my_avr_platform \ No newline at end of file diff --git a/test/utils_test.go b/test/utils_test.go deleted file mode 100644 index 6ada0c29..00000000 --- a/test/utils_test.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "strings" - "testing" -) - -func TestCommandLineParser(t *testing.T) { - command := "\"/home/federico/materiale/works_Arduino/Arduino/build/hardware/tools/coan\" source -m -E -P -kb -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=010600 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 '-DUSB_MANUFACTURER=' '-DUSB_PRODUCT=\"Arduino Leonardo\"' \"/tmp/sketch321469072.cpp\"" - - parts, err := utils.ParseCommandLine(command, i18n.HumanLogger{}) - NoError(t, err) - - require.Equal(t, 23, len(parts)) - - require.Equal(t, "/home/federico/materiale/works_Arduino/Arduino/build/hardware/tools/coan", parts[0]) - require.Equal(t, "source", parts[1]) - require.Equal(t, "-m", parts[2]) - require.Equal(t, "-E", parts[3]) - require.Equal(t, "-P", parts[4]) - require.Equal(t, "-kb", parts[5]) - require.Equal(t, "-c", parts[6]) - require.Equal(t, "-g", parts[7]) - require.Equal(t, "-Os", parts[8]) - require.Equal(t, "-w", parts[9]) - require.Equal(t, "-ffunction-sections", parts[10]) - require.Equal(t, "-fdata-sections", parts[11]) - require.Equal(t, "-MMD", parts[12]) - require.Equal(t, "-mmcu=atmega32u4", parts[13]) - require.Equal(t, "-DF_CPU=16000000L", parts[14]) - require.Equal(t, "-DARDUINO=010600", parts[15]) - require.Equal(t, "-DARDUINO_AVR_LEONARDO", parts[16]) - require.Equal(t, "-DARDUINO_ARCH_AVR", parts[17]) - require.Equal(t, "-DUSB_VID=0x2341", parts[18]) - require.Equal(t, "-DUSB_PID=0x8036", parts[19]) - require.Equal(t, "-DUSB_MANUFACTURER=", parts[20]) - require.Equal(t, "-DUSB_PRODUCT=\"Arduino Leonardo\"", parts[21]) - require.Equal(t, "/tmp/sketch321469072.cpp", parts[22]) -} - -func TestPrintableCommand(t *testing.T) { - parts := []string{ - "/path/to/dir with spaces/cmd", - "arg1", - "arg-\"with\"-quotes", - "specialchar-`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?-argument", - "arg with spaces", - "arg\twith\t\ttabs", - "lastarg", - } - correct := "\"/path/to/dir with spaces/cmd\"" + - " arg1 \"arg-\\\"with\\\"-quotes\"" + - " \"specialchar-`~!@#$%^&*()-_=+[{]}\\\\|;:'\\\",<.>/?-argument\"" + - " \"arg with spaces\" \"arg\twith\t\ttabs\"" + - " lastarg" - result := utils.PrintableCommand(parts) - require.Equal(t, correct, result) -} - -func TestCommandLineParserError(t *testing.T) { - command := "\"command missing quote" - - _, err := utils.ParseCommandLine(command, i18n.HumanLogger{}) - require.Error(t, err) -} - -func TestMapTrimSpace(t *testing.T) { - value := "hello, world , how are,you? " - parts := utils.Map(strings.Split(value, ","), utils.TrimSpace) - - require.Equal(t, 4, len(parts)) - require.Equal(t, "hello", parts[0]) - require.Equal(t, "world", parts[1]) - require.Equal(t, "how are", parts[2]) - require.Equal(t, "you?", parts[3]) -} - -func TestQuoteCppString(t *testing.T) { - cases := map[string]string{ - `foo`: `"foo"`, - `foo\bar`: `"foo\\bar"`, - `foo "is" quoted and \\bar"" escaped\`: `"foo \"is\" quoted and \\\\bar\"\" escaped\\"`, - // ASCII 0x20 - 0x7e, excluding ` - ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~`: `" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~"`, - } - for input, expected := range cases { - require.Equal(t, expected, utils.QuoteCppString(input)) - } -} - -func TestParseCppString(t *testing.T) { - str, rest, ok := utils.ParseCppString(`foo`) - require.Equal(t, false, ok) - - str, rest, ok = utils.ParseCppString(`"foo`) - require.Equal(t, false, ok) - - str, rest, ok = utils.ParseCppString(`"foo"`) - require.Equal(t, true, ok) - require.Equal(t, `foo`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"foo\\bar"`) - require.Equal(t, true, ok) - require.Equal(t, `foo\bar`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"foo \"is\" quoted and \\\\bar\"\" escaped\\" and "then" some`) - require.Equal(t, true, ok) - require.Equal(t, `foo "is" quoted and \\bar"" escaped\`, str) - require.Equal(t, ` and "then" some`, rest) - - str, rest, ok = utils.ParseCppString(`" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~"`) - require.Equal(t, true, ok) - require.Equal(t, ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"/home/ççç/"`) - require.Equal(t, true, ok) - require.Equal(t, `/home/ççç/`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"/home/ççç/ /$sdsdd\\"`) - require.Equal(t, true, ok) - require.Equal(t, `/home/ççç/ /$sdsdd\`, str) - require.Equal(t, ``, rest) -} diff --git a/test/wipeout_build_path_if_build_options_changed_test.go b/test/wipeout_build_path_if_build_options_changed_test.go deleted file mode 100644 index 51bfe80d..00000000 --- a/test/wipeout_build_path_if_build_options_changed_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" -) - -func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - ctx.BuildOptionsJsonPrevious = "{ \"old\":\"old\" }" - ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - - utils.TouchFile(filepath.Join(buildPath, "should_be_deleted.txt")) - - commands := []types.Command{ - &builder.WipeoutBuildPathIfBuildOptionsChanged{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - _, err := os.Stat(buildPath) - NoError(t, err) - - files, err := gohasissues.ReadDir(buildPath) - NoError(t, err) - require.Equal(t, 0, len(files)) - - _, err = os.Stat(filepath.Join(buildPath, "should_be_deleted.txt")) - require.Error(t, err) -} - -func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) - - ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - - utils.TouchFile(filepath.Join(buildPath, "should_not_be_deleted.txt")) - - commands := []types.Command{ - &builder.WipeoutBuildPathIfBuildOptionsChanged{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - _, err := os.Stat(buildPath) - NoError(t, err) - - files, err := gohasissues.ReadDir(buildPath) - NoError(t, err) - require.Equal(t, 1, len(files)) - - _, err = os.Stat(filepath.Join(buildPath, "should_not_be_deleted.txt")) - NoError(t, err) -} diff --git a/tools_loader.go b/tools_loader.go deleted file mode 100644 index 8fd3241d..00000000 --- a/tools_loader.go +++ /dev/null @@ -1,208 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type ToolsLoader struct{} - -func (s *ToolsLoader) Run(ctx *types.Context) error { - folders := ctx.ToolsFolders - - tools := []*types.Tool{} - - if ctx.CanUseCachedTools { - //fmt.Println("no fs modification, can use cached ctx") - return nil - } - - for _, folder := range folders { - builtinToolsVersionsFile, err := findBuiltinToolsVersionsFile(folder) - if err != nil { - return i18n.WrapError(err) - } - builtinHardwareFolder := "" - if len(ctx.BuiltInLibrariesFolders) > 0 { - builtinHardwareFolder, err = filepath.Abs(filepath.Join(ctx.BuiltInLibrariesFolders[0], "..")) - } - - if builtinToolsVersionsFile != constants.EMPTY_STRING && !strings.Contains(builtinToolsVersionsFile, builtinHardwareFolder) { - ctx.GetLogger().Println(constants.LOG_LEVEL_WARN, constants.MSG_IGNORED_BUILTIN_TOOLS_TXT, builtinToolsVersionsFile) - builtinToolsVersionsFile = constants.EMPTY_STRING - } - - if builtinToolsVersionsFile != constants.EMPTY_STRING { - err = loadToolsFrom(&tools, builtinToolsVersionsFile) - if err != nil { - return i18n.WrapError(err) - } - } else { - subfolders, err := collectAllToolsFolders(folder) - if err != nil { - return i18n.WrapError(err) - } - - for _, subfolder := range subfolders { - err = loadToolsFromFolderStructure(&tools, subfolder) - if err != nil { - return i18n.WrapError(err) - } - } - } - } - - ctx.CanUseCachedTools = true - - ctx.Tools = tools - - return nil -} - -func collectAllToolsFolders(from string) ([]string, error) { - folders := []string{} - walkFunc := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return nil - } - - if !info.IsDir() { - return nil - } - - rel, err := filepath.Rel(from, currentPath) - if err != nil { - return i18n.WrapError(err) - } - depth := len(strings.Split(rel, string(os.PathSeparator))) - - if info.Name() == constants.FOLDER_TOOLS && depth == 2 { - folders = append(folders, currentPath) - } else if depth > 2 { - return filepath.SkipDir - } - - return nil - } - err := gohasissues.Walk(from, walkFunc) - - if len(folders) == 0 { - folders = append(folders, from) - } - - return folders, i18n.WrapError(err) -} - -func toolsSliceContains(tools *[]*types.Tool, name, version string) bool { - for _, tool := range *tools { - if name == tool.Name && version == tool.Version { - return true - } - } - return false -} - -func loadToolsFrom(tools *[]*types.Tool, builtinToolsVersionsFilePath string) error { - rows, err := utils.ReadFileToRows(builtinToolsVersionsFilePath) - if err != nil { - return i18n.WrapError(err) - } - - folder, err := filepath.Abs(filepath.Dir(builtinToolsVersionsFilePath)) - if err != nil { - return i18n.WrapError(err) - } - - for _, row := range rows { - row = strings.TrimSpace(row) - if row != constants.EMPTY_STRING { - rowParts := strings.Split(row, "=") - toolName := strings.Split(rowParts[0], ".")[1] - toolVersion := rowParts[1] - if !toolsSliceContains(tools, toolName, toolVersion) { - *tools = append(*tools, &types.Tool{Name: toolName, Version: toolVersion, Folder: folder}) - } - } - } - - return nil -} - -func findBuiltinToolsVersionsFile(folder string) (string, error) { - builtinToolsVersionsFilePath := constants.EMPTY_STRING - findBuiltInToolsVersionsTxt := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return nil - } - - if builtinToolsVersionsFilePath != constants.EMPTY_STRING { - return nil - } - if filepath.Base(currentPath) == constants.FILE_BUILTIN_TOOLS_VERSIONS_TXT { - builtinToolsVersionsFilePath = currentPath - } - return nil - } - err := gohasissues.Walk(folder, findBuiltInToolsVersionsTxt) - return builtinToolsVersionsFilePath, i18n.WrapError(err) -} - -func loadToolsFromFolderStructure(tools *[]*types.Tool, folder string) error { - toolsNames, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - for _, toolName := range toolsNames { - toolVersions, err := utils.ReadDirFiltered(filepath.Join(folder, toolName.Name()), utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - for _, toolVersion := range toolVersions { - toolFolder, err := filepath.Abs(filepath.Join(folder, toolName.Name(), toolVersion.Name())) - if err != nil { - return i18n.WrapError(err) - } - if !toolsSliceContains(tools, toolName.Name(), toolVersion.Name()) { - *tools = append(*tools, &types.Tool{Name: toolName.Name(), Version: toolVersion.Name(), Folder: toolFolder}) - } - } - } - - return nil -} diff --git a/types/accessories.go b/types/accessories.go deleted file mode 100644 index 4c87c30c..00000000 --- a/types/accessories.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -import ( - "bytes" - "sync" -) - -type UniqueStringQueue []string - -func (queue UniqueStringQueue) Len() int { return len(queue) } -func (queue UniqueStringQueue) Less(i, j int) bool { return false } -func (queue UniqueStringQueue) Swap(i, j int) { panic("Who called me?!?") } - -func (queue *UniqueStringQueue) Push(value string) { - if !sliceContains(*queue, value) { - *queue = append(*queue, value) - } -} - -func (queue *UniqueStringQueue) Pop() interface{} { - old := *queue - x := old[0] - *queue = old[1:] - return x -} - -func (queue *UniqueStringQueue) Empty() bool { - return queue.Len() == 0 -} - -type UniqueSourceFileQueue []SourceFile - -func (queue UniqueSourceFileQueue) Len() int { return len(queue) } -func (queue UniqueSourceFileQueue) Less(i, j int) bool { return false } -func (queue UniqueSourceFileQueue) Swap(i, j int) { panic("Who called me?!?") } - -func (queue *UniqueSourceFileQueue) Push(value SourceFile) { - if !sliceContainsSourceFile(*queue, value) { - *queue = append(*queue, value) - } -} - -func (queue *UniqueSourceFileQueue) Pop() SourceFile { - old := *queue - x := old[0] - *queue = old[1:] - return x -} - -func (queue *UniqueSourceFileQueue) Empty() bool { - return queue.Len() == 0 -} - -type BufferedUntilNewLineWriter struct { - PrintFunc PrintFunc - Buffer bytes.Buffer - lock sync.Mutex -} - -type PrintFunc func([]byte) - -func (w *BufferedUntilNewLineWriter) Write(p []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - writtenToBuffer, err := w.Buffer.Write(p) - return writtenToBuffer, err -} - -func (w *BufferedUntilNewLineWriter) Flush() { - w.lock.Lock() - defer w.lock.Unlock() - - remainingBytes := w.Buffer.Bytes() - if len(remainingBytes) > 0 { - if remainingBytes[len(remainingBytes)-1] != '\n' { - remainingBytes = append(remainingBytes, '\n') - } - w.PrintFunc(remainingBytes) - } -} diff --git a/types/context.go b/types/context.go deleted file mode 100644 index e9368c08..00000000 --- a/types/context.go +++ /dev/null @@ -1,150 +0,0 @@ -package types - -import ( - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/go-properties-map" -) - -type ProgressStruct struct { - PrintEnabled bool - Steps float64 - Progress float64 -} - -// Context structure -type Context struct { - // Build options - HardwareFolders []string - ToolsFolders []string - LibrariesFolders []string - BuiltInLibrariesFolders []string - OtherLibrariesFolders []string - WatchedLocations []string - SketchLocation string - ArduinoAPIVersion string - FQBN string - CodeCompleteAt string - - // Build options are serialized here - BuildOptionsJson string - BuildOptionsJsonPrevious string - - Hardware *Packages - Tools []*Tool - TargetBoard *Board - TargetPackage *Package - TargetPlatform *Platform - ActualPlatform *Platform - USBVidPid string - - PlatformKeyRewrites PlatforKeysRewrite - HardwareRewriteResults map[*Platform][]PlatforKeyRewrite - - BuildProperties properties.Map - BuildCore string - BuildPath string - BuildCachePath string - SketchBuildPath string - CoreBuildPath string - CoreBuildCachePath string - CoreArchiveFilePath string - CoreObjectsFiles []string - LibrariesBuildPath string - LibrariesObjectFiles []string - PreprocPath string - SketchObjectFiles []string - - CollectedSourceFiles *UniqueSourceFileQueue - - Sketch *Sketch - Source string - SourceGccMinusE string - CodeCompletions string - - WarningsLevel string - - // Libraries handling - Libraries []*Library - HeaderToLibraries map[string][]*Library - ImportedLibraries []*Library - LibrariesResolutionResults map[string]LibraryResolutionResult - IncludeFolders []string - OutputGccMinusM string - - // C++ Parsing - CTagsOutput string - CTagsTargetFile string - CTagsOfPreprocessedSource []*CTag - IncludeSection string - LineOffset int - PrototypesSection string - PrototypesLineWhereToInsert int - Prototypes []*Prototype - - // Verbosity settings - Verbose bool - DebugPreprocessor bool - - // Dry run, only create progress map - Progress ProgressStruct - - // Contents of a custom build properties file (line by line) - CustomBuildProperties []string - - // Logging - logger i18n.Logger - DebugLevel int - - // Reuse old tools since the backing storage didn't change - CanUseCachedTools bool - - // Experimental: use arduino-preprocessor to create prototypes - UseArduinoPreprocessor bool -} - -func (ctx *Context) ExtractBuildOptions() properties.Map { - opts := make(properties.Map) - var additionalFilesRelative []string - if ctx.Sketch != nil { - for _, sketch := range ctx.Sketch.AdditionalFiles { - absPath := filepath.Dir(ctx.SketchLocation) - relPath := strings.TrimPrefix(sketch.Name, absPath) - additionalFilesRelative = append(additionalFilesRelative, relPath) - } - } - opts["hardwareFolders"] = strings.Join(ctx.HardwareFolders, ",") - opts["toolsFolders"] = strings.Join(ctx.ToolsFolders, ",") - opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesFolders, ",") - opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesFolders, ",") - opts["sketchLocation"] = ctx.SketchLocation - opts["fqbn"] = ctx.FQBN - opts["runtime.ide.version"] = ctx.ArduinoAPIVersion - opts["customBuildProperties"] = strings.Join(ctx.CustomBuildProperties, ",") - opts["additionalFiles"] = strings.Join(additionalFilesRelative, ",") - return opts -} - -func (ctx *Context) InjectBuildOptions(opts properties.Map) { - ctx.HardwareFolders = strings.Split(opts["hardwareFolders"], ",") - ctx.ToolsFolders = strings.Split(opts["toolsFolders"], ",") - ctx.BuiltInLibrariesFolders = strings.Split(opts["builtInLibrariesFolders"], ",") - ctx.OtherLibrariesFolders = strings.Split(opts["otherLibrariesFolders"], ",") - ctx.SketchLocation = opts["sketchLocation"] - ctx.FQBN = opts["fqbn"] - ctx.ArduinoAPIVersion = opts["runtime.ide.version"] - ctx.CustomBuildProperties = strings.Split(opts["customBuildProperties"], ",") -} - -func (ctx *Context) GetLogger() i18n.Logger { - if ctx.logger == nil { - return &i18n.HumanLogger{} - } - return ctx.logger -} - -func (ctx *Context) SetLogger(l i18n.Logger) { - ctx.logger = l -} diff --git a/types/types.go b/types/types.go deleted file mode 100644 index d535386d..00000000 --- a/types/types.go +++ /dev/null @@ -1,276 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -import ( - "fmt" - "path/filepath" - "strconv" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/go-properties-map" -) - -type SourceFile struct { - // Sketch or Library pointer that this source file lives in - Origin interface{} - // Path to the source file within the sketch/library root folder - RelativePath string -} - -// Create a SourceFile containing the given source file path within the -// given origin. The given path can be absolute, or relative within the -// origin's root source folder -func MakeSourceFile(ctx *Context, origin interface{}, path string) (SourceFile, error) { - if filepath.IsAbs(path) { - var err error - path, err = filepath.Rel(sourceRoot(ctx, origin), path) - if err != nil { - return SourceFile{}, err - } - } - return SourceFile{Origin: origin, RelativePath: path}, nil -} - -// Return the build root for the given origin, where build products will -// be placed. Any directories inside SourceFile.RelativePath will be -// appended here. -func buildRoot(ctx *Context, origin interface{}) string { - switch o := origin.(type) { - case *Sketch: - return ctx.SketchBuildPath - case *Library: - return filepath.Join(ctx.LibrariesBuildPath, o.Name) - default: - panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) - } -} - -// Return the source root for the given origin, where its source files -// can be found. Prepending this to SourceFile.RelativePath will give -// the full path to that source file. -func sourceRoot(ctx *Context, origin interface{}) string { - switch o := origin.(type) { - case *Sketch: - return ctx.SketchBuildPath - case *Library: - return o.SrcFolder - default: - panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) - } -} - -func (f *SourceFile) SourcePath(ctx *Context) string { - return filepath.Join(sourceRoot(ctx, f.Origin), f.RelativePath) -} - -func (f *SourceFile) ObjectPath(ctx *Context) string { - return filepath.Join(buildRoot(ctx, f.Origin), f.RelativePath+".o") -} - -func (f *SourceFile) DepfilePath(ctx *Context) string { - return filepath.Join(buildRoot(ctx, f.Origin), f.RelativePath+".d") -} - -type SketchFile struct { - Name string - Source string -} - -type SketchFileSortByName []SketchFile - -func (s SketchFileSortByName) Len() int { - return len(s) -} - -func (s SketchFileSortByName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s SketchFileSortByName) Less(i, j int) bool { - return s[i].Name < s[j].Name -} - -type Sketch struct { - MainFile SketchFile - OtherSketchFiles []SketchFile - AdditionalFiles []SketchFile -} - -type Packages struct { - Properties properties.Map - Packages map[string]*Package -} - -type Package struct { - PackageId string - Properties properties.Map - Platforms map[string]*Platform -} - -type Platform struct { - PlatformId string - Folder string - Boards map[string]*Board - Properties properties.Map - Programmers map[string]properties.Map -} - -type Board struct { - BoardId string - Properties properties.Map -} - -type Tool struct { - Name string - Version string - Folder string -} - -type LibraryLayout uint16 - -const ( - LIBRARY_FLAT LibraryLayout = 1 << iota - LIBRARY_RECURSIVE -) - -type Library struct { - Folder string - SrcFolder string - UtilityFolder string - Layout LibraryLayout - Name string - RealName string - Archs []string - DotALinkage bool - Precompiled bool - LDflags string - IsLegacy bool - Version string - Author string - Maintainer string - Sentence string - Paragraph string - URL string - Category string - License string - Properties map[string]string -} - -func (library *Library) String() string { - return library.Name + " : " + library.SrcFolder -} - -func (library *Library) SupportsArchitectures(archs []string) bool { - if sliceContains(archs, constants.LIBRARY_ALL_ARCHS) || sliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { - return true - } - - for _, libraryArch := range library.Archs { - if sliceContains(archs, libraryArch) { - return true - } - } - - return false -} - -type PlatforKeysRewrite struct { - Rewrites []PlatforKeyRewrite -} - -func (p *PlatforKeysRewrite) Empty() bool { - return len(p.Rewrites) == 0 -} - -type PlatforKeyRewrite struct { - Key string - OldValue string - NewValue string -} - -type KeyValuePair struct { - Key string - Value string -} - -type Prototype struct { - FunctionName string - File string - Prototype string - Modifiers string - Line int -} - -func (proto *Prototype) String() string { - return proto.Modifiers + " " + proto.Prototype + " @ " + strconv.Itoa(proto.Line) -} - -type SourceFolder struct { - Folder string - Recurse bool -} - -type LibraryResolutionResult struct { - Library *Library - NotUsedLibraries []*Library -} - -type CTag struct { - FunctionName string - Kind string - Line int - Code string - Class string - Struct string - Namespace string - Filename string - Typeref string - SkipMe bool - Signature string - - Prototype string - Function string - PrototypeModifiers string -} - -func LibraryToSourceFolder(library *Library) []SourceFolder { - sourceFolders := []SourceFolder{} - recurse := library.Layout == LIBRARY_RECURSIVE - sourceFolders = append(sourceFolders, SourceFolder{Folder: library.SrcFolder, Recurse: recurse}) - if library.UtilityFolder != "" { - sourceFolders = append(sourceFolders, SourceFolder{Folder: library.UtilityFolder, Recurse: false}) - } - return sourceFolders -} - -type Command interface { - Run(ctx *Context) error -} diff --git a/types/utils.go b/types/utils.go deleted file mode 100644 index a7200f0e..00000000 --- a/types/utils.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -// duplication of utils.SliceContains! Thanks golang! Why? Because with golang you can't have import cycles -func sliceContains(slice []string, target string) bool { - for _, value := range slice { - if value == target { - return true - } - } - return false -} - -func sliceContainsSourceFile(slice []SourceFile, target SourceFile) bool { - for _, elem := range slice { - if elem.Origin == target.Origin && elem.RelativePath == target.RelativePath { - return true - } - } - return false -} diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go deleted file mode 100644 index f163efbb..00000000 --- a/unused_compiled_libraries_remover.go +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "io/ioutil" - "os" - "path/filepath" -) - -type UnusedCompiledLibrariesRemover struct{} - -func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { - librariesBuildPath := ctx.LibrariesBuildPath - - _, err := os.Stat(librariesBuildPath) - if err != nil && os.IsNotExist(err) { - return nil - } - - libraryNames := toLibraryNames(ctx.ImportedLibraries) - - files, err := ioutil.ReadDir(librariesBuildPath) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - if file.IsDir() { - if !utils.SliceContains(libraryNames, file.Name()) { - err := os.RemoveAll(filepath.Join(librariesBuildPath, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - } - - return nil -} - -func toLibraryNames(libraries []*types.Library) []string { - libraryNames := []string{} - for _, library := range libraries { - libraryNames = append(libraryNames, library.Name) - } - return libraryNames -} diff --git a/utils/utils.go b/utils/utils.go deleted file mode 100644 index 700d41d7..00000000 --- a/utils/utils.go +++ /dev/null @@ -1,704 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package utils - -import ( - "bytes" - "crypto/md5" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "unicode" - "unicode/utf8" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "golang.org/x/text/transform" - "golang.org/x/text/unicode/norm" -) - -func PrettyOSName() string { - switch osName := runtime.GOOS; osName { - case "darwin": - return "macosx" - case "freebsd": - return "freebsd" - case "linux": - return "linux" - case "windows": - return "windows" - default: - return "other" - } -} - -func ParseCommandLine(input string, logger i18n.Logger) ([]string, error) { - var parts []string - escapingChar := constants.EMPTY_STRING - escapedArg := constants.EMPTY_STRING - for _, inputPart := range strings.Split(input, constants.SPACE) { - inputPart = strings.TrimSpace(inputPart) - if len(inputPart) == 0 { - continue - } - - if escapingChar == constants.EMPTY_STRING { - if inputPart[0] != '"' && inputPart[0] != '\'' { - parts = append(parts, inputPart) - continue - } - - escapingChar = string(inputPart[0]) - inputPart = inputPart[1:] - escapedArg = constants.EMPTY_STRING - } - - if inputPart[len(inputPart)-1] != '"' && inputPart[len(inputPart)-1] != '\'' { - escapedArg = escapedArg + inputPart + " " - continue - } - - escapedArg = escapedArg + inputPart[:len(inputPart)-1] - escapedArg = strings.TrimSpace(escapedArg) - if len(escapedArg) > 0 { - parts = append(parts, escapedArg) - } - escapingChar = constants.EMPTY_STRING - } - - if escapingChar != constants.EMPTY_STRING { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_INVALID_QUOTING, escapingChar) - } - - return parts, nil -} - -type filterFiles func([]os.FileInfo) []os.FileInfo - -func ReadDirFiltered(folder string, fn filterFiles) ([]os.FileInfo, error) { - files, err := gohasissues.ReadDir(folder) - if err != nil { - return nil, i18n.WrapError(err) - } - return fn(files), nil -} - -func FilterDirs(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, info := range files { - if info.IsDir() { - filtered = append(filtered, info) - } - } - return filtered -} - -func FilterFilesWithExtensions(extensions ...string) filterFiles { - return func(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, file := range files { - if !file.IsDir() && SliceContains(extensions, filepath.Ext(file.Name())) { - filtered = append(filtered, file) - } - } - return filtered - } -} - -func FilterFiles() filterFiles { - return func(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, file := range files { - if !file.IsDir() { - filtered = append(filtered, file) - } - } - return filtered - } -} - -var SOURCE_CONTROL_FOLDERS = map[string]bool{"CVS": true, "RCS": true, ".git": true, ".github": true, ".svn": true, ".hg": true, ".bzr": true, ".vscode": true, ".settings": true, ".pioenvs": true, ".piolibdeps": true} - -func IsSCCSOrHiddenFile(file os.FileInfo) bool { - return IsSCCSFile(file) || IsHiddenFile(file) -} - -func IsHiddenFile(file os.FileInfo) bool { - name := filepath.Base(file.Name()) - - if name[0] == '.' { - return true - } - - return false -} - -func IsSCCSFile(file os.FileInfo) bool { - name := filepath.Base(file.Name()) - - if SOURCE_CONTROL_FOLDERS[name] { - return true - } - - return false -} - -func SliceContains(slice []string, target string) bool { - for _, value := range slice { - if value == target { - return true - } - } - return false -} - -type mapFunc func(string) string - -func Map(slice []string, fn mapFunc) []string { - newSlice := []string{} - for _, elem := range slice { - newSlice = append(newSlice, fn(elem)) - } - return newSlice -} - -type filterFunc func(string) bool - -func Filter(slice []string, fn filterFunc) []string { - newSlice := []string{} - for _, elem := range slice { - if fn(elem) { - newSlice = append(newSlice, elem) - } - } - return newSlice -} - -func WrapWithHyphenI(value string) string { - return "\"-I" + value + "\"" -} - -func TrimSpace(value string) string { - return strings.TrimSpace(value) -} - -type argFilterFunc func(int, string, []string) bool - -func PrepareCommandFilteredArgs(pattern string, filter argFilterFunc, logger i18n.Logger, relativePath string) (*exec.Cmd, error) { - parts, err := ParseCommandLine(pattern, logger) - if err != nil { - return nil, i18n.WrapError(err) - } - command := parts[0] - parts = parts[1:] - var args []string - for idx, part := range parts { - if filter(idx, part, parts) { - // if relativePath is specified, the overall commandline is too long for the platform - // try reducing the length by making the filenames relative - // and changing working directory to build.path - if relativePath != "" { - if _, err := os.Stat(part); !os.IsNotExist(err) { - tmp, err := filepath.Rel(relativePath, part) - if err == nil { - part = tmp - } - } - } - args = append(args, part) - } - } - - cmd := exec.Command(command, args...) - - if relativePath != "" { - cmd.Dir = relativePath - } - - return cmd, nil -} - -func filterEmptyArg(_ int, arg string, _ []string) bool { - return arg != constants.EMPTY_STRING -} - -func PrepareCommand(pattern string, logger i18n.Logger, relativePath string) (*exec.Cmd, error) { - return PrepareCommandFilteredArgs(pattern, filterEmptyArg, logger, relativePath) -} - -func printableArgument(arg string) string { - if strings.ContainsAny(arg, "\"\\ \t") { - arg = strings.Replace(arg, "\\", "\\\\", -1) - arg = strings.Replace(arg, "\"", "\\\"", -1) - return "\"" + arg + "\"" - } else { - return arg - } -} - -// Convert a command and argument slice back to a printable string. -// This adds basic escaping which is sufficient for debug output, but -// probably not for shell interpretation. This essentially reverses -// ParseCommandLine. -func PrintableCommand(parts []string) string { - return strings.Join(Map(parts, printableArgument), " ") -} - -const ( - Ignore = 0 // Redirect to null - Show = 1 // Show on stdout/stderr as normal - ShowIfVerbose = 2 // Show if verbose is set, Ignore otherwise - Capture = 3 // Capture into buffer -) - -func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int) ([]byte, []byte, error) { - if ctx.Verbose { - ctx.GetLogger().UnformattedFprintln(os.Stdout, PrintableCommand(command.Args)) - } - - if stdout == Capture { - buffer := &bytes.Buffer{} - command.Stdout = buffer - } else if stdout == Show || stdout == ShowIfVerbose && ctx.Verbose { - command.Stdout = os.Stdout - } - - if stderr == Capture { - buffer := &bytes.Buffer{} - command.Stderr = buffer - } else if stderr == Show || stderr == ShowIfVerbose && ctx.Verbose { - command.Stderr = os.Stderr - } - - err := command.Start() - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - err = command.Wait() - - var outbytes, errbytes []byte - if buf, ok := command.Stdout.(*bytes.Buffer); ok { - outbytes = buf.Bytes() - } - if buf, ok := command.Stderr.(*bytes.Buffer); ok { - errbytes = buf.Bytes() - } - - return outbytes, errbytes, i18n.WrapError(err) -} - -func MapHas(aMap map[string]interface{}, key string) bool { - _, ok := aMap[key] - return ok -} - -func MapStringStringHas(aMap map[string]string, key string) bool { - _, ok := aMap[key] - return ok -} - -func SliceToMapStringBool(keys []string, value bool) map[string]bool { - aMap := make(map[string]bool) - for _, key := range keys { - aMap[key] = value - } - return aMap -} - -func AbsolutizePaths(files []string) ([]string, error) { - for idx, file := range files { - if file == "" { - continue - } - absFile, err := filepath.Abs(file) - if err != nil { - return nil, i18n.WrapError(err) - } - files[idx] = absFile - } - - return files, nil -} - -func ReadFileToRows(file string) ([]string, error) { - bytes, err := ioutil.ReadFile(file) - if err != nil { - return nil, i18n.WrapError(err) - } - txt := string(bytes) - txt = strings.Replace(txt, "\r\n", "\n", -1) - - return strings.Split(txt, "\n"), nil -} - -func TheOnlySubfolderOf(folder string) (string, error) { - subfolders, err := ReadDirFiltered(folder, FilterDirs) - if err != nil { - return constants.EMPTY_STRING, i18n.WrapError(err) - } - - if len(subfolders) != 1 { - return constants.EMPTY_STRING, nil - } - - return subfolders[0].Name(), nil -} - -func FilterOutFoldersByNames(folders []os.FileInfo, names ...string) []os.FileInfo { - filterNames := SliceToMapStringBool(names, true) - - var filtered []os.FileInfo - for _, folder := range folders { - if !filterNames[folder.Name()] { - filtered = append(filtered, folder) - } - } - - return filtered -} - -type CheckExtensionFunc func(ext string) bool - -func FindAllSubdirectories(folder string, output *[]string) error { - walkFunc := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - // Skip source control and hidden files and directories - if IsSCCSOrHiddenFile(info) { - if info.IsDir() { - return filepath.SkipDir - } - return nil - } - - // Skip directories unless recurse is on, or this is the - // root directory - if info.IsDir() { - *output = AppendIfNotPresent(*output, path) - } - return nil - } - return gohasissues.Walk(folder, walkFunc) -} - -func FindFilesInFolder(files *[]string, folder string, extensions CheckExtensionFunc, recurse bool) error { - walkFunc := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - // Skip source control and hidden files and directories - if IsSCCSOrHiddenFile(info) { - if info.IsDir() { - return filepath.SkipDir - } - return nil - } - - // Skip directories unless recurse is on, or this is the - // root directory - if info.IsDir() { - if recurse || path == folder { - return nil - } else { - return filepath.SkipDir - } - } - - // Check (lowercased) extension against list of extensions - if extensions != nil && !extensions(strings.ToLower(filepath.Ext(path))) { - return nil - } - - // See if the file is readable by opening it - currentFile, err := os.Open(path) - if err != nil { - return nil - } - currentFile.Close() - - *files = append(*files, path) - return nil - } - return gohasissues.Walk(folder, walkFunc) -} - -func GetParentFolder(basefolder string, n int) string { - tempFolder := basefolder - i := 0 - for i < n { - tempFolder = filepath.Dir(tempFolder) - i++ - } - return tempFolder -} - -func AppendIfNotPresent(target []string, elements ...string) []string { - for _, element := range elements { - if !SliceContains(target, element) { - target = append(target, element) - } - } - return target -} - -func EnsureFolderExists(folder string) error { - return os.MkdirAll(folder, os.FileMode(0755)) -} - -func WriteFileBytes(targetFilePath string, data []byte) error { - return ioutil.WriteFile(targetFilePath, data, os.FileMode(0644)) -} - -func WriteFile(targetFilePath string, data string) error { - return WriteFileBytes(targetFilePath, []byte(data)) -} - -func TouchFile(targetFilePath string) error { - return WriteFileBytes(targetFilePath, []byte{}) -} - -func NULLFile() string { - if runtime.GOOS == "windows" { - return "nul" - } - return "/dev/null" -} - -func MD5Sum(data []byte) string { - md5sumBytes := md5.Sum(data) - return hex.EncodeToString(md5sumBytes[:]) -} - -type loggerAction struct { - onlyIfVerbose bool - level string - format string - args []interface{} -} - -func (l *loggerAction) Run(ctx *types.Context) error { - if !l.onlyIfVerbose || ctx.Verbose { - ctx.GetLogger().Println(l.level, l.format, l.args...) - } - return nil -} - -func LogIfVerbose(level string, format string, args ...interface{}) types.Command { - return &loggerAction{true, level, format, args} -} - -func LogThis(level string, format string, args ...interface{}) types.Command { - return &loggerAction{false, level, format, args} -} - -// Returns the given string as a quoted string for use with the C -// preprocessor. This adds double quotes around it and escapes any -// double quotes and backslashes in the string. -func QuoteCppString(str string) string { - str = strings.Replace(str, "\\", "\\\\", -1) - str = strings.Replace(str, "\"", "\\\"", -1) - return "\"" + str + "\"" -} - -// Parse a C-preprocessor string as emitted by the preprocessor. This -// is a string contained in double quotes, with any backslashes or -// quotes escaped with a backslash. If a valid string was present at the -// start of the given line, returns the unquoted string contents, the -// remaineder of the line (everything after the closing "), and true. -// Otherwise, returns the empty string, the entire line and false. -func ParseCppString(line string) (string, string, bool) { - // For details about how these strings are output by gcc, see: - // https://github.com/gcc-mirror/gcc/blob/a588355ab948cf551bc9d2b89f18e5ae5140f52c/libcpp/macro.c#L491-L511 - // Note that the documentaiton suggests all non-printable - // characters are also escaped, but the implementation does not - // actually do this. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51259 - if len(line) < 1 || line[0] != '"' { - return "", line, false - } - - i := 1 - res := "" - for { - if i >= len(line) { - return "", line, false - } - - c, width := utf8.DecodeRuneInString(line[i:]) - - switch c { - // Backslash, next character is used unmodified - case '\\': - i += width - if i >= len(line) { - return "", line, false - } - res += string(line[i]) - break - // Quote, end of string - case '"': - return res, line[i+width:], true - default: - res += string(c) - break - } - - i += width - } -} - -func isMn(r rune) bool { - return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks -} - -// Normalizes an UTF8 byte slice -// TODO: use it more often troughout all the project (maybe on logger interface?) -func NormalizeUTF8(buf []byte) []byte { - t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC) - result, _, _ := transform.Bytes(t, buf) - return result -} - -// CopyFile copies the contents of the file named src to the file named -// by dst. The file will be created if it does not already exist. If the -// destination file exists, all it's contents will be replaced by the contents -// of the source file. The file mode will be copied from the source and -// the copied data is synced/flushed to stable storage. -func CopyFile(src, dst string) (err error) { - in, err := os.Open(src) - if err != nil { - return - } - defer in.Close() - - out, err := os.Create(dst) - if err != nil { - return - } - defer func() { - if e := out.Close(); e != nil { - err = e - } - }() - - _, err = io.Copy(out, in) - if err != nil { - return - } - - err = out.Sync() - if err != nil { - return - } - - si, err := os.Stat(src) - if err != nil { - return - } - err = os.Chmod(dst, si.Mode()) - if err != nil { - return - } - - return -} - -// CopyDir recursively copies a directory tree, attempting to preserve permissions. -// Source directory must exist, destination directory must *not* exist. -// Symlinks are ignored and skipped. -func CopyDir(src string, dst string, extensions CheckExtensionFunc) (err error) { - src = filepath.Clean(src) - dst = filepath.Clean(dst) - - si, err := os.Stat(src) - if err != nil { - return err - } - if !si.IsDir() { - return fmt.Errorf("source is not a directory") - } - - _, err = os.Stat(dst) - if err != nil && !os.IsNotExist(err) { - return - } - if err == nil { - return fmt.Errorf("destination already exists") - } - - err = os.MkdirAll(dst, si.Mode()) - if err != nil { - return - } - - entries, err := ioutil.ReadDir(src) - if err != nil { - return - } - - for _, entry := range entries { - srcPath := filepath.Join(src, entry.Name()) - dstPath := filepath.Join(dst, entry.Name()) - - if entry.IsDir() { - err = CopyDir(srcPath, dstPath, extensions) - if err != nil { - return - } - } else { - // Skip symlinks. - if entry.Mode()&os.ModeSymlink != 0 { - continue - } - - if extensions != nil && !extensions(strings.ToLower(filepath.Ext(srcPath))) { - continue - } - - err = CopyFile(srcPath, dstPath) - if err != nil { - return - } - } - } - - return -} diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go deleted file mode 100644 index 8d320717..00000000 --- a/warn_about_arch_incompatible_libraries.go +++ /dev/null @@ -1,76 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "os" - "strings" -) - -type WarnAboutArchIncompatibleLibraries struct{} - -func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { - if ctx.DebugLevel < 0 { - return nil - } - - targetPlatform := ctx.TargetPlatform - buildProperties := ctx.BuildProperties - logger := ctx.GetLogger() - - archs := []string{} - archs = append(archs, targetPlatform.PlatformId) - - if buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK] != constants.EMPTY_STRING { - overrides := strings.Split(buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK], ",") - for _, override := range overrides { - archs = append(archs, override) - } - } - - for _, importedLibrary := range ctx.ImportedLibraries { - if !importedLibrary.SupportsArchitectures(archs) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, importedLibrary.Name, sliceToCommaSeparatedString(importedLibrary.Archs), sliceToCommaSeparatedString(archs)) - } - } - - return nil -} - -func sliceToCommaSeparatedString(slice []string) string { - str := "(" - str = str + slice[0] - for i := 1; i < len(slice); i++ { - str = str + ", " + slice[i] - } - return str + ")" -} diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go deleted file mode 100644 index 247e0256..00000000 --- a/warn_about_platform_rewrites.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "os" -) - -type WarnAboutPlatformRewrites struct{} - -func (s *WarnAboutPlatformRewrites) Run(ctx *types.Context) error { - if ctx.DebugLevel < 0 { - return nil - } - - logger := ctx.GetLogger() - hardwareRewriteResults := ctx.HardwareRewriteResults - targetPlatform := ctx.TargetPlatform - actualPlatform := ctx.ActualPlatform - - platforms := []*types.Platform{targetPlatform} - if actualPlatform != targetPlatform { - platforms = append(platforms, actualPlatform) - } - - for _, platform := range platforms { - if hardwareRewriteResults[platform] != nil { - for _, rewrite := range hardwareRewriteResults[platform] { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_WARNING_PLATFORM_OLD_VALUES, platform.Properties[constants.PLATFORM_NAME], rewrite.Key+"="+rewrite.OldValue, rewrite.Key+"="+rewrite.NewValue) - } - } - } - - return nil -} diff --git a/wipeout_build_path_if_build_options_changed.go b/wipeout_build_path_if_build_options_changed.go deleted file mode 100644 index 0b6c9d17..00000000 --- a/wipeout_build_path_if_build_options_changed.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "encoding/json" - "os" - "path/filepath" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" -) - -type WipeoutBuildPathIfBuildOptionsChanged struct{} - -func (s *WipeoutBuildPathIfBuildOptionsChanged) Run(ctx *types.Context) error { - if ctx.BuildOptionsJsonPrevious == "" { - return nil - } - buildOptionsJson := ctx.BuildOptionsJson - previousBuildOptionsJson := ctx.BuildOptionsJsonPrevious - logger := ctx.GetLogger() - - var opts properties.Map - var prevOpts properties.Map - json.Unmarshal([]byte(buildOptionsJson), &opts) - json.Unmarshal([]byte(previousBuildOptionsJson), &prevOpts) - - // If SketchLocation path is different but filename is the same, consider it equal - if filepath.Base(opts["sketchLocation"]) == filepath.Base(prevOpts["sketchLocation"]) { - delete(opts, "sketchLocation") - delete(prevOpts, "sketchLocation") - } - - // check if any of the files contained in the core folders has changed - // since the json was generated - like platform.txt or similar - // if so, trigger a "safety" wipe - buildProperties := ctx.BuildProperties - targetCoreFolder := buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] - coreFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] - realCoreFolder := utils.GetParentFolder(coreFolder, 2) - jsonPath := filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE) - coreHasChanged := builder_utils.TXTBuildRulesHaveChanged(realCoreFolder, targetCoreFolder, jsonPath) - - if opts.Equals(prevOpts) && !coreHasChanged { - return nil - } - - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_BUILD_OPTIONS_CHANGED) - - buildPath := ctx.BuildPath - files, err := gohasissues.ReadDir(buildPath) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - os.RemoveAll(filepath.Join(buildPath, file.Name())) - } - - return nil -}