You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by ma...@apache.org on 2017/03/06 21:44:01 UTC

[01/41] incubator-mynewt-newt git commit: MYNEWT-558 newt - depgraph should show api / hard

Repository: incubator-mynewt-newt
Updated Branches:
  refs/heads/mynewt_1_0_0 [created] 50d5f1f10


MYNEWT-558 newt - depgraph should show api / hard

The `target dep` and `target revdep` commands only indicated package
names in the dependency graph.  This change enhances the output of these
commands to show what created the dependency in the first place.
Specifically, they now show whether the dependency is "hard" (package
explicitly depends on another) or "soft" (package requires an API; other
package happens to implement that API).  This is useful when trying to
completely remove a package from a build.

In the future, we should also indicate which, if any, syscfg settings
generated a particular dependency.

The fix required a lot of changes to the newt code.  The major change
was to scale back the responsibilities of the pkg.LocalPackage type.
This struct was being used during build and depgraph resolution, and its
client relied on its inheritance of the pkg.Package interface.
Consequently, it was difficult to add new features without breaking
everything or bloating the LocalPackage struct.

Now, instances of LocalPackage get converted to resolve.ResolvePackage
during dependency and API resolution.  Furthermore, builder.BuildPackage
and resolve.ResolvePackage no longer inherit from LocalPackage.
Instead, each contains a pointer to its corresponding LocalPackage or
ResolvePackage.  Since these types never need to be treated as generic
package types, the code is simplified by eliminating these edges from
the inheritance tree.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/4c0c1b14
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/4c0c1b14
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/4c0c1b14

Branch: refs/heads/mynewt_1_0_0
Commit: 4c0c1b14cdbd526b85e8b65ceedc117a2a843036
Parents: fdac74f
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Feb 2 07:30:00 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:28:40 2017 -0800

----------------------------------------------------------------------
 newt/builder/build.go        |  98 +++++++++--------
 newt/builder/buildpackage.go |  59 +++++------
 newt/builder/buildutil.go    |  32 +++---
 newt/builder/depgraph.go     | 102 +++++++++---------
 newt/builder/library.go      |   2 +-
 newt/builder/load.go         |   2 +-
 newt/builder/paths.go        |  30 +++---
 newt/builder/selftest.go     |  86 ++++++++++-----
 newt/builder/targetbuild.go  |  75 +++++++------
 newt/cli/target_cmds.go      |  26 ++---
 newt/cli/util.go             |  23 ++++
 newt/pkg/localpackage.go     |  32 ------
 newt/pkg/package.go          |   2 -
 newt/resolve/resolve.go      | 218 +++++++++++++++++++++++++-------------
 newt/resolve/resolveutil.go  |  92 ++++++++++++++++
 15 files changed, 538 insertions(+), 341 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/build.go
----------------------------------------------------------------------
diff --git a/newt/builder/build.go b/newt/builder/build.go
index 232a39e..d82d9ff 100644
--- a/newt/builder/build.go
+++ b/newt/builder/build.go
@@ -30,6 +30,7 @@ import (
 	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/repo"
+	"mynewt.apache.org/newt/newt/resolve"
 	"mynewt.apache.org/newt/newt/symbol"
 	"mynewt.apache.org/newt/newt/syscfg"
 	"mynewt.apache.org/newt/newt/target"
@@ -38,7 +39,7 @@ import (
 )
 
 type Builder struct {
-	PkgMap map[*pkg.LocalPackage]*BuildPackage
+	PkgMap map[*resolve.ResolvePackage]*BuildPackage
 
 	apiMap           map[string]*BuildPackage
 	appPkg           *BuildPackage
@@ -54,11 +55,15 @@ type Builder struct {
 	injectedSettings map[string]string
 }
 
-func NewBuilder(t *TargetBuilder, buildName string, lpkgs []*pkg.LocalPackage,
-	apiMap map[string]*pkg.LocalPackage, cfg syscfg.Cfg) (*Builder, error) {
+func NewBuilder(
+	t *TargetBuilder,
+	buildName string,
+	rpkgs []*resolve.ResolvePackage,
+	apiMap map[string]*resolve.ResolvePackage,
+	cfg syscfg.Cfg) (*Builder, error) {
 
 	b := &Builder{
-		PkgMap: make(map[*pkg.LocalPackage]*BuildPackage, len(lpkgs)),
+		PkgMap: make(map[*resolve.ResolvePackage]*BuildPackage, len(rpkgs)),
 		cfg:    cfg,
 
 		buildName:        buildName,
@@ -68,8 +73,8 @@ func NewBuilder(t *TargetBuilder, buildName string, lpkgs []*pkg.LocalPackage,
 		injectedSettings: map[string]string{},
 	}
 
-	for _, lpkg := range lpkgs {
-		if _, err := b.addPackage(lpkg); err != nil {
+	for _, rpkg := range rpkgs {
+		if _, err := b.addPackage(rpkg); err != nil {
 			return nil, err
 		}
 	}
@@ -79,15 +84,15 @@ func NewBuilder(t *TargetBuilder, buildName string, lpkgs []*pkg.LocalPackage,
 		return nil, err
 	}
 
-	for api, lpkg := range apiMap {
-		bpkg := b.PkgMap[lpkg]
+	for api, rpkg := range apiMap {
+		bpkg := b.PkgMap[rpkg]
 		if bpkg == nil {
-			for _, lpkg := range b.sortedLocalPackages() {
-				log.Debugf("    * %s", lpkg.Name())
+			for _, rpkg := range b.sortedRpkgs() {
+				log.Debugf("    * %s", rpkg.Lpkg.Name())
 			}
 			return nil, util.FmtNewtError(
 				"Unexpected unsatisfied API: %s; required by: %s", api,
-				lpkg.Name())
+				rpkg.Lpkg.Name())
 		}
 
 		b.apiMap[api] = bpkg
@@ -96,17 +101,19 @@ func NewBuilder(t *TargetBuilder, buildName string, lpkgs []*pkg.LocalPackage,
 	return b, nil
 }
 
-func (b *Builder) addPackage(npkg *pkg.LocalPackage) (*BuildPackage, error) {
+func (b *Builder) addPackage(rpkg *resolve.ResolvePackage) (
+	*BuildPackage, error) {
+
 	// Don't allow nil entries to the map
-	if npkg == nil {
+	if rpkg == nil {
 		panic("Cannot add nil package builder map")
 	}
 
-	bpkg := b.PkgMap[npkg]
+	bpkg := b.PkgMap[rpkg]
 	if bpkg == nil {
-		bpkg = NewBuildPackage(npkg)
+		bpkg = NewBuildPackage(rpkg)
 
-		switch bpkg.Type() {
+		switch bpkg.rpkg.Lpkg.Type() {
 		case pkg.PACKAGE_TYPE_APP:
 			if b.appPkg != nil {
 				return nil, pkgTypeConflictErr(b.appPkg, bpkg)
@@ -132,7 +139,7 @@ func (b *Builder) addPackage(npkg *pkg.LocalPackage) (*BuildPackage, error) {
 			b.targetPkg = bpkg
 		}
 
-		b.PkgMap[npkg] = bpkg
+		b.PkgMap[rpkg] = bpkg
 	}
 
 	return bpkg, nil
@@ -140,7 +147,9 @@ func (b *Builder) addPackage(npkg *pkg.LocalPackage) (*BuildPackage, error) {
 
 func pkgTypeConflictErr(p1 *BuildPackage, p2 *BuildPackage) error {
 	return util.FmtNewtError("Two %s packages in build: %s, %s",
-		pkg.PackageTypeNames[p1.Type()], p1.Name(), p2.Name())
+		pkg.PackageTypeNames[p1.rpkg.Lpkg.Type()],
+		p1.rpkg.Lpkg.Name(),
+		p2.rpkg.Lpkg.Name())
 }
 
 // Recursively compiles all the .c and .s files in the specified directory.
@@ -243,7 +252,8 @@ func (b *Builder) newCompiler(bpkg *BuildPackage,
 	c.AddInfo(b.compilerInfo)
 
 	if bpkg != nil {
-		log.Debugf("Generating build flags for package %s", bpkg.FullName())
+		log.Debugf("Generating build flags for package %s",
+			bpkg.rpkg.Lpkg.FullName())
 		ci, err := bpkg.CompilerInfo(b)
 		if err != nil {
 			return nil, err
@@ -266,7 +276,7 @@ func (b *Builder) collectCompileEntriesBpkg(bpkg *BuildPackage) (
 
 	if len(bpkg.SourceDirectories) > 0 {
 		for _, relDir := range bpkg.SourceDirectories {
-			dir := bpkg.BasePath() + "/" + relDir
+			dir := bpkg.rpkg.Lpkg.BasePath() + "/" + relDir
 			if util.NodeNotExist(dir) {
 				return nil, util.NewNewtError(fmt.Sprintf(
 					"Specified source directory %s, does not exist.",
@@ -275,7 +285,7 @@ func (b *Builder) collectCompileEntriesBpkg(bpkg *BuildPackage) (
 			srcDirs = append(srcDirs, dir)
 		}
 	} else {
-		srcDir := bpkg.BasePath() + "/src"
+		srcDir := bpkg.rpkg.Lpkg.BasePath() + "/src"
 		if util.NodeNotExist(srcDir) {
 			// Nothing to compile.
 			return nil, nil
@@ -302,7 +312,7 @@ func (b *Builder) createArchive(c *toolchain.Compiler,
 	bpkg *BuildPackage) error {
 
 	// Create a static library ("archive").
-	c.SetSrcDir(bpkg.RelativePath())
+	c.SetSrcDir(bpkg.rpkg.Lpkg.RelativePath())
 	archiveFile := b.ArchivePath(bpkg)
 	if err := c.CompileArchive(archiveFile); err != nil {
 		return err
@@ -314,7 +324,7 @@ func (b *Builder) createArchive(c *toolchain.Compiler,
 func (b *Builder) RemovePackages(cmn map[string]bool) error {
 	for pkgName, _ := range cmn {
 		for lp, bpkg := range b.PkgMap {
-			if bpkg.Name() == pkgName {
+			if bpkg.rpkg.Lpkg.Name() == pkgName {
 				delete(b.PkgMap, lp)
 			}
 		}
@@ -387,7 +397,7 @@ func (b *Builder) PrepBuild() error {
 
 	// Target flags.
 	log.Debugf("Generating build flags for target %s",
-		b.targetPkg.FullName())
+		b.targetPkg.rpkg.Lpkg.FullName())
 	targetCi, err := b.targetPkg.CompilerInfo(b)
 	if err != nil {
 		return err
@@ -396,7 +406,8 @@ func (b *Builder) PrepBuild() error {
 
 	// App flags.
 	if b.appPkg != nil {
-		log.Debugf("Generating build flags for app %s", b.appPkg.FullName())
+		log.Debugf("Generating build flags for app %s",
+			b.appPkg.rpkg.Lpkg.FullName())
 		appCi, err := b.appPkg.CompilerInfo(b)
 		if err != nil {
 			return err
@@ -406,7 +417,8 @@ func (b *Builder) PrepBuild() error {
 	}
 
 	// Bsp flags.
-	log.Debugf("Generating build flags for bsp %s", b.bspPkg.FullName())
+	log.Debugf("Generating build flags for bsp %s",
+		b.bspPkg.rpkg.Lpkg.FullName())
 	bspCi, err := b.bspPkg.CompilerInfo(b)
 	if err != nil {
 		return err
@@ -420,12 +432,12 @@ func (b *Builder) PrepBuild() error {
 	bspCi.Cflags = append(bspCi.Cflags, "-DARCH_NAME="+archName+"")
 
 	if b.appPkg != nil {
-		appName := filepath.Base(b.appPkg.Name())
+		appName := filepath.Base(b.appPkg.rpkg.Lpkg.Name())
 		bspCi.Cflags = append(bspCi.Cflags, "-DAPP_"+util.CIdentifier(appName))
 		bspCi.Cflags = append(bspCi.Cflags, "-DAPP_NAME="+appName+"")
 	}
 
-	bspName := filepath.Base(b.bspPkg.Name())
+	bspName := filepath.Base(b.bspPkg.rpkg.Lpkg.Name())
 	bspCi.Cflags = append(bspCi.Cflags, "-DBSP_"+util.CIdentifier(bspName))
 	bspCi.Cflags = append(bspCi.Cflags, "-DBSP_NAME="+bspName+"")
 
@@ -433,7 +445,7 @@ func (b *Builder) PrepBuild() error {
 
 	// All packages have access to the generated code header directory.
 	baseCi.Cflags = append(baseCi.Cflags,
-		"-I"+GeneratedIncludeDir(b.targetPkg.Name()))
+		"-I"+GeneratedIncludeDir(b.targetPkg.rpkg.Lpkg.Name()))
 
 	// Note: Compiler flags get added at the end, after the flags for library
 	// package being built are calculated.
@@ -447,12 +459,14 @@ func (b *Builder) AddCompilerInfo(info *toolchain.CompilerInfo) {
 }
 
 func (b *Builder) addSysinitBpkg() (*BuildPackage, error) {
-	lpkg := pkg.NewLocalPackage(b.targetPkg.Repo().(*repo.Repo),
-		GeneratedBaseDir(b.targetPkg.Name()))
-	lpkg.SetName(pkg.ShortName(b.targetPkg) + "-sysinit-" + b.buildName)
+	lpkg := pkg.NewLocalPackage(b.targetPkg.rpkg.Lpkg.Repo().(*repo.Repo),
+		GeneratedBaseDir(b.targetPkg.rpkg.Lpkg.Name()))
+	lpkg.SetName(pkg.ShortName(b.targetPkg.rpkg.Lpkg) + "-sysinit-" +
+		b.buildName)
 	lpkg.SetType(pkg.PACKAGE_TYPE_GENERATED)
 
-	return b.addPackage(lpkg)
+	rpkg := resolve.NewResolvePkg(lpkg)
+	return b.addPackage(rpkg)
 }
 
 // Runs build jobs while any remain.  On failure, signals the other workers to
@@ -588,9 +602,9 @@ func (b *Builder) TentativeLink(linkerScripts []string) error {
 }
 
 func (b *Builder) pkgWithPath(path string) *BuildPackage {
-	for _, p := range b.PkgMap {
-		if p.BasePath() == path {
-			return p
+	for _, bpkg := range b.PkgMap {
+		if bpkg.rpkg.Lpkg.BasePath() == path {
+			return bpkg
 		}
 	}
 
@@ -598,21 +612,21 @@ func (b *Builder) pkgWithPath(path string) *BuildPackage {
 }
 
 func (b *Builder) FetchSymbolMap() (error, *symbol.SymbolMap) {
-	loader_sm := symbol.NewSymbolMap()
+	loaderSm := symbol.NewSymbolMap()
 
-	for _, value := range b.PkgMap {
-		err, sm := b.ParseObjectLibrary(value)
+	for _, bpkg := range b.PkgMap {
+		err, sm := b.ParseObjectLibrary(bpkg)
 		if err == nil {
 			util.StatusMessage(util.VERBOSITY_VERBOSE,
-				"Size of %s Loader Map %d\n", value.Name(), len(*sm))
-			loader_sm, err = loader_sm.Merge(sm)
+				"Size of %s Loader Map %d\n", bpkg.rpkg.Lpkg.Name(), len(*sm))
+			loaderSm, err = loaderSm.Merge(sm)
 			if err != nil {
 				return err, nil
 			}
 		}
 	}
 
-	return nil, loader_sm
+	return nil, loaderSm
 }
 
 func (b *Builder) GetTarget() *target.Target {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/buildpackage.go
----------------------------------------------------------------------
diff --git a/newt/builder/buildpackage.go b/newt/builder/buildpackage.go
index 5071185..e82566f 100644
--- a/newt/builder/buildpackage.go
+++ b/newt/builder/buildpackage.go
@@ -26,22 +26,21 @@ import (
 
 	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/newt/pkg"
-	"mynewt.apache.org/newt/newt/project"
+	"mynewt.apache.org/newt/newt/resolve"
 	"mynewt.apache.org/newt/newt/syscfg"
 	"mynewt.apache.org/newt/newt/toolchain"
 	"mynewt.apache.org/newt/util"
 )
 
 type BuildPackage struct {
-	*pkg.LocalPackage
-
-	ci                *toolchain.CompilerInfo
+	rpkg              *resolve.ResolvePackage
 	SourceDirectories []string
+	ci                *toolchain.CompilerInfo
 }
 
-func NewBuildPackage(pkg *pkg.LocalPackage) *BuildPackage {
+func NewBuildPackage(rpkg *resolve.ResolvePackage) *BuildPackage {
 	bpkg := &BuildPackage{
-		LocalPackage: pkg,
+		rpkg: rpkg,
 	}
 
 	return bpkg
@@ -58,22 +57,11 @@ func (bpkg *BuildPackage) collectDepsAux(b *Builder,
 
 	(*set)[bpkg] = true
 
-	for _, dep := range bpkg.Deps() {
-		if dep.Name == "" {
-			break
-		}
-
-		// Get pkg structure
-		p := project.GetProject().ResolveDependency(dep)
-		if p == nil {
-			return util.FmtNewtError("Cannot resolve dependency %+v", dep)
-		}
-		dpkg := p.(*pkg.LocalPackage)
-
-		dbpkg := b.PkgMap[dpkg]
+	for _, dep := range bpkg.rpkg.Deps {
+		dbpkg := b.PkgMap[dep.Rpkg]
 		if dbpkg == nil {
 			return util.FmtNewtError("Package not found %s; required by %s",
-				dpkg.Name(), bpkg.Name())
+				dbpkg.rpkg.Lpkg.Name(), bpkg.rpkg.Lpkg.Name())
 		}
 
 		if err := dbpkg.collectDepsAux(b, set); err != nil {
@@ -140,30 +128,30 @@ func (bpkg *BuildPackage) CompilerInfo(
 	}
 
 	ci := toolchain.NewCompilerInfo()
-	features := b.cfg.FeaturesForLpkg(bpkg.LocalPackage)
+	features := b.cfg.FeaturesForLpkg(bpkg.rpkg.Lpkg)
 
 	// Read each set of flags and expand repo designators ("@<repo-nme>") into
 	// paths.
-	ci.Cflags = newtutil.GetStringSliceFeatures(bpkg.PkgV, features,
+	ci.Cflags = newtutil.GetStringSliceFeatures(bpkg.rpkg.Lpkg.PkgV, features,
 		"pkg.cflags")
 	expandFlags(ci.Cflags)
 
-	ci.Lflags = newtutil.GetStringSliceFeatures(bpkg.PkgV, features,
+	ci.Lflags = newtutil.GetStringSliceFeatures(bpkg.rpkg.Lpkg.PkgV, features,
 		"pkg.lflags")
 	expandFlags(ci.Lflags)
 
-	ci.Aflags = newtutil.GetStringSliceFeatures(bpkg.PkgV, features,
+	ci.Aflags = newtutil.GetStringSliceFeatures(bpkg.rpkg.Lpkg.PkgV, features,
 		"pkg.aflags")
 	expandFlags(ci.Aflags)
 
 	// Package-specific injected settings get specified as C flags on the
 	// command line.
-	for k, _ := range bpkg.InjectedSettings() {
+	for k, _ := range bpkg.rpkg.Lpkg.InjectedSettings() {
 		ci.Cflags = append(ci.Cflags, syscfg.FeatureToCflag(k))
 	}
 
 	ci.IgnoreFiles = []*regexp.Regexp{}
-	ignPats := newtutil.GetStringSliceFeatures(bpkg.PkgV,
+	ignPats := newtutil.GetStringSliceFeatures(bpkg.rpkg.Lpkg.PkgV,
 		features, "pkg.ign_files")
 	for _, str := range ignPats {
 		re, err := regexp.Compile(str)
@@ -175,7 +163,7 @@ func (bpkg *BuildPackage) CompilerInfo(
 	}
 
 	ci.IgnoreDirs = []*regexp.Regexp{}
-	ignPats = newtutil.GetStringSliceFeatures(bpkg.PkgV,
+	ignPats = newtutil.GetStringSliceFeatures(bpkg.rpkg.Lpkg.PkgV,
 		features, "pkg.ign_dirs")
 	for _, str := range ignPats {
 		re, err := regexp.Compile(str)
@@ -186,7 +174,8 @@ func (bpkg *BuildPackage) CompilerInfo(
 		ci.IgnoreDirs = append(ci.IgnoreDirs, re)
 	}
 
-	bpkg.SourceDirectories = newtutil.GetStringSliceFeatures(bpkg.PkgV,
+	bpkg.SourceDirectories = newtutil.GetStringSliceFeatures(
+		bpkg.rpkg.Lpkg.PkgV,
 		features, "pkg.src_dirs")
 
 	includePaths, err := bpkg.recursiveIncludePaths(b)
@@ -201,7 +190,7 @@ func (bpkg *BuildPackage) CompilerInfo(
 }
 
 func (bpkg *BuildPackage) findSdkIncludes() []string {
-	sdkDir := bpkg.BasePath() + "/src/ext/"
+	sdkDir := bpkg.rpkg.Lpkg.BasePath() + "/src/ext/"
 
 	sdkPathList := []string{}
 	err := filepath.Walk(sdkDir,
@@ -221,15 +210,15 @@ func (bpkg *BuildPackage) findSdkIncludes() []string {
 }
 
 func (bpkg *BuildPackage) publicIncludeDirs(bspPkg *pkg.BspPackage) []string {
-	pkgBase := filepath.Base(bpkg.Name())
-	bp := bpkg.BasePath()
+	pkgBase := filepath.Base(bpkg.rpkg.Lpkg.Name())
+	bp := bpkg.rpkg.Lpkg.BasePath()
 
 	incls := []string{
 		bp + "/include",
 		bp + "/include/" + pkgBase + "/arch/" + bspPkg.Arch,
 	}
 
-	if bpkg.Type() == pkg.PACKAGE_TYPE_SDK {
+	if bpkg.rpkg.Lpkg.Type() == pkg.PACKAGE_TYPE_SDK {
 		incls = append(incls, bspPkg.BasePath()+"/include/bsp/")
 
 		sdkIncls := bpkg.findSdkIncludes()
@@ -240,17 +229,17 @@ func (bpkg *BuildPackage) publicIncludeDirs(bspPkg *pkg.BspPackage) []string {
 }
 
 func (bpkg *BuildPackage) privateIncludeDirs(b *Builder) []string {
-	srcDir := bpkg.BasePath() + "/src/"
+	srcDir := bpkg.rpkg.Lpkg.BasePath() + "/src/"
 
 	incls := []string{}
 	incls = append(incls, srcDir)
 	incls = append(incls, srcDir+"/arch/"+b.targetBuilder.bspPkg.Arch)
 
-	switch bpkg.Type() {
+	switch bpkg.rpkg.Lpkg.Type() {
 	case pkg.PACKAGE_TYPE_SDK:
 		// If pkgType == SDK, include all the items in "ext" directly into the
 		// include path
-		incls = append(incls, b.bspPkg.BasePath()+"/include/bsp/")
+		incls = append(incls, b.bspPkg.rpkg.Lpkg.BasePath()+"/include/bsp/")
 
 		sdkIncls := bpkg.findSdkIncludes()
 		incls = append(incls, sdkIncls...)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/buildutil.go
----------------------------------------------------------------------
diff --git a/newt/builder/buildutil.go b/newt/builder/buildutil.go
index e8299ff..15ab0c2 100644
--- a/newt/builder/buildutil.go
+++ b/newt/builder/buildutil.go
@@ -26,7 +26,7 @@ import (
 
 	log "github.com/Sirupsen/logrus"
 
-	"mynewt.apache.org/newt/newt/pkg"
+	"mynewt.apache.org/newt/newt/resolve"
 )
 
 func TestTargetName(testPkgName string) string {
@@ -64,7 +64,7 @@ func (b bpkgSorter) Swap(i, j int) {
 	b.bpkgs[i], b.bpkgs[j] = b.bpkgs[j], b.bpkgs[i]
 }
 func (b bpkgSorter) Less(i, j int) bool {
-	return b.bpkgs[i].Name() < b.bpkgs[j].Name()
+	return b.bpkgs[i].rpkg.Lpkg.Name() < b.bpkgs[j].rpkg.Lpkg.Name()
 }
 
 func (b *Builder) sortedBuildPackages() []*BuildPackage {
@@ -80,39 +80,33 @@ func (b *Builder) sortedBuildPackages() []*BuildPackage {
 	return sorter.bpkgs
 }
 
-func (b *Builder) sortedLocalPackages() []*pkg.LocalPackage {
+func (b *Builder) sortedRpkgs() []*resolve.ResolvePackage {
 	bpkgs := b.sortedBuildPackages()
 
-	lpkgs := make([]*pkg.LocalPackage, len(bpkgs), len(bpkgs))
+	rpkgs := make([]*resolve.ResolvePackage, len(bpkgs), len(bpkgs))
 	for i, bpkg := range bpkgs {
-		lpkgs[i] = bpkg.LocalPackage
+		rpkgs[i] = bpkg.rpkg
 	}
 
-	return lpkgs
+	return rpkgs
 }
 
-func logDepInfo(builders []*Builder) {
+func logDepInfo(res *resolve.Resolution) {
 	// Log API set.
 	apis := []string{}
-	apiMap := map[string]*BuildPackage{}
-	for _, b := range builders {
-		if b != nil {
-			for api, bpkg := range b.apiMap {
-				apiMap[api] = bpkg
-				apis = append(apis, api)
-			}
-		}
+	for api, _ := range res.ApiMap {
+		apis = append(apis, api)
 	}
 	sort.Strings(apis)
 
 	log.Debugf("API set:")
 	for _, api := range apis {
-		bpkg := apiMap[api]
-		log.Debugf("    * " + api + " (" + bpkg.FullName() + ")")
+		rpkg := res.ApiMap[api]
+		log.Debugf("    * " + api + " (" + rpkg.Lpkg.FullName() + ")")
 	}
 
 	// Log dependency graph.
-	dg, err := joinedDepGraph(builders)
+	dg, err := joinedDepGraph(res.Sets())
 	if err != nil {
 		log.Debugf("Error while constructing dependency graph: %s\n",
 			err.Error())
@@ -121,7 +115,7 @@ func logDepInfo(builders []*Builder) {
 	}
 
 	// Log reverse dependency graph.
-	rdg, err := joinedRevdepGraph(builders)
+	rdg, err := joinedRevdepGraph(res.Sets())
 	if err != nil {
 		log.Debugf("Error while constructing reverse dependency graph: %s\n",
 			err.Error())

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/depgraph.go
----------------------------------------------------------------------
diff --git a/newt/builder/depgraph.go b/newt/builder/depgraph.go
index 647028e..f38906c 100644
--- a/newt/builder/depgraph.go
+++ b/newt/builder/depgraph.go
@@ -23,18 +23,16 @@ import (
 	"bytes"
 	"fmt"
 
-	"mynewt.apache.org/newt/newt/pkg"
-	"mynewt.apache.org/newt/newt/project"
-	"mynewt.apache.org/newt/util"
+	"mynewt.apache.org/newt/newt/resolve"
 )
 
-type DepGraph map[*pkg.LocalPackage][]*pkg.LocalPackage
-type graphMap map[*pkg.LocalPackage]map[*pkg.LocalPackage]struct{}
+type DepGraph map[*resolve.ResolvePackage][]*resolve.ResolveDep
+type graphMap map[*resolve.ResolvePackage]map[*resolve.ResolveDep]struct{}
 
-func graphMapAdd(gm graphMap, p *pkg.LocalPackage, c *pkg.LocalPackage) {
+func graphMapAdd(gm graphMap, p *resolve.ResolvePackage, c *resolve.ResolveDep) {
 	dstGraph := gm[p]
 	if dstGraph == nil {
-		dstGraph = map[*pkg.LocalPackage]struct{}{}
+		dstGraph = map[*resolve.ResolveDep]struct{}{}
 	}
 	dstGraph[c] = struct{}{}
 
@@ -45,42 +43,34 @@ func graphMapToDepGraph(gm graphMap) DepGraph {
 	dg := DepGraph{}
 
 	for parent, childMap := range gm {
-		dg[parent] = []*pkg.LocalPackage{}
+		dg[parent] = []*resolve.ResolveDep{}
 		for child, _ := range childMap {
 			dg[parent] = append(dg[parent], child)
 		}
-		pkg.SortLclPkgs(dg[parent])
+		resolve.SortResolveDeps(dg[parent])
 	}
 
 	return dg
 }
 
-func (b *Builder) depGraph() (DepGraph, error) {
+func depGraph(rs *resolve.ResolveSet) (DepGraph, error) {
 	graph := DepGraph{}
 
-	proj := project.GetProject()
-	for parent, _ := range b.PkgMap {
-		graph[parent] = []*pkg.LocalPackage{}
+	for _, parent := range rs.Rpkgs {
+		graph[parent] = []*resolve.ResolveDep{}
 
-		for _, dep := range parent.Deps() {
-			child := proj.ResolveDependency(dep).(*pkg.LocalPackage)
-			if child == nil {
-				return nil, util.FmtNewtError(
-					"cannot resolve package \"%s\"; depender=\"%s\"",
-					dep.String(), parent.FullName())
-			}
-
-			graph[parent] = append(graph[parent], child)
+		for _, dep := range parent.Deps {
+			graph[parent] = append(graph[parent], dep)
 		}
 
-		pkg.SortLclPkgs(graph[parent])
+		resolve.SortResolveDeps(graph[parent])
 	}
 
 	return graph, nil
 }
 
-func (b *Builder) revdepGraph() (DepGraph, error) {
-	graph, err := b.depGraph()
+func revdepGraph(rs *resolve.ResolveSet) (DepGraph, error) {
+	graph, err := depGraph(rs)
 	if err != nil {
 		return nil, err
 	}
@@ -88,7 +78,11 @@ func (b *Builder) revdepGraph() (DepGraph, error) {
 	revGm := graphMap{}
 	for parent, children := range graph {
 		for _, child := range children {
-			graphMapAdd(revGm, child, parent)
+			rParent := child.Rpkg
+			rChild := *child
+			rChild.Rpkg = parent
+
+			graphMapAdd(revGm, rParent, &rChild)
 		}
 	}
 
@@ -101,7 +95,7 @@ func mergeDepGraphs(graphs ...DepGraph) DepGraph {
 	for _, graph := range graphs {
 		for parent, children := range graph {
 			if gm[parent] == nil {
-				gm[parent] = map[*pkg.LocalPackage]struct{}{}
+				gm[parent] = map[*resolve.ResolveDep]struct{}{}
 			}
 
 			for _, child := range children {
@@ -115,11 +109,11 @@ func mergeDepGraphs(graphs ...DepGraph) DepGraph {
 	return dg
 }
 
-func joinedDepGraph(builders []*Builder) (DepGraph, error) {
+func joinedDepGraph(rss []*resolve.ResolveSet) (DepGraph, error) {
 	finalGraph := DepGraph{}
 
-	for _, b := range builders {
-		graph, err := b.depGraph()
+	for _, rs := range rss {
+		graph, err := depGraph(rs)
 		if err != nil {
 			return nil, err
 		}
@@ -129,11 +123,11 @@ func joinedDepGraph(builders []*Builder) (DepGraph, error) {
 	return finalGraph, nil
 }
 
-func joinedRevdepGraph(builders []*Builder) (DepGraph, error) {
+func joinedRevdepGraph(rss []*resolve.ResolveSet) (DepGraph, error) {
 	finalGraph := DepGraph{}
 
-	for _, b := range builders {
-		graph, err := b.revdepGraph()
+	for _, rs := range rss {
+		graph, err := revdepGraph(rs)
 		if err != nil {
 			return nil, err
 		}
@@ -143,24 +137,33 @@ func joinedRevdepGraph(builders []*Builder) (DepGraph, error) {
 	return finalGraph, nil
 }
 
+func depString(dep *resolve.ResolveDep) string {
+	s := fmt.Sprintf("%s", dep.Rpkg.Lpkg.FullName())
+	if dep.Api != "" {
+		s += fmt.Sprintf("(api:%s)", dep.Api)
+	}
+
+	return s
+}
+
 func DepGraphText(graph DepGraph) string {
-	parents := make([]*pkg.LocalPackage, 0, len(graph))
+	parents := make([]*resolve.ResolvePackage, 0, len(graph))
 	for lpkg, _ := range graph {
 		parents = append(parents, lpkg)
 	}
-	parents = pkg.SortLclPkgs(parents)
+	parents = resolve.SortResolvePkgs(parents)
 
 	buffer := bytes.NewBufferString("")
 
 	fmt.Fprintf(buffer, "Dependency graph (depender --> [dependees]):")
 	for _, parent := range parents {
-		children := graph[parent]
-		fmt.Fprintf(buffer, "\n    * %s --> [", parent.FullName())
+		children := resolve.SortResolveDeps(graph[parent])
+		fmt.Fprintf(buffer, "\n    * %s --> [", parent.Lpkg.FullName())
 		for i, child := range children {
 			if i != 0 {
 				fmt.Fprintf(buffer, " ")
 			}
-			fmt.Fprintf(buffer, "%s", child.FullName())
+			fmt.Fprintf(buffer, "%s", depString(child))
 		}
 		fmt.Fprintf(buffer, "]")
 	}
@@ -169,23 +172,23 @@ func DepGraphText(graph DepGraph) string {
 }
 
 func RevdepGraphText(graph DepGraph) string {
-	parents := make([]*pkg.LocalPackage, 0, len(graph))
+	parents := make([]*resolve.ResolvePackage, 0, len(graph))
 	for lpkg, _ := range graph {
 		parents = append(parents, lpkg)
 	}
-	parents = pkg.SortLclPkgs(parents)
+	parents = resolve.SortResolvePkgs(parents)
 
 	buffer := bytes.NewBufferString("")
 
 	fmt.Fprintf(buffer, "Reverse dependency graph (dependee <-- [dependers]):")
 	for _, parent := range parents {
-		children := graph[parent]
-		fmt.Fprintf(buffer, "\n    * %s <-- [", parent.FullName())
+		children := resolve.SortResolveDeps(graph[parent])
+		fmt.Fprintf(buffer, "\n    * %s <-- [", parent.Lpkg.FullName())
 		for i, child := range children {
 			if i != 0 {
 				fmt.Fprintf(buffer, " ")
 			}
-			fmt.Fprintf(buffer, "%s", child.FullName())
+			fmt.Fprintf(buffer, "%s", depString(child))
 		}
 		fmt.Fprintf(buffer, "]")
 	}
@@ -195,15 +198,18 @@ func RevdepGraphText(graph DepGraph) string {
 
 // Extracts a new dependency graph containing only the specified parents.
 //
-// @return DepGraph             Filtered dependency graph
-//         []*pkg.LocalPackage  Specified packages that were not parents in
+// @param dg                    The source graph to filter.
+// @param parents               The parent nodes to keep.
+//
+// @return DepGraph             Filtered dependency graph.
+//         []*ResolvePackage    Specified packages that were not parents in
 //                                  original graph.
-func FilterDepGraph(dg DepGraph, parents []*pkg.LocalPackage) (
-	DepGraph, []*pkg.LocalPackage) {
+func FilterDepGraph(dg DepGraph, parents []*resolve.ResolvePackage) (
+	DepGraph, []*resolve.ResolvePackage) {
 
 	newDg := DepGraph{}
 
-	var missing []*pkg.LocalPackage
+	var missing []*resolve.ResolvePackage
 	for _, p := range parents {
 		if dg[p] == nil {
 			missing = append(missing, p)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/library.go
----------------------------------------------------------------------
diff --git a/newt/builder/library.go b/newt/builder/library.go
index fd6f71c..af3c5b8 100644
--- a/newt/builder/library.go
+++ b/newt/builder/library.go
@@ -162,7 +162,7 @@ func (b *Builder) ParseObjectLibraryFile(bp *BuildPackage,
 
 			/* assign the library */
 			if bp != nil {
-				(*si).Bpkg = bp.Name()
+				(*si).Bpkg = bp.rpkg.Lpkg.Name()
 			} else {
 				(*si).Bpkg = "elf"
 			}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/load.go
----------------------------------------------------------------------
diff --git a/newt/builder/load.go b/newt/builder/load.go
index 1cf9a84..eb7396e 100644
--- a/newt/builder/load.go
+++ b/newt/builder/load.go
@@ -171,7 +171,7 @@ func (b *Builder) debugBin(binPath string, extraJtagCmd string, reset bool,
 		return err
 	}
 
-	bspPath := b.bspPkg.BasePath()
+	bspPath := b.bspPkg.rpkg.Lpkg.BasePath()
 	binBaseName := binPath
 	featureString := b.FeatureString()
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/paths.go
----------------------------------------------------------------------
diff --git a/newt/builder/paths.go b/newt/builder/paths.go
index b57dd2c..5beb6b3 100644
--- a/newt/builder/paths.go
+++ b/newt/builder/paths.go
@@ -123,39 +123,41 @@ func MfgBootDir(mfgPkgName string) string {
 }
 
 func (b *Builder) BinDir() string {
-	return BinDir(b.targetPkg.Name(), b.buildName)
+	return BinDir(b.targetPkg.rpkg.Lpkg.Name(), b.buildName)
 }
 
 func (b *Builder) FileBinDir(pkgName string) string {
-	return FileBinDir(b.targetPkg.Name(), b.buildName, pkgName)
+	return FileBinDir(b.targetPkg.rpkg.Lpkg.Name(), b.buildName, pkgName)
 }
 
 func (b *Builder) PkgBinDir(bpkg *BuildPackage) string {
-	return PkgBinDir(b.targetPkg.Name(), b.buildName, bpkg.Name(), bpkg.Type())
+	return PkgBinDir(b.targetPkg.rpkg.Lpkg.Name(), b.buildName, bpkg.rpkg.Lpkg.Name(),
+		bpkg.rpkg.Lpkg.Type())
 }
 
 // Generates the path+filename of the specified package's .a file.
 func (b *Builder) ArchivePath(bpkg *BuildPackage) string {
-	return ArchivePath(b.targetPkg.Name(), b.buildName, bpkg.Name(),
-		bpkg.Type())
+	return ArchivePath(b.targetPkg.rpkg.Lpkg.Name(), b.buildName, bpkg.rpkg.Lpkg.Name(),
+		bpkg.rpkg.Lpkg.Type())
 }
 
 func (b *Builder) AppTentativeElfPath() string {
-	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.Name()) +
+	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.rpkg.Lpkg.Name()) +
 		"_tmp.elf"
 }
 
 func (b *Builder) AppElfPath() string {
-	return AppElfPath(b.targetPkg.Name(), b.buildName, b.appPkg.Name())
+	return AppElfPath(b.targetPkg.rpkg.Lpkg.Name(), b.buildName,
+		b.appPkg.rpkg.Lpkg.Name())
 }
 
 func (b *Builder) AppLinkerElfPath() string {
-	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.Name()) +
+	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.rpkg.Lpkg.Name()) +
 		"linker.elf"
 }
 
 func (b *Builder) AppImgPath() string {
-	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.Name()) +
+	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.rpkg.Lpkg.Name()) +
 		".img"
 }
 
@@ -168,14 +170,16 @@ func (b *Builder) AppPath() string {
 }
 
 func (b *Builder) TestExePath(bpkg *BuildPackage) string {
-	return TestExePath(b.targetPkg.Name(), b.buildName, bpkg.Name(),
-		bpkg.Type())
+	return TestExePath(b.targetPkg.rpkg.Lpkg.Name(), b.buildName,
+		bpkg.rpkg.Lpkg.Name(), bpkg.rpkg.Lpkg.Type())
 }
 
 func (b *Builder) ManifestPath() string {
-	return ManifestPath(b.targetPkg.Name(), b.buildName, b.appPkg.Name())
+	return ManifestPath(b.targetPkg.rpkg.Lpkg.Name(), b.buildName,
+		b.appPkg.rpkg.Lpkg.Name())
 }
 
 func (b *Builder) AppBinBasePath() string {
-	return b.PkgBinDir(b.appPkg) + "/" + filepath.Base(b.appPkg.Name())
+	return b.PkgBinDir(b.appPkg) + "/" +
+		filepath.Base(b.appPkg.rpkg.Lpkg.Name())
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/selftest.go
----------------------------------------------------------------------
diff --git a/newt/builder/selftest.go b/newt/builder/selftest.go
index 36781b7..fc7268c 100644
--- a/newt/builder/selftest.go
+++ b/newt/builder/selftest.go
@@ -27,11 +27,28 @@ import (
 
 	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
+	"mynewt.apache.org/newt/newt/resolve"
 	"mynewt.apache.org/newt/util"
 )
 
-func (b *Builder) SelfTestLink(p *pkg.LocalPackage) error {
-	testBpkg := b.PkgMap[p]
+func (b *Builder) getTestBpkg(rpkg *resolve.ResolvePackage) (
+	*BuildPackage, error) {
+
+	testBpkg := b.PkgMap[rpkg]
+	if testBpkg == nil {
+		return nil, util.FmtNewtError("builder missing test package: %s",
+			rpkg.Lpkg.FullName())
+	}
+
+	return testBpkg, nil
+}
+
+func (b *Builder) SelfTestLink(rpkg *resolve.ResolvePackage) error {
+	testBpkg, err := b.getTestBpkg(rpkg)
+	if err != nil {
+		return err
+	}
+
 	testPath := b.TestExePath(testBpkg)
 	if err := b.link(testPath, nil, nil); err != nil {
 		return err
@@ -40,6 +57,16 @@ func (b *Builder) SelfTestLink(p *pkg.LocalPackage) error {
 	return nil
 }
 
+func (t *TargetBuilder) getTestRpkg() (*resolve.ResolvePackage, error) {
+	testRpkg := t.res.LpkgRpkgMap[t.testPkg]
+	if testRpkg == nil {
+		return nil, util.FmtNewtError("resolution missing test package: %s",
+			t.testPkg.FullName())
+	}
+
+	return testRpkg, nil
+}
+
 func (t *TargetBuilder) SelfTestCreateExe() error {
 	if err := t.PrepBuild(); err != nil {
 		return err
@@ -49,7 +76,12 @@ func (t *TargetBuilder) SelfTestCreateExe() error {
 		return err
 	}
 
-	if err := t.AppBuilder.SelfTestLink(t.testPkg); err != nil {
+	testRpkg, err := t.getTestRpkg()
+	if err != nil {
+		return err
+	}
+
+	if err := t.AppBuilder.SelfTestLink(testRpkg); err != nil {
 		return err
 	}
 
@@ -61,7 +93,12 @@ func (t *TargetBuilder) SelfTestExecute() error {
 		return err
 	}
 
-	if err := t.AppBuilder.SelfTestExecute(t.testPkg); err != nil {
+	testRpkg, err := t.getTestRpkg()
+	if err != nil {
+		return err
+	}
+
+	if err := t.AppBuilder.SelfTestExecute(testRpkg); err != nil {
 		return err
 	}
 
@@ -73,29 +110,27 @@ func (t *TargetBuilder) SelfTestDebug() error {
 		return err
 	}
 
-	lpkg := t.GetTestPkg()
-	if lpkg == nil {
-		panic("internal error: attempt to debug target builder with no test " +
-			"package")
+	testRpkg, err := t.getTestRpkg()
+	if err != nil {
+		return err
 	}
 
-	bpkg := t.AppBuilder.PkgMap[lpkg]
-	if bpkg == nil {
-		panic("internal error: local package \"" + lpkg.FullName() +
-			"\" not built")
+	testBpkg, err := t.AppBuilder.getTestBpkg(testRpkg)
+	if err != nil {
+		return err
 	}
 
 	return t.AppBuilder.debugBin(
-		strings.TrimSuffix(t.AppBuilder.TestExePath(bpkg), ".elf"),
+		strings.TrimSuffix(t.AppBuilder.TestExePath(testBpkg), ".elf"),
 		"", false, false)
 }
 
-func (b *Builder) testOwner(p *BuildPackage) *BuildPackage {
-	if p.Type() != pkg.PACKAGE_TYPE_UNITTEST {
-		panic("Expected unittest package; got: " + p.Name())
+func (b *Builder) testOwner(bpkg *BuildPackage) *BuildPackage {
+	if bpkg.rpkg.Lpkg.Type() != pkg.PACKAGE_TYPE_UNITTEST {
+		panic("Expected unittest package; got: " + bpkg.rpkg.Lpkg.Name())
 	}
 
-	curPath := p.BasePath()
+	curPath := bpkg.rpkg.Lpkg.BasePath()
 
 	for {
 		parentPath := filepath.Dir(curPath)
@@ -104,7 +139,9 @@ func (b *Builder) testOwner(p *BuildPackage) *BuildPackage {
 		}
 
 		parentPkg := b.pkgWithPath(parentPath)
-		if parentPkg != nil && parentPkg.Type() != pkg.PACKAGE_TYPE_UNITTEST {
+		if parentPkg != nil &&
+			parentPkg.rpkg.Lpkg.Type() != pkg.PACKAGE_TYPE_UNITTEST {
+
 			return parentPkg
 		}
 
@@ -112,11 +149,10 @@ func (b *Builder) testOwner(p *BuildPackage) *BuildPackage {
 	}
 }
 
-func (b *Builder) SelfTestExecute(p *pkg.LocalPackage) error {
-	testBpkg := b.PkgMap[p]
-	if testBpkg == nil {
-		panic("internal error; package-under-test \"" + p.FullName() +
-			"\" not in builder")
+func (b *Builder) SelfTestExecute(testRpkg *resolve.ResolvePackage) error {
+	testBpkg, err := b.getTestBpkg(testRpkg)
+	if err != nil {
+		return err
 	}
 
 	testPath := b.TestExePath(testBpkg)
@@ -129,8 +165,8 @@ func (b *Builder) SelfTestExecute(p *pkg.LocalPackage) error {
 	cmd := []string{testPath}
 	if _, err := util.ShellCommand(cmd, nil); err != nil {
 		newtError := err.(*util.NewtError)
-		newtError.Text = fmt.Sprintf("Test failure (%s):\n%s", p.Name(),
-			newtError.Text)
+		newtError.Text = fmt.Sprintf("Test failure (%s):\n%s",
+			testRpkg.Lpkg.Name(), newtError.Text)
 		return newtError
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index 072e0b8..2bea6ef 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -98,19 +98,6 @@ func NewTargetBuilder(target *target.Target) (*TargetBuilder, error) {
 	return NewTargetTester(target, nil)
 }
 
-func (t *TargetBuilder) Builders() []*Builder {
-	builders := []*Builder{}
-
-	if t.LoaderBuilder != nil {
-		builders = append(builders, t.LoaderBuilder)
-	}
-	if t.AppBuilder != nil {
-		builders = append(builders, t.AppBuilder)
-	}
-
-	return builders
-}
-
 func (t *TargetBuilder) NewCompiler(dstDir string) (
 	*toolchain.Compiler, error) {
 
@@ -217,12 +204,14 @@ func (t *TargetBuilder) generateSysinit() error {
 
 	srcDir := GeneratedSrcDir(t.target.Name())
 
-	if t.res.LoaderPkgs != nil {
-		sysinit.EnsureWritten(t.res.LoaderPkgs, srcDir,
+	if t.res.LoaderSet != nil {
+		lpkgs := resolve.RpkgSliceToLpkgSlice(t.res.LoaderSet.Rpkgs)
+		sysinit.EnsureWritten(lpkgs, srcDir,
 			pkg.ShortName(t.target.Package()), true)
 	}
 
-	sysinit.EnsureWritten(t.res.AppPkgs, srcDir,
+	lpkgs := resolve.RpkgSliceToLpkgSlice(t.res.AppSet.Rpkgs)
+	sysinit.EnsureWritten(lpkgs, srcDir,
 		pkg.ShortName(t.target.Package()), false)
 
 	return nil
@@ -262,9 +251,9 @@ func (t *TargetBuilder) PrepBuild() error {
 	}
 
 	var err error
-	if t.res.LoaderPkgs != nil {
+	if t.res.LoaderSet != nil {
 		t.LoaderBuilder, err = NewBuilder(t, BUILD_NAME_LOADER,
-			t.res.LoaderPkgs, t.res.ApiMap, t.res.Cfg)
+			t.res.LoaderSet.Rpkgs, t.res.ApiMap, t.res.Cfg)
 		if err != nil {
 			return err
 		}
@@ -279,7 +268,7 @@ func (t *TargetBuilder) PrepBuild() error {
 		t.LoaderList = project.ResetDeps(nil)
 	}
 
-	t.AppBuilder, err = NewBuilder(t, BUILD_NAME_APP, t.res.AppPkgs,
+	t.AppBuilder, err = NewBuilder(t, BUILD_NAME_APP, t.res.AppSet.Rpkgs,
 		t.res.ApiMap, t.res.Cfg)
 	if err != nil {
 		return err
@@ -288,7 +277,7 @@ func (t *TargetBuilder) PrepBuild() error {
 		return err
 	}
 
-	if t.res.LoaderPkgs != nil {
+	if t.res.LoaderSet != nil {
 		appFlags := toolchain.NewCompilerInfo()
 		appFlags.Cflags = append(appFlags.Cflags, "-DSPLIT_APPLICATION")
 		t.AppBuilder.AddCompilerInfo(appFlags)
@@ -296,7 +285,7 @@ func (t *TargetBuilder) PrepBuild() error {
 
 	t.AppList = project.ResetDeps(nil)
 
-	logDepInfo(t.Builders())
+	logDepInfo(t.res)
 
 	if err := t.generateCode(); err != nil {
 		return err
@@ -400,12 +389,12 @@ func (t *TargetBuilder) RelinkLoader() (error, map[string]bool,
 
 	/* fetch symbols from the elf and from the libraries themselves */
 	log.Debugf("Loader packages:")
-	for _, lpkg := range t.LoaderBuilder.sortedLocalPackages() {
-		log.Debugf("    * %s", lpkg.Name())
+	for _, rpkg := range t.LoaderBuilder.sortedRpkgs() {
+		log.Debugf("    * %s", rpkg.Lpkg.Name())
 	}
 	log.Debugf("App packages:")
-	for _, lpkg := range t.AppBuilder.sortedLocalPackages() {
-		log.Debugf("    * %s", lpkg.Name())
+	for _, rpkg := range t.AppBuilder.sortedRpkgs() {
+		log.Debugf("    * %s", rpkg.Lpkg.Name())
 	}
 	err, appLibSym := t.AppBuilder.ExtractSymbolInfo()
 	if err != nil {
@@ -439,14 +428,14 @@ func (t *TargetBuilder) RelinkLoader() (error, map[string]bool,
 	uncommonPkgs := smNomatch.Packages()
 
 	/* ensure that the loader and app packages are never shared */
-	delete(commonPkgs, t.AppBuilder.appPkg.Name())
-	uncommonPkgs[t.AppBuilder.appPkg.Name()] = true
-	ma := smMatch.FilterPkg(t.AppBuilder.appPkg.Name())
+	delete(commonPkgs, t.AppBuilder.appPkg.rpkg.Lpkg.Name())
+	uncommonPkgs[t.AppBuilder.appPkg.rpkg.Lpkg.Name()] = true
+	ma := smMatch.FilterPkg(t.AppBuilder.appPkg.rpkg.Lpkg.Name())
 	smMatch.RemoveMap(ma)
 
-	delete(commonPkgs, t.LoaderBuilder.appPkg.Name())
-	uncommonPkgs[t.LoaderBuilder.appPkg.Name()] = true
-	ml := smMatch.FilterPkg(t.LoaderBuilder.appPkg.Name())
+	delete(commonPkgs, t.LoaderBuilder.appPkg.rpkg.Lpkg.Name())
+	uncommonPkgs[t.LoaderBuilder.appPkg.rpkg.Lpkg.Name()] = true
+	ml := smMatch.FilterPkg(t.LoaderBuilder.appPkg.rpkg.Lpkg.Name())
 	smMatch.RemoveMap(ml)
 
 	util.StatusMessage(util.VERBOSITY_VERBOSE,
@@ -457,9 +446,9 @@ func (t *TargetBuilder) RelinkLoader() (error, map[string]bool,
 	var symbolStr string
 	for v, _ := range uncommonPkgs {
 		if t.AppBuilder.appPkg != nil &&
-			t.AppBuilder.appPkg.Name() != v &&
+			t.AppBuilder.appPkg.rpkg.Lpkg.Name() != v &&
 			t.LoaderBuilder.appPkg != nil &&
-			t.LoaderBuilder.appPkg.Name() != v {
+			t.LoaderBuilder.appPkg.rpkg.Lpkg.Name() != v {
 
 			trouble := smNomatch.FilterPkg(v)
 
@@ -551,15 +540,15 @@ func (t *TargetBuilder) createManifest() error {
 	}
 
 	rm := image.NewRepoManager()
-	for _, lpkg := range t.AppBuilder.sortedLocalPackages() {
+	for _, rpkg := range t.AppBuilder.sortedRpkgs() {
 		manifest.Pkgs = append(manifest.Pkgs,
-			rm.GetImageManifestPkg(lpkg))
+			rm.GetImageManifestPkg(rpkg.Lpkg))
 	}
 
 	if t.LoaderBuilder != nil {
-		for _, lpkg := range t.LoaderBuilder.sortedLocalPackages() {
+		for _, rpkg := range t.LoaderBuilder.sortedRpkgs() {
 			manifest.LoaderPkgs = append(manifest.LoaderPkgs,
-				rm.GetImageManifestPkg(lpkg))
+				rm.GetImageManifestPkg(rpkg.Lpkg))
 		}
 	}
 
@@ -676,9 +665,17 @@ func (t *TargetBuilder) CreateImages(version string,
 }
 
 func (t *TargetBuilder) CreateDepGraph() (DepGraph, error) {
-	return joinedDepGraph(t.Builders())
+	if err := t.ensureResolved(); err != nil {
+		return nil, err
+	}
+
+	return joinedDepGraph(t.res.Sets())
 }
 
 func (t *TargetBuilder) CreateRevdepGraph() (DepGraph, error) {
-	return joinedRevdepGraph(t.Builders())
+	if err := t.ensureResolved(); err != nil {
+		return nil, err
+	}
+
+	return joinedRevdepGraph(t.res.Sets())
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/cli/target_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/target_cmds.go b/newt/cli/target_cmds.go
index ded8183..54511fa 100644
--- a/newt/cli/target_cmds.go
+++ b/newt/cli/target_cmds.go
@@ -615,7 +615,8 @@ func targetDepCmd(cmd *cobra.Command, args []string) {
 		NewtUsage(cmd, err)
 	}
 
-	if err := b.PrepBuild(); err != nil {
+	res, err := b.Resolve()
+	if err != nil {
 		NewtUsage(nil, err)
 	}
 
@@ -626,17 +627,17 @@ func targetDepCmd(cmd *cobra.Command, args []string) {
 
 	// If user specified any package names, only include specified packages.
 	if len(args) > 1 {
-		lpkgs, err := ResolvePackages(args[1:])
+		rpkgs, err := ResolveRpkgs(res, args[1:])
 		if err != nil {
 			NewtUsage(cmd, err)
 		}
 
-		var missingLpkgs []*pkg.LocalPackage
-		dg, missingLpkgs = builder.FilterDepGraph(dg, lpkgs)
-		for _, lpkg := range missingLpkgs {
+		var missingRpkgs []*resolve.ResolvePackage
+		dg, missingRpkgs = builder.FilterDepGraph(dg, rpkgs)
+		for _, rpkg := range missingRpkgs {
 			util.StatusMessage(util.VERBOSITY_QUIET,
 				"Warning: Package \"%s\" not included in target \"%s\"\n",
-				lpkg.FullName(), b.GetTarget().FullName())
+				rpkg.Lpkg.FullName(), b.GetTarget().FullName())
 		}
 	}
 
@@ -658,7 +659,8 @@ func targetRevdepCmd(cmd *cobra.Command, args []string) {
 		NewtUsage(cmd, err)
 	}
 
-	if err := b.PrepBuild(); err != nil {
+	res, err := b.Resolve()
+	if err != nil {
 		NewtUsage(nil, err)
 	}
 
@@ -669,17 +671,17 @@ func targetRevdepCmd(cmd *cobra.Command, args []string) {
 
 	// If user specified any package names, only include specified packages.
 	if len(args) > 1 {
-		lpkgs, err := ResolvePackages(args[1:])
+		rpkgs, err := ResolveRpkgs(res, args[1:])
 		if err != nil {
 			NewtUsage(cmd, err)
 		}
 
-		var missingLpkgs []*pkg.LocalPackage
-		dg, missingLpkgs = builder.FilterDepGraph(dg, lpkgs)
-		for _, lpkg := range missingLpkgs {
+		var missingRpkgs []*resolve.ResolvePackage
+		dg, missingRpkgs = builder.FilterDepGraph(dg, rpkgs)
+		for _, rpkg := range missingRpkgs {
 			util.StatusMessage(util.VERBOSITY_QUIET,
 				"Warning: Package \"%s\" not included in target \"%s\"\n",
-				lpkg.FullName(), b.GetTarget().FullName())
+				rpkg.Lpkg.FullName(), b.GetTarget().FullName())
 		}
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/cli/util.go
----------------------------------------------------------------------
diff --git a/newt/cli/util.go b/newt/cli/util.go
index 0ab578e..e9c0b4c 100644
--- a/newt/cli/util.go
+++ b/newt/cli/util.go
@@ -35,6 +35,7 @@ import (
 	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
+	"mynewt.apache.org/newt/newt/resolve"
 	"mynewt.apache.org/newt/newt/target"
 	"mynewt.apache.org/newt/util"
 )
@@ -296,6 +297,28 @@ func ResolvePackages(pkgNames []string) ([]*pkg.LocalPackage, error) {
 	return lpkgs, nil
 }
 
+func ResolveRpkgs(res *resolve.Resolution, pkgNames []string) (
+	[]*resolve.ResolvePackage, error) {
+
+	lpkgs, err := ResolvePackages(pkgNames)
+	if err != nil {
+		return nil, err
+	}
+
+	rpkgs := []*resolve.ResolvePackage{}
+	for _, lpkg := range lpkgs {
+		rpkg := res.LpkgRpkgMap[lpkg]
+		if rpkg == nil {
+			return nil, util.FmtNewtError("Unexpected error; local package "+
+				"%s lacks a corresponding resolve package", lpkg.FullName())
+		}
+
+		rpkgs = append(rpkgs, rpkg)
+	}
+
+	return rpkgs, nil
+}
+
 func TargetBuilderForTargetOrUnittest(pkgName string) (
 	*builder.TargetBuilder, error) {
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/pkg/localpackage.go
----------------------------------------------------------------------
diff --git a/newt/pkg/localpackage.go b/newt/pkg/localpackage.go
index b34bd59..8c935b1 100644
--- a/newt/pkg/localpackage.go
+++ b/newt/pkg/localpackage.go
@@ -61,9 +61,6 @@ type LocalPackage struct {
 	// General information about the package
 	desc *PackageDesc
 
-	// Dependencies for this package
-	deps map[string]*Dependency
-
 	// Package init function name and stage.  These are used to generate the
 	// sysinit C file.
 	init map[string]int
@@ -89,7 +86,6 @@ func NewLocalPackage(r *repo.Repo, pkgDir string) *LocalPackage {
 		SyscfgV:          viper.New(),
 		repo:             r,
 		basePath:         filepath.ToSlash(filepath.Clean(pkgDir)),
-		deps:             map[string]*Dependency{},
 		init:             map[string]int{},
 		injectedSettings: map[string]string{},
 	}
@@ -196,34 +192,6 @@ func (pkg *LocalPackage) AddCfgFilename(cfgFilename string) {
 	pkg.cfgFilenames = append(pkg.cfgFilenames, cfgFilename)
 }
 
-func (pkg *LocalPackage) HasDep(searchDep *Dependency) bool {
-	return pkg.deps[searchDep.String()] != nil
-}
-
-func (pkg *LocalPackage) AddDep(dep *Dependency) bool {
-	if pkg.deps[dep.String()] != nil {
-		return false
-	}
-
-	pkg.deps[dep.String()] = dep
-	return true
-}
-
-func (pkg *LocalPackage) Deps() []*Dependency {
-	names := make([]string, 0, len(pkg.deps))
-	for name, _ := range pkg.deps {
-		names = append(names, name)
-	}
-	sort.Strings(names)
-
-	deps := make([]*Dependency, len(names))
-	for i, name := range names {
-		deps[i] = pkg.deps[name]
-	}
-
-	return deps
-}
-
 func (pkg *LocalPackage) readDesc(v *viper.Viper) (*PackageDesc, error) {
 	pdesc := &PackageDesc{}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/pkg/package.go
----------------------------------------------------------------------
diff --git a/newt/pkg/package.go b/newt/pkg/package.go
index 03795cb..d5d9403 100644
--- a/newt/pkg/package.go
+++ b/newt/pkg/package.go
@@ -75,8 +75,6 @@ type Package interface {
 	Hash() (string, error)
 	// Description of this package
 	Desc() *PackageDesc
-	// Dependency list for this package
-	Deps() []*Dependency
 	// APIs exported by this package
 	Apis() []string
 	// APIs required by this package

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/resolve/resolve.go
----------------------------------------------------------------------
diff --git a/newt/resolve/resolve.go b/newt/resolve/resolve.go
index 916f38c..c4a1d38 100644
--- a/newt/resolve/resolve.go
+++ b/newt/resolve/resolve.go
@@ -42,8 +42,19 @@ type Resolver struct {
 	cfg              syscfg.Cfg
 }
 
+type ResolveDep struct {
+	// Package being depended on.
+	Rpkg *ResolvePackage
+
+	// Name of API that generated the dependency; "" if a hard dependency.
+	Api string
+
+	// XXX: slice of syscfg settings that generated this dependency.
+}
+
 type ResolvePackage struct {
-	*pkg.LocalPackage
+	Lpkg *pkg.LocalPackage
+	Deps map[*ResolvePackage]*ResolveDep
 
 	// Keeps track of API requirements and whether they are satisfied.
 	reqApiMap map[string]bool
@@ -52,14 +63,23 @@ type ResolvePackage struct {
 	apisSatisfied bool
 }
 
+type ResolveSet struct {
+	// Parent resoluion.  Contains this ResolveSet.
+	Res *Resolution
+
+	// All seed pacakges and their dependencies.
+	Rpkgs []*ResolvePackage
+}
+
 // The result of resolving a target's configuration, APIs, and dependencies.
 type Resolution struct {
 	Cfg             syscfg.Cfg
-	ApiMap          map[string]*pkg.LocalPackage
-	UnsatisfiedApis map[string][]*pkg.LocalPackage
+	ApiMap          map[string]*ResolvePackage
+	UnsatisfiedApis map[string][]*ResolvePackage
 
-	LoaderPkgs []*pkg.LocalPackage
-	AppPkgs    []*pkg.LocalPackage
+	LpkgRpkgMap map[*pkg.LocalPackage]*ResolvePackage
+	LoaderSet   *ResolveSet
+	AppSet      *ResolveSet
 }
 
 func newResolver(
@@ -86,23 +106,80 @@ func newResolver(
 	return r
 }
 
-func newResolvePkg(lpkg *pkg.LocalPackage) *ResolvePackage {
+func newResolution() *Resolution {
+	r := &Resolution{
+		ApiMap:          map[string]*ResolvePackage{},
+		UnsatisfiedApis: map[string][]*ResolvePackage{},
+	}
+
+	r.LoaderSet = &ResolveSet{Res: r}
+	r.AppSet = &ResolveSet{Res: r}
+
+	return r
+}
+
+func (res *Resolution) Sets() []*ResolveSet {
+	rss := []*ResolveSet{}
+
+	if res.LoaderSet != nil {
+		rss = append(rss, res.LoaderSet)
+	}
+	if res.AppSet != nil {
+		rss = append(rss, res.AppSet)
+	}
+
+	return rss
+}
+
+func NewResolvePkg(lpkg *pkg.LocalPackage) *ResolvePackage {
 	return &ResolvePackage{
-		LocalPackage: lpkg,
-		reqApiMap:    map[string]bool{},
+		Lpkg:      lpkg,
+		reqApiMap: map[string]bool{},
+		Deps:      map[*ResolvePackage]*ResolveDep{},
 	}
 }
 
-func (r *Resolver) lpkgSlice() []*pkg.LocalPackage {
-	lpkgs := make([]*pkg.LocalPackage, len(r.pkgMap))
+func (r *Resolver) resolveDep(dep *pkg.Dependency) (*pkg.LocalPackage, error) {
+	proj := project.GetProject()
+
+	lpkg := proj.ResolveDependency(dep).(*pkg.LocalPackage)
+	if lpkg == nil {
+		return nil, util.FmtNewtError("Could not resolve package dependency: "+
+			"%s; depender: %s", dep.String(), dep.Name)
+	}
+
+	return lpkg, nil
+}
+
+// @return                      true if rhe package's dependency list was
+//                                  modified.
+func (rpkg *ResolvePackage) AddDep(apiPkg *ResolvePackage, api string) bool {
+	if dep := rpkg.Deps[apiPkg]; dep != nil {
+		if dep.Api != "" && api == "" {
+			dep.Api = api
+			return true
+		} else {
+			return false
+		}
+	} else {
+		rpkg.Deps[apiPkg] = &ResolveDep{
+			Rpkg: apiPkg,
+			Api:  api,
+		}
+		return true
+	}
+}
+
+func (r *Resolver) rpkgSlice() []*ResolvePackage {
+	rpkgs := make([]*ResolvePackage, len(r.pkgMap))
 
 	i := 0
 	for _, rpkg := range r.pkgMap {
-		lpkgs[i] = rpkg.LocalPackage
+		rpkgs[i] = rpkg
 		i++
 	}
 
-	return lpkgs
+	return rpkgs
 }
 
 func (r *Resolver) apiSlice() []string {
@@ -117,14 +194,18 @@ func (r *Resolver) apiSlice() []string {
 	return apis
 }
 
-// @return bool					true if this is a new package.
-func (r *Resolver) addPkg(lpkg *pkg.LocalPackage) bool {
+// @return ResolvePackage		The rpkg corresponding to the specified lpkg.
+//                                  This is a new package if a package was
+//                                  added; old if it was already present.
+//         bool					true if this is a new package.
+func (r *Resolver) addPkg(lpkg *pkg.LocalPackage) (*ResolvePackage, bool) {
 	if rpkg := r.pkgMap[lpkg]; rpkg != nil {
-		return false
+		return rpkg, false
 	}
 
-	r.pkgMap[lpkg] = newResolvePkg(lpkg)
-	return true
+	rpkg := NewResolvePkg(lpkg)
+	r.pkgMap[lpkg] = rpkg
+	return rpkg, true
 }
 
 // @return bool                 true if this is a new API.
@@ -137,7 +218,7 @@ func (r *Resolver) addApi(apiString string, rpkg *ResolvePackage) bool {
 		if curRpkg != rpkg {
 			util.StatusMessage(util.VERBOSITY_QUIET,
 				"Warning: API conflict: %s (%s <-> %s)\n", apiString,
-				curRpkg.Name(), rpkg.Name())
+				curRpkg.Lpkg.Name(), rpkg.Lpkg.Name())
 		}
 		return false
 	}
@@ -146,6 +227,8 @@ func (r *Resolver) addApi(apiString string, rpkg *ResolvePackage) bool {
 // Searches for a package which can satisfy bpkg's API requirement.  If such a
 // package is found, bpkg's API requirement is marked as satisfied, and the
 // package is added to bpkg's dependency list.
+//
+// @return bool                 true if the API is now satisfied.
 func (r *Resolver) satisfyApi(rpkg *ResolvePackage, reqApi string) bool {
 	depRpkg := r.apis[reqApi]
 	if depRpkg == nil {
@@ -160,7 +243,7 @@ func (r *Resolver) satisfyApi(rpkg *ResolvePackage, reqApi string) bool {
 	rpkg.depsResolved = false
 
 	log.Debugf("API requirement satisfied; pkg=%s API=(%s, %s)",
-		rpkg.Name(), reqApi, depRpkg.FullName())
+		rpkg.Lpkg.Name(), reqApi, depRpkg.Lpkg.FullName())
 
 	return true
 }
@@ -174,11 +257,11 @@ func (r *Resolver) satisfyApis(rpkg *ResolvePackage) bool {
 	rpkg.apisSatisfied = true
 	newDeps := false
 
-	features := r.cfg.FeaturesForLpkg(rpkg.LocalPackage)
+	features := r.cfg.FeaturesForLpkg(rpkg.Lpkg)
 
 	// Determine if any of the package's API requirements can now be satisfied.
 	// If so, another full iteration is required.
-	reqApis := newtutil.GetStringSliceFeatures(rpkg.PkgV, features,
+	reqApis := newtutil.GetStringSliceFeatures(rpkg.Lpkg.PkgV, features,
 		"pkg.req_apis")
 	for _, reqApi := range reqApis {
 		reqStatus := rpkg.reqApiMap[reqApi]
@@ -204,39 +287,34 @@ func (r *Resolver) satisfyApis(rpkg *ResolvePackage) bool {
 //                                  in this case.
 //         error                non-nil on failure.
 func (r *Resolver) loadDepsForPkg(rpkg *ResolvePackage) (bool, error) {
-	proj := project.GetProject()
-	features := r.cfg.FeaturesForLpkg(rpkg.LocalPackage)
+	features := r.cfg.FeaturesForLpkg(rpkg.Lpkg)
 
 	changed := false
-	newDeps := newtutil.GetStringSliceFeatures(rpkg.PkgV, features, "pkg.deps")
+	newDeps := newtutil.GetStringSliceFeatures(rpkg.Lpkg.PkgV, features,
+		"pkg.deps")
 	for _, newDepStr := range newDeps {
-		newDep, err := pkg.NewDependency(rpkg.Repo(), newDepStr)
+		newDep, err := pkg.NewDependency(rpkg.Lpkg.Repo(), newDepStr)
 		if err != nil {
 			return false, err
 		}
 
-		lpkg, ok := proj.ResolveDependency(newDep).(*pkg.LocalPackage)
-		if !ok {
-			return false,
-				util.FmtNewtError("Could not resolve package dependency: "+
-					"%s; depender: %s", newDep.String(), rpkg.FullName())
-		}
-
-		if r.addPkg(lpkg) {
-			changed = true
+		lpkg, err := r.resolveDep(newDep)
+		if err != nil {
+			return false, err
 		}
 
-		if rpkg.AddDep(newDep) {
+		depRpkg, _ := r.addPkg(lpkg)
+		if rpkg.AddDep(depRpkg, "") {
 			changed = true
 		}
 	}
 
 	// Determine if this package supports any APIs that we haven't seen
 	// yet.  If so, another full iteration is required.
-	apis := newtutil.GetStringSliceFeatures(rpkg.PkgV, features, "pkg.apis")
+	apis := newtutil.GetStringSliceFeatures(rpkg.Lpkg.PkgV, features,
+		"pkg.apis")
 	for _, api := range apis {
-		newApi := r.addApi(api, rpkg)
-		if newApi {
+		if r.addApi(api, rpkg) {
 			changed = true
 		}
 	}
@@ -278,7 +356,7 @@ func (r *Resolver) resolvePkg(rpkg *ResolvePackage) (bool, error) {
 
 // @return                      changed,err
 func (r *Resolver) reloadCfg() (bool, error) {
-	lpkgs := r.lpkgSlice()
+	lpkgs := RpkgSliceToLpkgSlice(r.rpkgSlice())
 	apis := r.apiSlice()
 
 	// Determine which features have been detected so far.  The feature map is
@@ -330,7 +408,7 @@ func (r *Resolver) resolveDepsOnce() (bool, error) {
 	return newDeps, nil
 }
 
-func (r *Resolver) resolveDeps() ([]*pkg.LocalPackage, error) {
+func (r *Resolver) resolveDeps() ([]*ResolvePackage, error) {
 	if _, err := r.resolveDepsOnce(); err != nil {
 		return nil, err
 	}
@@ -340,8 +418,8 @@ func (r *Resolver) resolveDeps() ([]*pkg.LocalPackage, error) {
 		return nil, err
 	}
 
-	lpkgs := r.lpkgSlice()
-	return lpkgs, nil
+	rpkgs := r.rpkgSlice()
+	return rpkgs, nil
 }
 
 func (r *Resolver) resolveDepsAndCfg() error {
@@ -393,15 +471,8 @@ func (r *Resolver) resolveApiDeps() error {
 	for _, rpkg := range r.pkgMap {
 		for api, _ := range rpkg.reqApiMap {
 			apiPkg := r.apis[api]
-			if apiPkg == nil {
-				//return util.FmtNewtError(
-				//"Unsatisfied API at unexpected time: %s", api)
-			} else {
-
-				rpkg.AddDep(&pkg.Dependency{
-					Name: apiPkg.Name(),
-					Repo: apiPkg.Repo().Name(),
-				})
+			if apiPkg != nil {
+				rpkg.AddDep(apiPkg, api)
 			}
 		}
 	}
@@ -410,26 +481,26 @@ func (r *Resolver) resolveApiDeps() error {
 }
 
 func (r *Resolver) apiResolution() (
-	map[string]*pkg.LocalPackage,
-	map[string][]*pkg.LocalPackage) {
+	map[string]*ResolvePackage,
+	map[string][]*ResolvePackage) {
 
-	apiMap := make(map[string]*pkg.LocalPackage, len(r.apis))
+	apiMap := make(map[string]*ResolvePackage, len(r.apis))
 	anyUnsatisfied := false
 	for api, rpkg := range r.apis {
 		if rpkg == nil {
 			anyUnsatisfied = true
 		} else {
-			apiMap[api] = rpkg.LocalPackage
+			apiMap[api] = rpkg
 		}
 	}
 
-	unsatisfied := map[string][]*pkg.LocalPackage{}
+	unsatisfied := map[string][]*ResolvePackage{}
 	if anyUnsatisfied {
 		for _, rpkg := range r.pkgMap {
 			for api, satisfied := range rpkg.reqApiMap {
 				if !satisfied {
 					slice := unsatisfied[api]
-					slice = append(slice, rpkg.LocalPackage)
+					slice = append(slice, rpkg)
 					unsatisfied[api] = slice
 				}
 			}
@@ -458,7 +529,7 @@ func ResolveFull(
 		return nil, err
 	}
 
-	res := &Resolution{}
+	res := newResolution()
 	res.Cfg = r.cfg
 	if err := r.resolveApiDeps(); err != nil {
 		return nil, err
@@ -466,14 +537,17 @@ func ResolveFull(
 
 	// Determine which package satisfies each API and which APIs are
 	// unsatisfied.
-	apiMap := map[string]*pkg.LocalPackage{}
+	apiMap := map[string]*ResolvePackage{}
 	apiMap, res.UnsatisfiedApis = r.apiResolution()
 
+	res.LpkgRpkgMap = r.pkgMap
+
 	// If there is no loader, then the set of all packages is just the app
 	// packages.  We already resolved the necessary dependency information when
 	// syscfg was calculated above.
 	if loaderSeeds == nil {
-		res.AppPkgs = r.lpkgSlice()
+		res.AppSet.Rpkgs = r.rpkgSlice()
+		res.LoaderSet = nil
 		return res, nil
 	}
 
@@ -486,9 +560,9 @@ func ResolveFull(
 
 	// It is OK if the app requires an API that is supplied by the loader.
 	// Ensure each set of packages has access to the API-providers.
-	for _, lpkg := range apiMap {
-		loaderSeeds = append(loaderSeeds, lpkg)
-		appSeeds = append(appSeeds, lpkg)
+	for _, rpkg := range apiMap {
+		loaderSeeds = append(loaderSeeds, rpkg.Lpkg)
+		appSeeds = append(appSeeds, rpkg.Lpkg)
 	}
 
 	// Resolve loader dependencies.
@@ -497,23 +571,23 @@ func ResolveFull(
 
 	var err error
 
-	res.LoaderPkgs, err = r.resolveDeps()
+	res.LoaderSet.Rpkgs, err = r.resolveDeps()
 	if err != nil {
 		return nil, err
 	}
 
 	// Resolve app dependencies.  The app automtically gets all the packages
 	// from the loader except for the loader-app-package.
-	for _, lpkg := range res.LoaderPkgs {
-		if lpkg.Type() != pkg.PACKAGE_TYPE_APP {
-			appSeeds = append(appSeeds, lpkg)
+	for _, rpkg := range res.LoaderSet.Rpkgs {
+		if rpkg.Lpkg.Type() != pkg.PACKAGE_TYPE_APP {
+			appSeeds = append(appSeeds, rpkg.Lpkg)
 		}
 	}
 
 	r = newResolver(appSeeds, injectedSettings, flashMap)
 	r.cfg = res.Cfg
 
-	res.AppPkgs, err = r.resolveDeps()
+	res.AppSet.Rpkgs, err = r.resolveDeps()
 	if err != nil {
 		return nil, err
 	}
@@ -535,10 +609,10 @@ func (res *Resolution) ErrorText() string {
 		for _, api := range apiNames {
 			str += fmt.Sprintf("    * %s, required by: ", api)
 
-			pkgs := res.UnsatisfiedApis[api]
-			pkgNames := make([]string, len(pkgs))
-			for i, lpkg := range pkgs {
-				pkgNames[i] = lpkg.Name()
+			rpkgs := res.UnsatisfiedApis[api]
+			pkgNames := make([]string, len(rpkgs))
+			for i, rpkg := range rpkgs {
+				pkgNames[i] = rpkg.Lpkg.Name()
 			}
 			sort.Strings(pkgNames)
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/4c0c1b14/newt/resolve/resolveutil.go
----------------------------------------------------------------------
diff --git a/newt/resolve/resolveutil.go b/newt/resolve/resolveutil.go
new file mode 100644
index 0000000..23884d3
--- /dev/null
+++ b/newt/resolve/resolveutil.go
@@ -0,0 +1,92 @@
+/**
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements.  See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership.  The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License.  You may obtain a copy of the License at
+*
+*  http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied.  See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package resolve
+
+import (
+	"sort"
+
+	"mynewt.apache.org/newt/newt/pkg"
+)
+
+type rpkgSorter struct {
+	pkgs []*ResolvePackage
+}
+
+func (s rpkgSorter) Len() int {
+	return len(s.pkgs)
+}
+func (s rpkgSorter) Swap(i, j int) {
+	s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
+}
+func (s rpkgSorter) Less(i, j int) bool {
+	return s.pkgs[i].Lpkg.FullName() < s.pkgs[j].Lpkg.FullName()
+}
+
+func SortResolvePkgs(pkgs []*ResolvePackage) []*ResolvePackage {
+	sorter := rpkgSorter{
+		pkgs: make([]*ResolvePackage, 0, len(pkgs)),
+	}
+
+	for _, p := range pkgs {
+		sorter.pkgs = append(sorter.pkgs, p)
+	}
+
+	sort.Sort(sorter)
+	return sorter.pkgs
+}
+
+type rdepSorter struct {
+	deps []*ResolveDep
+}
+
+func (s rdepSorter) Len() int {
+	return len(s.deps)
+}
+func (s rdepSorter) Swap(i, j int) {
+	s.deps[i], s.deps[j] = s.deps[j], s.deps[i]
+}
+
+func (s rdepSorter) Less(i, j int) bool {
+	return s.deps[i].Rpkg.Lpkg.FullName() < s.deps[j].Rpkg.Lpkg.FullName()
+}
+func SortResolveDeps(deps []*ResolveDep) []*ResolveDep {
+	sorter := rdepSorter{
+		deps: make([]*ResolveDep, 0, len(deps)),
+	}
+
+	for _, d := range deps {
+		sorter.deps = append(sorter.deps, d)
+	}
+
+	sort.Sort(sorter)
+	return sorter.deps
+}
+
+func RpkgSliceToLpkgSlice(rpkgs []*ResolvePackage) []*pkg.LocalPackage {
+	lpkgs := make([]*pkg.LocalPackage, len(rpkgs))
+
+	i := 0
+	for _, rpkg := range rpkgs {
+		lpkgs[i] = rpkg.Lpkg
+		i++
+	}
+
+	return lpkgs
+}


[28/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/cmd/cmd.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/cmd/cmd.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/cmd/cmd.go
deleted file mode 100644
index 937f802..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/cmd/cmd.go
+++ /dev/null
@@ -1,995 +0,0 @@
-package cmd
-
-import (
-	"bytes"
-	"errors"
-	"fmt"
-	"io"
-	"log"
-
-	"github.com/runtimeinc/gatt/linux/evt"
-	"github.com/runtimeinc/gatt/linux/util"
-)
-
-type CmdParam interface {
-	Marshal([]byte)
-	Opcode() int
-	Len() int
-}
-
-func NewCmd(d io.Writer) *Cmd {
-	c := &Cmd{
-		dev:     d,
-		sent:    []*cmdPkt{},
-		compc:   make(chan evt.CommandCompleteEP),
-		statusc: make(chan evt.CommandStatusEP),
-	}
-	go c.processCmdEvents()
-	return c
-}
-
-type cmdPkt struct {
-	op   int
-	cp   CmdParam
-	done chan []byte
-}
-
-func (c cmdPkt) Marshal() []byte {
-	b := make([]byte, 1+2+1+c.cp.Len())
-	b[0] = byte(0x1) // typCommandPkt
-	b[1] = byte(c.op)
-	b[2] = byte(c.op >> 8)
-	b[3] = byte(c.cp.Len())
-	c.cp.Marshal(b[4:])
-	return b
-}
-
-type Cmd struct {
-	dev     io.Writer
-	sent    []*cmdPkt
-	compc   chan evt.CommandCompleteEP
-	statusc chan evt.CommandStatusEP
-}
-
-func (c Cmd) trace(fmt string, v ...interface{}) {}
-
-func (c *Cmd) HandleComplete(b []byte) error {
-	var e evt.CommandCompleteEP
-	if err := e.Unmarshal(b); err != nil {
-		return err
-	}
-	c.compc <- e
-	return nil
-}
-
-func (c *Cmd) HandleStatus(b []byte) error {
-	var e evt.CommandStatusEP
-	if err := e.Unmarshal(b); err != nil {
-		return err
-	}
-	c.statusc <- e
-	return nil
-}
-
-func (c *Cmd) Send(cp CmdParam) ([]byte, error) {
-	op := cp.Opcode()
-	p := &cmdPkt{op: op, cp: cp, done: make(chan []byte)}
-	raw := p.Marshal()
-
-	c.sent = append(c.sent, p)
-	if n, err := c.dev.Write(raw); err != nil {
-		return nil, err
-	} else if n != len(raw) {
-		return nil, errors.New("Failed to send whole Cmd pkt to HCI socket")
-	}
-	return <-p.done, nil
-}
-
-func (c *Cmd) SendAndCheckResp(cp CmdParam, exp []byte) error {
-	rsp, err := c.Send(cp)
-	if err != nil {
-		return err
-	}
-	// Don't care about the response
-	if len(exp) == 0 {
-		return nil
-	}
-	// Check the if status is one of the expected value
-	if !bytes.Contains(exp, rsp[0:1]) {
-		return fmt.Errorf("HCI command: '0x%04x' return 0x%02X, expect: [%X] ", cp.Opcode(), rsp[0], exp)
-	}
-	return nil
-}
-
-func (c *Cmd) processCmdEvents() {
-	for {
-		select {
-		case status := <-c.statusc:
-			found := false
-			for i, p := range c.sent {
-				if uint16(p.op) == status.CommandOpcode {
-					found = true
-					c.sent = append(c.sent[:i], c.sent[i+1:]...)
-					close(p.done)
-					break
-				}
-			}
-			if !found {
-				log.Printf("Can't find the cmdPkt for this CommandStatusEP: %v", status)
-			}
-		case comp := <-c.compc:
-			found := false
-			for i, p := range c.sent {
-				if uint16(p.op) == comp.CommandOPCode {
-					found = true
-					c.sent = append(c.sent[:i], c.sent[i+1:]...)
-					p.done <- comp.ReturnParameters
-					break
-				}
-			}
-			if !found {
-				log.Printf("Can't find the cmdPkt for this CommandCompleteEP: %v", comp)
-			}
-		}
-	}
-}
-
-const (
-	linkCtl     = 0x01
-	linkPolicy  = 0x02
-	hostCtl     = 0x03
-	infoParam   = 0x04
-	statusParam = 0x05
-	testingCmd  = 0X3E
-	leCtl       = 0x08
-	vendorCmd   = 0X3F
-)
-
-const (
-	opInquiry                = linkCtl<<10 | 0x0001 // Inquiry
-	opInquiryCancel          = linkCtl<<10 | 0x0002 // Inquiry Cancel
-	opPeriodicInquiry        = linkCtl<<10 | 0x0003 // Periodic Inquiry Mode
-	opExitPeriodicInquiry    = linkCtl<<10 | 0x0004 // Exit Periodic Inquiry Mode
-	opCreateConn             = linkCtl<<10 | 0x0005 // Create Connection
-	opDisconnect             = linkCtl<<10 | 0x0006 // Disconnect
-	opCreateConnCancel       = linkCtl<<10 | 0x0008 // Create Connection Cancel
-	opAcceptConnReq          = linkCtl<<10 | 0x0009 // Accept Connection Request
-	opRejectConnReq          = linkCtl<<10 | 0x000A // Reject Connection Request
-	opLinkKeyReply           = linkCtl<<10 | 0x000B // Link Key Request Reply
-	opLinkKeyNegReply        = linkCtl<<10 | 0x000C // Link Key Request Negative Reply
-	opPinCodeReply           = linkCtl<<10 | 0x000D // PIN Code Request Reply
-	opPinCodeNegReply        = linkCtl<<10 | 0x000E // PIN Code Request Negative Reply
-	opSetConnPtype           = linkCtl<<10 | 0x000F // Change Connection Packet Type
-	opAuthRequested          = linkCtl<<10 | 0x0011 // Authentication Request
-	opSetConnEncrypt         = linkCtl<<10 | 0x0013 // Set Connection Encryption
-	opChangeConnLinkKey      = linkCtl<<10 | 0x0015 // Change Connection Link Key
-	opMasterLinkKey          = linkCtl<<10 | 0x0017 // Master Link Key
-	opRemoteNameReq          = linkCtl<<10 | 0x0019 // Remote Name Request
-	opRemoteNameReqCancel    = linkCtl<<10 | 0x001A // Remote Name Request Cancel
-	opReadRemoteFeatures     = linkCtl<<10 | 0x001B // Read Remote Supported Features
-	opReadRemoteExtFeatures  = linkCtl<<10 | 0x001C // Read Remote Extended Features
-	opReadRemoteVersion      = linkCtl<<10 | 0x001D // Read Remote Version Information
-	opReadClockOffset        = linkCtl<<10 | 0x001F // Read Clock Offset
-	opReadLMPHandle          = linkCtl<<10 | 0x0020 // Read LMP Handle
-	opSetupSyncConn          = linkCtl<<10 | 0x0028 // Setup Synchronous Connection
-	opAcceptSyncConnReq      = linkCtl<<10 | 0x0029 // Aceept Synchronous Connection
-	opRejectSyncConnReq      = linkCtl<<10 | 0x002A // Recject Synchronous Connection
-	opIOCapabilityReply      = linkCtl<<10 | 0x002B // IO Capability Request Reply
-	opUserConfirmReply       = linkCtl<<10 | 0x002C // User Confirmation Request Reply
-	opUserConfirmNegReply    = linkCtl<<10 | 0x002D // User Confirmation Negative Reply
-	opUserPasskeyReply       = linkCtl<<10 | 0x002E // User Passkey Request Reply
-	opUserPasskeyNegReply    = linkCtl<<10 | 0x002F // User Passkey Request Negative Reply
-	opRemoteOOBDataReply     = linkCtl<<10 | 0x0030 // Remote OOB Data Request Reply
-	opRemoteOOBDataNegReply  = linkCtl<<10 | 0x0033 // Remote OOB Data Request Negative Reply
-	opIOCapabilityNegReply   = linkCtl<<10 | 0x0034 // IO Capability Request Negative Reply
-	opCreatePhysicalLink     = linkCtl<<10 | 0x0035 // Create Physical Link
-	opAcceptPhysicalLink     = linkCtl<<10 | 0x0036 // Accept Physical Link
-	opDisconnectPhysicalLink = linkCtl<<10 | 0x0037 // Disconnect Physical Link
-	opCreateLogicalLink      = linkCtl<<10 | 0x0038 // Create Logical Link
-	opAcceptLogicalLink      = linkCtl<<10 | 0x0039 // Accept Logical Link
-	opDisconnectLogicalLink  = linkCtl<<10 | 0x003A // Disconnect Logical Link
-	opLogicalLinkCancel      = linkCtl<<10 | 0x003B // Logical Link Cancel
-	opFlowSpecModify         = linkCtl<<10 | 0x003C // Flow Spec Modify
-)
-
-const (
-	opHoldMode               = linkPolicy<<10 | 0x0001 // Hold Mode
-	opSniffMode              = linkPolicy<<10 | 0x0003 // Sniff Mode
-	opExitSniffMode          = linkPolicy<<10 | 0x0004 // Exit Sniff Mode
-	opParkMode               = linkPolicy<<10 | 0x0005 // Park State
-	opExitParkMode           = linkPolicy<<10 | 0x0006 // Exit Park State
-	opQoSSetup               = linkPolicy<<10 | 0x0007 // QoS Setup
-	opRoleDiscovery          = linkPolicy<<10 | 0x0009 // Role Discovery
-	opSwitchRole             = linkPolicy<<10 | 0x000B // Switch Role
-	opReadLinkPolicy         = linkPolicy<<10 | 0x000C // Read Link Policy Settings
-	opWriteLinkPolicy        = linkPolicy<<10 | 0x000D // Write Link Policy Settings
-	opReadDefaultLinkPolicy  = linkPolicy<<10 | 0x000E // Read Default Link Policy Settings
-	opWriteDefaultLinkPolicy = linkPolicy<<10 | 0x000F // Write Default Link Policy Settings
-	opFlowSpecification      = linkPolicy<<10 | 0x0010 // Flow Specification
-	opSniffSubrating         = linkPolicy<<10 | 0x0011 // Sniff Subrating
-)
-
-const (
-	opSetEventMask                      = hostCtl<<10 | 0x0001 // Set Event Mask
-	opReset                             = hostCtl<<10 | 0x0003 // Reset
-	opSetEventFlt                       = hostCtl<<10 | 0x0005 // Set Event Filter
-	opFlush                             = hostCtl<<10 | 0x0008 // Flush
-	opReadPinType                       = hostCtl<<10 | 0x0009 // Read PIN Type
-	opWritePinType                      = hostCtl<<10 | 0x000A // Write PIN Type
-	opCreateNewUnitKey                  = hostCtl<<10 | 0x000B // Create New Unit Key
-	opReadStoredLinkKey                 = hostCtl<<10 | 0x000D // Read Stored Link Key
-	opWriteStoredLinkKey                = hostCtl<<10 | 0x0011 // Write Stored Link Key
-	opDeleteStoredLinkKey               = hostCtl<<10 | 0x0012 // Delete Stored Link Key
-	opWriteLocalName                    = hostCtl<<10 | 0x0013 // Write Local Name
-	opReadLocalName                     = hostCtl<<10 | 0x0014 // Read Local Name
-	opReadConnAcceptTimeout             = hostCtl<<10 | 0x0015 // Read Connection Accept Timeout
-	opWriteConnAcceptTimeout            = hostCtl<<10 | 0x0016 // Write Connection Accept Timeout
-	opReadPageTimeout                   = hostCtl<<10 | 0x0017 // Read Page Timeout
-	opWritePageTimeout                  = hostCtl<<10 | 0x0018 // Write Page Timeout
-	opReadScanEnable                    = hostCtl<<10 | 0x0019 // Read Scan Enable
-	opWriteScanEnable                   = hostCtl<<10 | 0x001A // Write Scan Enable
-	opReadPageActivity                  = hostCtl<<10 | 0x001B // Read Page Scan Activity
-	opWritePageActivity                 = hostCtl<<10 | 0x001C // Write Page Scan Activity
-	opReadInqActivity                   = hostCtl<<10 | 0x001D // Read Inquiry Scan Activity
-	opWriteInqActivity                  = hostCtl<<10 | 0x001E // Write Inquiry Scan Activity
-	opReadAuthEnable                    = hostCtl<<10 | 0x001F // Read Authentication Enable
-	opWriteAuthEnable                   = hostCtl<<10 | 0x0020 // Write Authentication Enable
-	opReadEncryptMode                   = hostCtl<<10 | 0x0021
-	opWriteEncryptMode                  = hostCtl<<10 | 0x0022
-	opReadClassOfDev                    = hostCtl<<10 | 0x0023 // Read Class of Device
-	opWriteClassOfDevice                = hostCtl<<10 | 0x0024 // Write Class of Device
-	opReadVoiceSetting                  = hostCtl<<10 | 0x0025 // Read Voice Setting
-	opWriteVoiceSetting                 = hostCtl<<10 | 0x0026 // Write Voice Setting
-	opReadAutomaticFlushTimeout         = hostCtl<<10 | 0x0027 // Read Automatic Flush Timeout
-	opWriteAutomaticFlushTimeout        = hostCtl<<10 | 0x0028 // Write Automatic Flush Timeout
-	opReadNumBroadcastRetrans           = hostCtl<<10 | 0x0029 // Read Num Broadcast Retransmissions
-	opWriteNumBroadcastRetrans          = hostCtl<<10 | 0x002A // Write Num Broadcast Retransmissions
-	opReadHoldModeActivity              = hostCtl<<10 | 0x002B // Read Hold Mode Activity
-	opWriteHoldModeActivity             = hostCtl<<10 | 0x002C // Write Hold Mode Activity
-	opReadTransmitPowerLevel            = hostCtl<<10 | 0x002D // Read Transmit Power Level
-	opReadSyncFlowEnable                = hostCtl<<10 | 0x002E // Read Synchronous Flow Control
-	opWriteSyncFlowEnable               = hostCtl<<10 | 0x002F // Write Synchronous Flow Control
-	opSetControllerToHostFC             = hostCtl<<10 | 0x0031 // Set Controller To Host Flow Control
-	opHostBufferSize                    = hostCtl<<10 | 0x0033 // Host Buffer Size
-	opHostNumCompPkts                   = hostCtl<<10 | 0x0035 // Host Number Of Completed Packets
-	opReadLinkSupervisionTimeout        = hostCtl<<10 | 0x0036 // Read Link Supervision Timeout
-	opWriteLinkSupervisionTimeout       = hostCtl<<10 | 0x0037 // Write Link Supervision Timeout
-	opReadNumSupportedIAC               = hostCtl<<10 | 0x0038 // Read Number Of Supported IAC
-	opReadCurrentIACLAP                 = hostCtl<<10 | 0x0039 // Read Current IAC LAP
-	opWriteCurrentIACLAP                = hostCtl<<10 | 0x003A // Write Current IAC LAP
-	opReadPageScanPeriodMode            = hostCtl<<10 | 0x003B
-	opWritePageScanPeriodMode           = hostCtl<<10 | 0x003C
-	opReadPageScanMode                  = hostCtl<<10 | 0x003D
-	opWritePageScanMode                 = hostCtl<<10 | 0x003E
-	opSetAFHClassification              = hostCtl<<10 | 0x003F // Set AFH Host Channel Classification
-	opReadInquiryScanType               = hostCtl<<10 | 0x0042 // Read Inquiry Scan Type
-	opWriteInquiryScanType              = hostCtl<<10 | 0x0043 // Write Inquiry Scan Type
-	opReadInquiryMode                   = hostCtl<<10 | 0x0044 // Read Inquiry Mode
-	opWriteInquiryMode                  = hostCtl<<10 | 0x0045 // Write Inquiry Mode
-	opReadPageScanType                  = hostCtl<<10 | 0x0046 // Read Page Scan Type
-	opWritePageScanType                 = hostCtl<<10 | 0x0047 // Write Page Scan Type
-	opReadAFHMode                       = hostCtl<<10 | 0x0048 // Read AFH Channel Assessment Mode
-	opWriteAFHMode                      = hostCtl<<10 | 0x0049 // Write AFH Channel Assesment Mode
-	opReadExtInquiryResponse            = hostCtl<<10 | 0x0051 // Read Extended Inquiry Response
-	opWriteExtInquiryResponse           = hostCtl<<10 | 0x0052 // Write Extended Inquiry Response
-	opRefreshEncryptionKey              = hostCtl<<10 | 0x0053 // Refresh Encryption Key
-	opReadSimplePairingMode             = hostCtl<<10 | 0x0055 // Read Simple Pairing Mode
-	opWriteSimplePairingMode            = hostCtl<<10 | 0x0056 // Write Simple Pairing Mode
-	opReadLocalOobData                  = hostCtl<<10 | 0x0057 // Read Local OOB Data
-	opReadInqResponseTransmitPowerLevel = hostCtl<<10 | 0x0058 // Read Inquiry Response Transmit Power Level
-	opWriteInquiryTransmitPowerLevel    = hostCtl<<10 | 0x0059 // Write Inquiry Response Transmit Power Level
-	opReadDefaultErrorDataReporting     = hostCtl<<10 | 0x005A // Read Default Erroneous Data Reporting
-	opWriteDefaultErrorDataReporting    = hostCtl<<10 | 0x005B // Write Default Erroneous Data Reporting
-	opEnhancedFlush                     = hostCtl<<10 | 0x005F // Enhanced Flush
-	opSendKeypressNotify                = hostCtl<<10 | 0x0060 // send Keypress Notification
-	opReadLogicalLinkAcceptTimeout      = hostCtl<<10 | 0x0061 // Read Logical Link Accept Timeout
-	opWriteLogicalLinkAcceptTimeout     = hostCtl<<10 | 0x0062 // Write Logical Link Accept Timeout
-	opSetEventMaskPage2                 = hostCtl<<10 | 0x0063 // Set Event Mask Page 2
-	opReadLocationData                  = hostCtl<<10 | 0x0064 // Read Location Data
-	opWriteLocationData                 = hostCtl<<10 | 0x0065 // Write Location Data
-	opReadFlowControlMode               = hostCtl<<10 | 0x0066 // Read Flow Control Mode
-	opWriteFlowControlMode              = hostCtl<<10 | 0x0067 // Write Flow Control Mode
-	opReadEnhancedTransmitpowerLevel    = hostCtl<<10 | 0x0068 // Read Enhanced Transmit Power Level
-	opReadBestEffortFlushTimeout        = hostCtl<<10 | 0x0069 // Read Best Effort Flush Timeout
-	opWriteBestEffortFlushTimeout       = hostCtl<<10 | 0x006A // Write Best Effort Flush Timeout
-	opReadLEHostSupported               = hostCtl<<10 | 0x006C // Read LE Host Supported
-	opWriteLEHostSupported              = hostCtl<<10 | 0x006D // Write LE Host Supported
-)
-const (
-	opReadLocalVersionInformation = infoParam<<10 | 0x0001 // Read Local Version Information
-	opReadLocalSupportedCommands  = infoParam<<10 | 0x0002 // Read Local Supported Commands
-	opReadLocalSupportedFeatures  = infoParam<<10 | 0x0003 // Read Local Supported Features
-	opReadLocalExtendedFeatures   = infoParam<<10 | 0x0004 // Read Local Extended Features
-	opReadBufferSize              = infoParam<<10 | 0x0005 // Read Buffer Size
-	opReadBDADDR                  = infoParam<<10 | 0x0009 // Read BD_ADDR
-	opReadDataBlockSize           = infoParam<<10 | 0x000A // Read Data Block Size
-	opReadLocalSupportedCodecs    = infoParam<<10 | 0x000B // Read Local Supported Codecs
-)
-const (
-	opLESetEventMask                      = leCtl<<10 | 0x0001 // LE Set Event Mask
-	opLEReadBufferSize                    = leCtl<<10 | 0x0002 // LE Read Buffer Size
-	opLEReadLocalSupportedFeatures        = leCtl<<10 | 0x0003 // LE Read Local Supported Features
-	opLESetRandomAddress                  = leCtl<<10 | 0x0005 // LE Set Random Address
-	opLESetAdvertisingParameters          = leCtl<<10 | 0x0006 // LE Set Advertising Parameters
-	opLEReadAdvertisingChannelTxPower     = leCtl<<10 | 0x0007 // LE Read Advertising Channel Tx Power
-	opLESetAdvertisingData                = leCtl<<10 | 0x0008 // LE Set Advertising Data
-	opLESetScanResponseData               = leCtl<<10 | 0x0009 // LE Set Scan Response Data
-	opLESetAdvertiseEnable                = leCtl<<10 | 0x000a // LE Set Advertising Enable
-	opLESetScanParameters                 = leCtl<<10 | 0x000b // LE Set Scan Parameters
-	opLESetScanEnable                     = leCtl<<10 | 0x000c // LE Set Scan Enable
-	opLECreateConn                        = leCtl<<10 | 0x000d // LE Create Connection
-	opLECreateConnCancel                  = leCtl<<10 | 0x000e // LE Create Connection Cancel
-	opLEReadWhiteListSize                 = leCtl<<10 | 0x000f // LE Read White List Size
-	opLEClearWhiteList                    = leCtl<<10 | 0x0010 // LE Clear White List
-	opLEAddDeviceToWhiteList              = leCtl<<10 | 0x0011 // LE Add Device To White List
-	opLERemoveDeviceFromWhiteList         = leCtl<<10 | 0x0012 // LE Remove Device From White List
-	opLEConnUpdate                        = leCtl<<10 | 0x0013 // LE Connection Update
-	opLESetHostChannelClassification      = leCtl<<10 | 0x0014 // LE Set Host Channel Classification
-	opLEReadChannelMap                    = leCtl<<10 | 0x0015 // LE Read Channel Map
-	opLEReadRemoteUsedFeatures            = leCtl<<10 | 0x0016 // LE Read Remote Used Features
-	opLEEncrypt                           = leCtl<<10 | 0x0017 // LE Encrypt
-	opLERand                              = leCtl<<10 | 0x0018 // LE Rand
-	opLEStartEncryption                   = leCtl<<10 | 0x0019 // LE Star Encryption
-	opLELTKReply                          = leCtl<<10 | 0x001a // LE Long Term Key Request Reply
-	opLELTKNegReply                       = leCtl<<10 | 0x001b // LE Long Term Key Request Negative Reply
-	opLEReadSupportedStates               = leCtl<<10 | 0x001c // LE Read Supported States
-	opLEReceiverTest                      = leCtl<<10 | 0x001d // LE Reciever Test
-	opLETransmitterTest                   = leCtl<<10 | 0x001e // LE Transmitter Test
-	opLETestEnd                           = leCtl<<10 | 0x001f // LE Test End
-	opLERemoteConnectionParameterReply    = leCtl<<10 | 0x0020 // LE Remote Connection Parameter Request Reply
-	opLERemoteConnectionParameterNegReply = leCtl<<10 | 0x0021 // LE Remote Connection Parameter Request Negative Reply
-)
-
-var o = util.Order
-
-// Link Control Commands
-
-// Disconnect (0x0006)
-type Disconnect struct {
-	ConnectionHandle uint16
-	Reason           uint8
-}
-
-func (c Disconnect) Opcode() int { return opDisconnect }
-func (c Disconnect) Len() int    { return 3 }
-func (c Disconnect) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	b[2] = c.Reason
-}
-
-// No Return Parameters, Check for Disconnection Complete Event
-type DisconnectRP struct{}
-
-// Link Policy Commands
-
-// Write Default Link Policy
-type WriteDefaultLinkPolicy struct{ DefaultLinkPolicySettings uint16 }
-
-func (c WriteDefaultLinkPolicy) Opcode() int      { return opWriteDefaultLinkPolicy }
-func (c WriteDefaultLinkPolicy) Len() int         { return 2 }
-func (c WriteDefaultLinkPolicy) Marshal(b []byte) { o.PutUint16(b, c.DefaultLinkPolicySettings) }
-
-type WriteDefaultLinkPolicyRP struct{ Status uint8 }
-
-// Host Control Commands
-
-// Set Event Mask (0x0001)
-type SetEventMask struct{ EventMask uint64 }
-
-func (c SetEventMask) Opcode() int      { return opSetEventMask }
-func (c SetEventMask) Len() int         { return 8 }
-func (c SetEventMask) Marshal(b []byte) { o.PutUint64(b, c.EventMask) }
-
-type SetEventMaskRP struct{ Status uint8 }
-
-// Reset (0x0002)
-type Reset struct{}
-
-func (c Reset) Opcode() int      { return opReset }
-func (c Reset) Len() int         { return 0 }
-func (c Reset) Marshal(b []byte) {}
-
-type ResetRP struct{ Status uint8 }
-
-// Set Event Filter (0x0003)
-// FIXME: This structures are overloading.
-// Both Marshal() and Len() are just placeholder.
-// Need more effort for decoding.
-// type SetEventFlt struct {
-// 	FilterType          uint8
-// 	FilterConditionType uint8
-// 	Condition           uint8
-// }
-
-// func (c SetEventFlt) Opcode() int   { return opSetEventFlt }
-// func (c SetEventFlt) Len() int         { return 0 }
-// func (c SetEventFlt) Marshal(b []byte) {}
-
-type SetEventFltRP struct{ Status uint8 }
-
-// Flush (0x0008)
-type Flush struct{ ConnectionHandle uint16 }
-
-func (c Flush) Opcode() int      { return opFlush }
-func (c Flush) Len() int         { return 2 }
-func (c Flush) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
-
-type flushRP struct{ status uint8 }
-
-// Write Page Timeout (0x0018)
-type WritePageTimeout struct{ PageTimeout uint16 }
-
-func (c WritePageTimeout) Opcode() int      { return opWritePageTimeout }
-func (c WritePageTimeout) Len() int         { return 2 }
-func (c WritePageTimeout) Marshal(b []byte) { o.PutUint16(b, c.PageTimeout) }
-
-type WritePageTimeoutRP struct{}
-
-// Write Class of Device (0x0024)
-type WriteClassOfDevice struct{ ClassOfDevice [3]byte }
-
-func (c WriteClassOfDevice) Opcode() int      { return opWriteClassOfDevice }
-func (c WriteClassOfDevice) Len() int         { return 3 }
-func (c WriteClassOfDevice) Marshal(b []byte) { copy(b, c.ClassOfDevice[:]) }
-
-type WriteClassOfDevRP struct{ status uint8 }
-
-// Write Host Buffer Size (0x0033)
-type HostBufferSize struct {
-	HostACLDataPacketLength            uint16
-	HostSynchronousDataPacketLength    uint8
-	HostTotalNumACLDataPackets         uint16
-	HostTotalNumSynchronousDataPackets uint16
-}
-
-func (c HostBufferSize) Opcode() int { return opHostBufferSize }
-func (c HostBufferSize) Len() int    { return 7 }
-func (c HostBufferSize) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.HostACLDataPacketLength)
-	o.PutUint8(b[2:], c.HostSynchronousDataPacketLength)
-	o.PutUint16(b[3:], c.HostTotalNumACLDataPackets)
-	o.PutUint16(b[5:], c.HostTotalNumSynchronousDataPackets)
-}
-
-type HostBufferSizeRP struct{ Status uint8 }
-
-// Write Inquiry Scan Type (0x0043)
-type WriteInquiryScanType struct{ ScanType uint8 }
-
-func (c WriteInquiryScanType) Opcode() int      { return opWriteInquiryScanType }
-func (c WriteInquiryScanType) Len() int         { return 1 }
-func (c WriteInquiryScanType) Marshal(b []byte) { b[0] = c.ScanType }
-
-type WriteInquiryScanTypeRP struct{ Status uint8 }
-
-// Write Inquiry Mode (0x0045)
-type WriteInquiryMode struct {
-	InquiryMode uint8
-}
-
-func (c WriteInquiryMode) Opcode() int      { return opWriteInquiryMode }
-func (c WriteInquiryMode) Len() int         { return 1 }
-func (c WriteInquiryMode) Marshal(b []byte) { b[0] = c.InquiryMode }
-
-type WriteInquiryModeRP struct{ Status uint8 }
-
-// Write Page Scan Type (0x0046)
-type WritePageScanType struct{ PageScanType uint8 }
-
-func (c WritePageScanType) Opcode() int      { return opWritePageScanType }
-func (c WritePageScanType) Len() int         { return 1 }
-func (c WritePageScanType) Marshal(b []byte) { b[0] = c.PageScanType }
-
-type WritePageScanTypeRP struct{ Status uint8 }
-
-// Write Simple Pairing Mode (0x0056)
-type WriteSimplePairingMode struct{ SimplePairingMode uint8 }
-
-func (c WriteSimplePairingMode) Opcode() int      { return opWriteSimplePairingMode }
-func (c WriteSimplePairingMode) Len() int         { return 1 }
-func (c WriteSimplePairingMode) Marshal(b []byte) { b[0] = c.SimplePairingMode }
-
-type WriteSimplePairingModeRP struct{}
-
-// Set Event Mask Page 2 (0x0063)
-type SetEventMaskPage2 struct{ EventMaskPage2 uint64 }
-
-func (c SetEventMaskPage2) Opcode() int      { return opSetEventMaskPage2 }
-func (c SetEventMaskPage2) Len() int         { return 8 }
-func (c SetEventMaskPage2) Marshal(b []byte) { o.PutUint64(b, c.EventMaskPage2) }
-
-type SetEventMaskPage2RP struct{ Status uint8 }
-
-// Write LE Host Supported (0x006D)
-type WriteLEHostSupported struct {
-	LESupportedHost    uint8
-	SimultaneousLEHost uint8
-}
-
-func (c WriteLEHostSupported) Opcode() int      { return opWriteLEHostSupported }
-func (c WriteLEHostSupported) Len() int         { return 2 }
-func (c WriteLEHostSupported) Marshal(b []byte) { b[0], b[1] = c.LESupportedHost, c.SimultaneousLEHost }
-
-type WriteLeHostSupportedRP struct{ Status uint8 }
-
-// LE Controller Commands
-
-// LE Set Event Mask (0x0001)
-type LESetEventMask struct{ LEEventMask uint64 }
-
-func (c LESetEventMask) Opcode() int      { return opLESetEventMask }
-func (c LESetEventMask) Len() int         { return 8 }
-func (c LESetEventMask) Marshal(b []byte) { o.PutUint64(b, c.LEEventMask) }
-
-type LESetEventMaskRP struct{ Status uint8 }
-
-// LE Read Buffer Size (0x0002)
-type LEReadBufferSize struct{}
-
-func (c LEReadBufferSize) Opcode() int      { return opLEReadBufferSize }
-func (c LEReadBufferSize) Len() int         { return 1 }
-func (c LEReadBufferSize) Marshal(b []byte) {}
-
-type LEReadBufferSizeRP struct {
-	Status                     uint8
-	HCLEACLDataPacketLength    uint16
-	HCTotalNumLEACLDataPackets uint8
-}
-
-// LE Read Local Supported Features (0x0003)
-type LEReadLocalSupportedFeatures struct{}
-
-func (c LEReadLocalSupportedFeatures) Opcode() int      { return opLEReadLocalSupportedFeatures }
-func (c LEReadLocalSupportedFeatures) Len() int         { return 0 }
-func (c LEReadLocalSupportedFeatures) Marshal(b []byte) {}
-
-type LEReadLocalSupportedFeaturesRP struct {
-	Status     uint8
-	LEFeatures uint64
-}
-
-// LE Set Random Address (0x0005)
-type LESetRandomAddress struct{ RandomAddress [6]byte }
-
-func (c LESetRandomAddress) Opcode() int      { return opLESetRandomAddress }
-func (c LESetRandomAddress) Len() int         { return 6 }
-func (c LESetRandomAddress) Marshal(b []byte) { o.PutMAC(b, c.RandomAddress) }
-
-type LESetRandomAddressRP struct{ Status uint8 }
-
-// LE Set Advertising Parameters (0x0006)
-type LESetAdvertisingParameters struct {
-	AdvertisingIntervalMin  uint16
-	AdvertisingIntervalMax  uint16
-	AdvertisingType         uint8
-	OwnAddressType          uint8
-	DirectAddressType       uint8
-	DirectAddress           [6]byte
-	AdvertisingChannelMap   uint8
-	AdvertisingFilterPolicy uint8
-}
-
-func (c LESetAdvertisingParameters) Opcode() int { return opLESetAdvertisingParameters }
-func (c LESetAdvertisingParameters) Len() int    { return 15 }
-func (c LESetAdvertisingParameters) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.AdvertisingIntervalMin)
-	o.PutUint16(b[2:], c.AdvertisingIntervalMax)
-	o.PutUint8(b[4:], c.AdvertisingType)
-	o.PutUint8(b[5:], c.OwnAddressType)
-	o.PutUint8(b[6:], c.DirectAddressType)
-	o.PutMAC(b[7:], c.DirectAddress)
-	o.PutUint8(b[13:], c.AdvertisingChannelMap)
-	o.PutUint8(b[14:], c.AdvertisingFilterPolicy)
-}
-
-type LESetAdvertisingParametersRP struct{ Status uint8 }
-
-// LE Read Advertising Channel Tx Power (0x0007)
-type LEReadAdvertisingChannelTxPower struct{}
-
-func (c LEReadAdvertisingChannelTxPower) Opcode() int      { return opLEReadAdvertisingChannelTxPower }
-func (c LEReadAdvertisingChannelTxPower) Len() int         { return 0 }
-func (c LEReadAdvertisingChannelTxPower) Marshal(b []byte) {}
-
-type LEReadAdvertisingChannelTxPowerRP struct {
-	Status             uint8
-	TransmitPowerLevel uint8
-}
-
-// LE Set Advertising Data (0x0008)
-type LESetAdvertisingData struct {
-	AdvertisingDataLength uint8
-	AdvertisingData       [31]byte
-}
-
-func (c LESetAdvertisingData) Opcode() int { return opLESetAdvertisingData }
-func (c LESetAdvertisingData) Len() int    { return 32 }
-func (c LESetAdvertisingData) Marshal(b []byte) {
-	b[0] = c.AdvertisingDataLength
-	copy(b[1:], c.AdvertisingData[:c.AdvertisingDataLength])
-}
-
-type LESetAdvertisingDataRP struct{ Status uint8 }
-
-// LE Set Scan Response Data (0x0009)
-type LESetScanResponseData struct {
-	ScanResponseDataLength uint8
-	ScanResponseData       [31]byte
-}
-
-func (c LESetScanResponseData) Opcode() int { return opLESetScanResponseData }
-func (c LESetScanResponseData) Len() int    { return 32 }
-func (c LESetScanResponseData) Marshal(b []byte) {
-	b[0] = c.ScanResponseDataLength
-	copy(b[1:], c.ScanResponseData[:c.ScanResponseDataLength])
-}
-
-type LESetScanResponseDataRP struct{ Status uint8 }
-
-// LE Set Advertising Enable (0x000A)
-type LESetAdvertiseEnable struct{ AdvertisingEnable uint8 }
-
-func (c LESetAdvertiseEnable) Opcode() int      { return opLESetAdvertiseEnable }
-func (c LESetAdvertiseEnable) Len() int         { return 1 }
-func (c LESetAdvertiseEnable) Marshal(b []byte) { b[0] = c.AdvertisingEnable }
-
-type LESetAdvertiseEnableRP struct{ Status uint8 }
-
-// LE Set Scan Parameters (0x000B)
-type LESetScanParameters struct {
-	LEScanType           uint8
-	LEScanInterval       uint16
-	LEScanWindow         uint16
-	OwnAddressType       uint8
-	ScanningFilterPolicy uint8
-}
-
-func (c LESetScanParameters) Opcode() int { return opLESetScanParameters }
-func (c LESetScanParameters) Len() int    { return 7 }
-func (c LESetScanParameters) Marshal(b []byte) {
-	o.PutUint8(b[0:], c.LEScanType)
-	o.PutUint16(b[1:], c.LEScanInterval)
-	o.PutUint16(b[3:], c.LEScanWindow)
-	o.PutUint8(b[5:], c.OwnAddressType)
-	o.PutUint8(b[6:], c.ScanningFilterPolicy)
-}
-
-type LESetScanParametersRP struct{ Status uint8 }
-
-// LE Set Scan Enable (0x000C)
-type LESetScanEnable struct {
-	LEScanEnable     uint8
-	FilterDuplicates uint8
-}
-
-func (c LESetScanEnable) Opcode() int      { return opLESetScanEnable }
-func (c LESetScanEnable) Len() int         { return 2 }
-func (c LESetScanEnable) Marshal(b []byte) { b[0], b[1] = c.LEScanEnable, c.FilterDuplicates }
-
-type LESetScanEnableRP struct{ Status uint8 }
-
-// LE Create Connection (0x000D)
-type LECreateConn struct {
-	LEScanInterval        uint16
-	LEScanWindow          uint16
-	InitiatorFilterPolicy uint8
-	PeerAddressType       uint8
-	PeerAddress           [6]byte
-	OwnAddressType        uint8
-	ConnIntervalMin       uint16
-	ConnIntervalMax       uint16
-	ConnLatency           uint16
-	SupervisionTimeout    uint16
-	MinimumCELength       uint16
-	MaximumCELength       uint16
-}
-
-func (c LECreateConn) Opcode() int { return opLECreateConn }
-func (c LECreateConn) Len() int    { return 25 }
-func (c LECreateConn) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.LEScanInterval)
-	o.PutUint16(b[2:], c.LEScanWindow)
-	o.PutUint8(b[4:], c.InitiatorFilterPolicy)
-	o.PutUint8(b[5:], c.PeerAddressType)
-	o.PutMAC(b[6:], c.PeerAddress)
-	o.PutUint8(b[12:], c.OwnAddressType)
-	o.PutUint16(b[13:], c.ConnIntervalMin)
-	o.PutUint16(b[15:], c.ConnIntervalMax)
-	o.PutUint16(b[17:], c.ConnLatency)
-	o.PutUint16(b[19:], c.SupervisionTimeout)
-	o.PutUint16(b[21:], c.MinimumCELength)
-	o.PutUint16(b[23:], c.MaximumCELength)
-}
-
-type LECreateConnRP struct{}
-
-// LE Create Connection Cancel (0x000E)
-type LECreateConnCancel struct{}
-
-func (c LECreateConnCancel) Opcode() int      { return opLECreateConnCancel }
-func (c LECreateConnCancel) Len() int         { return 0 }
-func (c LECreateConnCancel) Marshal(b []byte) {}
-
-type LECreateConnCancelRP struct{ Status uint8 }
-
-// LE Read White List Size (0x000F)
-type LEReadWhiteListSize struct{}
-
-func (c LEReadWhiteListSize) Opcode() int      { return opLEReadWhiteListSize }
-func (c LEReadWhiteListSize) Len() int         { return 0 }
-func (c LEReadWhiteListSize) Marshal(b []byte) {}
-
-type LEReadWhiteListSizeRP struct {
-	Status        uint8
-	WhiteListSize uint8
-}
-
-// LE Clear White List (0x0010)
-type LEClearWhiteList struct{}
-
-func (c LEClearWhiteList) Opcode() int      { return opLEClearWhiteList }
-func (c LEClearWhiteList) Len() int         { return 0 }
-func (c LEClearWhiteList) Marshal(b []byte) {}
-
-type LEClearWhiteListRP struct{ Status uint8 }
-
-// LE Add Device To White List (0x0011)
-type LEAddDeviceToWhiteList struct {
-	AddressType uint8
-	Address     [6]byte
-}
-
-func (c LEAddDeviceToWhiteList) Opcode() int { return opLEAddDeviceToWhiteList }
-func (c LEAddDeviceToWhiteList) Len() int    { return 7 }
-func (c LEAddDeviceToWhiteList) Marshal(b []byte) {
-	b[0] = c.AddressType
-	o.PutMAC(b[1:], c.Address)
-}
-
-type LEAddDeviceToWhiteListRP struct{ Status uint8 }
-
-// LE Remove Device From White List (0x0012)
-type LERemoveDeviceFromWhiteList struct {
-	AddressType uint8
-	Address     [6]byte
-}
-
-func (c LERemoveDeviceFromWhiteList) Opcode() int { return opLERemoveDeviceFromWhiteList }
-func (c LERemoveDeviceFromWhiteList) Len() int    { return 7 }
-func (c LERemoveDeviceFromWhiteList) Marshal(b []byte) {
-	b[0] = c.AddressType
-	o.PutMAC(b[1:], c.Address)
-}
-
-type LERemoveDeviceFromWhiteListRP struct{ Status uint8 }
-
-// LE Connection Update (0x0013)
-type LEConnUpdate struct {
-	ConnectionHandle   uint16
-	ConnIntervalMin    uint16
-	ConnIntervalMax    uint16
-	ConnLatency        uint16
-	SupervisionTimeout uint16
-	MinimumCELength    uint16
-	MaximumCELength    uint16
-}
-
-func (c LEConnUpdate) Opcode() int { return opLEConnUpdate }
-func (c LEConnUpdate) Len() int    { return 14 }
-func (c LEConnUpdate) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	o.PutUint16(b[2:], c.ConnIntervalMin)
-	o.PutUint16(b[4:], c.ConnIntervalMax)
-	o.PutUint16(b[6:], c.ConnLatency)
-	o.PutUint16(b[8:], c.SupervisionTimeout)
-	o.PutUint16(b[10:], c.MinimumCELength)
-	o.PutUint16(b[12:], c.MaximumCELength)
-}
-
-type LEConnUpdateRP struct{}
-
-// LE Set Host Channel Classification (0x0014)
-type LESetHostChannelClassification struct{ ChannelMap [5]byte }
-
-func (c LESetHostChannelClassification) Opcode() int      { return opLESetHostChannelClassification }
-func (c LESetHostChannelClassification) Len() int         { return 5 }
-func (c LESetHostChannelClassification) Marshal(b []byte) { copy(b, c.ChannelMap[:]) }
-
-type LESetHostChannelClassificationRP struct{ Status uint8 }
-
-// LE Read Channel Map (0x0015)
-type LEReadChannelMap struct{ ConnectionHandle uint16 }
-
-func (c LEReadChannelMap) Opcode() int      { return opLEReadChannelMap }
-func (c LEReadChannelMap) Len() int         { return 2 }
-func (c LEReadChannelMap) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
-
-type LEReadChannelMapRP struct {
-	Status           uint8
-	ConnectionHandle uint16
-	ChannelMap       [5]byte
-}
-
-// LE Read Remote Used Features (0x0016)
-type LEReadRemoteUsedFeatures struct{ ConnectionHandle uint16 }
-
-func (c LEReadRemoteUsedFeatures) Opcode() int      { return opLEReadRemoteUsedFeatures }
-func (c LEReadRemoteUsedFeatures) Len() int         { return 8 }
-func (c LEReadRemoteUsedFeatures) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
-
-type LEReadRemoteUsedFeaturesRP struct{}
-
-// LE Encrypt (0x0017)
-type LEEncrypt struct {
-	Key           [16]byte
-	PlaintextData [16]byte
-}
-
-func (c LEEncrypt) Opcode() int { return opLEEncrypt }
-func (c LEEncrypt) Len() int    { return 32 }
-func (c LEEncrypt) Marshal(b []byte) {
-	copy(b[0:], c.Key[:])
-	copy(b[16:], c.PlaintextData[:])
-}
-
-type LEEncryptRP struct {
-	Stauts        uint8
-	EncryptedData [16]byte
-}
-
-// LE Rand (0x0018)
-type LERand struct{}
-
-func (c LERand) Opcode() int      { return opLERand }
-func (c LERand) Len() int         { return 0 }
-func (c LERand) Marshal(b []byte) {}
-
-type LERandRP struct {
-	Status       uint8
-	RandomNumber uint64
-}
-
-// LE Start Encryption (0x0019)
-type LEStartEncryption struct {
-	ConnectionHandle     uint16
-	RandomNumber         uint64
-	EncryptedDiversifier uint16
-	LongTermKey          [16]byte
-}
-
-func (c LEStartEncryption) Opcode() int { return opLEStartEncryption }
-func (c LEStartEncryption) Len() int    { return 28 }
-func (c LEStartEncryption) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	o.PutUint64(b[2:], c.RandomNumber)
-	o.PutUint16(b[10:], c.EncryptedDiversifier)
-	copy(b[12:], c.LongTermKey[:])
-}
-
-type LEStartEncryptionRP struct{}
-
-// LE Long Term Key Reply (0x001A)
-type LELTKReply struct {
-	ConnectionHandle uint16
-	LongTermKey      [16]byte
-}
-
-func (c LELTKReply) Opcode() int { return opLELTKReply }
-func (c LELTKReply) Len() int    { return 18 }
-func (c LELTKReply) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	copy(b[2:], c.LongTermKey[:])
-}
-
-type LELTKReplyRP struct {
-	Status           uint8
-	ConnectionHandle uint16
-}
-
-// LE Long Term Key  Negative Reply (0x001B)
-type LELTKNegReply struct{ ConnectionHandle uint16 }
-
-func (c LELTKNegReply) Opcode() int      { return opLELTKNegReply }
-func (c LELTKNegReply) Len() int         { return 2 }
-func (c LELTKNegReply) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
-
-type LELTKNegReplyRP struct {
-	Status           uint8
-	ConnectionHandle uint16
-}
-
-// LE Read Supported States (0x001C)
-type LEReadSupportedStates struct{}
-
-func (c LEReadSupportedStates) Opcode() int      { return opLEReadSupportedStates }
-func (c LEReadSupportedStates) Len() int         { return 0 }
-func (c LEReadSupportedStates) Marshal(b []byte) {}
-
-type LEReadSupportedStatesRP struct {
-	Status   uint8
-	LEStates [8]byte
-}
-
-// LE Reciever Test (0x001D)
-type LEReceiverTest struct{ RxChannel uint8 }
-
-func (c LEReceiverTest) Opcode() int      { return opLEReceiverTest }
-func (c LEReceiverTest) Len() int         { return 1 }
-func (c LEReceiverTest) Marshal(b []byte) { b[0] = c.RxChannel }
-
-type LEReceiverTestRP struct{ Status uint8 }
-
-// LE Transmitter Test (0x001E)
-type LETransmitterTest struct {
-	TxChannel        uint8
-	LengthOfTestData uint8
-	PacketPayload    uint8
-}
-
-func (c LETransmitterTest) Opcode() int { return opLETransmitterTest }
-func (c LETransmitterTest) Len() int    { return 3 }
-func (c LETransmitterTest) Marshal(b []byte) {
-	b[0], b[1], b[2] = c.TxChannel, c.LengthOfTestData, c.PacketPayload
-}
-
-type LETransmitterTestRP struct{ Status uint8 }
-
-// LE Test End (0x001F)
-type LETestEnd struct{}
-
-func (c LETestEnd) Opcode() int      { return opLETestEnd }
-func (c LETestEnd) Len() int         { return 0 }
-func (c LETestEnd) Marshal(b []byte) {}
-
-type LETestEndRP struct {
-	Status          uint8
-	NumberOfPackets uint16
-}
-
-// LE Remote Connection Parameters Reply (0x0020)
-type LERemoteConnectionParameterReply struct {
-	ConnectionHandle uint16
-	IntervalMin      uint16
-	IntervalMax      uint16
-	Latency          uint16
-	Timeout          uint16
-	MinimumCELength  uint16
-	MaximumCELength  uint16
-}
-
-func (c LERemoteConnectionParameterReply) Opcode() int { return opLERemoteConnectionParameterReply }
-func (c LERemoteConnectionParameterReply) Len() int    { return 14 }
-func (c LERemoteConnectionParameterReply) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	o.PutUint16(b[2:], c.IntervalMin)
-	o.PutUint16(b[4:], c.IntervalMax)
-	o.PutUint16(b[6:], c.Latency)
-	o.PutUint16(b[8:], c.Timeout)
-	o.PutUint16(b[10:], c.MinimumCELength)
-	o.PutUint16(b[12:], c.MaximumCELength)
-}
-
-type LERemoteConnectionParameterReplyRP struct {
-	Status           uint8
-	ConnectionHandle uint16
-}
-
-// LE Remote Connection Parameters Negative Reply (0x0021)
-type LERemoteConnectionParameterNegReply struct {
-	ConnectionHandle uint16
-	Reason           uint8
-}
-
-func (c LERemoteConnectionParameterNegReply) Opcode() int {
-	return opLERemoteConnectionParameterNegReply
-}
-func (c LERemoteConnectionParameterNegReply) Len() int { return 3 }
-func (c LERemoteConnectionParameterNegReply) Marshal(b []byte) {
-	o.PutUint16(b[0:], c.ConnectionHandle)
-	b[2] = c.Reason
-}
-
-type LERemoteConnectionParameterNegReplyRP struct {
-	Status           uint8
-	ConnectionHandle uint16
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/const.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/const.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/const.go
deleted file mode 100644
index 8c0a140..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/const.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package linux
-
-type packetType uint8
-
-// HCI Packet types
-const (
-	typCommandPkt packetType = 0X01
-	typACLDataPkt            = 0X02
-	typSCODataPkt            = 0X03
-	typEventPkt              = 0X04
-	typVendorPkt             = 0XFF
-)
-
-// Event Type
-const (
-	advInd        = 0x00 // Connectable undirected advertising (ADV_IND).
-	advDirectInd  = 0x01 // Connectable directed advertising (ADV_DIRECT_IND)
-	advScanInd    = 0x02 // Scannable undirected advertising (ADV_SCAN_IND)
-	advNonconnInd = 0x03 // Non connectable undirected advertising (ADV_NONCONN_IND)
-	scanRsp       = 0x04 // Scan Response (SCAN_RSP)
-)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/device.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/device.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/device.go
deleted file mode 100644
index ef55268..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/device.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package linux
-
-import (
-	"errors"
-	"log"
-	"sync"
-	"syscall"
-	"unsafe"
-
-	"github.com/runtimeinc/gatt/linux/gioctl"
-	"github.com/runtimeinc/gatt/linux/socket"
-)
-
-type device struct {
-	fd   int
-	dev  int
-	name string
-	rmu  *sync.Mutex
-	wmu  *sync.Mutex
-}
-
-func newDevice(n int, chk bool) (*device, error) {
-	fd, err := socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)
-	if err != nil {
-		return nil, err
-	}
-	if n != -1 {
-		return newSocket(fd, n, chk)
-	}
-
-	req := devListRequest{devNum: hciMaxDevices}
-	if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceList, uintptr(unsafe.Pointer(&req))); err != nil {
-		return nil, err
-	}
-	for i := 0; i < int(req.devNum); i++ {
-		d, err := newSocket(fd, i, chk)
-		if err == nil {
-			log.Printf("dev: %s opened", d.name)
-			return d, err
-		}
-	}
-	return nil, errors.New("no supported devices available")
-}
-
-func newSocket(fd, n int, chk bool) (*device, error) {
-	i := hciDevInfo{id: uint16(n)}
-	if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceInfo, uintptr(unsafe.Pointer(&i))); err != nil {
-		return nil, err
-	}
-	name := string(i.name[:])
-	// Check the feature list returned feature list.
-	if chk && i.features[4]&0x40 == 0 {
-		err := errors.New("does not support LE")
-		log.Printf("dev: %s %s", name, err)
-		return nil, err
-	}
-	log.Printf("dev: %s up", name)
-	if err := gioctl.Ioctl(uintptr(fd), hciUpDevice, uintptr(n)); err != nil {
-		if err != syscall.EALREADY {
-			return nil, err
-		}
-		log.Printf("dev: %s reset", name)
-		if err := gioctl.Ioctl(uintptr(fd), hciResetDevice, uintptr(n)); err != nil {
-			return nil, err
-		}
-	}
-	log.Printf("dev: %s down", name)
-	if err := gioctl.Ioctl(uintptr(fd), hciDownDevice, uintptr(n)); err != nil {
-		return nil, err
-	}
-
-	// Attempt to use the linux 3.14 feature, if this fails with EINVAL fall back to raw access
-	// on older kernels.
-	sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_USER}
-	if err := socket.Bind(fd, &sa); err != nil {
-		if err != syscall.EINVAL {
-			return nil, err
-		}
-		log.Printf("dev: %s can't bind to hci user channel, err: %s.", name, err)
-		sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_RAW}
-		if err := socket.Bind(fd, &sa); err != nil {
-			log.Printf("dev: %s can't bind to hci raw channel, err: %s.", name, err)
-			return nil, err
-		}
-	}
-	return &device{
-		fd:   fd,
-		dev:  n,
-		name: name,
-		rmu:  &sync.Mutex{},
-		wmu:  &sync.Mutex{},
-	}, nil
-}
-
-func (d device) Read(b []byte) (int, error) {
-	d.rmu.Lock()
-	defer d.rmu.Unlock()
-	return syscall.Read(d.fd, b)
-}
-
-func (d device) Write(b []byte) (int, error) {
-	d.wmu.Lock()
-	defer d.wmu.Unlock()
-	return syscall.Write(d.fd, b)
-}
-
-func (d device) Close() error {
-	return syscall.Close(d.fd)
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/devices.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/devices.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/devices.go
deleted file mode 100644
index 7c5336f..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/devices.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package linux
-
-import "github.com/runtimeinc/gatt/linux/gioctl"
-
-const (
-	ioctlSize     = uintptr(4)
-	hciMaxDevices = 16
-	typHCI        = 72 // 'H'
-)
-
-var (
-	hciUpDevice      = gioctl.IoW(typHCI, 201, ioctlSize) // HCIDEVUP
-	hciDownDevice    = gioctl.IoW(typHCI, 202, ioctlSize) // HCIDEVDOWN
-	hciResetDevice   = gioctl.IoW(typHCI, 203, ioctlSize) // HCIDEVRESET
-	hciGetDeviceList = gioctl.IoR(typHCI, 210, ioctlSize) // HCIGETDEVLIST
-	hciGetDeviceInfo = gioctl.IoR(typHCI, 211, ioctlSize) // HCIGETDEVINFO
-)
-
-type devRequest struct {
-	id  uint16
-	opt uint32
-}
-
-type devListRequest struct {
-	devNum     uint16
-	devRequest [hciMaxDevices]devRequest
-}
-
-type hciDevInfo struct {
-	id         uint16
-	name       [8]byte
-	bdaddr     [6]byte
-	flags      uint32
-	devType    uint8
-	features   [8]uint8
-	pktType    uint32
-	linkPolicy uint32
-	linkMode   uint32
-	aclMtu     uint16
-	aclPkts    uint16
-	scoMtu     uint16
-	scoPkts    uint16
-
-	stats hciDevStats
-}
-
-type hciDevStats struct {
-	errRx  uint32
-	errTx  uint32
-	cmdTx  uint32
-	evtRx  uint32
-	aclTx  uint32
-	aclRx  uint32
-	scoTx  uint32
-	scoRx  uint32
-	byteRx uint32
-	byteTx uint32
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/doc.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/doc.go
deleted file mode 100644
index c41c53e..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/doc.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// Package linux provides linux-specific support for gatt.
-//
-// This package is work in progress. We expect the APIs to change significantly before stabilizing.
-
-package linux

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/evt/evt.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/evt/evt.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/evt/evt.go
deleted file mode 100644
index 2461a30..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/evt/evt.go
+++ /dev/null
@@ -1,382 +0,0 @@
-package evt
-
-import (
-	"bytes"
-	"encoding/binary"
-	"errors"
-
-	"github.com/runtimeinc/gatt/linux/util"
-)
-
-type EventHandler interface {
-	HandleEvent([]byte) error
-}
-
-type HandlerFunc func(b []byte) error
-
-func (f HandlerFunc) HandleEvent(b []byte) error {
-	return f(b)
-}
-
-type Evt struct {
-	evtHandlers map[int]EventHandler
-}
-
-func NewEvt() *Evt {
-	return &Evt{
-		evtHandlers: map[int]EventHandler{},
-	}
-}
-
-func (e *Evt) HandleEvent(c int, h EventHandler) {
-	e.evtHandlers[c] = h
-}
-
-func (e *Evt) Dispatch(b []byte) error {
-	h := &EventHeader{}
-	if err := h.Unmarshal(b); err != nil {
-		return err
-	}
-	b = b[2:] // Skip Event Header (uint8 + uint8)
-	if f, found := e.evtHandlers[h.code]; found {
-		e.trace("> HCI Event: %s (0x%02X) plen %d: [ % X ])\n", h.code, uint8(h.code), h.plen, b)
-		return f.HandleEvent(b)
-	}
-	e.trace("> HCI Event: no handler for %s (0x%02X)\n", h.code, uint8(h.code))
-	return nil
-}
-
-func (e *Evt) trace(fmt string, v ...interface{}) {}
-
-const (
-	InquiryComplete                              = 0x01 // Inquiry Complete
-	InquiryResult                                = 0x02 // Inquiry Result
-	ConnectionComplete                           = 0x03 // Connection Complete
-	ConnectionRequest                            = 0x04 // Connection Request
-	DisconnectionComplete                        = 0x05 // Disconnection Complete
-	AuthenticationComplete                       = 0x06 // Authentication
-	RemoteNameReqComplete                        = 0x07 // Remote Name Request Complete
-	EncryptionChange                             = 0x08 // Encryption Change
-	ChangeConnectionLinkKeyComplete              = 0x09 // Change Conection Link Key Complete
-	MasterLinkKeyComplete                        = 0x0A // Master Link Keye Complete
-	ReadRemoteSupportedFeaturesComplete          = 0x0B // Read Remote Supported Features Complete
-	ReadRemoteVersionInformationComplete         = 0x0C // Read Remote Version Information Complete
-	QoSSetupComplete                             = 0x0D // QoSSetupComplete
-	CommandComplete                              = 0x0E // Command Complete
-	CommandStatus                                = 0x0F // Command status
-	HardwareError                                = 0x10 // Hardware Error
-	FlushOccurred                                = 0x11 // Flush Occured
-	RoleChange                                   = 0x12 // Role Change
-	NumberOfCompletedPkts                        = 0x13 // Number Of Completed Packets
-	ModeChange                                   = 0x14 // Mode Change
-	ReturnLinkKeys                               = 0x15 // Return Link Keys
-	PinCodeRequest                               = 0x16 // PIN Code Request
-	LinkKeyRequest                               = 0x17 // Link Key Request
-	LinkKeyNotification                          = 0x18 // Link Key Notification
-	LoopbackCommand                              = 0x19 // Loopback Command
-	DataBufferOverflow                           = 0x1A // Data Buffer Overflow
-	MaxSlotsChange                               = 0x1B // Max Slots Change
-	ReadClockOffsetComplete                      = 0x1C // Read Clock Offset Complete
-	ConnectionPtypeChanged                       = 0x1D // Connection Packet Type Changed
-	QoSViolation                                 = 0x1E // QoS Violation
-	PageScanRepetitionModeChange                 = 0x20 // Page Scan Repetition Mode Change
-	FlowSpecificationComplete                    = 0x21 // Flow Specification
-	InquiryResultWithRssi                        = 0x22 // Inquery Result with RSSI
-	ReadRemoteExtendedFeaturesComplete           = 0x23 // Read Remote Extended Features Complete
-	SyncConnectionComplete                       = 0x2C // Synchronous Connection Complete
-	SyncConnectionChanged                        = 0x2D // Synchronous Connection Changed
-	SniffSubrating                               = 0x2E // Sniff Subrating
-	ExtendedInquiryResult                        = 0x2F // Extended Inquiry Result
-	EncryptionKeyRefreshComplete                 = 0x30 // Encryption Key Refresh Complete
-	IOCapabilityRequest                          = 0x31 // IO Capability Request
-	IOCapabilityResponse                         = 0x32 // IO Capability Changed
-	UserConfirmationRequest                      = 0x33 // User Confirmation Request
-	UserPasskeyRequest                           = 0x34 // User Passkey Request
-	RemoteOOBDataRequest                         = 0x35 // Remote OOB Data
-	SimplePairingComplete                        = 0x36 // Simple Pairing Complete
-	LinkSupervisionTimeoutChanged                = 0x38 // Link Supervision Timeout Changed
-	EnhancedFlushComplete                        = 0x39 // Enhanced Flush Complete
-	UserPasskeyNotify                            = 0x3B // User Passkey Notification
-	KeypressNotify                               = 0x3C // Keypass Notification
-	RemoteHostFeaturesNotify                     = 0x3D // Remote Host Supported Features Notification
-	LEMeta                                       = 0x3E // LE Meta
-	PhysicalLinkComplete                         = 0x40 // Physical Link Complete
-	ChannelSelected                              = 0x41 // Channel Selected
-	DisconnectionPhysicalLinkComplete            = 0x42 // Disconnection Physical Link Complete
-	PhysicalLinkLossEarlyWarning                 = 0x43 // Physical Link Loss Early Warning
-	PhysicalLinkRecovery                         = 0x44 // Physical Link Recovery
-	LogicalLinkComplete                          = 0x45 // Logical Link Complete
-	DisconnectionLogicalLinkComplete             = 0x46 // Disconnection Logical Link Complete
-	FlowSpecModifyComplete                       = 0x47 // Flow Spec Modify Complete
-	NumberOfCompletedBlocks                      = 0x48 // Number Of Completed Data Blocks
-	AMPStartTest                                 = 0x49 // AMP Start Test
-	AMPTestEnd                                   = 0x4A // AMP Test End
-	AMPReceiverReport                            = 0x4b // AMP Receiver Report
-	AMPStatusChange                              = 0x4D // AMP status Change
-	TriggeredClockCapture                        = 0x4e // Triggered Clock Capture
-	SynchronizationTrainComplete                 = 0x4F // Synchronization Train Complete
-	SynchronizationTrainReceived                 = 0x50 // Synchronization Train Received
-	ConnectionlessSlaveBroadcastReceive          = 0x51 // Connectionless Slave Broadcast Receive
-	ConnectionlessSlaveBroadcastTimeout          = 0x52 // Connectionless Slave Broadcast Timeout
-	TruncatedPageComplete                        = 0x53 // Truncated Page Complete
-	SlavePageResponseTimeout                     = 0x54 // Slave Page Response Timeout
-	ConnectionlessSlaveBroadcastChannelMapChange = 0x55 // Connectionless Slave Broadcast Channel Map Change
-	InquiryResponseNotification                  = 0x56 // Inquiry Response Notification
-	AuthenticatedPayloadTimeoutExpired           = 0x57 // Authenticated Payload Timeout Expired
-)
-
-type LEEventCode int
-
-const (
-	LEConnectionComplete               LEEventCode = 0x01 // LE Connection Complete
-	LEAdvertisingReport                            = 0x02 // LE Advertising Report
-	LEConnectionUpdateComplete                     = 0x03 // LE Connection Update Complete
-	LEReadRemoteUsedFeaturesComplete               = 0x04 // LE Read Remote Used Features Complete
-	LELTKRequest                                   = 0x05 // LE LTK Request
-	LERemoteConnectionParameterRequest             = 0x06 // LE Remote Connection Parameter Request
-)
-
-type EventHeader struct {
-	code int
-	plen uint8
-}
-
-func (h *EventHeader) Unmarshal(b []byte) error {
-	if len(b) < 2 {
-		return errors.New("malformed header")
-	}
-	h.code = int(b[0])
-	h.plen = b[1]
-	if uint8(len(b)) != 2+h.plen {
-		return errors.New("wrong length")
-	}
-	return nil
-}
-
-var o = util.Order
-
-// Event Parameters
-
-type InquiryCompleteEP struct {
-	Status uint8
-}
-
-type InquiryResultEP struct {
-	NumResponses           uint8
-	BDAddr                 [][6]byte
-	PageScanRepetitionMode []uint8
-	Reserved1              []byte
-	Reserved2              []byte
-	ClassOfDevice          [][3]byte
-	ClockOffset            []uint16
-}
-
-type ConnectionCompleteEP struct {
-	Status            uint8
-	ConnectionHandle  uint16
-	BDAddr            [6]byte
-	LinkType          uint8
-	EncryptionEnabled uint8
-}
-
-type ConnectionRequestEP struct {
-	BDAddr        [6]byte
-	ClassofDevice [3]byte
-	LinkType      uint8
-}
-
-type DisconnectionCompleteEP struct {
-	Status           uint8
-	ConnectionHandle uint16
-	Reason           uint8
-}
-
-func (e *DisconnectionCompleteEP) Unmarshal(b []byte) error {
-	buf := bytes.NewBuffer(b)
-	binary.Read(buf, binary.LittleEndian, &e.Status)
-	binary.Read(buf, binary.LittleEndian, &e.ConnectionHandle)
-	return binary.Read(buf, binary.LittleEndian, &e.Reason)
-}
-
-type CommandCompleteEP struct {
-	NumHCICommandPackets uint8
-	CommandOPCode        uint16
-	ReturnParameters     []byte
-}
-
-func (e *CommandCompleteEP) Unmarshal(b []byte) error {
-	buf := bytes.NewBuffer(b)
-	if err := binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets); err != nil {
-		return err
-	}
-	if err := binary.Read(buf, binary.LittleEndian, &e.CommandOPCode); err != nil {
-		return err
-	}
-	e.ReturnParameters = buf.Bytes()
-	return nil
-}
-
-type CommandStatusEP struct {
-	Status               uint8
-	NumHCICommandPackets uint8
-	CommandOpcode        uint16
-}
-
-func (e *CommandStatusEP) Unmarshal(b []byte) error {
-	buf := bytes.NewBuffer(b)
-	binary.Read(buf, binary.LittleEndian, &e.Status)
-	binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets)
-	return binary.Read(buf, binary.LittleEndian, &e.CommandOpcode)
-}
-
-type NumOfCompletedPkt struct {
-	ConnectionHandle   uint16
-	NumOfCompletedPkts uint16
-}
-
-type NumberOfCompletedPktsEP struct {
-	NumberOfHandles uint8
-	Packets         []NumOfCompletedPkt
-}
-
-func (e *NumberOfCompletedPktsEP) Unmarshal(b []byte) error {
-	e.NumberOfHandles = b[0]
-	n := int(e.NumberOfHandles)
-	buf := bytes.NewBuffer(b[1:])
-	e.Packets = make([]NumOfCompletedPkt, n)
-	for i := 0; i < n; i++ {
-		binary.Read(buf, binary.LittleEndian, &e.Packets[i].ConnectionHandle)
-		binary.Read(buf, binary.LittleEndian, &e.Packets[i].NumOfCompletedPkts)
-
-		e.Packets[i].ConnectionHandle &= 0xfff
-	}
-	return nil
-}
-
-// LE Meta Subevents
-type LEConnectionCompleteEP struct {
-	SubeventCode        uint8
-	Status              uint8
-	ConnectionHandle    uint16
-	Role                uint8
-	PeerAddressType     uint8
-	PeerAddress         [6]byte
-	ConnInterval        uint16
-	ConnLatency         uint16
-	SupervisionTimeout  uint16
-	MasterClockAccuracy uint8
-}
-
-func (e *LEConnectionCompleteEP) Unmarshal(b []byte) error {
-	e.SubeventCode = o.Uint8(b[0:])
-	e.Status = o.Uint8(b[1:])
-	e.ConnectionHandle = o.Uint16(b[2:])
-	e.Role = o.Uint8(b[4:])
-	e.PeerAddressType = o.Uint8(b[5:])
-	e.PeerAddress = o.MAC(b[6:])
-	e.ConnInterval = o.Uint16(b[12:])
-	e.ConnLatency = o.Uint16(b[14:])
-	e.SupervisionTimeout = o.Uint16(b[16:])
-	e.MasterClockAccuracy = o.Uint8(b[17:])
-	return nil
-}
-
-type LEAdvertisingReportEP struct {
-	SubeventCode uint8
-	NumReports   uint8
-	EventType    []uint8
-	AddressType  []uint8
-	Address      [][6]byte
-	Length       []uint8
-	Data         [][]byte
-	RSSI         []int8
-}
-
-func (e *LEAdvertisingReportEP) Unmarshal(b []byte) error {
-	e.SubeventCode = o.Uint8(b)
-	b = b[1:]
-	e.NumReports = o.Uint8(b)
-	b = b[1:]
-	n := int(e.NumReports)
-	e.EventType = make([]uint8, n)
-	e.AddressType = make([]uint8, n)
-	e.Address = make([][6]byte, n)
-	e.Length = make([]uint8, n)
-	e.Data = make([][]byte, n)
-	e.RSSI = make([]int8, n)
-
-	for i := 0; i < n; i++ {
-		e.EventType[i] = o.Uint8(b)
-		b = b[1:]
-	}
-	for i := 0; i < n; i++ {
-		e.AddressType[i] = o.Uint8(b)
-		b = b[1:]
-	}
-	for i := 0; i < n; i++ {
-		e.Address[i] = o.MAC(b)
-		b = b[6:]
-	}
-	for i := 0; i < n; i++ {
-		e.Length[i] = o.Uint8(b)
-		b = b[1:]
-	}
-	for i := 0; i < n; i++ {
-		e.Data[i] = make([]byte, e.Length[i])
-		copy(e.Data[i], b)
-		b = b[e.Length[i]:]
-	}
-	for i := 0; i < n; i++ {
-		e.RSSI[i] = o.Int8(b)
-		b = b[1:]
-	}
-	return nil
-}
-
-type LEConnectionUpdateCompleteEP struct {
-	SubeventCode       uint8
-	Status             uint8
-	ConnectionHandle   uint16
-	ConnInterval       uint16
-	ConnLatency        uint16
-	SupervisionTimeout uint16
-}
-
-func (e *LEConnectionUpdateCompleteEP) Unmarshal(b []byte) error {
-	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
-}
-
-type LEReadRemoteUsedFeaturesCompleteEP struct {
-	SubeventCode     uint8
-	Status           uint8
-	ConnectionHandle uint16
-	LEFeatures       uint64
-}
-
-func (e *LEReadRemoteUsedFeaturesCompleteEP) Unmarshal(b []byte) error {
-	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
-}
-
-type LELTKRequestEP struct {
-	SubeventCode          uint8
-	ConnectionHandle      uint16
-	RandomNumber          uint64
-	EncryptionDiversifier uint16
-}
-
-func (e *LELTKRequestEP) Unmarshal(b []byte) error {
-	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
-}
-
-type LERemoteConnectionParameterRequestEP struct {
-	SubeventCode     uint8
-	ConnectionHandle uint16
-	IntervalMin      uint16
-	IntervalMax      uint16
-	Latency          uint16
-	Timeout          uint16
-}
-
-func (e *LERemoteConnectionParameterRequestEP) Unmarshal(b []byte) error {
-	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/LICENSE.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/LICENSE.md b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/LICENSE.md
deleted file mode 100644
index 1e1b7cd..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/LICENSE.md
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2012 Mark Wolfe
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/README.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/README.md b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/README.md
deleted file mode 100644
index 837fa03..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# gioctl [![GoDoc](https://img.shields.io/badge/godoc-Reference-brightgreen.svg?style=flat)](http://godoc.org/github.com/wolfeidau/gioctl)
-
-Simple library which provides golang versions of the ioctl macros in linux.
-
-# References
-
-* https://github.com/luismesas/goPi started with the IOCTL stuff from this project initally.
-* http://www.circlemud.org/jelson/software/fusd/docs/node31.html good information on IOCTL macros.
-
-# License
-
-This code is Copyright (c) 2014 Mark Wolfe and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/ioctl.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/ioctl.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/ioctl.go
deleted file mode 100644
index 0097459..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/gioctl/ioctl.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package gioctl
-
-import "syscall"
-
-const (
-	typeBits      = 8
-	numberBits    = 8
-	sizeBits      = 14
-	directionBits = 2
-
-	typeMask      = (1 << typeBits) - 1
-	numberMask    = (1 << numberBits) - 1
-	sizeMask      = (1 << sizeBits) - 1
-	directionMask = (1 << directionBits) - 1
-
-	directionNone  = 0
-	directionWrite = 1
-	directionRead  = 2
-
-	numberShift    = 0
-	typeShift      = numberShift + numberBits
-	sizeShift      = typeShift + typeBits
-	directionShift = sizeShift + sizeBits
-)
-
-func ioc(dir, t, nr, size uintptr) uintptr {
-	return (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)
-}
-
-// Io used for a simple ioctl that sends nothing but the type and number, and receives back nothing but an (integer) retval.
-func Io(t, nr uintptr) uintptr {
-	return ioc(directionNone, t, nr, 0)
-}
-
-// IoR used for an ioctl that reads data from the device driver. The driver will be allowed to return sizeof(data_type) bytes to the user.
-func IoR(t, nr, size uintptr) uintptr {
-	return ioc(directionRead, t, nr, size)
-}
-
-// IoW used for an ioctl that writes data to the device driver.
-func IoW(t, nr, size uintptr) uintptr {
-	return ioc(directionWrite, t, nr, size)
-}
-
-// IoRW  a combination of IoR and IoW. That is, data is both written to the driver and then read back from the driver by the client.
-func IoRW(t, nr, size uintptr) uintptr {
-	return ioc(directionRead|directionWrite, t, nr, size)
-}
-
-// Ioctl simplified ioct call
-func Ioctl(fd, op, arg uintptr) error {
-	_, _, ep := syscall.Syscall(syscall.SYS_IOCTL, fd, op, arg)
-	if ep != 0 {
-		return syscall.Errno(ep)
-	}
-	return nil
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/hci.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/hci.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/hci.go
deleted file mode 100644
index c41d0bf..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/hci.go
+++ /dev/null
@@ -1,400 +0,0 @@
-package linux
-
-import (
-	"fmt"
-	"io"
-	"log"
-	"sync"
-
-	"github.com/runtimeinc/gatt/linux/cmd"
-	"github.com/runtimeinc/gatt/linux/evt"
-)
-
-type HCI struct {
-	AcceptMasterHandler  func(pd *PlatData)
-	AcceptSlaveHandler   func(pd *PlatData)
-	AdvertisementHandler func(pd *PlatData)
-
-	d io.ReadWriteCloser
-	c *cmd.Cmd
-	e *evt.Evt
-
-	plist   map[bdaddr]*PlatData
-	plistmu *sync.Mutex
-
-	bufCnt  chan struct{}
-	bufSize int
-
-	maxConn int
-	connsmu *sync.Mutex
-	conns   map[uint16]*conn
-
-	adv   bool
-	advmu *sync.Mutex
-}
-
-type bdaddr [6]byte
-
-type PlatData struct {
-	Name        string
-	AddressType uint8
-	Address     [6]byte
-	Data        []byte
-	Connectable bool
-	RSSI        int8
-
-	Conn io.ReadWriteCloser
-}
-
-func NewHCI(devID int, chk bool, maxConn int) (*HCI, error) {
-	d, err := newDevice(devID, chk)
-	if err != nil {
-		return nil, err
-	}
-	c := cmd.NewCmd(d)
-	e := evt.NewEvt()
-
-	h := &HCI{
-		d: d,
-		c: c,
-		e: e,
-
-		plist:   make(map[bdaddr]*PlatData),
-		plistmu: &sync.Mutex{},
-
-		bufCnt:  make(chan struct{}, 15-1),
-		bufSize: 27,
-
-		maxConn: maxConn,
-		connsmu: &sync.Mutex{},
-		conns:   map[uint16]*conn{},
-
-		advmu: &sync.Mutex{},
-	}
-
-	e.HandleEvent(evt.LEMeta, evt.HandlerFunc(h.handleLEMeta))
-	e.HandleEvent(evt.DisconnectionComplete, evt.HandlerFunc(h.handleDisconnectionComplete))
-	e.HandleEvent(evt.NumberOfCompletedPkts, evt.HandlerFunc(h.handleNumberOfCompletedPkts))
-	e.HandleEvent(evt.CommandComplete, evt.HandlerFunc(c.HandleComplete))
-	e.HandleEvent(evt.CommandStatus, evt.HandlerFunc(c.HandleStatus))
-
-	go h.mainLoop()
-	h.resetDevice()
-	return h, nil
-}
-
-func (h *HCI) Close() error {
-	for _, c := range h.conns {
-		c.Close()
-	}
-	return h.d.Close()
-}
-
-func (h *HCI) SetAdvertiseEnable(en bool) error {
-	h.advmu.Lock()
-	h.adv = en
-	h.advmu.Unlock()
-	return h.setAdvertiseEnable(en)
-}
-
-func (h *HCI) setAdvertiseEnable(en bool) error {
-	h.advmu.Lock()
-	defer h.advmu.Unlock()
-	if en && h.adv && (len(h.conns) == h.maxConn) {
-		return nil
-	}
-	return h.c.SendAndCheckResp(
-		cmd.LESetAdvertiseEnable{
-			AdvertisingEnable: btoi(en),
-		}, []byte{0x00})
-}
-
-func (h *HCI) SendCmdWithAdvOff(c cmd.CmdParam) error {
-	h.setAdvertiseEnable(false)
-	err := h.c.SendAndCheckResp(c, nil)
-	if h.adv {
-		h.setAdvertiseEnable(true)
-	}
-	return err
-}
-
-func (h *HCI) SetScanEnable(en bool, dup bool) error {
-	return h.c.SendAndCheckResp(
-		cmd.LESetScanEnable{
-			LEScanEnable:     btoi(en),
-			FilterDuplicates: btoi(!dup),
-		}, []byte{0x00})
-}
-
-func (h *HCI) Connect(pd *PlatData) error {
-	h.c.Send(
-		cmd.LECreateConn{
-			LEScanInterval:        0x0004,         // N x 0.625ms
-			LEScanWindow:          0x0004,         // N x 0.625ms
-			InitiatorFilterPolicy: 0x00,           // white list not used
-			PeerAddressType:       pd.AddressType, // public or random
-			PeerAddress:           pd.Address,     //
-			OwnAddressType:        0x00,           // public
-			ConnIntervalMin:       6,         // N x 0.125ms
-			ConnIntervalMax:       7,         // N x 0.125ms
-			ConnLatency:           0x0000,         //
-			SupervisionTimeout:    0x00100,         // N x 10ms
-			MinimumCELength:       0x0000,         // N x 0.625ms
-			MaximumCELength:       0x0000,         // N x 0.625ms
-		})
-	return nil
-}
-
-func (h *HCI) CancelConnection(pd *PlatData) error {
-	return pd.Conn.Close()
-}
-
-func (h *HCI) SendRawCommand(c cmd.CmdParam) ([]byte, error) {
-	return h.c.Send(c)
-}
-
-func btoi(b bool) uint8 {
-	if b {
-		return 1
-	}
-	return 0
-}
-
-func (h *HCI) mainLoop() {
-	b := make([]byte, 4096)
-	for {
-		n, err := h.d.Read(b)
-		if err != nil {
-			return
-		}
-		if n == 0 {
-			return
-		}
-		p := make([]byte, n)
-		copy(p, b)
-		h.handlePacket(p)
-	}
-}
-
-func (h *HCI) handlePacket(b []byte) {
-	t, b := packetType(b[0]), b[1:]
-	var err error
-	switch t {
-	case typCommandPkt:
-		op := uint16(b[0]) | uint16(b[1])<<8
-		log.Printf("unmanaged cmd: opcode (%04x) [ % X ]\n", op, b)
-	case typACLDataPkt:
-		err = h.handleL2CAP(b)
-	case typSCODataPkt:
-		err = fmt.Errorf("SCO packet not supported")
-	case typEventPkt:
-		go func() {
-			err := h.e.Dispatch(b)
-			if err != nil {
-				log.Printf("hci: %s, [ % X]", err, b)
-			}
-		}()
-	case typVendorPkt:
-		err = fmt.Errorf("Vendor packet not supported")
-	default:
-		log.Fatalf("Unknown event: 0x%02X [ % X ]\n", t, b)
-	}
-	if err != nil {
-		log.Printf("hci: %s, [ % X]", err, b)
-	}
-}
-
-func (h *HCI) resetDevice() error {
-	seq := []cmd.CmdParam{
-		cmd.Reset{},
-		cmd.SetEventMask{EventMask: 0x3dbff807fffbffff},
-		cmd.LESetEventMask{LEEventMask: 0x000000000000001F},
-		cmd.WriteSimplePairingMode{SimplePairingMode: 1},
-		cmd.WriteLEHostSupported{LESupportedHost: 1, SimultaneousLEHost: 0},
-		cmd.WriteInquiryMode{InquiryMode: 2},
-		cmd.WritePageScanType{PageScanType: 1},
-		cmd.WriteInquiryScanType{ScanType: 1},
-		cmd.WriteClassOfDevice{ClassOfDevice: [3]byte{0x40, 0x02, 0x04}},
-		cmd.WritePageTimeout{PageTimeout: 0x2000},
-		cmd.WriteDefaultLinkPolicy{DefaultLinkPolicySettings: 0x5},
-		cmd.HostBufferSize{
-			HostACLDataPacketLength:            0x1000,
-			HostSynchronousDataPacketLength:    0xff,
-			HostTotalNumACLDataPackets:         0x0014,
-			HostTotalNumSynchronousDataPackets: 0x000a},
-		cmd.LESetScanParameters{
-			LEScanType:           0x01,   // [0x00]: passive, 0x01: active
-			LEScanInterval:       0x0010, // [0x10]: 0.625ms * 16
-			LEScanWindow:         0x0010, // [0x10]: 0.625ms * 16
-			OwnAddressType:       0x00,   // [0x00]: public, 0x01: random
-			ScanningFilterPolicy: 0x00,   // [0x00]: accept all, 0x01: ignore non-white-listed.
-		},
-	}
-	for _, s := range seq {
-		if err := h.c.SendAndCheckResp(s, []byte{0x00}); err != nil {
-			return err
-		}
-	}
-	return nil
-}
-
-func (h *HCI) handleAdvertisement(b []byte) {
-	// If no one is interested, don't bother.
-	if h.AdvertisementHandler == nil {
-		return
-	}
-	ep := &evt.LEAdvertisingReportEP{}
-	if err := ep.Unmarshal(b); err != nil {
-		return
-	}
-	for i := 0; i < int(ep.NumReports); i++ {
-		addr := bdaddr(ep.Address[i])
-		et := ep.EventType[i]
-		connectable := et == advInd || et == advDirectInd
-		scannable := et == advInd || et == advScanInd
-
-		if et == scanRsp {
-			h.plistmu.Lock()
-			pd, ok := h.plist[addr]
-			h.plistmu.Unlock()
-			if ok {
-				pd.Data = append(pd.Data, ep.Data[i]...)
-				h.AdvertisementHandler(pd)
-			}
-			continue
-		}
-
-		pd := &PlatData{
-			AddressType: ep.AddressType[i],
-			Address:     ep.Address[i],
-			Data:        ep.Data[i],
-			Connectable: connectable,
-			RSSI:        ep.RSSI[i],
-		}
-		h.plistmu.Lock()
-		h.plist[addr] = pd
-		h.plistmu.Unlock()
-		if scannable {
-			continue
-		}
-		h.AdvertisementHandler(pd)
-	}
-}
-
-func (h *HCI) handleNumberOfCompletedPkts(b []byte) error {
-	ep := &evt.NumberOfCompletedPktsEP{}
-	if err := ep.Unmarshal(b); err != nil {
-		return err
-	}
-	for _, r := range ep.Packets {
-		for i := 0; i < int(r.NumOfCompletedPkts); i++ {
-			<-h.bufCnt
-		}
-	}
-	return nil
-}
-
-func (h *HCI) handleConnection(b []byte) {
-	ep := &evt.LEConnectionCompleteEP{}
-	if err := ep.Unmarshal(b); err != nil {
-		return // FIXME
-	}
-	hh := ep.ConnectionHandle
-	c := newConn(h, hh)
-	h.connsmu.Lock()
-	h.conns[hh] = c
-	h.connsmu.Unlock()
-	h.setAdvertiseEnable(true)
-
-	// FIXME: sloppiness. This call should be called by the package user once we
-	// flesh out the support of l2cap signaling packets (CID:0x0001,0x0005)
-	if ep.ConnLatency != 0 || ep.ConnInterval > 0x18 {
-		c.updateConnection()
-	}
-
-	// master connection
-	if ep.Role == 0x01 {
-		pd := &PlatData{
-			Address: ep.PeerAddress,
-			Conn:    c,
-		}
-		h.AcceptMasterHandler(pd)
-		return
-	}
-	h.plistmu.Lock()
-	pd := h.plist[ep.PeerAddress]
-	h.plistmu.Unlock()
-	pd.Conn = c
-	h.AcceptSlaveHandler(pd)
-}
-
-func (h *HCI) handleDisconnectionComplete(b []byte) error {
-	ep := &evt.DisconnectionCompleteEP{}
-	if err := ep.Unmarshal(b); err != nil {
-		return err
-	}
-	hh := ep.ConnectionHandle
-	h.connsmu.Lock()
-	defer h.connsmu.Unlock()
-	c, found := h.conns[hh]
-	if !found {
-		// should not happen, just be cautious for now.
-		log.Printf("l2conn: disconnecting a disconnected 0x%04X connection", hh)
-		return nil
-	}
-	delete(h.conns, hh)
-	close(c.aclc)
-	h.setAdvertiseEnable(true)
-	return nil
-}
-
-func (h *HCI) handleLEMeta(b []byte) error {
-	code := evt.LEEventCode(b[0])
-	switch code {
-	case evt.LEConnectionComplete:
-		go h.handleConnection(b)
-	case evt.LEConnectionUpdateComplete:
-		// anything to do here?
-	case evt.LEAdvertisingReport:
-		go h.handleAdvertisement(b)
-	// case evt.LEReadRemoteUsedFeaturesComplete:
-	// case evt.LELTKRequest:
-	// case evt.LERemoteConnectionParameterRequest:
-	default:
-		return fmt.Errorf("Unhandled LE event: %s, [ % X ]", code, b)
-	}
-	return nil
-}
-
-func (h *HCI) handleL2CAP(b []byte) error {
-        a := &aclData{}
-	if err := a.unmarshal(b); err != nil {
-		return err
-	}
-	h.connsmu.Lock()
-	defer h.connsmu.Unlock()
-	c, found := h.conns[a.attr]
-
-        if a.flags != 0x002 {
-	    if !found {
-		    // should not happen, just be cautious for now.
-		    log.Printf("l2conn: got data for disconnected handle: 0x%04x", a.attr)
-		    return nil
-	        if len(a.b) < 4 {
-		    log.Printf("l2conn: l2cap packet is too short/corrupt, length is %d", len(a.b))
-		    return nil
-	        }
-	        cid := uint16(a.b[2]) | (uint16(a.b[3]) << 8)
-	        if cid == 5 {
-		    c.handleSignal(a)
-		    return nil
-	        }
-            }
-        }
-	c.aclc <- a
-	return nil
-}
-
-func (h *HCI) trace(fmt string, v ...interface{}) {
-	log.Printf(fmt, v)
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/l2cap.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/l2cap.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/l2cap.go
deleted file mode 100644
index 19c2968..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/l2cap.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package linux
-
-import (
-	"fmt"
-	"io"
-	"log"
-
-	"github.com/runtimeinc/gatt/linux/cmd"
-)
-
-type aclData struct {
-	attr  uint16
-	flags uint8
-	dlen  uint16
-	b     []byte
-}
-
-func (a *aclData) unmarshal(b []byte) error {
-	if len(b) < 4 {
-		return fmt.Errorf("malformed acl packet")
-	}
-	attr := uint16(b[0]) | (uint16(b[1]&0x0f) << 8)
-	flags := b[1] >> 4
-	dlen := uint16(b[2]) | (uint16(b[3]) << 8)
-	if len(b) != 4+int(dlen) {
-		return fmt.Errorf("malformed acl packet")
-	}
-
-	*a = aclData{attr: attr, flags: flags, dlen: dlen, b: b[4:]}
-	return nil
-}
-
-type conn struct {
-	hci  *HCI
-	attr uint16
-	aclc chan *aclData
-}
-
-func newConn(hci *HCI, hh uint16) *conn {
-	return &conn{
-		hci:  hci,
-		attr: hh,
-		aclc: make(chan *aclData),
-	}
-}
-
-func (c *conn) updateConnection() (int, error) {
-	b := []byte{
-		0x12,       // Code (Connection Param Update)
-		0x02,       // ID
-		0x08, 0x00, // DataLength
-		0x08, 0x00, // IntervalMin
-		0x18, 0x00, // IntervalMax
-		0x00, 0x00, // SlaveLatency
-		0xC8, 0x00} // TimeoutMultiplier
-	return c.write(0x05, b)
-}
-
-// write writes the l2cap payload to the controller.
-// It first prepend the l2cap header (4-bytes), and diassemble the payload
-// if it is larger than the HCI LE buffer size that the conntroller can support.
-func (c *conn) write(cid int, b []byte) (int, error) {
-	flag := uint8(0) // ACL data continuation flag
-	tlen := len(b)   // Total length of the l2cap payload
-
-	// log.Printf("W: [ % X ]", b)
-	w := append(
-		[]byte{
-			0,    // packet type
-			0, 0, // attr
-			0, 0, // dlen
-			uint8(tlen), uint8(tlen >> 8), // l2cap header
-			uint8(cid), uint8(cid >> 8), // l2cap header
-		}, b...)
-
-	n := 4 + tlen // l2cap header + l2cap payload
-	for n > 0 {
-		dlen := n
-		if dlen > c.hci.bufSize {
-			dlen = c.hci.bufSize
-		}
-		w[0] = 0x02 // packetTypeACL
-		w[1] = uint8(c.attr)
-		w[2] = uint8(c.attr>>8) | flag
-		w[3] = uint8(dlen)
-		w[4] = uint8(dlen >> 8)
-
-		// make sure we don't send more buffers than the controller can handdle
-		c.hci.bufCnt <- struct{}{}
-
-		c.hci.d.Write(w[:5+dlen])
-		w = w[dlen:] // advance the pointer to the next segment, if any.
-		flag = 0x10  // the rest of iterations attr continued segments, if any.
-		n -= dlen
-	}
-
-	return len(b), nil
-}
-
-func (c *conn) Read(b []byte) (int, error) {
-	a, ok := <-c.aclc
-	if !ok {
-		return 0, io.EOF
-	}
-	tlen := int(uint16(a.b[0]) | uint16(a.b[1])<<8)
-	if tlen > len(b) {
-		return 0, io.ErrShortBuffer
-	}
-	d := a.b[4:] // skip l2cap header
-	copy(b, d)
-	n := len(d)
-
-	// Keep receiving and reassemble continued l2cap segments
-	for n != tlen {
-		if a, ok = <-c.aclc; !ok || (a.flags&0x1) == 0 {
-			return n, io.ErrUnexpectedEOF
-		}
-		copy(b[n:], a.b)
-		n += len(a.b)
-	}
-	// log.Printf("R: [ % X ]", b[:n])
-	return n, nil
-}
-
-func (c *conn) Write(b []byte) (int, error) {
-	return c.write(0x04, b)
-}
-
-// Close disconnects the connection by sending HCI disconnect command to the device.
-func (c *conn) Close() error {
-	h := c.hci
-	hh := c.attr
-	h.connsmu.Lock()
-	defer h.connsmu.Unlock()
-	_, found := h.conns[hh]
-	if !found {
-		// log.Printf("l2conn: 0x%04x already disconnected", hh)
-		return nil
-	}
-	if err, _ := h.c.Send(cmd.Disconnect{ConnectionHandle: hh, Reason: 0x13}); err != nil {
-		return fmt.Errorf("l2conn: failed to disconnect, %s", err)
-	}
-	return nil
-}
-
-// Signal Packets
-// 0x00 Reserved								Any
-// 0x01 Command reject							0x0001 and 0x0005
-// 0x02 Connection request						0x0001
-// 0x03 Connection response 					0x0001
-// 0x04 Configure request						0x0001
-// 0x05 Configure response						0x0001
-// 0x06 Disconnection request					0x0001 and 0x0005
-// 0x07 Disconnection response					0x0001 and 0x0005
-// 0x08 Echo request							0x0001
-// 0x09 Echo response							0x0001
-// 0x0A Information request						0x0001
-// 0x0B Information response					0x0001
-// 0x0C Create Channel request					0x0001
-// 0x0D Create Channel response					0x0001
-// 0x0E Move Channel request					0x0001
-// 0x0F Move Channel response					0x0001
-// 0x10 Move Channel Confirmation				0x0001
-// 0x11 Move Channel Confirmation response		0x0001
-// 0x12 Connection Parameter Update request		0x0005
-// 0x13 Connection Parameter Update response	0x0005
-// 0x14 LE Credit Based Connection request		0x0005
-// 0x15 LE Credit Based Connection response		0x0005
-// 0x16 LE Flow Control Credit					0x0005
-func (c *conn) handleSignal(a *aclData) error {
-	log.Printf("ignore l2cap signal:[ % X ]", a.b)
-	// FIXME: handle LE signaling channel (CID: 5)
-	return nil
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm.s
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm.s b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm.s
deleted file mode 100644
index d4ca868..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm.s
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright 2014 The Go Authors.  All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-#include "textflag.h"
-
-TEXT �use(SB),NOSPLIT,$0
-	RET

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm_linux_386.s
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm_linux_386.s b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm_linux_386.s
deleted file mode 100644
index 5d3ad9a..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/asm_linux_386.s
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-#include "textflag.h"
-
-//
-// System calls for 386, Linux
-//
-
-// Just jump to package syscall's implementation for all these functions.
-// The runtime may know about them.
-
-TEXT	�Syscall(SB),NOSPLIT,$0-28
-	JMP	syscall�Syscall(SB)
-
-TEXT	�Syscall6(SB),NOSPLIT,$0-40
-	JMP	syscall�Syscall6(SB)
-
-TEXT �RawSyscall(SB),NOSPLIT,$0-28
-	JMP	syscall�RawSyscall(SB)
-
-TEXT	�RawSyscall6(SB),NOSPLIT,$0-40
-	JMP	syscall�RawSyscall6(SB)
-
-TEXT �socketcall(SB),NOSPLIT,$0-36
-	JMP	syscall�socketcall(SB)
-
-TEXT �rawsocketcall(SB),NOSPLIT,$0-36
-	JMP	syscall�rawsocketcall(SB)
-
-TEXT �seek(SB),NOSPLIT,$0-28
-	JMP	syscall�seek(SB)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket.go
deleted file mode 100644
index ffc49a6..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// Package socket implements a minimal set of function of the HCI Socket,
-// which is not yet supported by the Go standard library. Most of the code
-// follow suit the existing code in the standard library. Once it gets
-// supported officially, we can get rid of this package entirely.
-
-package socket
-
-import (
-	"errors"
-	"syscall"
-	"time"
-	"unsafe"
-)
-
-// Bluetooth Protocols
-const (
-	BTPROTO_L2CAP  = 0
-	BTPROTO_HCI    = 1
-	BTPROTO_SCO    = 2
-	BTPROTO_RFCOMM = 3
-	BTPROTO_BNEP   = 4
-	BTPROTO_CMTP   = 5
-	BTPROTO_HIDP   = 6
-	BTPROTO_AVDTP  = 7
-)
-
-const (
-	HCI_CHANNEL_RAW     = 0
-	HCI_CHANNEL_USER    = 1
-	HCI_CHANNEL_MONITOR = 2
-	HCI_CHANNEL_CONTROL = 3
-)
-
-var (
-	ErrSocketOpenFailed  = errors.New("unable to open bluetooth socket to device")
-	ErrSocketBindTimeout = errors.New("timeout occured binding to bluetooth device")
-)
-
-type _Socklen uint32
-
-type Sockaddr interface {
-	sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
-}
-
-type rawSockaddrHCI struct {
-	Family  uint16
-	Dev     uint16
-	Channel uint16
-}
-
-type SockaddrHCI struct {
-	Dev     int
-	Channel uint16
-	raw     rawSockaddrHCI
-}
-
-const sizeofSockaddrHCI = unsafe.Sizeof(rawSockaddrHCI{})
-
-func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
-	if sa.Dev < 0 || sa.Dev > 0xFFFF {
-		return nil, 0, syscall.EINVAL
-	}
-	if sa.Channel < 0 || sa.Channel > 0xFFFF {
-		return nil, 0, syscall.EINVAL
-	}
-	sa.raw.Family = AF_BLUETOOTH
-	sa.raw.Dev = uint16(sa.Dev)
-	sa.raw.Channel = sa.Channel
-	return unsafe.Pointer(&sa.raw), _Socklen(sizeofSockaddrHCI), nil
-}
-
-func Socket(domain, typ, proto int) (int, error) {
-	for i := 0; i < 5; i++ {
-		if fd, err := syscall.Socket(domain, typ, proto); err == nil || err != syscall.EBUSY {
-			return fd, err
-		}
-		time.Sleep(time.Second)
-	}
-	return 0, ErrSocketOpenFailed
-}
-
-func Bind(fd int, sa Sockaddr) (err error) {
-	ptr, n, err := sa.sockaddr()
-	if err != nil {
-		return err
-	}
-	for i := 0; i < 5; i++ {
-		if err = bind(fd, ptr, n); err == nil || err != syscall.EBUSY {
-			return err
-		}
-		time.Sleep(time.Second)
-	}
-	return ErrSocketBindTimeout
-}
-
-// Socket Level
-const (
-	SOL_HCI    = 0
-	SOL_L2CAP  = 6
-	SOL_SCO    = 17
-	SOL_RFCOMM = 18
-
-	SOL_BLUETOOTH = 274
-)
-
-// HCI Socket options
-const (
-	HCI_DATA_DIR   = 1
-	HCI_FILTER     = 2
-	HCI_TIME_STAMP = 3
-)
-
-type HCIFilter struct {
-	TypeMask  uint32
-	EventMask [2]uint32
-	opcode    uint16
-}
-
-func SetsockoptFilter(fd int, f *HCIFilter) (err error) {
-	return setsockopt(fd, SOL_HCI, HCI_FILTER, unsafe.Pointer(f), unsafe.Sizeof(*f))
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_common.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_common.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_common.go
deleted file mode 100644
index b01ceeb..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_common.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// +build !386
-
-package socket
-
-import (
-	"syscall"
-	"unsafe"
-)
-
-func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
-	_, _, e1 := syscall.Syscall(syscall.SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
-	if e1 != 0 {
-		err = e1
-	}
-	return
-}
-
-func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
-	_, _, e1 := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
-	if e1 != 0 {
-		err = e1
-	}
-	return
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_darwin.go
deleted file mode 100644
index abb96a5..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_darwin.go
+++ /dev/null
@@ -1,6 +0,0 @@
-// +build darwin
-
-package socket
-
-// For compile time compatibility
-const AF_BLUETOOTH = 0

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux.go
deleted file mode 100644
index 4793915..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build linux
-
-package socket
-
-import "syscall"
-
-const AF_BLUETOOTH = syscall.AF_BLUETOOTH

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux_386.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux_386.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux_386.go
deleted file mode 100644
index 05ca65c..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/socket/socket_linux_386.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// +build linux,386
-
-package socket
-
-import (
-	"syscall"
-	"unsafe"
-)
-
-const (
-	BIND         = 2
-	SETSOCKETOPT = 14
-)
-
-func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
-	_, e1 := socketcall(BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
-	if e1 != 0 {
-		err = e1
-	}
-	return
-}
-
-func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
-	_, e1 := socketcall(SETSOCKETOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0)
-	if e1 != 0 {
-		err = e1
-	}
-	return
-}
-
-func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno)



[25/41] incubator-mynewt-newt git commit: MYNEWT-509 - Newt: fail on image flash overflow.

Posted by ma...@apache.org.
MYNEWT-509 - Newt: fail on image flash overflow.

Ensure each generated image leaves sufficient room at the end of its
slot for a boot trailer.  Newt calculates the size of a boot trailer by
using the MCU_FLASH_MIN_WRITE_SIZE syscfg setting (newly added to each
MCU package).  If this setting is not defined, newt warns the user and
assumes a min-write-size of 1.

The "-f" (force) option causes newt to only warn about overflow.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/249ee54f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/249ee54f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/249ee54f

Branch: refs/heads/mynewt_1_0_0
Commit: 249ee54f4aada49a9c3e6545d7881ac066a34ebe
Parents: 52d031e
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Mar 2 16:09:01 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:37:47 2017 -0800

----------------------------------------------------------------------
 newt/builder/targetbuild.go | 113 +++++++++++++++++++++++++++++++++++++++
 newt/cli/image_cmds.go      |   7 ++-
 newt/cli/project_cmds.go    |  20 +++----
 newt/cli/run_cmds.go        |   5 ++
 newt/cli/target_cmds.go     |   7 ++-
 newt/image/image.go         |   9 ++++
 newt/newtutil/newtutil.go   |   1 +
 7 files changed, 149 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index 2576764..c522597 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -31,8 +31,10 @@ import (
 
 	log "github.com/Sirupsen/logrus"
 
+	"mynewt.apache.org/newt/newt/flash"
 	"mynewt.apache.org/newt/newt/image"
 	"mynewt.apache.org/newt/newt/interfaces"
+	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
 	"mynewt.apache.org/newt/newt/resolve"
@@ -645,6 +647,113 @@ func (t *TargetBuilder) augmentManifest(
 	return nil
 }
 
+// Calculates the size of a single boot trailer.  This is the amount of flash
+// that must be reserved at the end of each image slot.
+func (t *TargetBuilder) bootTrailerSize() int {
+	var minWriteSz int
+
+	entry, ok := t.res.Cfg.Settings["MCU_FLASH_MIN_WRITE_SIZE"]
+	if !ok {
+		util.StatusMessage(util.VERBOSITY_DEFAULT,
+			"* Warning: target does not define MCU_FLASH_MIN_WRITE_SIZE "+
+				"setting; assuming a value of 1.\n")
+		minWriteSz = 1
+	} else {
+		val, err := util.AtoiNoOct(entry.Value)
+		if err != nil {
+			util.StatusMessage(util.VERBOSITY_DEFAULT,
+				"* Warning: target specifies invalid non-integer "+
+					"MCU_FLASH_MIN_WRITE_SIZE setting; assuming a "+
+					"value of 1.\n")
+			minWriteSz = 1
+		} else {
+			minWriteSz = val
+		}
+	}
+
+	/* Mynewt boot trailer format:
+	 *
+	 *  0                   1                   2                   3
+	 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+	 * ~                       MAGIC (16 octets)                       ~
+	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+	 * ~                                                               ~
+	 * ~             Swap status (128 * min-write-size * 3)            ~
+	 * ~                                                               ~
+	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+	 * |   Copy done   |     0xff padding (up to min-write-sz - 1)     |
+	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+	 * |   Image OK    |     0xff padding (up to min-write-sz - 1)     |
+	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+	 */
+
+	tsize := 16 + // Magic.
+		128*minWriteSz*3 + // Swap status.
+		minWriteSz + // Copy done.
+		minWriteSz // Image Ok.
+
+	log.Debugf("Min-write-size=%d; boot-trailer-size=%d", minWriteSz, tsize)
+
+	return tsize
+}
+
+// Calculates the size of the largest image that can be written to each image
+// slot.
+func (t *TargetBuilder) maxImgSizes() []int {
+	sz0 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_0].Size
+	sz1 := t.bspPkg.FlashMap.Areas[flash.FLASH_AREA_NAME_IMAGE_1].Size
+	trailerSz := t.bootTrailerSize()
+
+	return []int{
+		sz0 - trailerSz,
+		sz1 - trailerSz,
+	}
+}
+
+// Verifies that each already-built image leaves enough room for a boot trailer
+// a the end of its slot.
+func (t *TargetBuilder) verifyImgSizes(li *image.Image, ai *image.Image) error {
+	maxSizes := t.maxImgSizes()
+
+	errLines := []string{}
+	if li != nil {
+		if overflow := int(li.TotalSize) - maxSizes[0]; overflow > 0 {
+			errLines = append(errLines,
+				fmt.Sprintf("loader overflows slot-0 by %d bytes "+
+					"(image=%d max=%d)",
+					overflow, li.TotalSize, maxSizes[0]))
+		}
+		if overflow := int(ai.TotalSize) - maxSizes[1]; overflow > 0 {
+			errLines = append(errLines,
+				fmt.Sprintf("app overflows slot-1 by %d bytes "+
+					"(image=%d max=%d)",
+					overflow, ai.TotalSize, maxSizes[1]))
+
+		}
+	} else {
+		if overflow := int(ai.TotalSize) - maxSizes[0]; overflow > 0 {
+			errLines = append(errLines,
+				fmt.Sprintf("app overflows slot-0 by %d bytes "+
+					"(image=%d max=%d)",
+					overflow, ai.TotalSize, maxSizes[0]))
+		}
+	}
+
+	if len(errLines) > 0 {
+		if !newtutil.NewtForce {
+			return util.NewNewtError(strings.Join(errLines, "; "))
+		} else {
+			for _, e := range errLines {
+				util.StatusMessage(util.VERBOSITY_QUIET,
+					"* Warning: %s (ignoring due to force flag)\n", e)
+			}
+		}
+	}
+
+	return nil
+}
+
 // @return                      app-image, loader-image, error
 func (t *TargetBuilder) CreateImages(version string,
 	keystr string, keyId uint8) (*image.Image, *image.Image, error) {
@@ -675,6 +784,10 @@ func (t *TargetBuilder) CreateImages(version string,
 		return nil, nil, err
 	}
 
+	if err := t.verifyImgSizes(loaderImg, appImg); err != nil {
+		return nil, nil, err
+	}
+
 	return appImg, loaderImg, nil
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/cli/image_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/image_cmds.go b/newt/cli/image_cmds.go
index 991c4c5..5a19c63 100644
--- a/newt/cli/image_cmds.go
+++ b/newt/cli/image_cmds.go
@@ -24,6 +24,7 @@ import (
 
 	"github.com/spf13/cobra"
 	"mynewt.apache.org/newt/newt/builder"
+	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/util"
 )
 
@@ -63,7 +64,7 @@ func createImageRunCmd(cmd *cobra.Command, args []string) {
 	}
 
 	if _, _, err := b.CreateImages(version, keystr, keyId); err != nil {
-		NewtUsage(cmd, err)
+		NewtUsage(nil, err)
 		return
 	}
 }
@@ -85,6 +86,10 @@ func AddImageCommands(cmd *cobra.Command) {
 		Run:     createImageRunCmd,
 	}
 
+	createImageCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
+		"Ignore flash overflow errors during image creation")
+
 	cmd.AddCommand(createImageCmd)
 	AddTabCompleteFn(createImageCmd, targetList)
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/cli/project_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/project_cmds.go b/newt/cli/project_cmds.go
index 003a42c..a8d93b2 100644
--- a/newt/cli/project_cmds.go
+++ b/newt/cli/project_cmds.go
@@ -32,9 +32,6 @@ import (
 	"mynewt.apache.org/newt/util"
 )
 
-var projectForce bool = false
-var syncForce bool = false
-
 func newRunCmd(cmd *cobra.Command, args []string) {
 	if len(args) < 1 {
 		NewtUsage(cmd, util.NewNewtError("Must specify "+
@@ -78,7 +75,7 @@ func installRunCmd(cmd *cobra.Command, args []string) {
 	proj := TryGetProject()
 	interfaces.SetProject(proj)
 
-	if err := proj.Install(false, projectForce); err != nil {
+	if err := proj.Install(false, newtutil.NewtForce); err != nil {
 		NewtUsage(cmd, err)
 	}
 }
@@ -87,7 +84,7 @@ func upgradeRunCmd(cmd *cobra.Command, args []string) {
 	proj := TryGetProject()
 	interfaces.SetProject(proj)
 
-	if err := proj.Upgrade(projectForce); err != nil {
+	if err := proj.Upgrade(newtutil.NewtForce); err != nil {
 		NewtUsage(cmd, err)
 	}
 }
@@ -170,11 +167,11 @@ func syncRunCmd(cmd *cobra.Command, args []string) {
 				"No installed version of %s found, skipping\n",
 				repo.Name())
 		}
-		if err, exists = repo.Sync(vers, syncForce); err != nil {
+		if err, exists = repo.Sync(vers, newtutil.NewtForce); err != nil {
 			NewtUsage(nil, err)
 		}
 
-		if exists && !syncForce {
+		if exists && !newtutil.NewtForce {
 			util.StatusMessage(util.VERBOSITY_DEFAULT,
 				"Skipping resync of %s because directory exists.  To "+
 					"force resync, add the -f (force) option.\n", repo.Name())
@@ -192,7 +189,8 @@ func AddProjectCommands(cmd *cobra.Command) {
 		Example: installHelpEx,
 		Run:     installRunCmd,
 	}
-	installCmd.PersistentFlags().BoolVarP(&projectForce, "force", "f", false,
+	installCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
 		"Force install of the repositories in project, regardless of what "+
 			"exists in repos directory")
 
@@ -207,7 +205,8 @@ func AddProjectCommands(cmd *cobra.Command) {
 		Example: upgradeHelpEx,
 		Run:     upgradeRunCmd,
 	}
-	upgradeCmd.PersistentFlags().BoolVarP(&projectForce, "force", "f", false,
+	upgradeCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
 		"Force upgrade of the repositories to latest state in project.yml")
 
 	cmd.AddCommand(upgradeCmd)
@@ -221,7 +220,8 @@ func AddProjectCommands(cmd *cobra.Command) {
 		Example: syncHelpEx,
 		Run:     syncRunCmd,
 	}
-	syncCmd.PersistentFlags().BoolVarP(&syncForce, "force", "f", false,
+	syncCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
 		"Force overwrite of existing remote repositories.")
 	cmd.AddCommand(syncCmd)
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/cli/run_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/run_cmds.go b/newt/cli/run_cmds.go
index 8f923bb..16620dd 100644
--- a/newt/cli/run_cmds.go
+++ b/newt/cli/run_cmds.go
@@ -23,6 +23,8 @@ import (
 	"os"
 
 	"github.com/spf13/cobra"
+
+	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/util"
 )
 
@@ -102,6 +104,9 @@ func AddRunCommands(cmd *cobra.Command) {
 		"Extra commands to send to JTAG software")
 	runCmd.PersistentFlags().BoolVarP(&noGDB_flag, "noGDB", "n", false,
 		"Do not start GDB from command line")
+	runCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
+		"Ignore flash overflow errors during image creation")
 
 	cmd.AddCommand(runCmd)
 	AddTabCompleteFn(runCmd, func() []string {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/cli/target_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/target_cmds.go b/newt/cli/target_cmds.go
index a6ea7df..786838c 100644
--- a/newt/cli/target_cmds.go
+++ b/newt/cli/target_cmds.go
@@ -31,6 +31,7 @@ import (
 	log "github.com/Sirupsen/logrus"
 	"github.com/spf13/cobra"
 	"mynewt.apache.org/newt/newt/builder"
+	"mynewt.apache.org/newt/newt/newtutil"
 	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/resolve"
 	"mynewt.apache.org/newt/newt/syscfg"
@@ -717,7 +718,8 @@ func AddTargetCommands(cmd *cobra.Command) {
 		Example: delHelpEx,
 		Run:     targetDelCmd,
 	}
-	delCmd.PersistentFlags().BoolVarP(&targetForce, "force", "f", false,
+	delCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
 		"Force delete of targets with user files without prompt")
 
 	targetCmd.AddCommand(delCmd)
@@ -768,7 +770,8 @@ func AddTargetCommands(cmd *cobra.Command) {
 			"Unspecified settings are given default values.",
 		Run: targetConfigInitCmd,
 	}
-	configInitCmd.PersistentFlags().BoolVarP(&targetForce, "force", "f", false,
+	configInitCmd.PersistentFlags().BoolVarP(&newtutil.NewtForce,
+		"force", "f", false,
 		"Force overwrite of target configuration")
 
 	configCmd.AddCommand(configInitCmd)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/image/image.go
----------------------------------------------------------------------
diff --git a/newt/image/image.go b/newt/image/image.go
index c63eb2e..3589275 100644
--- a/newt/image/image.go
+++ b/newt/image/image.go
@@ -63,6 +63,7 @@ type Image struct {
 	Hash       []byte
 	SrcSkip    uint // Number of bytes to skip from the source image.
 	HeaderSize uint // If non-zero pad out the header to this size.
+	TotalSize  uint // Total size, in bytes, of the generated .img file.
 }
 
 type ImageHdr struct {
@@ -582,6 +583,14 @@ func (image *Image) Generate(loader *Image) error {
 	util.StatusMessage(util.VERBOSITY_VERBOSE,
 		"Computed Hash for image %s as %s \n",
 		image.TargetImg, hex.EncodeToString(image.Hash))
+
+	sz, err := imgFile.Seek(0, io.SeekCurrent)
+	if err != nil {
+		return util.FmtNewtError("Failed to calculate file size of generated "+
+			"image %s: %s", image.TargetImg, err.Error())
+	}
+	image.TotalSize = uint(sz)
+
 	return nil
 }
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/249ee54f/newt/newtutil/newtutil.go
----------------------------------------------------------------------
diff --git a/newt/newtutil/newtutil.go b/newt/newtutil/newtutil.go
index c5d3957..6a981ec 100644
--- a/newt/newtutil/newtutil.go
+++ b/newt/newtutil/newtutil.go
@@ -37,6 +37,7 @@ import (
 var NewtVersionStr string = "Apache Newt (incubating) version: 1.0.0.b2"
 var NewtBlinkyTag string = "mynewt_1_0_0_b2_rc1_tag"
 var NewtNumJobs int
+var NewtForce bool
 
 const NEWTRC_DIR string = ".newt"
 const REPOS_FILENAME string = "repos.yml"


[08/41] incubator-mynewt-newt git commit: MYNEWT-623; github api server and git server are the same hostname in enterprise github servers. API calls have a different prefix.

Posted by ma...@apache.org.
MYNEWT-623; github api server and git server are the same hostname
in enterprise github servers. API calls have a different prefix.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/c06ba1f3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/c06ba1f3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/c06ba1f3

Branch: refs/heads/mynewt_1_0_0
Commit: c06ba1f3ffb3fe7f186bb7f6b1d7a8cd22ee746b
Parents: 3e4102b
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Tue Feb 14 12:34:58 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:31:51 2017 -0800

----------------------------------------------------------------------
 newt/downloader/downloader.go | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/c06ba1f3/newt/downloader/downloader.go
----------------------------------------------------------------------
diff --git a/newt/downloader/downloader.go b/newt/downloader/downloader.go
index 06557dd..0ab201e 100644
--- a/newt/downloader/downloader.go
+++ b/newt/downloader/downloader.go
@@ -118,12 +118,14 @@ func (gd *GenericDownloader) TempDir() (string, error) {
 }
 
 func (gd *GithubDownloader) FetchFile(name string, dest string) error {
-	server := "github.com"
+	server := "api.github.com"
+	prefix := "repos"
 	if gd.Server != "" {
 		server = gd.Server
+		prefix = "api/v3/repos"
 	}
-	url := fmt.Sprintf("https://api.%s/repos/%s/%s/contents/%s?ref=%s",
-		server, gd.User, gd.Repo, name, gd.Branch())
+	url := fmt.Sprintf("https://%s/%s/%s/%s/contents/%s?ref=%s",
+		server, prefix, gd.User, gd.Repo, name, gd.Branch())
 
 	req, err := http.NewRequest("GET", url, nil)
 	req.Header.Add("Accept", "application/vnd.github.v3.raw")


[17/41] incubator-mynewt-newt git commit: MYNEWT-557 Print DEBUG message when overriding undefined setting

Posted by ma...@apache.org.
MYNEWT-557 Print DEBUG message when overriding undefined setting


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/ffdbc54f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/ffdbc54f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/ffdbc54f

Branch: refs/heads/mynewt_1_0_0
Commit: ffdbc54fc8b80c2f08f9990a019e5de71c80649d
Parents: c2e1b6c
Author: cwanda <wa...@happycity.com>
Authored: Thu Feb 16 21:15:43 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:35:46 2017 -0800

----------------------------------------------------------------------
 newt/builder/targetbuild.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/ffdbc54f/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index b8ac724..f6bc2f6 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -191,7 +191,7 @@ func (t *TargetBuilder) validateAndWriteCfg() error {
 	warningText := strings.TrimSpace(t.res.WarningText())
 	if warningText != "" {
 		for _, line := range strings.Split(warningText, "\n") {
-			log.Warn(line)
+			log.Debugf(line)
 		}
 	}
 


[34/41] incubator-mynewt-newt git commit: MYNEWT-651; newt - include package size info in manifest file.

Posted by ma...@apache.org.
MYNEWT-651; newt - include package size info in manifest file.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/9691f961
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/9691f961
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/9691f961

Branch: refs/heads/mynewt_1_0_0
Commit: 9691f961cca5211dedbc44c020fcfd5ef8c9513e
Parents: 31e23b2
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Mar 2 12:59:43 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:38:29 2017 -0800

----------------------------------------------------------------------
 newt/builder/size.go        | 209 +++++++++++++++++++++++++++++++--------
 newt/builder/targetbuild.go |  10 ++
 newt/image/image.go         |  80 ++++++++++++++-
 3 files changed, 257 insertions(+), 42 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/9691f961/newt/builder/size.go
----------------------------------------------------------------------
diff --git a/newt/builder/size.go b/newt/builder/size.go
index 5ce2939..70b4dc2 100644
--- a/newt/builder/size.go
+++ b/newt/builder/size.go
@@ -28,6 +28,7 @@ import (
 	"strconv"
 	"strings"
 
+	"mynewt.apache.org/newt/newt/image"
 	"mynewt.apache.org/newt/util"
 )
 
@@ -41,6 +42,8 @@ type MemSection struct {
 }
 type MemSectionArray []*MemSection
 
+var globalMemSections map[string]*MemSection
+
 func (array MemSectionArray) Len() int {
 	return len(array)
 }
@@ -71,11 +74,23 @@ func (m *MemSection) PartOf(addr uint64) bool {
 }
 
 /*
+ * Info about specific symbol size
+ */
+type SymbolData struct {
+	Name    string
+	ObjName string            /* Which object file it came from */
+	Sizes   map[string]uint32 /* Sizes indexed by mem section name */
+}
+
+type SymbolDataArray []*SymbolData
+
+/*
  * We accumulate the size of libraries to elements in this.
  */
 type PkgSize struct {
 	Name  string
-	Sizes map[string]uint32 /* Sizes indexed by mem section name */
+	Sizes map[string]uint32      /* Sizes indexed by mem section name */
+	Syms  map[string]*SymbolData /* Symbols indexed by symbol name */
 }
 
 type PkgSizeArray []*PkgSize
@@ -92,33 +107,76 @@ func (array PkgSizeArray) Swap(i, j int) {
 	array[i], array[j] = array[j], array[i]
 }
 
-func MakePkgSize(name string, memSections map[string]*MemSection) *PkgSize {
+func (array SymbolDataArray) Len() int {
+	return len(array)
+}
+
+func (array SymbolDataArray) Less(i, j int) bool {
+	return array[i].Name < array[j].Name
+}
+
+func (array SymbolDataArray) Swap(i, j int) {
+	array[i], array[j] = array[j], array[i]
+}
+
+func MakeSymbolData(name string, objName string) *SymbolData {
+	sym := &SymbolData{
+		Name:    name,
+		ObjName: objName,
+	}
+	sym.Sizes = make(map[string]uint32)
+	for _, sec := range globalMemSections {
+		sym.Sizes[sec.Name] = 0
+	}
+	return sym
+}
+
+func MakePkgSize(name string) *PkgSize {
 	pkgSize := &PkgSize{
 		Name: name,
 	}
 	pkgSize.Sizes = make(map[string]uint32)
-	for secName, _ := range memSections {
-		pkgSize.Sizes[secName] = 0
+	for _, sec := range globalMemSections {
+		pkgSize.Sizes[sec.Name] = 0
 	}
+	pkgSize.Syms = make(map[string]*SymbolData)
 	return pkgSize
 }
 
+func (ps *PkgSize) addSymSize(symName string, objName string, size uint32, addr uint64) {
+	for _, section := range globalMemSections {
+		if section.PartOf(addr) {
+			name := section.Name
+			size32 := uint32(size)
+			if size32 > 0 {
+				sym := ps.Syms[symName]
+				if sym == nil {
+					sym = MakeSymbolData(symName, objName)
+					ps.Syms[symName] = sym
+				}
+				ps.Sizes[name] += size32
+				sym.Sizes[name] += size32
+			}
+			break
+		}
+	}
+}
+
 /*
  * Go through GCC generated mapfile, and collect info about symbol sizes
  */
-func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
-	map[string]*MemSection, error) {
+func ParseMapFileSizes(fileName string) (map[string]*PkgSize, error) {
 	var state int = 0
 
 	file, err := os.Open(fileName)
 	if err != nil {
-		return nil, nil,
-			util.NewNewtError("Mapfile failed: " + err.Error())
+		return nil, util.NewNewtError("Mapfile failed: " + err.Error())
 	}
 
-	memSections := make(map[string]*MemSection)
-	pkgSizes := make(map[string]*PkgSize)
+	var symName string = ""
 
+	globalMemSections = make(map[string]*MemSection)
+	pkgSizes := make(map[string]*PkgSize)
 	scanner := bufio.NewScanner(file)
 	for scanner.Scan() {
 		switch state {
@@ -138,13 +196,13 @@ func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
 			array := strings.Fields(scanner.Text())
 			offset, err := strconv.ParseUint(array[1], 0, 64)
 			if err != nil {
-				return nil, nil, util.NewNewtError("Can't parse mem info")
+				return nil, util.NewNewtError("Can't parse mem info")
 			}
 			size, err := strconv.ParseUint(array[2], 0, 64)
 			if err != nil {
-				return nil, nil, util.NewNewtError("Can't parse mem info")
+				return nil, util.NewNewtError("Can't parse mem info")
 			}
-			memSections[array[0]] = MakeMemSection(array[0], offset,
+			globalMemSections[array[0]] = MakeMemSection(array[0], offset,
 				size)
 		case 3:
 			if strings.Contains(scanner.Text(),
@@ -177,6 +235,7 @@ func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
 				 *
 				 * ignore these for now
 				 */
+				symName = array[0]
 				continue
 			case 2:
 				/*
@@ -214,6 +273,7 @@ func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
 					addrStr = array[1]
 					sizeStr = array[2]
 					srcFile = array[0]
+					symName = array[0]
 				} else {
 					addrStr = array[0]
 					sizeStr = array[1]
@@ -230,6 +290,7 @@ func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
 				 * crud, e.g.:
 				 * 0x8 (size before relaxing)
 				 */
+				symName = array[0]
 				addrStr = array[1]
 				sizeStr = array[2]
 				srcFile = array[3]
@@ -248,44 +309,49 @@ func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
 				continue
 			}
 			tmpStrArr := strings.Split(srcFile, "(")
-			srcLib := filepath.Base(tmpStrArr[0])
-			for name, section := range memSections {
-				if section.PartOf(addr) {
-					pkgSize := pkgSizes[srcLib]
-					if pkgSize == nil {
-						pkgSize =
-							MakePkgSize(srcLib, memSections)
-						pkgSizes[srcLib] = pkgSize
-					}
-					pkgSize.Sizes[name] += uint32(size)
-					break
+			srcLib := tmpStrArr[0]
+			objName := ""
+			if srcLib != "*fill*" {
+				tmpStrArr = strings.Split(tmpStrArr[1], ")")
+				objName = tmpStrArr[0]
+			}
+			tmpStrArr = strings.Split(symName, ".")
+			if len(tmpStrArr) > 2 {
+				if tmpStrArr[1] == "rodata" && tmpStrArr[2] == "str1" {
+					symName = ".rodata.str1"
+				} else {
+					symName = tmpStrArr[2]
 				}
 			}
+			pkgSize := pkgSizes[srcLib]
+			if pkgSize == nil {
+				pkgSize = MakePkgSize(srcLib)
+				pkgSizes[srcLib] = pkgSize
+			}
+			pkgSize.addSymSize(symName, objName, uint32(size), addr)
+			symName = ".unknown"
 		default:
 		}
 	}
 	file.Close()
-	for name, section := range memSections {
+	for name, section := range globalMemSections {
 		util.StatusMessage(util.VERBOSITY_VERBOSE, "Mem %s: 0x%x-0x%x\n",
 			name, section.Offset, section.EndOff)
 	}
 
-	return pkgSizes, memSections, nil
+	return pkgSizes, nil
 }
 
 /*
  * Return a printable string containing size data for the libraries
  */
-func PrintSizes(libs map[string]*PkgSize,
-	sectMap map[string]*MemSection) (string, error) {
-	ret := ""
-
+func PrintSizes(libs map[string]*PkgSize) error {
 	/*
 	 * Order sections by offset, and display lib sizes in that order.
 	 */
-	memSections := make(MemSectionArray, len(sectMap))
+	memSections := make(MemSectionArray, len(globalMemSections))
 	var i int = 0
-	for _, sec := range sectMap {
+	for _, sec := range globalMemSections {
 		memSections[i] = sec
 		i++
 	}
@@ -303,16 +369,17 @@ func PrintSizes(libs map[string]*PkgSize,
 	sort.Sort(pkgSizes)
 
 	for _, sec := range memSections {
-		ret += fmt.Sprintf("%7s ", sec.Name)
+		fmt.Printf("%7s ", sec.Name)
 	}
-	ret += "\n"
+	fmt.Printf("\n")
 	for _, es := range pkgSizes {
 		for i := 0; i < len(memSections); i++ {
-			ret += fmt.Sprintf("%7d ", es.Sizes[memSections[i].Name])
+			fmt.Printf("%7d ", es.Sizes[memSections[i].Name])
 		}
-		ret += fmt.Sprintf("%s\n", es.Name)
+		fmt.Printf("%s\n", filepath.Base(es.Name))
 	}
-	return ret, nil
+
+	return nil
 }
 
 func (t *TargetBuilder) Size() error {
@@ -336,6 +403,67 @@ func (t *TargetBuilder) Size() error {
 	return err
 }
 
+func (b *Builder) FindPkgNameByArName(arName string) string {
+	for rpkg, bpkg := range b.PkgMap {
+		if (b.ArchivePath(bpkg) == arName) {
+			return rpkg.Lpkg.FullName()
+		}
+	}
+	return filepath.Base(arName)
+}
+
+func (b *Builder) PkgSizes() (*image.ImageManifestSizeCollector, error) {
+	if b.appPkg == nil {
+		return nil, util.NewNewtError("app package not specified for this target")
+	}
+
+	if b.targetBuilder.bspPkg.Arch == "sim" {
+		return nil, util.NewNewtError("'newt size' not supported for sim targets")
+	}
+	mapFile := b.AppElfPath() + ".map"
+
+	libs, err := ParseMapFileSizes(mapFile)
+	if err != nil {
+		return nil, err
+	}
+
+	/*
+	 * Order libraries by name.
+	 */
+	pkgSizes := make(PkgSizeArray, len(libs))
+	i := 0
+	for _, es := range libs {
+		pkgSizes[i] = es
+		i++
+	}
+	sort.Sort(pkgSizes)
+
+	c := image.NewImageManifestSizeCollector()
+	for _, es := range pkgSizes {
+		p := c.AddPkg(b.FindPkgNameByArName(es.Name))
+
+		/*
+		 * Order symbols by name.
+		 */
+		symbols := make(SymbolDataArray, len(es.Syms))
+		i := 0
+		for _, sym := range es.Syms {
+			symbols[i] = sym
+			i++
+		}
+		sort.Sort(symbols)
+		for _, sym := range symbols {
+			for area, areaSz := range sym.Sizes {
+				if areaSz != 0 {
+					p.AddSymbol(sym.ObjName, sym.Name, area, areaSz)
+				}
+			}
+		}
+	}
+
+	return c, nil
+}
+
 func (b *Builder) Size() error {
 	if b.appPkg == nil {
 		return util.NewNewtError("app package not specified for this target")
@@ -351,15 +479,14 @@ func (b *Builder) Size() error {
 	}
 	mapFile := b.AppElfPath() + ".map"
 
-	pkgSizes, memSections, err := ParseMapFileSizes(mapFile)
+	pkgSizes, err := ParseMapFileSizes(mapFile)
 	if err != nil {
 		return err
 	}
-	output, err := PrintSizes(pkgSizes, memSections)
+	err = PrintSizes(pkgSizes)
 	if err != nil {
 		return err
 	}
-	fmt.Printf("%s", output)
 
 	c, err := b.newCompiler(b.appPkg, b.FileBinDir(b.AppElfPath()))
 	if err != nil {
@@ -367,7 +494,7 @@ func (b *Builder) Size() error {
 	}
 
 	fmt.Printf("\nobjsize\n")
-	output, err = c.PrintSize(b.AppElfPath())
+	output, err := c.PrintSize(b.AppElfPath())
 	if err != nil {
 		return err
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/9691f961/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index c522597..9c5dc1e 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -579,6 +579,16 @@ func (t *TargetBuilder) createManifest() error {
 		manifest.TgtVars = append(manifest.TgtVars, tgtSyscfg)
 	}
 
+	c, err := t.AppBuilder.PkgSizes()
+	if err == nil {
+		manifest.PkgSizes = c.Pkgs
+	}
+	if t.LoaderBuilder != nil {
+		c, err = t.LoaderBuilder.PkgSizes()
+		if err == nil {
+			manifest.LoaderPkgSizes = c.Pkgs
+		}
+	}
 	file, err := os.Create(t.AppBuilder.ManifestPath())
 	if err != nil {
 		return util.FmtNewtError("Cannot create manifest file %s: %s",

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/9691f961/newt/image/image.go
----------------------------------------------------------------------
diff --git a/newt/image/image.go b/newt/image/image.go
index 3589275..38715e3 100644
--- a/newt/image/image.go
+++ b/newt/image/image.go
@@ -118,6 +118,30 @@ const (
 /*
  * Data that's going to go to build manifest file
  */
+type ImageManifestSizeArea struct {
+	Name string
+	Size uint32
+}
+
+type ImageManifestSizeSym struct {
+	Name  string                   `json:"name"`
+	Areas []*ImageManifestSizeArea `json:"areas"`
+}
+
+type ImageManifestSizeFile struct {
+	Name string                  `json:"name"`
+	Syms []*ImageManifestSizeSym `json:"sym"`
+}
+
+type ImageManifestSizePkg struct {
+	Name  string                   `json:"name"`
+	Files []*ImageManifestSizeFile `json:"files"`
+}
+
+type ImageManifestSizeCollector struct {
+	Pkgs []*ImageManifestSizePkg
+}
+
 type ImageManifest struct {
 	Name       string              `json:"name"`
 	Date       string              `json:"build_time"`
@@ -128,9 +152,12 @@ type ImageManifest struct {
 	Loader     string              `json:"loader"`
 	LoaderHash string              `json:"loader_hash"`
 	Pkgs       []*ImageManifestPkg `json:"pkgs"`
-	LoaderPkgs []*ImageManifestPkg `json:"loader_pkgs"`
+	LoaderPkgs []*ImageManifestPkg `json:"loader_pkgs,omitempty"`
 	TgtVars    []string            `json:"target"`
 	Repos      []ImageManifestRepo `json:"repos"`
+
+	PkgSizes       []*ImageManifestSizePkg `json:"pkgsz"`
+	LoaderPkgSizes []*ImageManifestSizePkg `json:"loader_pkgsz,omitempty"`
 }
 
 type ImageManifestPkg struct {
@@ -697,3 +724,54 @@ func (r *RepoManager) AllRepos() []ImageManifestRepo {
 
 	return repos
 }
+
+func NewImageManifestSizeCollector() *ImageManifestSizeCollector {
+	return &ImageManifestSizeCollector{}
+}
+
+func (c *ImageManifestSizeCollector) AddPkg(pkg string) *ImageManifestSizePkg {
+	p := &ImageManifestSizePkg {
+		Name: pkg,
+	}
+	c.Pkgs = append(c.Pkgs, p)
+
+	return p
+}
+
+func (c *ImageManifestSizePkg) AddSymbol(file string, sym string, area string,
+					symSz uint32) {
+	f := c.addFile(file)
+	s := f.addSym(sym)
+	s.addArea(area, symSz)
+}
+
+func (p *ImageManifestSizePkg) addFile(file string) *ImageManifestSizeFile {
+	for _, f := range p.Files {
+		if f.Name == file {
+			return f
+		}
+	}
+	f := &ImageManifestSizeFile {
+		Name: file,
+	}
+	p.Files = append(p.Files, f)
+
+	return f
+}
+
+func (f *ImageManifestSizeFile) addSym(sym string) *ImageManifestSizeSym {
+	s := &ImageManifestSizeSym {
+		Name: sym,
+	}
+	f.Syms = append(f.Syms, s)
+
+	return s
+}
+
+func (s *ImageManifestSizeSym) addArea(area string, areaSz uint32) {
+	a := &ImageManifestSizeArea {
+		Name: area,
+		Size: areaSz,
+	}
+	s.Areas = append(s.Areas, a)
+}


[39/41] incubator-mynewt-newt git commit: There are two issues here:

Posted by ma...@apache.org.
There are two issues here:

1. newtmgr tool always includes an extraneous rc:0 key-value pair in its
   outgoing datetime commands.
2. Server-side, the firmware parses the "rc" value and writes the result
   to null.

This commit addresses the first issue: Remove the rc entry from the
datetime request.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/42047768
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/42047768
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/42047768

Branch: refs/heads/mynewt_1_0_0
Commit: 4204776896b09737d2ffbe9199aef9d99088521c
Parents: 0c35824
Author: Christopher Collins <cc...@apache.org>
Authored: Sat Mar 4 14:27:45 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:39:29 2017 -0800

----------------------------------------------------------------------
 newtmgr/protocol/datetime.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/42047768/newtmgr/protocol/datetime.go
----------------------------------------------------------------------
diff --git a/newtmgr/protocol/datetime.go b/newtmgr/protocol/datetime.go
index 451b84a..3f213f6 100644
--- a/newtmgr/protocol/datetime.go
+++ b/newtmgr/protocol/datetime.go
@@ -28,7 +28,7 @@ import (
 
 type DateTime struct {
 	DateTime string `codec:"datetime"`
-	Return   uint64 `codec:"rc"`
+	Return   uint64 `codec:"rc,omitempty"`
 }
 
 func NewDateTime() (*DateTime, error) {


[21/41] incubator-mynewt-newt git commit: MYNEWT-527; allow build machine OS dependent overrides in bsp.yml.

Posted by ma...@apache.org.
MYNEWT-527; allow build machine OS dependent overrides in bsp.yml.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/188d8b60
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/188d8b60
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/188d8b60

Branch: refs/heads/mynewt_1_0_0
Commit: 188d8b6096cd301732176206a1369b2d72c1e7ec
Parents: 65aab9c
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Feb 27 21:02:51 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:36:31 2017 -0800

----------------------------------------------------------------------
 newt/pkg/bsp_package.go | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/188d8b60/newt/pkg/bsp_package.go
----------------------------------------------------------------------
diff --git a/newt/pkg/bsp_package.go b/newt/pkg/bsp_package.go
index 572255c..146347f 100644
--- a/newt/pkg/bsp_package.go
+++ b/newt/pkg/bsp_package.go
@@ -20,6 +20,7 @@
 package pkg
 
 import (
+	"runtime"
 	"strings"
 
 	"mynewt.apache.org/newt/newt/flash"
@@ -101,6 +102,13 @@ func (bsp *BspPackage) resolveLinkerScriptSetting(
 func (bsp *BspPackage) Reload(features map[string]bool) error {
 	var err error
 
+	if features == nil {
+		features = map[string]bool{
+			strings.ToUpper(runtime.GOOS): true,
+		}
+	} else {
+		features[strings.ToUpper(runtime.GOOS)] = true
+	}
 	bsp.BspV, err = util.ReadConfig(bsp.BasePath(),
 		strings.TrimSuffix(BSP_YAML_FILENAME, ".yml"))
 	if err != nil {
@@ -131,7 +139,6 @@ func (bsp *BspPackage) Reload(features map[string]bool) error {
 	if err != nil {
 		return err
 	}
-
 	bsp.DebugScript, err = bsp.resolvePathSetting(
 		features, "bsp.debugscript")
 	if err != nil {


[26/41] incubator-mynewt-newt git commit: MYNEWT-653 Change Golang imports to runtimeco

Posted by ma...@apache.org.
MYNEWT-653 Change Golang imports to runtimeco


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/351d90a7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/351d90a7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/351d90a7

Branch: refs/heads/mynewt_1_0_0
Commit: 351d90a7dd7cb2df7ba5418a9c51e25ec058af47
Parents: 249ee54
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Mar 2 19:12:22 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:37:57 2017 -0800

----------------------------------------------------------------------
 newtmgr/transport/connble.go        | 10 +++++-----
 newtmgr/transport/connble_darwin.go |  2 +-
 newtmgr/transport/connble_linux.go  |  2 +-
 3 files changed, 7 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/351d90a7/newtmgr/transport/connble.go
----------------------------------------------------------------------
diff --git a/newtmgr/transport/connble.go b/newtmgr/transport/connble.go
index e8bcb66..f19b0b8 100644
--- a/newtmgr/transport/connble.go
+++ b/newtmgr/transport/connble.go
@@ -22,7 +22,7 @@ import (
 	log "github.com/Sirupsen/logrus"
 	"time"
 
-	"github.com/runtimeinc/gatt"
+	"github.com/runtimeco/gatt"
 
 	"mynewt.apache.org/newt/newtmgr/config"
 	"mynewt.apache.org/newt/util"
@@ -119,7 +119,7 @@ func onPeriphConnected(p gatt.Peripheral, err error) {
 	for _, service := range services {
 
 		if service.UUID().Equal(newtmgrServiceId) ||
-		   service.UUID().Equal(newtmgrCoapServiceId) {
+			service.UUID().Equal(newtmgrCoapServiceId) {
 			log.Debugf("Newtmgr Service Found %s", service.Name())
 
 			if service.UUID().Equal(newtmgrCoapServiceId) {
@@ -130,9 +130,9 @@ func onPeriphConnected(p gatt.Peripheral, err error) {
 
 			for _, c := range cs {
 				if (isCoap == false &&
-				    c.UUID().Equal(newtmgrServiceCharId)) ||
-				   (isCoap == true &&
-				    c.UUID().Equal(newtmgrCoapServiceCharId)) {
+					c.UUID().Equal(newtmgrServiceCharId)) ||
+					(isCoap == true &&
+						c.UUID().Equal(newtmgrCoapServiceCharId)) {
 					log.Debugf("Newtmgr Characteristic Found")
 					p.SetNotifyValue(c, newtmgrNotifyCB)
 					deviceChar = c

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/351d90a7/newtmgr/transport/connble_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/transport/connble_darwin.go b/newtmgr/transport/connble_darwin.go
index 8708cb7..ebbdadd 100644
--- a/newtmgr/transport/connble_darwin.go
+++ b/newtmgr/transport/connble_darwin.go
@@ -18,6 +18,6 @@
  */
 package transport
 
-import "github.com/runtimeinc/gatt"
+import "github.com/runtimeco/gatt"
 
 var BleOptions = []gatt.Option{}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/351d90a7/newtmgr/transport/connble_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/transport/connble_linux.go b/newtmgr/transport/connble_linux.go
index 4074a5b..2c241f0 100644
--- a/newtmgr/transport/connble_linux.go
+++ b/newtmgr/transport/connble_linux.go
@@ -18,7 +18,7 @@
  */
 package transport
 
-import "github.com/runtimeinc/gatt"
+import "github.com/runtimeco/gatt"
 
 var BleOptions = []gatt.Option{
 	gatt.LnxMaxConnections(1),


[06/41] incubator-mynewt-newt git commit: MYNEWT-621; check that package exists before referencing it.

Posted by ma...@apache.org.
MYNEWT-621; check that package exists before referencing it.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/df3061f6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/df3061f6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/df3061f6

Branch: refs/heads/mynewt_1_0_0
Commit: df3061f6cdb7fd75e49652fd7d7ec342e721fbde
Parents: 3868c59
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Sat Feb 11 12:24:26 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:30:29 2017 -0800

----------------------------------------------------------------------
 newt/resolve/resolve.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/df3061f6/newt/resolve/resolve.go
----------------------------------------------------------------------
diff --git a/newt/resolve/resolve.go b/newt/resolve/resolve.go
index 8a675c0..283e96c 100644
--- a/newt/resolve/resolve.go
+++ b/newt/resolve/resolve.go
@@ -134,11 +134,11 @@ func NewResolvePkg(lpkg *pkg.LocalPackage) *ResolvePackage {
 func (r *Resolver) resolveDep(dep *pkg.Dependency) (*pkg.LocalPackage, error) {
 	proj := project.GetProject()
 
-	lpkg := proj.ResolveDependency(dep).(*pkg.LocalPackage)
-	if lpkg == nil {
+	if proj.ResolveDependency(dep) == nil {
 		return nil, util.FmtNewtError("Could not resolve package dependency: "+
 			"%s; depender: %s", dep.String(), dep.Name)
 	}
+	lpkg := proj.ResolveDependency(dep).(*pkg.LocalPackage)
 
 	return lpkg, nil
 }


[09/41] incubator-mynewt-newt git commit: Add newt pkg move command to move packages within a repository

Posted by ma...@apache.org.
Add newt pkg move command to move packages within a repository


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/d419f2a3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/d419f2a3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/d419f2a3

Branch: refs/heads/mynewt_1_0_0
Commit: d419f2a3cf069f7c3b5738cccf223ceb705084c7
Parents: c06ba1f
Author: Sterling Hughes <st...@runtime.io>
Authored: Sat Feb 11 15:25:05 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:04 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go                            | 116 +++++++++++++++++++
 newt/vendor/mynewt.apache.org/newt/util/util.go |  12 ++
 util/util.go                                    |  12 ++
 3 files changed, 140 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/d419f2a3/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 0972957..0b05f05 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -20,10 +20,16 @@
 package cli
 
 import (
+	"os"
+	"path"
 	"strings"
 
 	"github.com/spf13/cobra"
+	"mynewt.apache.org/newt/newt/interfaces"
+	"mynewt.apache.org/newt/newt/newtutil"
+	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
+	"mynewt.apache.org/newt/util"
 )
 
 var NewTypeStr = "pkg"
@@ -40,6 +46,103 @@ func pkgNewCmd(cmd *cobra.Command, args []string) {
 	}
 }
 
+func pkgMoveCmd(cmd *cobra.Command, args []string) {
+	if len(args) != 2 {
+		NewtUsage(cmd, util.NewNewtError("Exactly two arguments required to pkg move"))
+	}
+
+	srcLoc := args[0]
+	dstLoc := args[1]
+
+	proj := TryGetProject()
+	interfaces.SetProject(proj)
+
+	wd, err := os.Getwd()
+	if err != nil {
+		NewtUsage(cmd, util.NewNewtError(err.Error()))
+	}
+
+	if err := os.Chdir(proj.Path() + "/"); err != nil {
+		NewtUsage(cmd, util.NewNewtError(err.Error()))
+	}
+
+	/* Find source package, defaulting search to the local project if no
+	 * repository descriptor is found.
+	 */
+	srcRepoName, srcName, err := newtutil.ParsePackageString(srcLoc)
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	srcRepo := proj.LocalRepo()
+	if srcRepoName != "" {
+		srcRepo = proj.FindRepo(srcRepoName)
+	}
+
+	srcPkg, err := proj.ResolvePackage(srcRepo, srcName)
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	/* Resolve the destination package to a physical location, and then
+	 * move the source package to that location.
+	 * dstLoc is assumed to be in the format "@repo/pkg/loc"
+	 */
+	repoName, pkgName, err := newtutil.ParsePackageString(dstLoc)
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	dstPath := proj.Path() + "/"
+	repo := proj.LocalRepo()
+	if repoName != "" {
+		dstPath += "repos/" + repoName + "/"
+		repo = proj.FindRepo(repoName)
+		if repo == nil {
+			os.Chdir(wd)
+			NewtUsage(cmd, util.NewNewtError("Destination repo "+
+				repoName+" does not exist"))
+		}
+	}
+	dstPath += pkgName + "/"
+
+	if util.NodeExist(dstPath) {
+		os.Chdir(wd)
+		NewtUsage(cmd, util.NewNewtError("Cannot overwrite existing package, "+
+			"use pkg delete first"))
+	}
+
+	util.StatusMessage(util.VERBOSITY_DEFAULT, "Moving package %s to %s\n",
+		srcLoc, dstLoc)
+
+	if err := util.MoveDir(srcPkg.BasePath(), dstPath); err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	dstPkg, err := pkg.LoadLocalPackage(repo, pkgName)
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	dstPkg.SetName(pkgName)
+	dstPkg.Save()
+
+	/* If the last element of the package path changes, rename the include
+	 * directory.
+	 */
+	if path.Base(pkgName) != path.Base(srcPkg.Name()) {
+		util.MoveDir(dstPath+"/include/"+path.Base(srcPkg.Name()),
+			dstPath+"/include/"+path.Base(pkgName))
+	}
+
+	os.Chdir(wd)
+}
+
 func AddPackageCommands(cmd *cobra.Command) {
 	/* Add the base package command, on top of which other commands are
 	 * keyed
@@ -75,4 +178,17 @@ func AddPackageCommands(cmd *cobra.Command) {
 		"pkg", "Type of package to create: pkg, bsp, sdk.  Default pkg.")
 
 	pkgCmd.AddCommand(newCmd)
+
+	moveCmdHelpText := ""
+	moveCmdHelpEx := ""
+
+	moveCmd := &cobra.Command{
+		Use:     "move",
+		Short:   "Move a package from one location to another",
+		Long:    moveCmdHelpText,
+		Example: moveCmdHelpEx,
+		Run:     pkgMoveCmd,
+	}
+
+	pkgCmd.AddCommand(moveCmd)
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/d419f2a3/newt/vendor/mynewt.apache.org/newt/util/util.go
----------------------------------------------------------------------
diff --git a/newt/vendor/mynewt.apache.org/newt/util/util.go b/newt/vendor/mynewt.apache.org/newt/util/util.go
index bc7848b..fa3e60f 100644
--- a/newt/vendor/mynewt.apache.org/newt/util/util.go
+++ b/newt/vendor/mynewt.apache.org/newt/util/util.go
@@ -458,6 +458,18 @@ func MoveFile(srcFile string, destFile string) error {
 	return nil
 }
 
+func MoveDir(srcDir string, destDir string) error {
+	if err := CopyDir(srcDir, destDir); err != nil {
+		return err
+	}
+
+	if err := os.RemoveAll(srcDir); err != nil {
+		return err
+	}
+
+	return nil
+}
+
 // Reads each line from the specified text file into an array of strings.  If a
 // line ends with a backslash, it is concatenated with the following line.
 func ReadLines(path string) ([]string, error) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/d419f2a3/util/util.go
----------------------------------------------------------------------
diff --git a/util/util.go b/util/util.go
index bc7848b..fa3e60f 100644
--- a/util/util.go
+++ b/util/util.go
@@ -458,6 +458,18 @@ func MoveFile(srcFile string, destFile string) error {
 	return nil
 }
 
+func MoveDir(srcDir string, destDir string) error {
+	if err := CopyDir(srcDir, destDir); err != nil {
+		return err
+	}
+
+	if err := os.RemoveAll(srcDir); err != nil {
+		return err
+	}
+
+	return nil
+}
+
 // Reads each line from the specified text file into an array of strings.  If a
 // line ends with a backslash, it is concatenated with the following line.
 func ReadLines(path string) ([]string, error) {


[31/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/doc.go b/newtmgr/vendor/github.com/runtimeco/gatt/doc.go
new file mode 100644
index 0000000..c34a3e9
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/doc.go
@@ -0,0 +1,88 @@
+// Package gatt provides a Bluetooth Low Energy gatt implementation.
+//
+// Gatt (Generic Attribute Profile) is the protocol used to write
+// BLE peripherals (servers) and centrals (clients).
+//
+// STATUS
+//
+// This package is a work in progress. The API will change.
+//
+// As a peripheral, you can create services, characteristics, and descriptors,
+// advertise, accept connections, and handle requests.
+// As a central, you can scan, connect, discover services, and make requests.
+//
+// SETUP
+//
+// gatt supports both Linux and OS X.
+//
+// On Linux:
+// To gain complete and exclusive control of the HCI device, gatt uses
+// HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
+// Those who must use an older kernel may patch in these relevant commits
+// from Marcel Holtmann:
+//
+//     Bluetooth: Introduce new HCI socket channel for user operation
+//     Bluetooth: Introduce user channel flag for HCI devices
+//     Bluetooth: Refactor raw socket filter into more readable code
+//
+// Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
+// device no other program may access it.
+//
+// Before starting a gatt program, make sure that your BLE device is down:
+//
+//     sudo hciconfig
+//     sudo hciconfig hci0 down  # or whatever hci device you want to use
+//
+// If you have BlueZ 5.14+ (or aren't sure), stop the built-in
+// bluetooth server, which interferes with gatt, e.g.:
+//
+//     sudo service bluetooth stop
+//
+// Because gatt programs administer network devices, they must
+// either be run as root, or be granted appropriate capabilities:
+//
+//     sudo <executable>
+//     # OR
+//     sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
+//     <executable>
+//
+// USAGE
+//
+//     # Start a simple server.
+//     sudo go run example/server.go
+//
+//     # Discover surrounding peripherals.
+//     sudo go run example/discoverer.go
+//
+//     # Connect to and explorer a peripheral device.
+//     sudo go run example/explorer.go <peripheral ID>
+//
+// See the server.go, discoverer.go, and explorer.go in the examples/
+// directory for writing server or client programs that run on Linux
+// and OS X.
+//
+// Users, especially on Linux platforms, seeking finer-grained control
+// over the devices can see the examples/server_lnx.go for the usage
+// of Option, which are platform specific.
+//
+// See the rest of the docs for other options and finer-grained control.
+//
+// Note that some BLE central devices, particularly iOS, may aggressively
+// cache results from previous connections. If you change your services or
+// characteristics, you may need to reboot the other device to pick up the
+// changes. This is a common source of confusion and apparent bugs. For an
+// OS X central, see http://stackoverflow.com/questions/20553957.
+//
+//
+// REFERENCES
+//
+// gatt started life as a port of bleno, to which it is indebted:
+// https://github.com/sandeepmistry/bleno. If you are having
+// problems with gatt, particularly around installation, issues
+// filed with bleno might also be helpful references.
+//
+// To try out your GATT server, it is useful to experiment with a
+// generic BLE client. LightBlue is a good choice. It is available
+// free for both iOS and OS X.
+//
+package gatt

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/known_uuid.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/known_uuid.go b/newtmgr/vendor/github.com/runtimeco/gatt/known_uuid.go
new file mode 100644
index 0000000..2146af5
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/known_uuid.go
@@ -0,0 +1,122 @@
+package gatt
+
+// A dictionary of known service names and type (keyed by service uuid)
+var knownServices = map[string]struct{ Name, Type string }{
+	"1800": {Name: "Generic Access", Type: "org.bluetooth.service.generic_access"},
+	"1801": {Name: "Generic Attribute", Type: "org.bluetooth.service.generic_attribute"},
+	"1802": {Name: "Immediate Alert", Type: "org.bluetooth.service.immediate_alert"},
+	"1803": {Name: "Link Loss", Type: "org.bluetooth.service.link_loss"},
+	"1804": {Name: "Tx Power", Type: "org.bluetooth.service.tx_power"},
+	"1805": {Name: "Current Time Service", Type: "org.bluetooth.service.current_time"},
+	"1806": {Name: "Reference Time Update Service", Type: "org.bluetooth.service.reference_time_update"},
+	"1807": {Name: "Next DST Change Service", Type: "org.bluetooth.service.next_dst_change"},
+	"1808": {Name: "Glucose", Type: "org.bluetooth.service.glucose"},
+	"1809": {Name: "Health Thermometer", Type: "org.bluetooth.service.health_thermometer"},
+	"180a": {Name: "Device Information", Type: "org.bluetooth.service.device_information"},
+	"180d": {Name: "Heart Rate", Type: "org.bluetooth.service.heart_rate"},
+	"180e": {Name: "Phone Alert Status Service", Type: "org.bluetooth.service.phone_alert_service"},
+	"180f": {Name: "Battery Service", Type: "org.bluetooth.service.battery_service"},
+	"1810": {Name: "Blood Pressure", Type: "org.bluetooth.service.blood_pressuer"},
+	"1811": {Name: "Alert Notification Service", Type: "org.bluetooth.service.alert_notification"},
+	"1812": {Name: "Human Interface Device", Type: "org.bluetooth.service.human_interface_device"},
+	"1813": {Name: "Scan Parameters", Type: "org.bluetooth.service.scan_parameters"},
+	"1814": {Name: "Running Speed and Cadence", Type: "org.bluetooth.service.running_speed_and_cadence"},
+	"1815": {Name: "Cycling Speed and Cadence", Type: "org.bluetooth.service.cycling_speed_and_cadence"},
+}
+
+// A dictionary of known descriptor names and type (keyed by attribute uuid)
+var knownAttributes = map[string]struct{ Name, Type string }{
+	"2800": {Name: "Primary Service", Type: "org.bluetooth.attribute.gatt.primary_service_declaration"},
+	"2801": {Name: "Secondary Service", Type: "org.bluetooth.attribute.gatt.secondary_service_declaration"},
+	"2802": {Name: "Include", Type: "org.bluetooth.attribute.gatt.include_declaration"},
+	"2803": {Name: "Characteristic", Type: "org.bluetooth.attribute.gatt.characteristic_declaration"},
+}
+
+// A dictionary of known descriptor names and type (keyed by descriptor uuid)
+var knownDescriptors = map[string]struct{ Name, Type string }{
+	"2900": {Name: "Characteristic Extended Properties", Type: "org.bluetooth.descriptor.gatt.characteristic_extended_properties"},
+	"2901": {Name: "Characteristic User Description", Type: "org.bluetooth.descriptor.gatt.characteristic_user_description"},
+	"2902": {Name: "Client Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.client_characteristic_configuration"},
+	"2903": {Name: "Server Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.server_characteristic_configuration"},
+	"2904": {Name: "Characteristic Presentation Format", Type: "org.bluetooth.descriptor.gatt.characteristic_presentation_format"},
+	"2905": {Name: "Characteristic Aggregate Format", Type: "org.bluetooth.descriptor.gatt.characteristic_aggregate_format"},
+	"2906": {Name: "Valid Range", Type: "org.bluetooth.descriptor.valid_range"},
+	"2907": {Name: "External Report Reference", Type: "org.bluetooth.descriptor.external_report_reference"},
+	"2908": {Name: "Report Reference", Type: "org.bluetooth.descriptor.report_reference"},
+}
+
+// A dictionary of known characteristic names and type (keyed by characteristic uuid)
+var knownCharacteristics = map[string]struct{ Name, Type string }{
+	"2a00": {Name: "Device Name", Type: "org.bluetooth.characteristic.gap.device_name"},
+	"2a01": {Name: "Appearance", Type: "org.bluetooth.characteristic.gap.appearance"},
+	"2a02": {Name: "Peripheral Privacy Flag", Type: "org.bluetooth.characteristic.gap.peripheral_privacy_flag"},
+	"2a03": {Name: "Reconnection Address", Type: "org.bluetooth.characteristic.gap.reconnection_address"},
+	"2a04": {Name: "Peripheral Preferred Connection Parameters", Type: "org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters"},
+	"2a05": {Name: "Service Changed", Type: "org.bluetooth.characteristic.gatt.service_changed"},
+	"2a06": {Name: "Alert Level", Type: "org.bluetooth.characteristic.alert_level"},
+	"2a07": {Name: "Tx Power Level", Type: "org.bluetooth.characteristic.tx_power_level"},
+	"2a08": {Name: "Date Time", Type: "org.bluetooth.characteristic.date_time"},
+	"2a09": {Name: "Day of Week", Type: "org.bluetooth.characteristic.day_of_week"},
+	"2a0a": {Name: "Day Date Time", Type: "org.bluetooth.characteristic.day_date_time"},
+	"2a0c": {Name: "Exact Time 256", Type: "org.bluetooth.characteristic.exact_time_256"},
+	"2a0d": {Name: "DST Offset", Type: "org.bluetooth.characteristic.dst_offset"},
+	"2a0e": {Name: "Time Zone", Type: "org.bluetooth.characteristic.time_zone"},
+	"2a0f": {Name: "Local Time Information", Type: "org.bluetooth.characteristic.local_time_information"},
+	"2a11": {Name: "Time with DST", Type: "org.bluetooth.characteristic.time_with_dst"},
+	"2a12": {Name: "Time Accuracy", Type: "org.bluetooth.characteristic.time_accuracy"},
+	"2a13": {Name: "Time Source", Type: "org.bluetooth.characteristic.time_source"},
+	"2a14": {Name: "Reference Time Information", Type: "org.bluetooth.characteristic.reference_time_information"},
+	"2a16": {Name: "Time Update Control Point", Type: "org.bluetooth.characteristic.time_update_control_point"},
+	"2a17": {Name: "Time Update State", Type: "org.bluetooth.characteristic.time_update_state"},
+	"2a18": {Name: "Glucose Measurement", Type: "org.bluetooth.characteristic.glucose_measurement"},
+	"2a19": {Name: "Battery Level", Type: "org.bluetooth.characteristic.battery_level"},
+	"2a1c": {Name: "Temperature Measurement", Type: "org.bluetooth.characteristic.temperature_measurement"},
+	"2a1d": {Name: "Temperature Type", Type: "org.bluetooth.characteristic.temperature_type"},
+	"2a1e": {Name: "Intermediate Temperature", Type: "org.bluetooth.characteristic.intermediate_temperature"},
+	"2a21": {Name: "Measurement Interval", Type: "org.bluetooth.characteristic.measurement_interval"},
+	"2a22": {Name: "Boot Keyboard Input Report", Type: "org.bluetooth.characteristic.boot_keyboard_input_report"},
+	"2a23": {Name: "System ID", Type: "org.bluetooth.characteristic.system_id"},
+	"2a24": {Name: "Model Number String", Type: "org.bluetooth.characteristic.model_number_string"},
+	"2a25": {Name: "Serial Number String", Type: "org.bluetooth.characteristic.serial_number_string"},
+	"2a26": {Name: "Firmware Revision String", Type: "org.bluetooth.characteristic.firmware_revision_string"},
+	"2a27": {Name: "Hardware Revision String", Type: "org.bluetooth.characteristic.hardware_revision_string"},
+	"2a28": {Name: "Software Revision String", Type: "org.bluetooth.characteristic.software_revision_string"},
+	"2a29": {Name: "Manufacturer Name String", Type: "org.bluetooth.characteristic.manufacturer_name_string"},
+	"2a2a": {Name: "IEEE 11073-20601 Regulatory Certification Data List", Type: "org.bluetooth.characteristic.ieee_11073-20601_regulatory_certification_data_list"},
+	"2a2b": {Name: "Current Time", Type: "org.bluetooth.characteristic.current_time"},
+	"2a31": {Name: "Scan Refresh", Type: "org.bluetooth.characteristic.scan_refresh"},
+	"2a32": {Name: "Boot Keyboard Output Report", Type: "org.bluetooth.characteristic.boot_keyboard_output_report"},
+	"2a33": {Name: "Boot Mouse Input Report", Type: "org.bluetooth.characteristic.boot_mouse_input_report"},
+	"2a34": {Name: "Glucose Measurement Context", Type: "org.bluetooth.characteristic.glucose_measurement_context"},
+	"2a35": {Name: "Blood Pressure Measurement", Type: "org.bluetooth.characteristic.blood_pressure_measurement"},
+	"2a36": {Name: "Intermediate Cuff Pressure", Type: "org.bluetooth.characteristic.intermediate_blood_pressure"},
+	"2a37": {Name: "Heart Rate Measurement", Type: "org.bluetooth.characteristic.heart_rate_measurement"},
+	"2a38": {Name: "Body Sensor Location", Type: "org.bluetooth.characteristic.body_sensor_location"},
+	"2a39": {Name: "Heart Rate Control Point", Type: "org.bluetooth.characteristic.heart_rate_control_point"},
+	"2a3f": {Name: "Alert Status", Type: "org.bluetooth.characteristic.alert_status"},
+	"2a40": {Name: "Ringer Control Point", Type: "org.bluetooth.characteristic.ringer_control_point"},
+	"2a41": {Name: "Ringer Setting", Type: "org.bluetooth.characteristic.ringer_setting"},
+	"2a42": {Name: "Alert Category ID Bit Mask", Type: "org.bluetooth.characteristic.alert_category_id_bit_mask"},
+	"2a43": {Name: "Alert Category ID", Type: "org.bluetooth.characteristic.alert_category_id"},
+	"2a44": {Name: "Alert Notification Control Point", Type: "org.bluetooth.characteristic.alert_notification_control_point"},
+	"2a45": {Name: "Unread Alert Status", Type: "org.bluetooth.characteristic.unread_alert_status"},
+	"2a46": {Name: "New Alert", Type: "org.bluetooth.characteristic.new_alert"},
+	"2a47": {Name: "Supported New Alert Category", Type: "org.bluetooth.characteristic.supported_new_alert_category"},
+	"2a48": {Name: "Supported Unread Alert Category", Type: "org.bluetooth.characteristic.supported_unread_alert_category"},
+	"2a49": {Name: "Blood Pressure Feature", Type: "org.bluetooth.characteristic.blood_pressure_feature"},
+	"2a4a": {Name: "HID Information", Type: "org.bluetooth.characteristic.hid_information"},
+	"2a4b": {Name: "Report Map", Type: "org.bluetooth.characteristic.report_map"},
+	"2a4c": {Name: "HID Control Point", Type: "org.bluetooth.characteristic.hid_control_point"},
+	"2a4d": {Name: "Report", Type: "org.bluetooth.characteristic.report"},
+	"2a4e": {Name: "Protocol Mode", Type: "org.bluetooth.characteristic.protocol_mode"},
+	"2a4f": {Name: "Scan Interval Window", Type: "org.bluetooth.characteristic.scan_interval_window"},
+	"2a50": {Name: "PnP ID", Type: "org.bluetooth.characteristic.pnp_id"},
+	"2a51": {Name: "Glucose Feature", Type: "org.bluetooth.characteristic.glucose_feature"},
+	"2a52": {Name: "Record Access Control Point", Type: "org.bluetooth.characteristic.record_access_control_point"},
+	"2a53": {Name: "RSC Measurement", Type: "org.bluetooth.characteristic.rsc_measurement"},
+	"2a54": {Name: "RSC Feature", Type: "org.bluetooth.characteristic.rsc_feature"},
+	"2a55": {Name: "SC Control Point", Type: "org.bluetooth.characteristic.sc_control_point"},
+	"2a5b": {Name: "CSC Measurement", Type: "org.bluetooth.characteristic.csc_measurement"},
+	"2a5c": {Name: "CSC Feature", Type: "org.bluetooth.characteristic.csc_feature"},
+	"2a5d": {Name: "Sensor Location", Type: "org.bluetooth.characteristic.sensor_location"},
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/l2cap_writer_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/l2cap_writer_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/l2cap_writer_linux.go
new file mode 100644
index 0000000..f5cecaf
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/l2cap_writer_linux.go
@@ -0,0 +1,156 @@
+package gatt
+
+import "encoding/binary"
+
+// l2capWriter helps create l2cap responses.
+// It is not meant to be used with large writes.
+// TODO: benchmark the number of allocs here.
+// Reduce by letting WriteByteFit, WriteUint16Fit, etc.
+// extend b/chunk and write into it directly.
+type l2capWriter struct {
+	mtu     int
+	b       []byte
+	chunk   []byte
+	chunked bool
+}
+
+func newL2capWriter(mtu uint16) *l2capWriter {
+	return &l2capWriter{mtu: int(mtu), b: make([]byte, 0, mtu)}
+}
+
+// Chunk starts writing a new chunk. This chunk
+// is not committed until Commit is called.
+// Chunk panics if another chunk has already been
+// started and not committed.
+func (w *l2capWriter) Chunk() {
+	if w.chunked {
+		panic("l2capWriter: chunk called twice without committing")
+	}
+	w.chunked = true
+	if w.chunk == nil {
+		w.chunk = make([]byte, 0, w.mtu)
+	}
+}
+
+// Commit writes the current chunk and reports whether the
+// write succeeded. The write succeeds iff there is enough room.
+// Commit panics if no chunk has been started.
+func (w *l2capWriter) Commit() bool {
+	if !w.chunked {
+		panic("l2capWriter: commit without starting a chunk")
+	}
+	var success bool
+	if len(w.b)+len(w.chunk) <= w.mtu {
+		success = true
+		w.b = append(w.b, w.chunk...)
+	}
+	w.chunk = w.chunk[:0]
+	w.chunked = false
+	return success
+}
+
+// CommitFit writes as much of the current chunk as possible,
+// truncating as needed.
+// CommitFit panics if no chunk has been started.
+func (w *l2capWriter) CommitFit() {
+	if !w.chunked {
+		panic("l2capWriter: CommitFit without starting a chunk")
+	}
+	writeable := w.mtu - len(w.b)
+	if writeable > len(w.chunk) {
+		writeable = len(w.chunk)
+	}
+	w.b = append(w.b, w.chunk[:writeable]...)
+	w.chunk = w.chunk[:0]
+	w.chunked = false
+}
+
+// WriteByteFit writes b.
+// It reports whether the write succeeded,
+// using the criteria of WriteFit.
+func (w *l2capWriter) WriteByteFit(b byte) bool {
+	return w.WriteFit([]byte{b})
+}
+
+// WriteUint16Fit writes v using BLE (LittleEndian) encoding.
+// It reports whether the write succeeded, using the
+// criteria of WriteFit.
+func (w *l2capWriter) WriteUint16Fit(v uint16) bool {
+	b := make([]byte, 2)
+	binary.LittleEndian.PutUint16(b, v)
+	return w.WriteFit(b)
+}
+
+// WriteUUIDFit writes uuid using BLE (reversed) encoding.
+// It reports whether the write succeeded, using the
+// criteria of WriteFit.
+func (w *l2capWriter) WriteUUIDFit(u UUID) bool {
+	return w.WriteFit(u.b)
+}
+
+// Writeable returns the number of bytes from b
+// that would be written if pad bytes were written,
+// then as much of b as fits were written. When
+// writing to a chunk, any amount of bytes may be
+// written.
+func (w *l2capWriter) Writeable(pad int, b []byte) int {
+	if w.chunked {
+		return len(b)
+	}
+	avail := w.mtu - len(w.b) - pad
+	if avail > len(b) {
+		return len(b)
+	}
+	if avail < 0 {
+		return 0
+	}
+	return avail
+}
+
+// WriteFit writes as much of b as fits.
+// It reports whether the write succeeded without
+// truncation. A write succeeds without truncation
+// iff a chunk write is in progress or the entire
+// contents were written (without exceeding the mtu).
+func (w *l2capWriter) WriteFit(b []byte) bool {
+	if w.chunked {
+		w.chunk = append(w.chunk, b...)
+		return true
+	}
+	avail := w.mtu - len(w.b)
+	if avail >= len(b) {
+		w.b = append(w.b, b...)
+		return true
+	}
+	w.b = append(w.b, b[:avail]...)
+	return false
+}
+
+// ChunkSeek discards the first offset bytes from the
+// current chunk. It reports whether there were at least
+// offset bytes available to discard.
+// It panics if a chunked write is not in progress.
+func (w *l2capWriter) ChunkSeek(offset uint16) bool {
+	if !w.chunked {
+		panic("l2capWriter: ChunkSeek requested without chunked write in progress")
+	}
+	if len(w.chunk) < int(offset) {
+		w.chunk = w.chunk[:0]
+		return false
+	}
+	w.chunk = w.chunk[offset:]
+	return true
+}
+
+// Bytes returns the written bytes.
+// It will panic if a chunked write
+// is in progress.
+// It is meant to be used when writing
+// is completed. It does not return a copy.
+// Don't abuse this, it's not worth it.
+func (w *l2capWriter) Bytes() []byte {
+	if w.chunked {
+		panic("l2capWriter: Bytes requested while chunked write in progress")
+	}
+	return w.b
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/cmd/cmd.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/cmd/cmd.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/cmd/cmd.go
new file mode 100644
index 0000000..7052502
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/cmd/cmd.go
@@ -0,0 +1,995 @@
+package cmd
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"io"
+	"log"
+
+	"github.com/runtimeco/gatt/linux/evt"
+	"github.com/runtimeco/gatt/linux/util"
+)
+
+type CmdParam interface {
+	Marshal([]byte)
+	Opcode() int
+	Len() int
+}
+
+func NewCmd(d io.Writer) *Cmd {
+	c := &Cmd{
+		dev:     d,
+		sent:    []*cmdPkt{},
+		compc:   make(chan evt.CommandCompleteEP),
+		statusc: make(chan evt.CommandStatusEP),
+	}
+	go c.processCmdEvents()
+	return c
+}
+
+type cmdPkt struct {
+	op   int
+	cp   CmdParam
+	done chan []byte
+}
+
+func (c cmdPkt) Marshal() []byte {
+	b := make([]byte, 1+2+1+c.cp.Len())
+	b[0] = byte(0x1) // typCommandPkt
+	b[1] = byte(c.op)
+	b[2] = byte(c.op >> 8)
+	b[3] = byte(c.cp.Len())
+	c.cp.Marshal(b[4:])
+	return b
+}
+
+type Cmd struct {
+	dev     io.Writer
+	sent    []*cmdPkt
+	compc   chan evt.CommandCompleteEP
+	statusc chan evt.CommandStatusEP
+}
+
+func (c Cmd) trace(fmt string, v ...interface{}) {}
+
+func (c *Cmd) HandleComplete(b []byte) error {
+	var e evt.CommandCompleteEP
+	if err := e.Unmarshal(b); err != nil {
+		return err
+	}
+	c.compc <- e
+	return nil
+}
+
+func (c *Cmd) HandleStatus(b []byte) error {
+	var e evt.CommandStatusEP
+	if err := e.Unmarshal(b); err != nil {
+		return err
+	}
+	c.statusc <- e
+	return nil
+}
+
+func (c *Cmd) Send(cp CmdParam) ([]byte, error) {
+	op := cp.Opcode()
+	p := &cmdPkt{op: op, cp: cp, done: make(chan []byte)}
+	raw := p.Marshal()
+
+	c.sent = append(c.sent, p)
+	if n, err := c.dev.Write(raw); err != nil {
+		return nil, err
+	} else if n != len(raw) {
+		return nil, errors.New("Failed to send whole Cmd pkt to HCI socket")
+	}
+	return <-p.done, nil
+}
+
+func (c *Cmd) SendAndCheckResp(cp CmdParam, exp []byte) error {
+	rsp, err := c.Send(cp)
+	if err != nil {
+		return err
+	}
+	// Don't care about the response
+	if len(exp) == 0 {
+		return nil
+	}
+	// Check the if status is one of the expected value
+	if !bytes.Contains(exp, rsp[0:1]) {
+		return fmt.Errorf("HCI command: '0x%04x' return 0x%02X, expect: [%X] ", cp.Opcode(), rsp[0], exp)
+	}
+	return nil
+}
+
+func (c *Cmd) processCmdEvents() {
+	for {
+		select {
+		case status := <-c.statusc:
+			found := false
+			for i, p := range c.sent {
+				if uint16(p.op) == status.CommandOpcode {
+					found = true
+					c.sent = append(c.sent[:i], c.sent[i+1:]...)
+					close(p.done)
+					break
+				}
+			}
+			if !found {
+				log.Printf("Can't find the cmdPkt for this CommandStatusEP: %v", status)
+			}
+		case comp := <-c.compc:
+			found := false
+			for i, p := range c.sent {
+				if uint16(p.op) == comp.CommandOPCode {
+					found = true
+					c.sent = append(c.sent[:i], c.sent[i+1:]...)
+					p.done <- comp.ReturnParameters
+					break
+				}
+			}
+			if !found {
+				log.Printf("Can't find the cmdPkt for this CommandCompleteEP: %v", comp)
+			}
+		}
+	}
+}
+
+const (
+	linkCtl     = 0x01
+	linkPolicy  = 0x02
+	hostCtl     = 0x03
+	infoParam   = 0x04
+	statusParam = 0x05
+	testingCmd  = 0X3E
+	leCtl       = 0x08
+	vendorCmd   = 0X3F
+)
+
+const (
+	opInquiry                = linkCtl<<10 | 0x0001 // Inquiry
+	opInquiryCancel          = linkCtl<<10 | 0x0002 // Inquiry Cancel
+	opPeriodicInquiry        = linkCtl<<10 | 0x0003 // Periodic Inquiry Mode
+	opExitPeriodicInquiry    = linkCtl<<10 | 0x0004 // Exit Periodic Inquiry Mode
+	opCreateConn             = linkCtl<<10 | 0x0005 // Create Connection
+	opDisconnect             = linkCtl<<10 | 0x0006 // Disconnect
+	opCreateConnCancel       = linkCtl<<10 | 0x0008 // Create Connection Cancel
+	opAcceptConnReq          = linkCtl<<10 | 0x0009 // Accept Connection Request
+	opRejectConnReq          = linkCtl<<10 | 0x000A // Reject Connection Request
+	opLinkKeyReply           = linkCtl<<10 | 0x000B // Link Key Request Reply
+	opLinkKeyNegReply        = linkCtl<<10 | 0x000C // Link Key Request Negative Reply
+	opPinCodeReply           = linkCtl<<10 | 0x000D // PIN Code Request Reply
+	opPinCodeNegReply        = linkCtl<<10 | 0x000E // PIN Code Request Negative Reply
+	opSetConnPtype           = linkCtl<<10 | 0x000F // Change Connection Packet Type
+	opAuthRequested          = linkCtl<<10 | 0x0011 // Authentication Request
+	opSetConnEncrypt         = linkCtl<<10 | 0x0013 // Set Connection Encryption
+	opChangeConnLinkKey      = linkCtl<<10 | 0x0015 // Change Connection Link Key
+	opMasterLinkKey          = linkCtl<<10 | 0x0017 // Master Link Key
+	opRemoteNameReq          = linkCtl<<10 | 0x0019 // Remote Name Request
+	opRemoteNameReqCancel    = linkCtl<<10 | 0x001A // Remote Name Request Cancel
+	opReadRemoteFeatures     = linkCtl<<10 | 0x001B // Read Remote Supported Features
+	opReadRemoteExtFeatures  = linkCtl<<10 | 0x001C // Read Remote Extended Features
+	opReadRemoteVersion      = linkCtl<<10 | 0x001D // Read Remote Version Information
+	opReadClockOffset        = linkCtl<<10 | 0x001F // Read Clock Offset
+	opReadLMPHandle          = linkCtl<<10 | 0x0020 // Read LMP Handle
+	opSetupSyncConn          = linkCtl<<10 | 0x0028 // Setup Synchronous Connection
+	opAcceptSyncConnReq      = linkCtl<<10 | 0x0029 // Aceept Synchronous Connection
+	opRejectSyncConnReq      = linkCtl<<10 | 0x002A // Recject Synchronous Connection
+	opIOCapabilityReply      = linkCtl<<10 | 0x002B // IO Capability Request Reply
+	opUserConfirmReply       = linkCtl<<10 | 0x002C // User Confirmation Request Reply
+	opUserConfirmNegReply    = linkCtl<<10 | 0x002D // User Confirmation Negative Reply
+	opUserPasskeyReply       = linkCtl<<10 | 0x002E // User Passkey Request Reply
+	opUserPasskeyNegReply    = linkCtl<<10 | 0x002F // User Passkey Request Negative Reply
+	opRemoteOOBDataReply     = linkCtl<<10 | 0x0030 // Remote OOB Data Request Reply
+	opRemoteOOBDataNegReply  = linkCtl<<10 | 0x0033 // Remote OOB Data Request Negative Reply
+	opIOCapabilityNegReply   = linkCtl<<10 | 0x0034 // IO Capability Request Negative Reply
+	opCreatePhysicalLink     = linkCtl<<10 | 0x0035 // Create Physical Link
+	opAcceptPhysicalLink     = linkCtl<<10 | 0x0036 // Accept Physical Link
+	opDisconnectPhysicalLink = linkCtl<<10 | 0x0037 // Disconnect Physical Link
+	opCreateLogicalLink      = linkCtl<<10 | 0x0038 // Create Logical Link
+	opAcceptLogicalLink      = linkCtl<<10 | 0x0039 // Accept Logical Link
+	opDisconnectLogicalLink  = linkCtl<<10 | 0x003A // Disconnect Logical Link
+	opLogicalLinkCancel      = linkCtl<<10 | 0x003B // Logical Link Cancel
+	opFlowSpecModify         = linkCtl<<10 | 0x003C // Flow Spec Modify
+)
+
+const (
+	opHoldMode               = linkPolicy<<10 | 0x0001 // Hold Mode
+	opSniffMode              = linkPolicy<<10 | 0x0003 // Sniff Mode
+	opExitSniffMode          = linkPolicy<<10 | 0x0004 // Exit Sniff Mode
+	opParkMode               = linkPolicy<<10 | 0x0005 // Park State
+	opExitParkMode           = linkPolicy<<10 | 0x0006 // Exit Park State
+	opQoSSetup               = linkPolicy<<10 | 0x0007 // QoS Setup
+	opRoleDiscovery          = linkPolicy<<10 | 0x0009 // Role Discovery
+	opSwitchRole             = linkPolicy<<10 | 0x000B // Switch Role
+	opReadLinkPolicy         = linkPolicy<<10 | 0x000C // Read Link Policy Settings
+	opWriteLinkPolicy        = linkPolicy<<10 | 0x000D // Write Link Policy Settings
+	opReadDefaultLinkPolicy  = linkPolicy<<10 | 0x000E // Read Default Link Policy Settings
+	opWriteDefaultLinkPolicy = linkPolicy<<10 | 0x000F // Write Default Link Policy Settings
+	opFlowSpecification      = linkPolicy<<10 | 0x0010 // Flow Specification
+	opSniffSubrating         = linkPolicy<<10 | 0x0011 // Sniff Subrating
+)
+
+const (
+	opSetEventMask                      = hostCtl<<10 | 0x0001 // Set Event Mask
+	opReset                             = hostCtl<<10 | 0x0003 // Reset
+	opSetEventFlt                       = hostCtl<<10 | 0x0005 // Set Event Filter
+	opFlush                             = hostCtl<<10 | 0x0008 // Flush
+	opReadPinType                       = hostCtl<<10 | 0x0009 // Read PIN Type
+	opWritePinType                      = hostCtl<<10 | 0x000A // Write PIN Type
+	opCreateNewUnitKey                  = hostCtl<<10 | 0x000B // Create New Unit Key
+	opReadStoredLinkKey                 = hostCtl<<10 | 0x000D // Read Stored Link Key
+	opWriteStoredLinkKey                = hostCtl<<10 | 0x0011 // Write Stored Link Key
+	opDeleteStoredLinkKey               = hostCtl<<10 | 0x0012 // Delete Stored Link Key
+	opWriteLocalName                    = hostCtl<<10 | 0x0013 // Write Local Name
+	opReadLocalName                     = hostCtl<<10 | 0x0014 // Read Local Name
+	opReadConnAcceptTimeout             = hostCtl<<10 | 0x0015 // Read Connection Accept Timeout
+	opWriteConnAcceptTimeout            = hostCtl<<10 | 0x0016 // Write Connection Accept Timeout
+	opReadPageTimeout                   = hostCtl<<10 | 0x0017 // Read Page Timeout
+	opWritePageTimeout                  = hostCtl<<10 | 0x0018 // Write Page Timeout
+	opReadScanEnable                    = hostCtl<<10 | 0x0019 // Read Scan Enable
+	opWriteScanEnable                   = hostCtl<<10 | 0x001A // Write Scan Enable
+	opReadPageActivity                  = hostCtl<<10 | 0x001B // Read Page Scan Activity
+	opWritePageActivity                 = hostCtl<<10 | 0x001C // Write Page Scan Activity
+	opReadInqActivity                   = hostCtl<<10 | 0x001D // Read Inquiry Scan Activity
+	opWriteInqActivity                  = hostCtl<<10 | 0x001E // Write Inquiry Scan Activity
+	opReadAuthEnable                    = hostCtl<<10 | 0x001F // Read Authentication Enable
+	opWriteAuthEnable                   = hostCtl<<10 | 0x0020 // Write Authentication Enable
+	opReadEncryptMode                   = hostCtl<<10 | 0x0021
+	opWriteEncryptMode                  = hostCtl<<10 | 0x0022
+	opReadClassOfDev                    = hostCtl<<10 | 0x0023 // Read Class of Device
+	opWriteClassOfDevice                = hostCtl<<10 | 0x0024 // Write Class of Device
+	opReadVoiceSetting                  = hostCtl<<10 | 0x0025 // Read Voice Setting
+	opWriteVoiceSetting                 = hostCtl<<10 | 0x0026 // Write Voice Setting
+	opReadAutomaticFlushTimeout         = hostCtl<<10 | 0x0027 // Read Automatic Flush Timeout
+	opWriteAutomaticFlushTimeout        = hostCtl<<10 | 0x0028 // Write Automatic Flush Timeout
+	opReadNumBroadcastRetrans           = hostCtl<<10 | 0x0029 // Read Num Broadcast Retransmissions
+	opWriteNumBroadcastRetrans          = hostCtl<<10 | 0x002A // Write Num Broadcast Retransmissions
+	opReadHoldModeActivity              = hostCtl<<10 | 0x002B // Read Hold Mode Activity
+	opWriteHoldModeActivity             = hostCtl<<10 | 0x002C // Write Hold Mode Activity
+	opReadTransmitPowerLevel            = hostCtl<<10 | 0x002D // Read Transmit Power Level
+	opReadSyncFlowEnable                = hostCtl<<10 | 0x002E // Read Synchronous Flow Control
+	opWriteSyncFlowEnable               = hostCtl<<10 | 0x002F // Write Synchronous Flow Control
+	opSetControllerToHostFC             = hostCtl<<10 | 0x0031 // Set Controller To Host Flow Control
+	opHostBufferSize                    = hostCtl<<10 | 0x0033 // Host Buffer Size
+	opHostNumCompPkts                   = hostCtl<<10 | 0x0035 // Host Number Of Completed Packets
+	opReadLinkSupervisionTimeout        = hostCtl<<10 | 0x0036 // Read Link Supervision Timeout
+	opWriteLinkSupervisionTimeout       = hostCtl<<10 | 0x0037 // Write Link Supervision Timeout
+	opReadNumSupportedIAC               = hostCtl<<10 | 0x0038 // Read Number Of Supported IAC
+	opReadCurrentIACLAP                 = hostCtl<<10 | 0x0039 // Read Current IAC LAP
+	opWriteCurrentIACLAP                = hostCtl<<10 | 0x003A // Write Current IAC LAP
+	opReadPageScanPeriodMode            = hostCtl<<10 | 0x003B
+	opWritePageScanPeriodMode           = hostCtl<<10 | 0x003C
+	opReadPageScanMode                  = hostCtl<<10 | 0x003D
+	opWritePageScanMode                 = hostCtl<<10 | 0x003E
+	opSetAFHClassification              = hostCtl<<10 | 0x003F // Set AFH Host Channel Classification
+	opReadInquiryScanType               = hostCtl<<10 | 0x0042 // Read Inquiry Scan Type
+	opWriteInquiryScanType              = hostCtl<<10 | 0x0043 // Write Inquiry Scan Type
+	opReadInquiryMode                   = hostCtl<<10 | 0x0044 // Read Inquiry Mode
+	opWriteInquiryMode                  = hostCtl<<10 | 0x0045 // Write Inquiry Mode
+	opReadPageScanType                  = hostCtl<<10 | 0x0046 // Read Page Scan Type
+	opWritePageScanType                 = hostCtl<<10 | 0x0047 // Write Page Scan Type
+	opReadAFHMode                       = hostCtl<<10 | 0x0048 // Read AFH Channel Assessment Mode
+	opWriteAFHMode                      = hostCtl<<10 | 0x0049 // Write AFH Channel Assesment Mode
+	opReadExtInquiryResponse            = hostCtl<<10 | 0x0051 // Read Extended Inquiry Response
+	opWriteExtInquiryResponse           = hostCtl<<10 | 0x0052 // Write Extended Inquiry Response
+	opRefreshEncryptionKey              = hostCtl<<10 | 0x0053 // Refresh Encryption Key
+	opReadSimplePairingMode             = hostCtl<<10 | 0x0055 // Read Simple Pairing Mode
+	opWriteSimplePairingMode            = hostCtl<<10 | 0x0056 // Write Simple Pairing Mode
+	opReadLocalOobData                  = hostCtl<<10 | 0x0057 // Read Local OOB Data
+	opReadInqResponseTransmitPowerLevel = hostCtl<<10 | 0x0058 // Read Inquiry Response Transmit Power Level
+	opWriteInquiryTransmitPowerLevel    = hostCtl<<10 | 0x0059 // Write Inquiry Response Transmit Power Level
+	opReadDefaultErrorDataReporting     = hostCtl<<10 | 0x005A // Read Default Erroneous Data Reporting
+	opWriteDefaultErrorDataReporting    = hostCtl<<10 | 0x005B // Write Default Erroneous Data Reporting
+	opEnhancedFlush                     = hostCtl<<10 | 0x005F // Enhanced Flush
+	opSendKeypressNotify                = hostCtl<<10 | 0x0060 // send Keypress Notification
+	opReadLogicalLinkAcceptTimeout      = hostCtl<<10 | 0x0061 // Read Logical Link Accept Timeout
+	opWriteLogicalLinkAcceptTimeout     = hostCtl<<10 | 0x0062 // Write Logical Link Accept Timeout
+	opSetEventMaskPage2                 = hostCtl<<10 | 0x0063 // Set Event Mask Page 2
+	opReadLocationData                  = hostCtl<<10 | 0x0064 // Read Location Data
+	opWriteLocationData                 = hostCtl<<10 | 0x0065 // Write Location Data
+	opReadFlowControlMode               = hostCtl<<10 | 0x0066 // Read Flow Control Mode
+	opWriteFlowControlMode              = hostCtl<<10 | 0x0067 // Write Flow Control Mode
+	opReadEnhancedTransmitpowerLevel    = hostCtl<<10 | 0x0068 // Read Enhanced Transmit Power Level
+	opReadBestEffortFlushTimeout        = hostCtl<<10 | 0x0069 // Read Best Effort Flush Timeout
+	opWriteBestEffortFlushTimeout       = hostCtl<<10 | 0x006A // Write Best Effort Flush Timeout
+	opReadLEHostSupported               = hostCtl<<10 | 0x006C // Read LE Host Supported
+	opWriteLEHostSupported              = hostCtl<<10 | 0x006D // Write LE Host Supported
+)
+const (
+	opReadLocalVersionInformation = infoParam<<10 | 0x0001 // Read Local Version Information
+	opReadLocalSupportedCommands  = infoParam<<10 | 0x0002 // Read Local Supported Commands
+	opReadLocalSupportedFeatures  = infoParam<<10 | 0x0003 // Read Local Supported Features
+	opReadLocalExtendedFeatures   = infoParam<<10 | 0x0004 // Read Local Extended Features
+	opReadBufferSize              = infoParam<<10 | 0x0005 // Read Buffer Size
+	opReadBDADDR                  = infoParam<<10 | 0x0009 // Read BD_ADDR
+	opReadDataBlockSize           = infoParam<<10 | 0x000A // Read Data Block Size
+	opReadLocalSupportedCodecs    = infoParam<<10 | 0x000B // Read Local Supported Codecs
+)
+const (
+	opLESetEventMask                      = leCtl<<10 | 0x0001 // LE Set Event Mask
+	opLEReadBufferSize                    = leCtl<<10 | 0x0002 // LE Read Buffer Size
+	opLEReadLocalSupportedFeatures        = leCtl<<10 | 0x0003 // LE Read Local Supported Features
+	opLESetRandomAddress                  = leCtl<<10 | 0x0005 // LE Set Random Address
+	opLESetAdvertisingParameters          = leCtl<<10 | 0x0006 // LE Set Advertising Parameters
+	opLEReadAdvertisingChannelTxPower     = leCtl<<10 | 0x0007 // LE Read Advertising Channel Tx Power
+	opLESetAdvertisingData                = leCtl<<10 | 0x0008 // LE Set Advertising Data
+	opLESetScanResponseData               = leCtl<<10 | 0x0009 // LE Set Scan Response Data
+	opLESetAdvertiseEnable                = leCtl<<10 | 0x000a // LE Set Advertising Enable
+	opLESetScanParameters                 = leCtl<<10 | 0x000b // LE Set Scan Parameters
+	opLESetScanEnable                     = leCtl<<10 | 0x000c // LE Set Scan Enable
+	opLECreateConn                        = leCtl<<10 | 0x000d // LE Create Connection
+	opLECreateConnCancel                  = leCtl<<10 | 0x000e // LE Create Connection Cancel
+	opLEReadWhiteListSize                 = leCtl<<10 | 0x000f // LE Read White List Size
+	opLEClearWhiteList                    = leCtl<<10 | 0x0010 // LE Clear White List
+	opLEAddDeviceToWhiteList              = leCtl<<10 | 0x0011 // LE Add Device To White List
+	opLERemoveDeviceFromWhiteList         = leCtl<<10 | 0x0012 // LE Remove Device From White List
+	opLEConnUpdate                        = leCtl<<10 | 0x0013 // LE Connection Update
+	opLESetHostChannelClassification      = leCtl<<10 | 0x0014 // LE Set Host Channel Classification
+	opLEReadChannelMap                    = leCtl<<10 | 0x0015 // LE Read Channel Map
+	opLEReadRemoteUsedFeatures            = leCtl<<10 | 0x0016 // LE Read Remote Used Features
+	opLEEncrypt                           = leCtl<<10 | 0x0017 // LE Encrypt
+	opLERand                              = leCtl<<10 | 0x0018 // LE Rand
+	opLEStartEncryption                   = leCtl<<10 | 0x0019 // LE Star Encryption
+	opLELTKReply                          = leCtl<<10 | 0x001a // LE Long Term Key Request Reply
+	opLELTKNegReply                       = leCtl<<10 | 0x001b // LE Long Term Key Request Negative Reply
+	opLEReadSupportedStates               = leCtl<<10 | 0x001c // LE Read Supported States
+	opLEReceiverTest                      = leCtl<<10 | 0x001d // LE Reciever Test
+	opLETransmitterTest                   = leCtl<<10 | 0x001e // LE Transmitter Test
+	opLETestEnd                           = leCtl<<10 | 0x001f // LE Test End
+	opLERemoteConnectionParameterReply    = leCtl<<10 | 0x0020 // LE Remote Connection Parameter Request Reply
+	opLERemoteConnectionParameterNegReply = leCtl<<10 | 0x0021 // LE Remote Connection Parameter Request Negative Reply
+)
+
+var o = util.Order
+
+// Link Control Commands
+
+// Disconnect (0x0006)
+type Disconnect struct {
+	ConnectionHandle uint16
+	Reason           uint8
+}
+
+func (c Disconnect) Opcode() int { return opDisconnect }
+func (c Disconnect) Len() int    { return 3 }
+func (c Disconnect) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	b[2] = c.Reason
+}
+
+// No Return Parameters, Check for Disconnection Complete Event
+type DisconnectRP struct{}
+
+// Link Policy Commands
+
+// Write Default Link Policy
+type WriteDefaultLinkPolicy struct{ DefaultLinkPolicySettings uint16 }
+
+func (c WriteDefaultLinkPolicy) Opcode() int      { return opWriteDefaultLinkPolicy }
+func (c WriteDefaultLinkPolicy) Len() int         { return 2 }
+func (c WriteDefaultLinkPolicy) Marshal(b []byte) { o.PutUint16(b, c.DefaultLinkPolicySettings) }
+
+type WriteDefaultLinkPolicyRP struct{ Status uint8 }
+
+// Host Control Commands
+
+// Set Event Mask (0x0001)
+type SetEventMask struct{ EventMask uint64 }
+
+func (c SetEventMask) Opcode() int      { return opSetEventMask }
+func (c SetEventMask) Len() int         { return 8 }
+func (c SetEventMask) Marshal(b []byte) { o.PutUint64(b, c.EventMask) }
+
+type SetEventMaskRP struct{ Status uint8 }
+
+// Reset (0x0002)
+type Reset struct{}
+
+func (c Reset) Opcode() int      { return opReset }
+func (c Reset) Len() int         { return 0 }
+func (c Reset) Marshal(b []byte) {}
+
+type ResetRP struct{ Status uint8 }
+
+// Set Event Filter (0x0003)
+// FIXME: This structures are overloading.
+// Both Marshal() and Len() are just placeholder.
+// Need more effort for decoding.
+// type SetEventFlt struct {
+// 	FilterType          uint8
+// 	FilterConditionType uint8
+// 	Condition           uint8
+// }
+
+// func (c SetEventFlt) Opcode() int   { return opSetEventFlt }
+// func (c SetEventFlt) Len() int         { return 0 }
+// func (c SetEventFlt) Marshal(b []byte) {}
+
+type SetEventFltRP struct{ Status uint8 }
+
+// Flush (0x0008)
+type Flush struct{ ConnectionHandle uint16 }
+
+func (c Flush) Opcode() int      { return opFlush }
+func (c Flush) Len() int         { return 2 }
+func (c Flush) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
+
+type flushRP struct{ status uint8 }
+
+// Write Page Timeout (0x0018)
+type WritePageTimeout struct{ PageTimeout uint16 }
+
+func (c WritePageTimeout) Opcode() int      { return opWritePageTimeout }
+func (c WritePageTimeout) Len() int         { return 2 }
+func (c WritePageTimeout) Marshal(b []byte) { o.PutUint16(b, c.PageTimeout) }
+
+type WritePageTimeoutRP struct{}
+
+// Write Class of Device (0x0024)
+type WriteClassOfDevice struct{ ClassOfDevice [3]byte }
+
+func (c WriteClassOfDevice) Opcode() int      { return opWriteClassOfDevice }
+func (c WriteClassOfDevice) Len() int         { return 3 }
+func (c WriteClassOfDevice) Marshal(b []byte) { copy(b, c.ClassOfDevice[:]) }
+
+type WriteClassOfDevRP struct{ status uint8 }
+
+// Write Host Buffer Size (0x0033)
+type HostBufferSize struct {
+	HostACLDataPacketLength            uint16
+	HostSynchronousDataPacketLength    uint8
+	HostTotalNumACLDataPackets         uint16
+	HostTotalNumSynchronousDataPackets uint16
+}
+
+func (c HostBufferSize) Opcode() int { return opHostBufferSize }
+func (c HostBufferSize) Len() int    { return 7 }
+func (c HostBufferSize) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.HostACLDataPacketLength)
+	o.PutUint8(b[2:], c.HostSynchronousDataPacketLength)
+	o.PutUint16(b[3:], c.HostTotalNumACLDataPackets)
+	o.PutUint16(b[5:], c.HostTotalNumSynchronousDataPackets)
+}
+
+type HostBufferSizeRP struct{ Status uint8 }
+
+// Write Inquiry Scan Type (0x0043)
+type WriteInquiryScanType struct{ ScanType uint8 }
+
+func (c WriteInquiryScanType) Opcode() int      { return opWriteInquiryScanType }
+func (c WriteInquiryScanType) Len() int         { return 1 }
+func (c WriteInquiryScanType) Marshal(b []byte) { b[0] = c.ScanType }
+
+type WriteInquiryScanTypeRP struct{ Status uint8 }
+
+// Write Inquiry Mode (0x0045)
+type WriteInquiryMode struct {
+	InquiryMode uint8
+}
+
+func (c WriteInquiryMode) Opcode() int      { return opWriteInquiryMode }
+func (c WriteInquiryMode) Len() int         { return 1 }
+func (c WriteInquiryMode) Marshal(b []byte) { b[0] = c.InquiryMode }
+
+type WriteInquiryModeRP struct{ Status uint8 }
+
+// Write Page Scan Type (0x0046)
+type WritePageScanType struct{ PageScanType uint8 }
+
+func (c WritePageScanType) Opcode() int      { return opWritePageScanType }
+func (c WritePageScanType) Len() int         { return 1 }
+func (c WritePageScanType) Marshal(b []byte) { b[0] = c.PageScanType }
+
+type WritePageScanTypeRP struct{ Status uint8 }
+
+// Write Simple Pairing Mode (0x0056)
+type WriteSimplePairingMode struct{ SimplePairingMode uint8 }
+
+func (c WriteSimplePairingMode) Opcode() int      { return opWriteSimplePairingMode }
+func (c WriteSimplePairingMode) Len() int         { return 1 }
+func (c WriteSimplePairingMode) Marshal(b []byte) { b[0] = c.SimplePairingMode }
+
+type WriteSimplePairingModeRP struct{}
+
+// Set Event Mask Page 2 (0x0063)
+type SetEventMaskPage2 struct{ EventMaskPage2 uint64 }
+
+func (c SetEventMaskPage2) Opcode() int      { return opSetEventMaskPage2 }
+func (c SetEventMaskPage2) Len() int         { return 8 }
+func (c SetEventMaskPage2) Marshal(b []byte) { o.PutUint64(b, c.EventMaskPage2) }
+
+type SetEventMaskPage2RP struct{ Status uint8 }
+
+// Write LE Host Supported (0x006D)
+type WriteLEHostSupported struct {
+	LESupportedHost    uint8
+	SimultaneousLEHost uint8
+}
+
+func (c WriteLEHostSupported) Opcode() int      { return opWriteLEHostSupported }
+func (c WriteLEHostSupported) Len() int         { return 2 }
+func (c WriteLEHostSupported) Marshal(b []byte) { b[0], b[1] = c.LESupportedHost, c.SimultaneousLEHost }
+
+type WriteLeHostSupportedRP struct{ Status uint8 }
+
+// LE Controller Commands
+
+// LE Set Event Mask (0x0001)
+type LESetEventMask struct{ LEEventMask uint64 }
+
+func (c LESetEventMask) Opcode() int      { return opLESetEventMask }
+func (c LESetEventMask) Len() int         { return 8 }
+func (c LESetEventMask) Marshal(b []byte) { o.PutUint64(b, c.LEEventMask) }
+
+type LESetEventMaskRP struct{ Status uint8 }
+
+// LE Read Buffer Size (0x0002)
+type LEReadBufferSize struct{}
+
+func (c LEReadBufferSize) Opcode() int      { return opLEReadBufferSize }
+func (c LEReadBufferSize) Len() int         { return 1 }
+func (c LEReadBufferSize) Marshal(b []byte) {}
+
+type LEReadBufferSizeRP struct {
+	Status                     uint8
+	HCLEACLDataPacketLength    uint16
+	HCTotalNumLEACLDataPackets uint8
+}
+
+// LE Read Local Supported Features (0x0003)
+type LEReadLocalSupportedFeatures struct{}
+
+func (c LEReadLocalSupportedFeatures) Opcode() int      { return opLEReadLocalSupportedFeatures }
+func (c LEReadLocalSupportedFeatures) Len() int         { return 0 }
+func (c LEReadLocalSupportedFeatures) Marshal(b []byte) {}
+
+type LEReadLocalSupportedFeaturesRP struct {
+	Status     uint8
+	LEFeatures uint64
+}
+
+// LE Set Random Address (0x0005)
+type LESetRandomAddress struct{ RandomAddress [6]byte }
+
+func (c LESetRandomAddress) Opcode() int      { return opLESetRandomAddress }
+func (c LESetRandomAddress) Len() int         { return 6 }
+func (c LESetRandomAddress) Marshal(b []byte) { o.PutMAC(b, c.RandomAddress) }
+
+type LESetRandomAddressRP struct{ Status uint8 }
+
+// LE Set Advertising Parameters (0x0006)
+type LESetAdvertisingParameters struct {
+	AdvertisingIntervalMin  uint16
+	AdvertisingIntervalMax  uint16
+	AdvertisingType         uint8
+	OwnAddressType          uint8
+	DirectAddressType       uint8
+	DirectAddress           [6]byte
+	AdvertisingChannelMap   uint8
+	AdvertisingFilterPolicy uint8
+}
+
+func (c LESetAdvertisingParameters) Opcode() int { return opLESetAdvertisingParameters }
+func (c LESetAdvertisingParameters) Len() int    { return 15 }
+func (c LESetAdvertisingParameters) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.AdvertisingIntervalMin)
+	o.PutUint16(b[2:], c.AdvertisingIntervalMax)
+	o.PutUint8(b[4:], c.AdvertisingType)
+	o.PutUint8(b[5:], c.OwnAddressType)
+	o.PutUint8(b[6:], c.DirectAddressType)
+	o.PutMAC(b[7:], c.DirectAddress)
+	o.PutUint8(b[13:], c.AdvertisingChannelMap)
+	o.PutUint8(b[14:], c.AdvertisingFilterPolicy)
+}
+
+type LESetAdvertisingParametersRP struct{ Status uint8 }
+
+// LE Read Advertising Channel Tx Power (0x0007)
+type LEReadAdvertisingChannelTxPower struct{}
+
+func (c LEReadAdvertisingChannelTxPower) Opcode() int      { return opLEReadAdvertisingChannelTxPower }
+func (c LEReadAdvertisingChannelTxPower) Len() int         { return 0 }
+func (c LEReadAdvertisingChannelTxPower) Marshal(b []byte) {}
+
+type LEReadAdvertisingChannelTxPowerRP struct {
+	Status             uint8
+	TransmitPowerLevel uint8
+}
+
+// LE Set Advertising Data (0x0008)
+type LESetAdvertisingData struct {
+	AdvertisingDataLength uint8
+	AdvertisingData       [31]byte
+}
+
+func (c LESetAdvertisingData) Opcode() int { return opLESetAdvertisingData }
+func (c LESetAdvertisingData) Len() int    { return 32 }
+func (c LESetAdvertisingData) Marshal(b []byte) {
+	b[0] = c.AdvertisingDataLength
+	copy(b[1:], c.AdvertisingData[:c.AdvertisingDataLength])
+}
+
+type LESetAdvertisingDataRP struct{ Status uint8 }
+
+// LE Set Scan Response Data (0x0009)
+type LESetScanResponseData struct {
+	ScanResponseDataLength uint8
+	ScanResponseData       [31]byte
+}
+
+func (c LESetScanResponseData) Opcode() int { return opLESetScanResponseData }
+func (c LESetScanResponseData) Len() int    { return 32 }
+func (c LESetScanResponseData) Marshal(b []byte) {
+	b[0] = c.ScanResponseDataLength
+	copy(b[1:], c.ScanResponseData[:c.ScanResponseDataLength])
+}
+
+type LESetScanResponseDataRP struct{ Status uint8 }
+
+// LE Set Advertising Enable (0x000A)
+type LESetAdvertiseEnable struct{ AdvertisingEnable uint8 }
+
+func (c LESetAdvertiseEnable) Opcode() int      { return opLESetAdvertiseEnable }
+func (c LESetAdvertiseEnable) Len() int         { return 1 }
+func (c LESetAdvertiseEnable) Marshal(b []byte) { b[0] = c.AdvertisingEnable }
+
+type LESetAdvertiseEnableRP struct{ Status uint8 }
+
+// LE Set Scan Parameters (0x000B)
+type LESetScanParameters struct {
+	LEScanType           uint8
+	LEScanInterval       uint16
+	LEScanWindow         uint16
+	OwnAddressType       uint8
+	ScanningFilterPolicy uint8
+}
+
+func (c LESetScanParameters) Opcode() int { return opLESetScanParameters }
+func (c LESetScanParameters) Len() int    { return 7 }
+func (c LESetScanParameters) Marshal(b []byte) {
+	o.PutUint8(b[0:], c.LEScanType)
+	o.PutUint16(b[1:], c.LEScanInterval)
+	o.PutUint16(b[3:], c.LEScanWindow)
+	o.PutUint8(b[5:], c.OwnAddressType)
+	o.PutUint8(b[6:], c.ScanningFilterPolicy)
+}
+
+type LESetScanParametersRP struct{ Status uint8 }
+
+// LE Set Scan Enable (0x000C)
+type LESetScanEnable struct {
+	LEScanEnable     uint8
+	FilterDuplicates uint8
+}
+
+func (c LESetScanEnable) Opcode() int      { return opLESetScanEnable }
+func (c LESetScanEnable) Len() int         { return 2 }
+func (c LESetScanEnable) Marshal(b []byte) { b[0], b[1] = c.LEScanEnable, c.FilterDuplicates }
+
+type LESetScanEnableRP struct{ Status uint8 }
+
+// LE Create Connection (0x000D)
+type LECreateConn struct {
+	LEScanInterval        uint16
+	LEScanWindow          uint16
+	InitiatorFilterPolicy uint8
+	PeerAddressType       uint8
+	PeerAddress           [6]byte
+	OwnAddressType        uint8
+	ConnIntervalMin       uint16
+	ConnIntervalMax       uint16
+	ConnLatency           uint16
+	SupervisionTimeout    uint16
+	MinimumCELength       uint16
+	MaximumCELength       uint16
+}
+
+func (c LECreateConn) Opcode() int { return opLECreateConn }
+func (c LECreateConn) Len() int    { return 25 }
+func (c LECreateConn) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.LEScanInterval)
+	o.PutUint16(b[2:], c.LEScanWindow)
+	o.PutUint8(b[4:], c.InitiatorFilterPolicy)
+	o.PutUint8(b[5:], c.PeerAddressType)
+	o.PutMAC(b[6:], c.PeerAddress)
+	o.PutUint8(b[12:], c.OwnAddressType)
+	o.PutUint16(b[13:], c.ConnIntervalMin)
+	o.PutUint16(b[15:], c.ConnIntervalMax)
+	o.PutUint16(b[17:], c.ConnLatency)
+	o.PutUint16(b[19:], c.SupervisionTimeout)
+	o.PutUint16(b[21:], c.MinimumCELength)
+	o.PutUint16(b[23:], c.MaximumCELength)
+}
+
+type LECreateConnRP struct{}
+
+// LE Create Connection Cancel (0x000E)
+type LECreateConnCancel struct{}
+
+func (c LECreateConnCancel) Opcode() int      { return opLECreateConnCancel }
+func (c LECreateConnCancel) Len() int         { return 0 }
+func (c LECreateConnCancel) Marshal(b []byte) {}
+
+type LECreateConnCancelRP struct{ Status uint8 }
+
+// LE Read White List Size (0x000F)
+type LEReadWhiteListSize struct{}
+
+func (c LEReadWhiteListSize) Opcode() int      { return opLEReadWhiteListSize }
+func (c LEReadWhiteListSize) Len() int         { return 0 }
+func (c LEReadWhiteListSize) Marshal(b []byte) {}
+
+type LEReadWhiteListSizeRP struct {
+	Status        uint8
+	WhiteListSize uint8
+}
+
+// LE Clear White List (0x0010)
+type LEClearWhiteList struct{}
+
+func (c LEClearWhiteList) Opcode() int      { return opLEClearWhiteList }
+func (c LEClearWhiteList) Len() int         { return 0 }
+func (c LEClearWhiteList) Marshal(b []byte) {}
+
+type LEClearWhiteListRP struct{ Status uint8 }
+
+// LE Add Device To White List (0x0011)
+type LEAddDeviceToWhiteList struct {
+	AddressType uint8
+	Address     [6]byte
+}
+
+func (c LEAddDeviceToWhiteList) Opcode() int { return opLEAddDeviceToWhiteList }
+func (c LEAddDeviceToWhiteList) Len() int    { return 7 }
+func (c LEAddDeviceToWhiteList) Marshal(b []byte) {
+	b[0] = c.AddressType
+	o.PutMAC(b[1:], c.Address)
+}
+
+type LEAddDeviceToWhiteListRP struct{ Status uint8 }
+
+// LE Remove Device From White List (0x0012)
+type LERemoveDeviceFromWhiteList struct {
+	AddressType uint8
+	Address     [6]byte
+}
+
+func (c LERemoveDeviceFromWhiteList) Opcode() int { return opLERemoveDeviceFromWhiteList }
+func (c LERemoveDeviceFromWhiteList) Len() int    { return 7 }
+func (c LERemoveDeviceFromWhiteList) Marshal(b []byte) {
+	b[0] = c.AddressType
+	o.PutMAC(b[1:], c.Address)
+}
+
+type LERemoveDeviceFromWhiteListRP struct{ Status uint8 }
+
+// LE Connection Update (0x0013)
+type LEConnUpdate struct {
+	ConnectionHandle   uint16
+	ConnIntervalMin    uint16
+	ConnIntervalMax    uint16
+	ConnLatency        uint16
+	SupervisionTimeout uint16
+	MinimumCELength    uint16
+	MaximumCELength    uint16
+}
+
+func (c LEConnUpdate) Opcode() int { return opLEConnUpdate }
+func (c LEConnUpdate) Len() int    { return 14 }
+func (c LEConnUpdate) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	o.PutUint16(b[2:], c.ConnIntervalMin)
+	o.PutUint16(b[4:], c.ConnIntervalMax)
+	o.PutUint16(b[6:], c.ConnLatency)
+	o.PutUint16(b[8:], c.SupervisionTimeout)
+	o.PutUint16(b[10:], c.MinimumCELength)
+	o.PutUint16(b[12:], c.MaximumCELength)
+}
+
+type LEConnUpdateRP struct{}
+
+// LE Set Host Channel Classification (0x0014)
+type LESetHostChannelClassification struct{ ChannelMap [5]byte }
+
+func (c LESetHostChannelClassification) Opcode() int      { return opLESetHostChannelClassification }
+func (c LESetHostChannelClassification) Len() int         { return 5 }
+func (c LESetHostChannelClassification) Marshal(b []byte) { copy(b, c.ChannelMap[:]) }
+
+type LESetHostChannelClassificationRP struct{ Status uint8 }
+
+// LE Read Channel Map (0x0015)
+type LEReadChannelMap struct{ ConnectionHandle uint16 }
+
+func (c LEReadChannelMap) Opcode() int      { return opLEReadChannelMap }
+func (c LEReadChannelMap) Len() int         { return 2 }
+func (c LEReadChannelMap) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
+
+type LEReadChannelMapRP struct {
+	Status           uint8
+	ConnectionHandle uint16
+	ChannelMap       [5]byte
+}
+
+// LE Read Remote Used Features (0x0016)
+type LEReadRemoteUsedFeatures struct{ ConnectionHandle uint16 }
+
+func (c LEReadRemoteUsedFeatures) Opcode() int      { return opLEReadRemoteUsedFeatures }
+func (c LEReadRemoteUsedFeatures) Len() int         { return 8 }
+func (c LEReadRemoteUsedFeatures) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
+
+type LEReadRemoteUsedFeaturesRP struct{}
+
+// LE Encrypt (0x0017)
+type LEEncrypt struct {
+	Key           [16]byte
+	PlaintextData [16]byte
+}
+
+func (c LEEncrypt) Opcode() int { return opLEEncrypt }
+func (c LEEncrypt) Len() int    { return 32 }
+func (c LEEncrypt) Marshal(b []byte) {
+	copy(b[0:], c.Key[:])
+	copy(b[16:], c.PlaintextData[:])
+}
+
+type LEEncryptRP struct {
+	Stauts        uint8
+	EncryptedData [16]byte
+}
+
+// LE Rand (0x0018)
+type LERand struct{}
+
+func (c LERand) Opcode() int      { return opLERand }
+func (c LERand) Len() int         { return 0 }
+func (c LERand) Marshal(b []byte) {}
+
+type LERandRP struct {
+	Status       uint8
+	RandomNumber uint64
+}
+
+// LE Start Encryption (0x0019)
+type LEStartEncryption struct {
+	ConnectionHandle     uint16
+	RandomNumber         uint64
+	EncryptedDiversifier uint16
+	LongTermKey          [16]byte
+}
+
+func (c LEStartEncryption) Opcode() int { return opLEStartEncryption }
+func (c LEStartEncryption) Len() int    { return 28 }
+func (c LEStartEncryption) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	o.PutUint64(b[2:], c.RandomNumber)
+	o.PutUint16(b[10:], c.EncryptedDiversifier)
+	copy(b[12:], c.LongTermKey[:])
+}
+
+type LEStartEncryptionRP struct{}
+
+// LE Long Term Key Reply (0x001A)
+type LELTKReply struct {
+	ConnectionHandle uint16
+	LongTermKey      [16]byte
+}
+
+func (c LELTKReply) Opcode() int { return opLELTKReply }
+func (c LELTKReply) Len() int    { return 18 }
+func (c LELTKReply) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	copy(b[2:], c.LongTermKey[:])
+}
+
+type LELTKReplyRP struct {
+	Status           uint8
+	ConnectionHandle uint16
+}
+
+// LE Long Term Key  Negative Reply (0x001B)
+type LELTKNegReply struct{ ConnectionHandle uint16 }
+
+func (c LELTKNegReply) Opcode() int      { return opLELTKNegReply }
+func (c LELTKNegReply) Len() int         { return 2 }
+func (c LELTKNegReply) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
+
+type LELTKNegReplyRP struct {
+	Status           uint8
+	ConnectionHandle uint16
+}
+
+// LE Read Supported States (0x001C)
+type LEReadSupportedStates struct{}
+
+func (c LEReadSupportedStates) Opcode() int      { return opLEReadSupportedStates }
+func (c LEReadSupportedStates) Len() int         { return 0 }
+func (c LEReadSupportedStates) Marshal(b []byte) {}
+
+type LEReadSupportedStatesRP struct {
+	Status   uint8
+	LEStates [8]byte
+}
+
+// LE Reciever Test (0x001D)
+type LEReceiverTest struct{ RxChannel uint8 }
+
+func (c LEReceiverTest) Opcode() int      { return opLEReceiverTest }
+func (c LEReceiverTest) Len() int         { return 1 }
+func (c LEReceiverTest) Marshal(b []byte) { b[0] = c.RxChannel }
+
+type LEReceiverTestRP struct{ Status uint8 }
+
+// LE Transmitter Test (0x001E)
+type LETransmitterTest struct {
+	TxChannel        uint8
+	LengthOfTestData uint8
+	PacketPayload    uint8
+}
+
+func (c LETransmitterTest) Opcode() int { return opLETransmitterTest }
+func (c LETransmitterTest) Len() int    { return 3 }
+func (c LETransmitterTest) Marshal(b []byte) {
+	b[0], b[1], b[2] = c.TxChannel, c.LengthOfTestData, c.PacketPayload
+}
+
+type LETransmitterTestRP struct{ Status uint8 }
+
+// LE Test End (0x001F)
+type LETestEnd struct{}
+
+func (c LETestEnd) Opcode() int      { return opLETestEnd }
+func (c LETestEnd) Len() int         { return 0 }
+func (c LETestEnd) Marshal(b []byte) {}
+
+type LETestEndRP struct {
+	Status          uint8
+	NumberOfPackets uint16
+}
+
+// LE Remote Connection Parameters Reply (0x0020)
+type LERemoteConnectionParameterReply struct {
+	ConnectionHandle uint16
+	IntervalMin      uint16
+	IntervalMax      uint16
+	Latency          uint16
+	Timeout          uint16
+	MinimumCELength  uint16
+	MaximumCELength  uint16
+}
+
+func (c LERemoteConnectionParameterReply) Opcode() int { return opLERemoteConnectionParameterReply }
+func (c LERemoteConnectionParameterReply) Len() int    { return 14 }
+func (c LERemoteConnectionParameterReply) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	o.PutUint16(b[2:], c.IntervalMin)
+	o.PutUint16(b[4:], c.IntervalMax)
+	o.PutUint16(b[6:], c.Latency)
+	o.PutUint16(b[8:], c.Timeout)
+	o.PutUint16(b[10:], c.MinimumCELength)
+	o.PutUint16(b[12:], c.MaximumCELength)
+}
+
+type LERemoteConnectionParameterReplyRP struct {
+	Status           uint8
+	ConnectionHandle uint16
+}
+
+// LE Remote Connection Parameters Negative Reply (0x0021)
+type LERemoteConnectionParameterNegReply struct {
+	ConnectionHandle uint16
+	Reason           uint8
+}
+
+func (c LERemoteConnectionParameterNegReply) Opcode() int {
+	return opLERemoteConnectionParameterNegReply
+}
+func (c LERemoteConnectionParameterNegReply) Len() int { return 3 }
+func (c LERemoteConnectionParameterNegReply) Marshal(b []byte) {
+	o.PutUint16(b[0:], c.ConnectionHandle)
+	b[2] = c.Reason
+}
+
+type LERemoteConnectionParameterNegReplyRP struct {
+	Status           uint8
+	ConnectionHandle uint16
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/const.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/const.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/const.go
new file mode 100644
index 0000000..8c0a140
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/const.go
@@ -0,0 +1,21 @@
+package linux
+
+type packetType uint8
+
+// HCI Packet types
+const (
+	typCommandPkt packetType = 0X01
+	typACLDataPkt            = 0X02
+	typSCODataPkt            = 0X03
+	typEventPkt              = 0X04
+	typVendorPkt             = 0XFF
+)
+
+// Event Type
+const (
+	advInd        = 0x00 // Connectable undirected advertising (ADV_IND).
+	advDirectInd  = 0x01 // Connectable directed advertising (ADV_DIRECT_IND)
+	advScanInd    = 0x02 // Scannable undirected advertising (ADV_SCAN_IND)
+	advNonconnInd = 0x03 // Non connectable undirected advertising (ADV_NONCONN_IND)
+	scanRsp       = 0x04 // Scan Response (SCAN_RSP)
+)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/device.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/device.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/device.go
new file mode 100644
index 0000000..402c5eb
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/device.go
@@ -0,0 +1,109 @@
+package linux
+
+import (
+	"errors"
+	"log"
+	"sync"
+	"syscall"
+	"unsafe"
+
+	"github.com/runtimeco/gatt/linux/gioctl"
+	"github.com/runtimeco/gatt/linux/socket"
+)
+
+type device struct {
+	fd   int
+	dev  int
+	name string
+	rmu  *sync.Mutex
+	wmu  *sync.Mutex
+}
+
+func newDevice(n int, chk bool) (*device, error) {
+	fd, err := socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)
+	if err != nil {
+		return nil, err
+	}
+	if n != -1 {
+		return newSocket(fd, n, chk)
+	}
+
+	req := devListRequest{devNum: hciMaxDevices}
+	if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceList, uintptr(unsafe.Pointer(&req))); err != nil {
+		return nil, err
+	}
+	for i := 0; i < int(req.devNum); i++ {
+		d, err := newSocket(fd, i, chk)
+		if err == nil {
+			log.Printf("dev: %s opened", d.name)
+			return d, err
+		}
+	}
+	return nil, errors.New("no supported devices available")
+}
+
+func newSocket(fd, n int, chk bool) (*device, error) {
+	i := hciDevInfo{id: uint16(n)}
+	if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceInfo, uintptr(unsafe.Pointer(&i))); err != nil {
+		return nil, err
+	}
+	name := string(i.name[:])
+	// Check the feature list returned feature list.
+	if chk && i.features[4]&0x40 == 0 {
+		err := errors.New("does not support LE")
+		log.Printf("dev: %s %s", name, err)
+		return nil, err
+	}
+	log.Printf("dev: %s up", name)
+	if err := gioctl.Ioctl(uintptr(fd), hciUpDevice, uintptr(n)); err != nil {
+		if err != syscall.EALREADY {
+			return nil, err
+		}
+		log.Printf("dev: %s reset", name)
+		if err := gioctl.Ioctl(uintptr(fd), hciResetDevice, uintptr(n)); err != nil {
+			return nil, err
+		}
+	}
+	log.Printf("dev: %s down", name)
+	if err := gioctl.Ioctl(uintptr(fd), hciDownDevice, uintptr(n)); err != nil {
+		return nil, err
+	}
+
+	// Attempt to use the linux 3.14 feature, if this fails with EINVAL fall back to raw access
+	// on older kernels.
+	sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_USER}
+	if err := socket.Bind(fd, &sa); err != nil {
+		if err != syscall.EINVAL {
+			return nil, err
+		}
+		log.Printf("dev: %s can't bind to hci user channel, err: %s.", name, err)
+		sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_RAW}
+		if err := socket.Bind(fd, &sa); err != nil {
+			log.Printf("dev: %s can't bind to hci raw channel, err: %s.", name, err)
+			return nil, err
+		}
+	}
+	return &device{
+		fd:   fd,
+		dev:  n,
+		name: name,
+		rmu:  &sync.Mutex{},
+		wmu:  &sync.Mutex{},
+	}, nil
+}
+
+func (d device) Read(b []byte) (int, error) {
+	d.rmu.Lock()
+	defer d.rmu.Unlock()
+	return syscall.Read(d.fd, b)
+}
+
+func (d device) Write(b []byte) (int, error) {
+	d.wmu.Lock()
+	defer d.wmu.Unlock()
+	return syscall.Write(d.fd, b)
+}
+
+func (d device) Close() error {
+	return syscall.Close(d.fd)
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/devices.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/devices.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/devices.go
new file mode 100644
index 0000000..1c9c13c
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/devices.go
@@ -0,0 +1,58 @@
+package linux
+
+import "github.com/runtimeco/gatt/linux/gioctl"
+
+const (
+	ioctlSize     = uintptr(4)
+	hciMaxDevices = 16
+	typHCI        = 72 // 'H'
+)
+
+var (
+	hciUpDevice      = gioctl.IoW(typHCI, 201, ioctlSize) // HCIDEVUP
+	hciDownDevice    = gioctl.IoW(typHCI, 202, ioctlSize) // HCIDEVDOWN
+	hciResetDevice   = gioctl.IoW(typHCI, 203, ioctlSize) // HCIDEVRESET
+	hciGetDeviceList = gioctl.IoR(typHCI, 210, ioctlSize) // HCIGETDEVLIST
+	hciGetDeviceInfo = gioctl.IoR(typHCI, 211, ioctlSize) // HCIGETDEVINFO
+)
+
+type devRequest struct {
+	id  uint16
+	opt uint32
+}
+
+type devListRequest struct {
+	devNum     uint16
+	devRequest [hciMaxDevices]devRequest
+}
+
+type hciDevInfo struct {
+	id         uint16
+	name       [8]byte
+	bdaddr     [6]byte
+	flags      uint32
+	devType    uint8
+	features   [8]uint8
+	pktType    uint32
+	linkPolicy uint32
+	linkMode   uint32
+	aclMtu     uint16
+	aclPkts    uint16
+	scoMtu     uint16
+	scoPkts    uint16
+
+	stats hciDevStats
+}
+
+type hciDevStats struct {
+	errRx  uint32
+	errTx  uint32
+	cmdTx  uint32
+	evtRx  uint32
+	aclTx  uint32
+	aclRx  uint32
+	scoTx  uint32
+	scoRx  uint32
+	byteRx uint32
+	byteTx uint32
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/doc.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/doc.go
new file mode 100644
index 0000000..c41c53e
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/doc.go
@@ -0,0 +1,5 @@
+// Package linux provides linux-specific support for gatt.
+//
+// This package is work in progress. We expect the APIs to change significantly before stabilizing.
+
+package linux

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/evt/evt.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/evt/evt.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/evt/evt.go
new file mode 100644
index 0000000..2981e51
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/evt/evt.go
@@ -0,0 +1,382 @@
+package evt
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+
+	"github.com/runtimeco/gatt/linux/util"
+)
+
+type EventHandler interface {
+	HandleEvent([]byte) error
+}
+
+type HandlerFunc func(b []byte) error
+
+func (f HandlerFunc) HandleEvent(b []byte) error {
+	return f(b)
+}
+
+type Evt struct {
+	evtHandlers map[int]EventHandler
+}
+
+func NewEvt() *Evt {
+	return &Evt{
+		evtHandlers: map[int]EventHandler{},
+	}
+}
+
+func (e *Evt) HandleEvent(c int, h EventHandler) {
+	e.evtHandlers[c] = h
+}
+
+func (e *Evt) Dispatch(b []byte) error {
+	h := &EventHeader{}
+	if err := h.Unmarshal(b); err != nil {
+		return err
+	}
+	b = b[2:] // Skip Event Header (uint8 + uint8)
+	if f, found := e.evtHandlers[h.code]; found {
+		e.trace("> HCI Event: %s (0x%02X) plen %d: [ % X ])\n", h.code, uint8(h.code), h.plen, b)
+		return f.HandleEvent(b)
+	}
+	e.trace("> HCI Event: no handler for %s (0x%02X)\n", h.code, uint8(h.code))
+	return nil
+}
+
+func (e *Evt) trace(fmt string, v ...interface{}) {}
+
+const (
+	InquiryComplete                              = 0x01 // Inquiry Complete
+	InquiryResult                                = 0x02 // Inquiry Result
+	ConnectionComplete                           = 0x03 // Connection Complete
+	ConnectionRequest                            = 0x04 // Connection Request
+	DisconnectionComplete                        = 0x05 // Disconnection Complete
+	AuthenticationComplete                       = 0x06 // Authentication
+	RemoteNameReqComplete                        = 0x07 // Remote Name Request Complete
+	EncryptionChange                             = 0x08 // Encryption Change
+	ChangeConnectionLinkKeyComplete              = 0x09 // Change Conection Link Key Complete
+	MasterLinkKeyComplete                        = 0x0A // Master Link Keye Complete
+	ReadRemoteSupportedFeaturesComplete          = 0x0B // Read Remote Supported Features Complete
+	ReadRemoteVersionInformationComplete         = 0x0C // Read Remote Version Information Complete
+	QoSSetupComplete                             = 0x0D // QoSSetupComplete
+	CommandComplete                              = 0x0E // Command Complete
+	CommandStatus                                = 0x0F // Command status
+	HardwareError                                = 0x10 // Hardware Error
+	FlushOccurred                                = 0x11 // Flush Occured
+	RoleChange                                   = 0x12 // Role Change
+	NumberOfCompletedPkts                        = 0x13 // Number Of Completed Packets
+	ModeChange                                   = 0x14 // Mode Change
+	ReturnLinkKeys                               = 0x15 // Return Link Keys
+	PinCodeRequest                               = 0x16 // PIN Code Request
+	LinkKeyRequest                               = 0x17 // Link Key Request
+	LinkKeyNotification                          = 0x18 // Link Key Notification
+	LoopbackCommand                              = 0x19 // Loopback Command
+	DataBufferOverflow                           = 0x1A // Data Buffer Overflow
+	MaxSlotsChange                               = 0x1B // Max Slots Change
+	ReadClockOffsetComplete                      = 0x1C // Read Clock Offset Complete
+	ConnectionPtypeChanged                       = 0x1D // Connection Packet Type Changed
+	QoSViolation                                 = 0x1E // QoS Violation
+	PageScanRepetitionModeChange                 = 0x20 // Page Scan Repetition Mode Change
+	FlowSpecificationComplete                    = 0x21 // Flow Specification
+	InquiryResultWithRssi                        = 0x22 // Inquery Result with RSSI
+	ReadRemoteExtendedFeaturesComplete           = 0x23 // Read Remote Extended Features Complete
+	SyncConnectionComplete                       = 0x2C // Synchronous Connection Complete
+	SyncConnectionChanged                        = 0x2D // Synchronous Connection Changed
+	SniffSubrating                               = 0x2E // Sniff Subrating
+	ExtendedInquiryResult                        = 0x2F // Extended Inquiry Result
+	EncryptionKeyRefreshComplete                 = 0x30 // Encryption Key Refresh Complete
+	IOCapabilityRequest                          = 0x31 // IO Capability Request
+	IOCapabilityResponse                         = 0x32 // IO Capability Changed
+	UserConfirmationRequest                      = 0x33 // User Confirmation Request
+	UserPasskeyRequest                           = 0x34 // User Passkey Request
+	RemoteOOBDataRequest                         = 0x35 // Remote OOB Data
+	SimplePairingComplete                        = 0x36 // Simple Pairing Complete
+	LinkSupervisionTimeoutChanged                = 0x38 // Link Supervision Timeout Changed
+	EnhancedFlushComplete                        = 0x39 // Enhanced Flush Complete
+	UserPasskeyNotify                            = 0x3B // User Passkey Notification
+	KeypressNotify                               = 0x3C // Keypass Notification
+	RemoteHostFeaturesNotify                     = 0x3D // Remote Host Supported Features Notification
+	LEMeta                                       = 0x3E // LE Meta
+	PhysicalLinkComplete                         = 0x40 // Physical Link Complete
+	ChannelSelected                              = 0x41 // Channel Selected
+	DisconnectionPhysicalLinkComplete            = 0x42 // Disconnection Physical Link Complete
+	PhysicalLinkLossEarlyWarning                 = 0x43 // Physical Link Loss Early Warning
+	PhysicalLinkRecovery                         = 0x44 // Physical Link Recovery
+	LogicalLinkComplete                          = 0x45 // Logical Link Complete
+	DisconnectionLogicalLinkComplete             = 0x46 // Disconnection Logical Link Complete
+	FlowSpecModifyComplete                       = 0x47 // Flow Spec Modify Complete
+	NumberOfCompletedBlocks                      = 0x48 // Number Of Completed Data Blocks
+	AMPStartTest                                 = 0x49 // AMP Start Test
+	AMPTestEnd                                   = 0x4A // AMP Test End
+	AMPReceiverReport                            = 0x4b // AMP Receiver Report
+	AMPStatusChange                              = 0x4D // AMP status Change
+	TriggeredClockCapture                        = 0x4e // Triggered Clock Capture
+	SynchronizationTrainComplete                 = 0x4F // Synchronization Train Complete
+	SynchronizationTrainReceived                 = 0x50 // Synchronization Train Received
+	ConnectionlessSlaveBroadcastReceive          = 0x51 // Connectionless Slave Broadcast Receive
+	ConnectionlessSlaveBroadcastTimeout          = 0x52 // Connectionless Slave Broadcast Timeout
+	TruncatedPageComplete                        = 0x53 // Truncated Page Complete
+	SlavePageResponseTimeout                     = 0x54 // Slave Page Response Timeout
+	ConnectionlessSlaveBroadcastChannelMapChange = 0x55 // Connectionless Slave Broadcast Channel Map Change
+	InquiryResponseNotification                  = 0x56 // Inquiry Response Notification
+	AuthenticatedPayloadTimeoutExpired           = 0x57 // Authenticated Payload Timeout Expired
+)
+
+type LEEventCode int
+
+const (
+	LEConnectionComplete               LEEventCode = 0x01 // LE Connection Complete
+	LEAdvertisingReport                            = 0x02 // LE Advertising Report
+	LEConnectionUpdateComplete                     = 0x03 // LE Connection Update Complete
+	LEReadRemoteUsedFeaturesComplete               = 0x04 // LE Read Remote Used Features Complete
+	LELTKRequest                                   = 0x05 // LE LTK Request
+	LERemoteConnectionParameterRequest             = 0x06 // LE Remote Connection Parameter Request
+)
+
+type EventHeader struct {
+	code int
+	plen uint8
+}
+
+func (h *EventHeader) Unmarshal(b []byte) error {
+	if len(b) < 2 {
+		return errors.New("malformed header")
+	}
+	h.code = int(b[0])
+	h.plen = b[1]
+	if uint8(len(b)) != 2+h.plen {
+		return errors.New("wrong length")
+	}
+	return nil
+}
+
+var o = util.Order
+
+// Event Parameters
+
+type InquiryCompleteEP struct {
+	Status uint8
+}
+
+type InquiryResultEP struct {
+	NumResponses           uint8
+	BDAddr                 [][6]byte
+	PageScanRepetitionMode []uint8
+	Reserved1              []byte
+	Reserved2              []byte
+	ClassOfDevice          [][3]byte
+	ClockOffset            []uint16
+}
+
+type ConnectionCompleteEP struct {
+	Status            uint8
+	ConnectionHandle  uint16
+	BDAddr            [6]byte
+	LinkType          uint8
+	EncryptionEnabled uint8
+}
+
+type ConnectionRequestEP struct {
+	BDAddr        [6]byte
+	ClassofDevice [3]byte
+	LinkType      uint8
+}
+
+type DisconnectionCompleteEP struct {
+	Status           uint8
+	ConnectionHandle uint16
+	Reason           uint8
+}
+
+func (e *DisconnectionCompleteEP) Unmarshal(b []byte) error {
+	buf := bytes.NewBuffer(b)
+	binary.Read(buf, binary.LittleEndian, &e.Status)
+	binary.Read(buf, binary.LittleEndian, &e.ConnectionHandle)
+	return binary.Read(buf, binary.LittleEndian, &e.Reason)
+}
+
+type CommandCompleteEP struct {
+	NumHCICommandPackets uint8
+	CommandOPCode        uint16
+	ReturnParameters     []byte
+}
+
+func (e *CommandCompleteEP) Unmarshal(b []byte) error {
+	buf := bytes.NewBuffer(b)
+	if err := binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets); err != nil {
+		return err
+	}
+	if err := binary.Read(buf, binary.LittleEndian, &e.CommandOPCode); err != nil {
+		return err
+	}
+	e.ReturnParameters = buf.Bytes()
+	return nil
+}
+
+type CommandStatusEP struct {
+	Status               uint8
+	NumHCICommandPackets uint8
+	CommandOpcode        uint16
+}
+
+func (e *CommandStatusEP) Unmarshal(b []byte) error {
+	buf := bytes.NewBuffer(b)
+	binary.Read(buf, binary.LittleEndian, &e.Status)
+	binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets)
+	return binary.Read(buf, binary.LittleEndian, &e.CommandOpcode)
+}
+
+type NumOfCompletedPkt struct {
+	ConnectionHandle   uint16
+	NumOfCompletedPkts uint16
+}
+
+type NumberOfCompletedPktsEP struct {
+	NumberOfHandles uint8
+	Packets         []NumOfCompletedPkt
+}
+
+func (e *NumberOfCompletedPktsEP) Unmarshal(b []byte) error {
+	e.NumberOfHandles = b[0]
+	n := int(e.NumberOfHandles)
+	buf := bytes.NewBuffer(b[1:])
+	e.Packets = make([]NumOfCompletedPkt, n)
+	for i := 0; i < n; i++ {
+		binary.Read(buf, binary.LittleEndian, &e.Packets[i].ConnectionHandle)
+		binary.Read(buf, binary.LittleEndian, &e.Packets[i].NumOfCompletedPkts)
+
+		e.Packets[i].ConnectionHandle &= 0xfff
+	}
+	return nil
+}
+
+// LE Meta Subevents
+type LEConnectionCompleteEP struct {
+	SubeventCode        uint8
+	Status              uint8
+	ConnectionHandle    uint16
+	Role                uint8
+	PeerAddressType     uint8
+	PeerAddress         [6]byte
+	ConnInterval        uint16
+	ConnLatency         uint16
+	SupervisionTimeout  uint16
+	MasterClockAccuracy uint8
+}
+
+func (e *LEConnectionCompleteEP) Unmarshal(b []byte) error {
+	e.SubeventCode = o.Uint8(b[0:])
+	e.Status = o.Uint8(b[1:])
+	e.ConnectionHandle = o.Uint16(b[2:])
+	e.Role = o.Uint8(b[4:])
+	e.PeerAddressType = o.Uint8(b[5:])
+	e.PeerAddress = o.MAC(b[6:])
+	e.ConnInterval = o.Uint16(b[12:])
+	e.ConnLatency = o.Uint16(b[14:])
+	e.SupervisionTimeout = o.Uint16(b[16:])
+	e.MasterClockAccuracy = o.Uint8(b[17:])
+	return nil
+}
+
+type LEAdvertisingReportEP struct {
+	SubeventCode uint8
+	NumReports   uint8
+	EventType    []uint8
+	AddressType  []uint8
+	Address      [][6]byte
+	Length       []uint8
+	Data         [][]byte
+	RSSI         []int8
+}
+
+func (e *LEAdvertisingReportEP) Unmarshal(b []byte) error {
+	e.SubeventCode = o.Uint8(b)
+	b = b[1:]
+	e.NumReports = o.Uint8(b)
+	b = b[1:]
+	n := int(e.NumReports)
+	e.EventType = make([]uint8, n)
+	e.AddressType = make([]uint8, n)
+	e.Address = make([][6]byte, n)
+	e.Length = make([]uint8, n)
+	e.Data = make([][]byte, n)
+	e.RSSI = make([]int8, n)
+
+	for i := 0; i < n; i++ {
+		e.EventType[i] = o.Uint8(b)
+		b = b[1:]
+	}
+	for i := 0; i < n; i++ {
+		e.AddressType[i] = o.Uint8(b)
+		b = b[1:]
+	}
+	for i := 0; i < n; i++ {
+		e.Address[i] = o.MAC(b)
+		b = b[6:]
+	}
+	for i := 0; i < n; i++ {
+		e.Length[i] = o.Uint8(b)
+		b = b[1:]
+	}
+	for i := 0; i < n; i++ {
+		e.Data[i] = make([]byte, e.Length[i])
+		copy(e.Data[i], b)
+		b = b[e.Length[i]:]
+	}
+	for i := 0; i < n; i++ {
+		e.RSSI[i] = o.Int8(b)
+		b = b[1:]
+	}
+	return nil
+}
+
+type LEConnectionUpdateCompleteEP struct {
+	SubeventCode       uint8
+	Status             uint8
+	ConnectionHandle   uint16
+	ConnInterval       uint16
+	ConnLatency        uint16
+	SupervisionTimeout uint16
+}
+
+func (e *LEConnectionUpdateCompleteEP) Unmarshal(b []byte) error {
+	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
+}
+
+type LEReadRemoteUsedFeaturesCompleteEP struct {
+	SubeventCode     uint8
+	Status           uint8
+	ConnectionHandle uint16
+	LEFeatures       uint64
+}
+
+func (e *LEReadRemoteUsedFeaturesCompleteEP) Unmarshal(b []byte) error {
+	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
+}
+
+type LELTKRequestEP struct {
+	SubeventCode          uint8
+	ConnectionHandle      uint16
+	RandomNumber          uint64
+	EncryptionDiversifier uint16
+}
+
+func (e *LELTKRequestEP) Unmarshal(b []byte) error {
+	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
+}
+
+type LERemoteConnectionParameterRequestEP struct {
+	SubeventCode     uint8
+	ConnectionHandle uint16
+	IntervalMin      uint16
+	IntervalMax      uint16
+	Latency          uint16
+	Timeout          uint16
+}
+
+func (e *LERemoteConnectionParameterRequestEP) Unmarshal(b []byte) error {
+	return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/LICENSE.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/LICENSE.md b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/LICENSE.md
new file mode 100644
index 0000000..1e1b7cd
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/LICENSE.md
@@ -0,0 +1,22 @@
+Copyright (c) 2012 Mark Wolfe
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/README.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/README.md b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/README.md
new file mode 100644
index 0000000..837fa03
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/README.md
@@ -0,0 +1,12 @@
+# gioctl [![GoDoc](https://img.shields.io/badge/godoc-Reference-brightgreen.svg?style=flat)](http://godoc.org/github.com/wolfeidau/gioctl)
+
+Simple library which provides golang versions of the ioctl macros in linux.
+
+# References
+
+* https://github.com/luismesas/goPi started with the IOCTL stuff from this project initally.
+* http://www.circlemud.org/jelson/software/fusd/docs/node31.html good information on IOCTL macros.
+
+# License
+
+This code is Copyright (c) 2014 Mark Wolfe and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/ioctl.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/ioctl.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/ioctl.go
new file mode 100644
index 0000000..0097459
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/gioctl/ioctl.go
@@ -0,0 +1,57 @@
+package gioctl
+
+import "syscall"
+
+const (
+	typeBits      = 8
+	numberBits    = 8
+	sizeBits      = 14
+	directionBits = 2
+
+	typeMask      = (1 << typeBits) - 1
+	numberMask    = (1 << numberBits) - 1
+	sizeMask      = (1 << sizeBits) - 1
+	directionMask = (1 << directionBits) - 1
+
+	directionNone  = 0
+	directionWrite = 1
+	directionRead  = 2
+
+	numberShift    = 0
+	typeShift      = numberShift + numberBits
+	sizeShift      = typeShift + typeBits
+	directionShift = sizeShift + sizeBits
+)
+
+func ioc(dir, t, nr, size uintptr) uintptr {
+	return (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)
+}
+
+// Io used for a simple ioctl that sends nothing but the type and number, and receives back nothing but an (integer) retval.
+func Io(t, nr uintptr) uintptr {
+	return ioc(directionNone, t, nr, 0)
+}
+
+// IoR used for an ioctl that reads data from the device driver. The driver will be allowed to return sizeof(data_type) bytes to the user.
+func IoR(t, nr, size uintptr) uintptr {
+	return ioc(directionRead, t, nr, size)
+}
+
+// IoW used for an ioctl that writes data to the device driver.
+func IoW(t, nr, size uintptr) uintptr {
+	return ioc(directionWrite, t, nr, size)
+}
+
+// IoRW  a combination of IoR and IoW. That is, data is both written to the driver and then read back from the driver by the client.
+func IoRW(t, nr, size uintptr) uintptr {
+	return ioc(directionRead|directionWrite, t, nr, size)
+}
+
+// Ioctl simplified ioct call
+func Ioctl(fd, op, arg uintptr) error {
+	_, _, ep := syscall.Syscall(syscall.SYS_IOCTL, fd, op, arg)
+	if ep != 0 {
+		return syscall.Errno(ep)
+	}
+	return nil
+}


[19/41] incubator-mynewt-newt git commit: MYNEWT-639 Add help text and check for pkg name 1) Update help text for "newt pkg new" to have package name input. 2) Error check that a package name is provided for the command. 3) Changed "libs/mylib" to "sys/m

Posted by ma...@apache.org.
MYNEWT-639 Add help text and check for pkg name
1) Update help text for "newt pkg new" to have package name input.
2) Error check that a package name is provided for the command.
3) Changed "libs/mylib" to "sys/mylib" in "newt pkg" help text to reflect latest source structure.
   (this change is not related to MYNEWT-639)
4) Added <package-name> argument to "newt pkg remove" Usage help text


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/f7f8ad81
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/f7f8ad81
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/f7f8ad81

Branch: refs/heads/mynewt_1_0_0
Commit: f7f8ad814e39ccad7169acbdde999fc421f7f9b8
Parents: 6493620
Author: cwanda <wa...@happycity.com>
Authored: Fri Feb 24 22:15:46 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:36:11 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/f7f8ad81/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 0ddde3d..d17e81f 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -37,6 +37,15 @@ import (
 var NewTypeStr = "pkg"
 
 func pkgNewCmd(cmd *cobra.Command, args []string) {
+
+	if len(args) == 0 {
+		NewtUsage(cmd, util.NewNewtError("Must specify a package name"))
+	}
+
+	if len(args) != 1 {
+		NewtUsage(cmd, util.NewNewtError("Exactly one argument required"))
+	}
+
 	NewTypeStr = strings.ToUpper(NewTypeStr)
 
 	pw := project.NewPackageWriter()
@@ -51,11 +60,11 @@ func pkgNewCmd(cmd *cobra.Command, args []string) {
 type dirOperation func(string, string) error
 
 func pkgCloneCmd(cmd *cobra.Command, args []string) {
-	pkgCloneOrMoveCmd(cmd, args, util.CopyDir, "Cloning");
+	pkgCloneOrMoveCmd(cmd, args, util.CopyDir, "Cloning")
 }
 
 func pkgMoveCmd(cmd *cobra.Command, args []string) {
-	pkgCloneOrMoveCmd(cmd, args, util.MoveDir, "Moving");
+	pkgCloneOrMoveCmd(cmd, args, util.MoveDir, "Moving")
 }
 
 func pkgCloneOrMoveCmd(cmd *cobra.Command, args []string, dirOpFn dirOperation, opStr string) {
@@ -207,7 +216,7 @@ func AddPackageCommands(cmd *cobra.Command) {
 	 * keyed
 	 */
 	pkgHelpText := "Commands for creating and manipulating packages"
-	pkgHelpEx := "  newt pkg new --type=pkg libs/mylib"
+	pkgHelpEx := "  newt pkg new --type=pkg sys/mylib"
 
 	pkgCmd := &cobra.Command{
 		Use:     "pkg",
@@ -226,8 +235,8 @@ func AddPackageCommands(cmd *cobra.Command) {
 	newCmdHelpEx := ""
 
 	newCmd := &cobra.Command{
-		Use:     "new",
-		Short:   "Create a new package, from a template",
+		Use:     "new <package-name>",
+		Short:   "Create a new package in the current directory, from a template",
 		Long:    newCmdHelpText,
 		Example: newCmdHelpEx,
 		Run:     pkgNewCmd,
@@ -268,7 +277,7 @@ func AddPackageCommands(cmd *cobra.Command) {
 	removeCmdHelpEx := ""
 
 	removeCmd := &cobra.Command{
-		Use:     "remove",
+		Use:     "remove <package-name>",
 		Short:   "Remove a package",
 		Long:    removeCmdHelpText,
 		Example: removeCmdHelpEx,


[30/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/hci.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/hci.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/hci.go
new file mode 100644
index 0000000..967680d
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/hci.go
@@ -0,0 +1,400 @@
+package linux
+
+import (
+	"fmt"
+	"io"
+	"log"
+	"sync"
+
+	"github.com/runtimeco/gatt/linux/cmd"
+	"github.com/runtimeco/gatt/linux/evt"
+)
+
+type HCI struct {
+	AcceptMasterHandler  func(pd *PlatData)
+	AcceptSlaveHandler   func(pd *PlatData)
+	AdvertisementHandler func(pd *PlatData)
+
+	d io.ReadWriteCloser
+	c *cmd.Cmd
+	e *evt.Evt
+
+	plist   map[bdaddr]*PlatData
+	plistmu *sync.Mutex
+
+	bufCnt  chan struct{}
+	bufSize int
+
+	maxConn int
+	connsmu *sync.Mutex
+	conns   map[uint16]*conn
+
+	adv   bool
+	advmu *sync.Mutex
+}
+
+type bdaddr [6]byte
+
+type PlatData struct {
+	Name        string
+	AddressType uint8
+	Address     [6]byte
+	Data        []byte
+	Connectable bool
+	RSSI        int8
+
+	Conn io.ReadWriteCloser
+}
+
+func NewHCI(devID int, chk bool, maxConn int) (*HCI, error) {
+	d, err := newDevice(devID, chk)
+	if err != nil {
+		return nil, err
+	}
+	c := cmd.NewCmd(d)
+	e := evt.NewEvt()
+
+	h := &HCI{
+		d: d,
+		c: c,
+		e: e,
+
+		plist:   make(map[bdaddr]*PlatData),
+		plistmu: &sync.Mutex{},
+
+		bufCnt:  make(chan struct{}, 15-1),
+		bufSize: 27,
+
+		maxConn: maxConn,
+		connsmu: &sync.Mutex{},
+		conns:   map[uint16]*conn{},
+
+		advmu: &sync.Mutex{},
+	}
+
+	e.HandleEvent(evt.LEMeta, evt.HandlerFunc(h.handleLEMeta))
+	e.HandleEvent(evt.DisconnectionComplete, evt.HandlerFunc(h.handleDisconnectionComplete))
+	e.HandleEvent(evt.NumberOfCompletedPkts, evt.HandlerFunc(h.handleNumberOfCompletedPkts))
+	e.HandleEvent(evt.CommandComplete, evt.HandlerFunc(c.HandleComplete))
+	e.HandleEvent(evt.CommandStatus, evt.HandlerFunc(c.HandleStatus))
+
+	go h.mainLoop()
+	h.resetDevice()
+	return h, nil
+}
+
+func (h *HCI) Close() error {
+	for _, c := range h.conns {
+		c.Close()
+	}
+	return h.d.Close()
+}
+
+func (h *HCI) SetAdvertiseEnable(en bool) error {
+	h.advmu.Lock()
+	h.adv = en
+	h.advmu.Unlock()
+	return h.setAdvertiseEnable(en)
+}
+
+func (h *HCI) setAdvertiseEnable(en bool) error {
+	h.advmu.Lock()
+	defer h.advmu.Unlock()
+	if en && h.adv && (len(h.conns) == h.maxConn) {
+		return nil
+	}
+	return h.c.SendAndCheckResp(
+		cmd.LESetAdvertiseEnable{
+			AdvertisingEnable: btoi(en),
+		}, []byte{0x00})
+}
+
+func (h *HCI) SendCmdWithAdvOff(c cmd.CmdParam) error {
+	h.setAdvertiseEnable(false)
+	err := h.c.SendAndCheckResp(c, nil)
+	if h.adv {
+		h.setAdvertiseEnable(true)
+	}
+	return err
+}
+
+func (h *HCI) SetScanEnable(en bool, dup bool) error {
+	return h.c.SendAndCheckResp(
+		cmd.LESetScanEnable{
+			LEScanEnable:     btoi(en),
+			FilterDuplicates: btoi(!dup),
+		}, []byte{0x00})
+}
+
+func (h *HCI) Connect(pd *PlatData) error {
+	h.c.Send(
+		cmd.LECreateConn{
+			LEScanInterval:        0x0004,         // N x 0.625ms
+			LEScanWindow:          0x0004,         // N x 0.625ms
+			InitiatorFilterPolicy: 0x00,           // white list not used
+			PeerAddressType:       pd.AddressType, // public or random
+			PeerAddress:           pd.Address,     //
+			OwnAddressType:        0x00,           // public
+			ConnIntervalMin:       6,         // N x 0.125ms
+			ConnIntervalMax:       7,         // N x 0.125ms
+			ConnLatency:           0x0000,         //
+			SupervisionTimeout:    0x00100,         // N x 10ms
+			MinimumCELength:       0x0000,         // N x 0.625ms
+			MaximumCELength:       0x0000,         // N x 0.625ms
+		})
+	return nil
+}
+
+func (h *HCI) CancelConnection(pd *PlatData) error {
+	return pd.Conn.Close()
+}
+
+func (h *HCI) SendRawCommand(c cmd.CmdParam) ([]byte, error) {
+	return h.c.Send(c)
+}
+
+func btoi(b bool) uint8 {
+	if b {
+		return 1
+	}
+	return 0
+}
+
+func (h *HCI) mainLoop() {
+	b := make([]byte, 4096)
+	for {
+		n, err := h.d.Read(b)
+		if err != nil {
+			return
+		}
+		if n == 0 {
+			return
+		}
+		p := make([]byte, n)
+		copy(p, b)
+		h.handlePacket(p)
+	}
+}
+
+func (h *HCI) handlePacket(b []byte) {
+	t, b := packetType(b[0]), b[1:]
+	var err error
+	switch t {
+	case typCommandPkt:
+		op := uint16(b[0]) | uint16(b[1])<<8
+		log.Printf("unmanaged cmd: opcode (%04x) [ % X ]\n", op, b)
+	case typACLDataPkt:
+		err = h.handleL2CAP(b)
+	case typSCODataPkt:
+		err = fmt.Errorf("SCO packet not supported")
+	case typEventPkt:
+		go func() {
+			err := h.e.Dispatch(b)
+			if err != nil {
+				log.Printf("hci: %s, [ % X]", err, b)
+			}
+		}()
+	case typVendorPkt:
+		err = fmt.Errorf("Vendor packet not supported")
+	default:
+		log.Fatalf("Unknown event: 0x%02X [ % X ]\n", t, b)
+	}
+	if err != nil {
+		log.Printf("hci: %s, [ % X]", err, b)
+	}
+}
+
+func (h *HCI) resetDevice() error {
+	seq := []cmd.CmdParam{
+		cmd.Reset{},
+		cmd.SetEventMask{EventMask: 0x3dbff807fffbffff},
+		cmd.LESetEventMask{LEEventMask: 0x000000000000001F},
+		cmd.WriteSimplePairingMode{SimplePairingMode: 1},
+		cmd.WriteLEHostSupported{LESupportedHost: 1, SimultaneousLEHost: 0},
+		cmd.WriteInquiryMode{InquiryMode: 2},
+		cmd.WritePageScanType{PageScanType: 1},
+		cmd.WriteInquiryScanType{ScanType: 1},
+		cmd.WriteClassOfDevice{ClassOfDevice: [3]byte{0x40, 0x02, 0x04}},
+		cmd.WritePageTimeout{PageTimeout: 0x2000},
+		cmd.WriteDefaultLinkPolicy{DefaultLinkPolicySettings: 0x5},
+		cmd.HostBufferSize{
+			HostACLDataPacketLength:            0x1000,
+			HostSynchronousDataPacketLength:    0xff,
+			HostTotalNumACLDataPackets:         0x0014,
+			HostTotalNumSynchronousDataPackets: 0x000a},
+		cmd.LESetScanParameters{
+			LEScanType:           0x01,   // [0x00]: passive, 0x01: active
+			LEScanInterval:       0x0010, // [0x10]: 0.625ms * 16
+			LEScanWindow:         0x0010, // [0x10]: 0.625ms * 16
+			OwnAddressType:       0x00,   // [0x00]: public, 0x01: random
+			ScanningFilterPolicy: 0x00,   // [0x00]: accept all, 0x01: ignore non-white-listed.
+		},
+	}
+	for _, s := range seq {
+		if err := h.c.SendAndCheckResp(s, []byte{0x00}); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func (h *HCI) handleAdvertisement(b []byte) {
+	// If no one is interested, don't bother.
+	if h.AdvertisementHandler == nil {
+		return
+	}
+	ep := &evt.LEAdvertisingReportEP{}
+	if err := ep.Unmarshal(b); err != nil {
+		return
+	}
+	for i := 0; i < int(ep.NumReports); i++ {
+		addr := bdaddr(ep.Address[i])
+		et := ep.EventType[i]
+		connectable := et == advInd || et == advDirectInd
+		scannable := et == advInd || et == advScanInd
+
+		if et == scanRsp {
+			h.plistmu.Lock()
+			pd, ok := h.plist[addr]
+			h.plistmu.Unlock()
+			if ok {
+				pd.Data = append(pd.Data, ep.Data[i]...)
+				h.AdvertisementHandler(pd)
+			}
+			continue
+		}
+
+		pd := &PlatData{
+			AddressType: ep.AddressType[i],
+			Address:     ep.Address[i],
+			Data:        ep.Data[i],
+			Connectable: connectable,
+			RSSI:        ep.RSSI[i],
+		}
+		h.plistmu.Lock()
+		h.plist[addr] = pd
+		h.plistmu.Unlock()
+		if scannable {
+			continue
+		}
+		h.AdvertisementHandler(pd)
+	}
+}
+
+func (h *HCI) handleNumberOfCompletedPkts(b []byte) error {
+	ep := &evt.NumberOfCompletedPktsEP{}
+	if err := ep.Unmarshal(b); err != nil {
+		return err
+	}
+	for _, r := range ep.Packets {
+		for i := 0; i < int(r.NumOfCompletedPkts); i++ {
+			<-h.bufCnt
+		}
+	}
+	return nil
+}
+
+func (h *HCI) handleConnection(b []byte) {
+	ep := &evt.LEConnectionCompleteEP{}
+	if err := ep.Unmarshal(b); err != nil {
+		return // FIXME
+	}
+	hh := ep.ConnectionHandle
+	c := newConn(h, hh)
+	h.connsmu.Lock()
+	h.conns[hh] = c
+	h.connsmu.Unlock()
+	h.setAdvertiseEnable(true)
+
+	// FIXME: sloppiness. This call should be called by the package user once we
+	// flesh out the support of l2cap signaling packets (CID:0x0001,0x0005)
+	if ep.ConnLatency != 0 || ep.ConnInterval > 0x18 {
+		c.updateConnection()
+	}
+
+	// master connection
+	if ep.Role == 0x01 {
+		pd := &PlatData{
+			Address: ep.PeerAddress,
+			Conn:    c,
+		}
+		h.AcceptMasterHandler(pd)
+		return
+	}
+	h.plistmu.Lock()
+	pd := h.plist[ep.PeerAddress]
+	h.plistmu.Unlock()
+	pd.Conn = c
+	h.AcceptSlaveHandler(pd)
+}
+
+func (h *HCI) handleDisconnectionComplete(b []byte) error {
+	ep := &evt.DisconnectionCompleteEP{}
+	if err := ep.Unmarshal(b); err != nil {
+		return err
+	}
+	hh := ep.ConnectionHandle
+	h.connsmu.Lock()
+	defer h.connsmu.Unlock()
+	c, found := h.conns[hh]
+	if !found {
+		// should not happen, just be cautious for now.
+		log.Printf("l2conn: disconnecting a disconnected 0x%04X connection", hh)
+		return nil
+	}
+	delete(h.conns, hh)
+	close(c.aclc)
+	h.setAdvertiseEnable(true)
+	return nil
+}
+
+func (h *HCI) handleLEMeta(b []byte) error {
+	code := evt.LEEventCode(b[0])
+	switch code {
+	case evt.LEConnectionComplete:
+		go h.handleConnection(b)
+	case evt.LEConnectionUpdateComplete:
+		// anything to do here?
+	case evt.LEAdvertisingReport:
+		go h.handleAdvertisement(b)
+	// case evt.LEReadRemoteUsedFeaturesComplete:
+	// case evt.LELTKRequest:
+	// case evt.LERemoteConnectionParameterRequest:
+	default:
+		return fmt.Errorf("Unhandled LE event: %s, [ % X ]", code, b)
+	}
+	return nil
+}
+
+func (h *HCI) handleL2CAP(b []byte) error {
+        a := &aclData{}
+	if err := a.unmarshal(b); err != nil {
+		return err
+	}
+	h.connsmu.Lock()
+	defer h.connsmu.Unlock()
+	c, found := h.conns[a.attr]
+
+        if a.flags != 0x002 {
+	    if !found {
+		    // should not happen, just be cautious for now.
+		    log.Printf("l2conn: got data for disconnected handle: 0x%04x", a.attr)
+		    return nil
+	        if len(a.b) < 4 {
+		    log.Printf("l2conn: l2cap packet is too short/corrupt, length is %d", len(a.b))
+		    return nil
+	        }
+	        cid := uint16(a.b[2]) | (uint16(a.b[3]) << 8)
+	        if cid == 5 {
+		    c.handleSignal(a)
+		    return nil
+	        }
+            }
+        }
+	c.aclc <- a
+	return nil
+}
+
+func (h *HCI) trace(fmt string, v ...interface{}) {
+	log.Printf(fmt, v)
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/l2cap.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/l2cap.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/l2cap.go
new file mode 100644
index 0000000..daca82f
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/l2cap.go
@@ -0,0 +1,174 @@
+package linux
+
+import (
+	"fmt"
+	"io"
+	"log"
+
+	"github.com/runtimeco/gatt/linux/cmd"
+)
+
+type aclData struct {
+	attr  uint16
+	flags uint8
+	dlen  uint16
+	b     []byte
+}
+
+func (a *aclData) unmarshal(b []byte) error {
+	if len(b) < 4 {
+		return fmt.Errorf("malformed acl packet")
+	}
+	attr := uint16(b[0]) | (uint16(b[1]&0x0f) << 8)
+	flags := b[1] >> 4
+	dlen := uint16(b[2]) | (uint16(b[3]) << 8)
+	if len(b) != 4+int(dlen) {
+		return fmt.Errorf("malformed acl packet")
+	}
+
+	*a = aclData{attr: attr, flags: flags, dlen: dlen, b: b[4:]}
+	return nil
+}
+
+type conn struct {
+	hci  *HCI
+	attr uint16
+	aclc chan *aclData
+}
+
+func newConn(hci *HCI, hh uint16) *conn {
+	return &conn{
+		hci:  hci,
+		attr: hh,
+		aclc: make(chan *aclData),
+	}
+}
+
+func (c *conn) updateConnection() (int, error) {
+	b := []byte{
+		0x12,       // Code (Connection Param Update)
+		0x02,       // ID
+		0x08, 0x00, // DataLength
+		0x08, 0x00, // IntervalMin
+		0x18, 0x00, // IntervalMax
+		0x00, 0x00, // SlaveLatency
+		0xC8, 0x00} // TimeoutMultiplier
+	return c.write(0x05, b)
+}
+
+// write writes the l2cap payload to the controller.
+// It first prepend the l2cap header (4-bytes), and diassemble the payload
+// if it is larger than the HCI LE buffer size that the conntroller can support.
+func (c *conn) write(cid int, b []byte) (int, error) {
+	flag := uint8(0) // ACL data continuation flag
+	tlen := len(b)   // Total length of the l2cap payload
+
+	// log.Printf("W: [ % X ]", b)
+	w := append(
+		[]byte{
+			0,    // packet type
+			0, 0, // attr
+			0, 0, // dlen
+			uint8(tlen), uint8(tlen >> 8), // l2cap header
+			uint8(cid), uint8(cid >> 8), // l2cap header
+		}, b...)
+
+	n := 4 + tlen // l2cap header + l2cap payload
+	for n > 0 {
+		dlen := n
+		if dlen > c.hci.bufSize {
+			dlen = c.hci.bufSize
+		}
+		w[0] = 0x02 // packetTypeACL
+		w[1] = uint8(c.attr)
+		w[2] = uint8(c.attr>>8) | flag
+		w[3] = uint8(dlen)
+		w[4] = uint8(dlen >> 8)
+
+		// make sure we don't send more buffers than the controller can handdle
+		c.hci.bufCnt <- struct{}{}
+
+		c.hci.d.Write(w[:5+dlen])
+		w = w[dlen:] // advance the pointer to the next segment, if any.
+		flag = 0x10  // the rest of iterations attr continued segments, if any.
+		n -= dlen
+	}
+
+	return len(b), nil
+}
+
+func (c *conn) Read(b []byte) (int, error) {
+	a, ok := <-c.aclc
+	if !ok {
+		return 0, io.EOF
+	}
+	tlen := int(uint16(a.b[0]) | uint16(a.b[1])<<8)
+	if tlen > len(b) {
+		return 0, io.ErrShortBuffer
+	}
+	d := a.b[4:] // skip l2cap header
+	copy(b, d)
+	n := len(d)
+
+	// Keep receiving and reassemble continued l2cap segments
+	for n != tlen {
+		if a, ok = <-c.aclc; !ok || (a.flags&0x1) == 0 {
+			return n, io.ErrUnexpectedEOF
+		}
+		copy(b[n:], a.b)
+		n += len(a.b)
+	}
+	// log.Printf("R: [ % X ]", b[:n])
+	return n, nil
+}
+
+func (c *conn) Write(b []byte) (int, error) {
+	return c.write(0x04, b)
+}
+
+// Close disconnects the connection by sending HCI disconnect command to the device.
+func (c *conn) Close() error {
+	h := c.hci
+	hh := c.attr
+	h.connsmu.Lock()
+	defer h.connsmu.Unlock()
+	_, found := h.conns[hh]
+	if !found {
+		// log.Printf("l2conn: 0x%04x already disconnected", hh)
+		return nil
+	}
+	if err, _ := h.c.Send(cmd.Disconnect{ConnectionHandle: hh, Reason: 0x13}); err != nil {
+		return fmt.Errorf("l2conn: failed to disconnect, %s", err)
+	}
+	return nil
+}
+
+// Signal Packets
+// 0x00 Reserved								Any
+// 0x01 Command reject							0x0001 and 0x0005
+// 0x02 Connection request						0x0001
+// 0x03 Connection response 					0x0001
+// 0x04 Configure request						0x0001
+// 0x05 Configure response						0x0001
+// 0x06 Disconnection request					0x0001 and 0x0005
+// 0x07 Disconnection response					0x0001 and 0x0005
+// 0x08 Echo request							0x0001
+// 0x09 Echo response							0x0001
+// 0x0A Information request						0x0001
+// 0x0B Information response					0x0001
+// 0x0C Create Channel request					0x0001
+// 0x0D Create Channel response					0x0001
+// 0x0E Move Channel request					0x0001
+// 0x0F Move Channel response					0x0001
+// 0x10 Move Channel Confirmation				0x0001
+// 0x11 Move Channel Confirmation response		0x0001
+// 0x12 Connection Parameter Update request		0x0005
+// 0x13 Connection Parameter Update response	0x0005
+// 0x14 LE Credit Based Connection request		0x0005
+// 0x15 LE Credit Based Connection response		0x0005
+// 0x16 LE Flow Control Credit					0x0005
+func (c *conn) handleSignal(a *aclData) error {
+	log.Printf("ignore l2cap signal:[ % X ]", a.b)
+	// FIXME: handle LE signaling channel (CID: 5)
+	return nil
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm.s
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm.s b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm.s
new file mode 100644
index 0000000..d4ca868
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm.s
@@ -0,0 +1,8 @@
+// Copyright 2014 The Go Authors.  All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "textflag.h"
+
+TEXT �use(SB),NOSPLIT,$0
+	RET

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm_linux_386.s
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm_linux_386.s b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm_linux_386.s
new file mode 100644
index 0000000..5d3ad9a
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/asm_linux_386.s
@@ -0,0 +1,33 @@
+// Copyright 2009 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+#include "textflag.h"
+
+//
+// System calls for 386, Linux
+//
+
+// Just jump to package syscall's implementation for all these functions.
+// The runtime may know about them.
+
+TEXT	�Syscall(SB),NOSPLIT,$0-28
+	JMP	syscall�Syscall(SB)
+
+TEXT	�Syscall6(SB),NOSPLIT,$0-40
+	JMP	syscall�Syscall6(SB)
+
+TEXT �RawSyscall(SB),NOSPLIT,$0-28
+	JMP	syscall�RawSyscall(SB)
+
+TEXT	�RawSyscall6(SB),NOSPLIT,$0-40
+	JMP	syscall�RawSyscall6(SB)
+
+TEXT �socketcall(SB),NOSPLIT,$0-36
+	JMP	syscall�socketcall(SB)
+
+TEXT �rawsocketcall(SB),NOSPLIT,$0-36
+	JMP	syscall�rawsocketcall(SB)
+
+TEXT �seek(SB),NOSPLIT,$0-28
+	JMP	syscall�seek(SB)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket.go
new file mode 100644
index 0000000..ffc49a6
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket.go
@@ -0,0 +1,121 @@
+// Package socket implements a minimal set of function of the HCI Socket,
+// which is not yet supported by the Go standard library. Most of the code
+// follow suit the existing code in the standard library. Once it gets
+// supported officially, we can get rid of this package entirely.
+
+package socket
+
+import (
+	"errors"
+	"syscall"
+	"time"
+	"unsafe"
+)
+
+// Bluetooth Protocols
+const (
+	BTPROTO_L2CAP  = 0
+	BTPROTO_HCI    = 1
+	BTPROTO_SCO    = 2
+	BTPROTO_RFCOMM = 3
+	BTPROTO_BNEP   = 4
+	BTPROTO_CMTP   = 5
+	BTPROTO_HIDP   = 6
+	BTPROTO_AVDTP  = 7
+)
+
+const (
+	HCI_CHANNEL_RAW     = 0
+	HCI_CHANNEL_USER    = 1
+	HCI_CHANNEL_MONITOR = 2
+	HCI_CHANNEL_CONTROL = 3
+)
+
+var (
+	ErrSocketOpenFailed  = errors.New("unable to open bluetooth socket to device")
+	ErrSocketBindTimeout = errors.New("timeout occured binding to bluetooth device")
+)
+
+type _Socklen uint32
+
+type Sockaddr interface {
+	sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
+}
+
+type rawSockaddrHCI struct {
+	Family  uint16
+	Dev     uint16
+	Channel uint16
+}
+
+type SockaddrHCI struct {
+	Dev     int
+	Channel uint16
+	raw     rawSockaddrHCI
+}
+
+const sizeofSockaddrHCI = unsafe.Sizeof(rawSockaddrHCI{})
+
+func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
+	if sa.Dev < 0 || sa.Dev > 0xFFFF {
+		return nil, 0, syscall.EINVAL
+	}
+	if sa.Channel < 0 || sa.Channel > 0xFFFF {
+		return nil, 0, syscall.EINVAL
+	}
+	sa.raw.Family = AF_BLUETOOTH
+	sa.raw.Dev = uint16(sa.Dev)
+	sa.raw.Channel = sa.Channel
+	return unsafe.Pointer(&sa.raw), _Socklen(sizeofSockaddrHCI), nil
+}
+
+func Socket(domain, typ, proto int) (int, error) {
+	for i := 0; i < 5; i++ {
+		if fd, err := syscall.Socket(domain, typ, proto); err == nil || err != syscall.EBUSY {
+			return fd, err
+		}
+		time.Sleep(time.Second)
+	}
+	return 0, ErrSocketOpenFailed
+}
+
+func Bind(fd int, sa Sockaddr) (err error) {
+	ptr, n, err := sa.sockaddr()
+	if err != nil {
+		return err
+	}
+	for i := 0; i < 5; i++ {
+		if err = bind(fd, ptr, n); err == nil || err != syscall.EBUSY {
+			return err
+		}
+		time.Sleep(time.Second)
+	}
+	return ErrSocketBindTimeout
+}
+
+// Socket Level
+const (
+	SOL_HCI    = 0
+	SOL_L2CAP  = 6
+	SOL_SCO    = 17
+	SOL_RFCOMM = 18
+
+	SOL_BLUETOOTH = 274
+)
+
+// HCI Socket options
+const (
+	HCI_DATA_DIR   = 1
+	HCI_FILTER     = 2
+	HCI_TIME_STAMP = 3
+)
+
+type HCIFilter struct {
+	TypeMask  uint32
+	EventMask [2]uint32
+	opcode    uint16
+}
+
+func SetsockoptFilter(fd int, f *HCIFilter) (err error) {
+	return setsockopt(fd, SOL_HCI, HCI_FILTER, unsafe.Pointer(f), unsafe.Sizeof(*f))
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_common.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_common.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_common.go
new file mode 100644
index 0000000..b01ceeb
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_common.go
@@ -0,0 +1,24 @@
+// +build !386
+
+package socket
+
+import (
+	"syscall"
+	"unsafe"
+)
+
+func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+	_, _, e1 := syscall.Syscall(syscall.SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
+	if e1 != 0 {
+		err = e1
+	}
+	return
+}
+
+func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
+	_, _, e1 := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
+	if e1 != 0 {
+		err = e1
+	}
+	return
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_darwin.go
new file mode 100644
index 0000000..abb96a5
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_darwin.go
@@ -0,0 +1,6 @@
+// +build darwin
+
+package socket
+
+// For compile time compatibility
+const AF_BLUETOOTH = 0

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux.go
new file mode 100644
index 0000000..4793915
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux.go
@@ -0,0 +1,7 @@
+// +build linux
+
+package socket
+
+import "syscall"
+
+const AF_BLUETOOTH = syscall.AF_BLUETOOTH

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux_386.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux_386.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux_386.go
new file mode 100644
index 0000000..05ca65c
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/socket/socket_linux_386.go
@@ -0,0 +1,31 @@
+// +build linux,386
+
+package socket
+
+import (
+	"syscall"
+	"unsafe"
+)
+
+const (
+	BIND         = 2
+	SETSOCKETOPT = 14
+)
+
+func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
+	_, e1 := socketcall(BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
+	if e1 != 0 {
+		err = e1
+	}
+	return
+}
+
+func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
+	_, e1 := socketcall(SETSOCKETOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0)
+	if e1 != 0 {
+		err = e1
+	}
+	return
+}
+
+func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/linux/util/util.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/linux/util/util.go b/newtmgr/vendor/github.com/runtimeco/gatt/linux/util/util.go
new file mode 100644
index 0000000..4933008
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/linux/util/util.go
@@ -0,0 +1,16 @@
+package util
+
+import "encoding/binary"
+
+type order struct{ binary.ByteOrder }
+
+var Order = order{binary.LittleEndian}
+
+func (o order) Int8(b []byte) int8   { return int8(b[0]) }
+func (o order) Uint8(b []byte) uint8 { return b[0] }
+func (o order) MAC(b []byte) [6]byte { return [6]byte{b[5], b[4], b[3], b[2], b[1], b[0]} }
+
+func (o order) PutUint8(b []byte, v uint8) { b[0] = v }
+func (o order) PutMAC(b []byte, m [6]byte) {
+	b[0], b[1], b[2], b[3], b[4], b[5] = m[5], m[4], m[3], m[2], m[1], m[0]
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/option_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/option_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/option_darwin.go
new file mode 100644
index 0000000..617db21
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/option_darwin.go
@@ -0,0 +1,15 @@
+package gatt
+
+const (
+	CentralManager    = 0 // Client functions (default)
+	PeripheralManager = 1 // Server functions
+)
+
+// MacDeviceRole specify the XPC connection type to connect blued.
+// THis option can only be used with NewDevice on OS X implementation.
+func MacDeviceRole(r int) Option {
+	return func(d Device) error {
+		d.(*device).role = r
+		return nil
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/option_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/option_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/option_linux.go
new file mode 100644
index 0000000..bf2360c
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/option_linux.go
@@ -0,0 +1,87 @@
+package gatt
+
+import (
+	"errors"
+	"io"
+
+	"github.com/runtimeco/gatt/linux/cmd"
+)
+
+// LnxDeviceID specifies which HCI device to use.
+// If n is set to -1, all the available HCI devices will be probed.
+// If chk is set to true, LnxDeviceID checks the LE support in the feature list of the HCI device.
+// This is to filter devices that does not support LE. In case some LE driver that doesn't correctly
+// set the LE support in its feature list, user can turn off the check.
+// This option can only be used with NewDevice on Linux implementation.
+func LnxDeviceID(n int, chk bool) Option {
+	return func(d Device) error {
+		d.(*device).devID = n
+		d.(*device).chkLE = chk
+		return nil
+	}
+}
+
+// LnxMaxConnections is an optional parameter.
+// If set, it overrides the default max connections supported.
+// This option can only be used with NewDevice on Linux implementation.
+func LnxMaxConnections(n int) Option {
+	return func(d Device) error {
+		d.(*device).maxConn = n
+		return nil
+	}
+}
+
+// LnxSetAdvertisingEnable sets the advertising data to the HCI device.
+// This option can be used with Option on Linux implementation.
+func LnxSetAdvertisingEnable(en bool) Option {
+	return func(d Device) error {
+		dd := d.(*device)
+		if dd == nil {
+			return errors.New("device is not initialized")
+		}
+		if err := dd.update(); err != nil {
+			return err
+		}
+		return dd.hci.SetAdvertiseEnable(en)
+	}
+}
+
+// LnxSetAdvertisingData sets the advertising data to the HCI device.
+// This option can be used with NewDevice or Option on Linux implementation.
+func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option {
+	return func(d Device) error {
+		d.(*device).advData = c
+		return nil
+	}
+}
+
+// LnxSetScanResponseData sets the scan response data to the HXI device.
+// This option can be used with NewDevice or Option on Linux implementation.
+func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option {
+	return func(d Device) error {
+		d.(*device).scanResp = c
+		return nil
+	}
+}
+
+// LnxSetAdvertisingParameters sets the advertising parameters to the HCI device.
+// This option can be used with NewDevice or Option on Linux implementation.
+func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option {
+	return func(d Device) error {
+		d.(*device).advParam = c
+		return nil
+	}
+}
+
+// LnxSendHCIRawCommand sends a raw command to the HCI device
+// This option can be used with NewDevice or Option on Linux implementation.
+func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option {
+	return func(d Device) error {
+		b, err := d.(*device).SendHCIRawCommand(c)
+		if rsp == nil {
+			return err
+		}
+		rsp.Write(b)
+		return err
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/peripheral.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/peripheral.go b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral.go
new file mode 100644
index 0000000..36ad578
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral.go
@@ -0,0 +1,102 @@
+package gatt
+
+import (
+	"errors"
+	"sync"
+)
+
+// Peripheral is the interface that represent a remote peripheral device.
+type Peripheral interface {
+	// Device returns the underlying device.
+	Device() Device
+
+	// ID is the platform specific unique ID of the remote peripheral, e.g. MAC for Linux, Peripheral UUID for MacOS.
+	ID() string
+
+	// Name returns the name of the remote peripheral.
+	// This can be the advertised name, if exists, or the GAP device name, which takes priority
+	Name() string
+
+	// Services returnns the services of the remote peripheral which has been discovered.
+	Services() []*Service
+
+	// DiscoverServices discover the specified services of the remote peripheral.
+	// If the specified services is set to nil, all the available services of the remote peripheral are returned.
+	DiscoverServices(s []UUID) ([]*Service, error)
+
+	// DiscoverIncludedServices discovers the specified included services of a service.
+	// If the specified services is set to nil, all the included services of the service are returned.
+	DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error)
+
+	// DiscoverCharacteristics discovers the specified characteristics of a service.
+	// If the specified characterstics is set to nil, all the characteristic of the service are returned.
+	DiscoverCharacteristics(c []UUID, s *Service) ([]*Characteristic, error)
+
+	// DiscoverDescriptors discovers the descriptors of a characteristic.
+	// If the specified descriptors is set to nil, all the descriptors of the characteristic are returned.
+	DiscoverDescriptors(d []UUID, c *Characteristic) ([]*Descriptor, error)
+
+	// ReadCharacteristic retrieves the value of a specified characteristic.
+	ReadCharacteristic(c *Characteristic) ([]byte, error)
+
+	// ReadLongCharacteristic retrieves the value of a specified characteristic that is longer than the
+	// MTU.
+	ReadLongCharacteristic(c *Characteristic) ([]byte, error)
+
+	// ReadDescriptor retrieves the value of a specified characteristic descriptor.
+	ReadDescriptor(d *Descriptor) ([]byte, error)
+
+	// WriteCharacteristic writes the value of a characteristic.
+	WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error
+
+	// WriteDescriptor writes the value of a characteristic descriptor.
+	WriteDescriptor(d *Descriptor, b []byte) error
+
+	// SetNotifyValue sets notifications for the value of a specified characteristic.
+	SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
+
+	// SetIndicateValue sets indications for the value of a specified characteristic.
+	SetIndicateValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
+
+	// ReadRSSI retrieves the current RSSI value for the remote peripheral.
+	ReadRSSI() int
+
+	// SetMTU sets the mtu for the remote peripheral.
+	SetMTU(mtu uint16) error
+}
+
+type subscriber struct {
+	sub map[uint16]subscribefn
+	mu  *sync.Mutex
+}
+
+type subscribefn func([]byte, error)
+
+func newSubscriber() *subscriber {
+	return &subscriber{
+		sub: make(map[uint16]subscribefn),
+		mu:  &sync.Mutex{},
+	}
+}
+
+func (s *subscriber) subscribe(h uint16, f subscribefn) {
+	s.mu.Lock()
+	s.sub[h] = f
+	s.mu.Unlock()
+}
+
+func (s *subscriber) unsubscribe(h uint16) {
+	s.mu.Lock()
+	delete(s.sub, h)
+	s.mu.Unlock()
+}
+
+func (s *subscriber) fn(h uint16) subscribefn {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	return s.sub[h]
+}
+
+var (
+	ErrInvalidLength = errors.New("invalid length")
+)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_darwin.go
new file mode 100644
index 0000000..9174e61
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_darwin.go
@@ -0,0 +1,277 @@
+package gatt
+
+import (
+	"errors"
+	"log"
+
+	"github.com/runtimeco/gatt/xpc"
+)
+
+type peripheral struct {
+	// NameChanged is called whenever the peripheral GAP Device name has changed.
+	NameChanged func(Peripheral)
+
+	// ServicesModified is called when one or more service of a peripheral have changed.
+	// A list of invalid service is provided in the parameter.
+	ServicesModified func(Peripheral, []*Service)
+
+	d    *device
+	svcs []*Service
+
+	sub *subscriber
+
+	id   xpc.UUID
+	name string
+
+	reqc  chan message
+	rspc  chan message
+	quitc chan struct{}
+}
+
+func NewPeripheral(u UUID) Peripheral { return &peripheral{id: xpc.UUID(u.b)} }
+
+func (p *peripheral) Device() Device       { return p.d }
+func (p *peripheral) ID() string           { return p.id.String() }
+func (p *peripheral) Name() string         { return p.name }
+func (p *peripheral) Services() []*Service { return p.svcs }
+
+func (p *peripheral) DiscoverServices(ss []UUID) ([]*Service, error) {
+	rsp := p.sendReq(45, xpc.Dict{
+		"kCBMsgArgDeviceUUID": p.id,
+		"kCBMsgArgUUIDs":      uuidSlice(ss),
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return nil, attEcode(res)
+	}
+	svcs := []*Service{}
+	for _, xss := range rsp["kCBMsgArgServices"].(xpc.Array) {
+		xs := xss.(xpc.Dict)
+		u := MustParseUUID(xs.MustGetHexBytes("kCBMsgArgUUID"))
+		h := uint16(xs.MustGetInt("kCBMsgArgServiceStartHandle"))
+		endh := uint16(xs.MustGetInt("kCBMsgArgServiceEndHandle"))
+		svcs = append(svcs, &Service{uuid: u, h: h, endh: endh})
+	}
+	p.svcs = svcs
+	return svcs, nil
+}
+
+func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
+	rsp := p.sendReq(60, xpc.Dict{
+		"kCBMsgArgDeviceUUID":         p.id,
+		"kCBMsgArgServiceStartHandle": s.h,
+		"kCBMsgArgServiceEndHandle":   s.endh,
+		"kCBMsgArgUUIDs":              uuidSlice(ss),
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return nil, attEcode(res)
+	}
+	// TODO
+	return nil, notImplemented
+}
+
+func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
+	rsp := p.sendReq(62, xpc.Dict{
+		"kCBMsgArgDeviceUUID":         p.id,
+		"kCBMsgArgServiceStartHandle": s.h,
+		"kCBMsgArgServiceEndHandle":   s.endh,
+		"kCBMsgArgUUIDs":              uuidSlice(cs),
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return nil, attEcode(res)
+	}
+	for _, xcs := range rsp.MustGetArray("kCBMsgArgCharacteristics") {
+		xc := xcs.(xpc.Dict)
+		u := MustParseUUID(xc.MustGetHexBytes("kCBMsgArgUUID"))
+		ch := uint16(xc.MustGetInt("kCBMsgArgCharacteristicHandle"))
+		vh := uint16(xc.MustGetInt("kCBMsgArgCharacteristicValueHandle"))
+		props := Property(xc.MustGetInt("kCBMsgArgCharacteristicProperties"))
+		c := &Characteristic{uuid: u, svc: s, props: props, h: ch, vh: vh}
+		s.chars = append(s.chars, c)
+	}
+	return s.chars, nil
+}
+
+func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
+	rsp := p.sendReq(70, xpc.Dict{
+		"kCBMsgArgDeviceUUID":                p.id,
+		"kCBMsgArgCharacteristicHandle":      c.h,
+		"kCBMsgArgCharacteristicValueHandle": c.vh,
+		"kCBMsgArgUUIDs":                     uuidSlice(ds),
+	})
+	for _, xds := range rsp.MustGetArray("kCBMsgArgDescriptors") {
+		xd := xds.(xpc.Dict)
+		u := MustParseUUID(xd.MustGetHexBytes("kCBMsgArgUUID"))
+		h := uint16(xd.MustGetInt("kCBMsgArgDescriptorHandle"))
+		d := &Descriptor{uuid: u, char: c, h: h}
+		c.descs = append(c.descs, d)
+	}
+	return c.descs, nil
+}
+
+func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
+	rsp := p.sendReq(65, xpc.Dict{
+		"kCBMsgArgDeviceUUID":                p.id,
+		"kCBMsgArgCharacteristicHandle":      c.h,
+		"kCBMsgArgCharacteristicValueHandle": c.vh,
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return nil, attEcode(res)
+	}
+	b := rsp.MustGetBytes("kCBMsgArgData")
+	return b, nil
+}
+
+func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
+	return nil, errors.New("Not implemented")
+}
+
+func (p *peripheral) WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error {
+	args := xpc.Dict{
+		"kCBMsgArgDeviceUUID":                p.id,
+		"kCBMsgArgCharacteristicHandle":      c.h,
+		"kCBMsgArgCharacteristicValueHandle": c.vh,
+		"kCBMsgArgData":                      b,
+		"kCBMsgArgType":                      map[bool]int{false: 0, true: 1}[noRsp],
+	}
+	if noRsp {
+		p.sendCmd(66, args)
+		return nil
+	}
+	rsp := p.sendReq(65, args)
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return attEcode(res)
+	}
+	return nil
+}
+
+func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
+	rsp := p.sendReq(77, xpc.Dict{
+		"kCBMsgArgDeviceUUID":       p.id,
+		"kCBMsgArgDescriptorHandle": d.h,
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return nil, attEcode(res)
+	}
+	b := rsp.MustGetBytes("kCBMsgArgData")
+	return b, nil
+}
+
+func (p *peripheral) WriteDescriptor(d *Descriptor, b []byte) error {
+	rsp := p.sendReq(78, xpc.Dict{
+		"kCBMsgArgDeviceUUID":       p.id,
+		"kCBMsgArgDescriptorHandle": d.h,
+		"kCBMsgArgData":             b,
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return attEcode(res)
+	}
+	return nil
+}
+
+func (p *peripheral) SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error {
+	set := 1
+	if f == nil {
+		set = 0
+	}
+	// To avoid race condition, registeration is handled before requesting the server.
+	if f != nil {
+		// Note: when notified, core bluetooth reports characteristic handle, not value's handle.
+		p.sub.subscribe(c.h, func(b []byte, err error) { f(c, b, err) })
+	}
+	rsp := p.sendReq(68, xpc.Dict{
+		"kCBMsgArgDeviceUUID":                p.id,
+		"kCBMsgArgCharacteristicHandle":      c.h,
+		"kCBMsgArgCharacteristicValueHandle": c.vh,
+		"kCBMsgArgState":                     set,
+	})
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return attEcode(res)
+	}
+	// To avoid race condition, unregisteration is handled after server responses.
+	if f == nil {
+		p.sub.unsubscribe(c.h)
+	}
+	return nil
+}
+
+func (p *peripheral) SetIndicateValue(c *Characteristic,
+	f func(*Characteristic, []byte, error)) error {
+	// TODO: Implement set indications logic for darwin (https://github.com/runtimeco/gatt/issues/32)
+	return nil
+}
+
+func (p *peripheral) ReadRSSI() int {
+	rsp := p.sendReq(43, xpc.Dict{"kCBMsgArgDeviceUUID": p.id})
+	return rsp.MustGetInt("kCBMsgArgData")
+}
+
+func (p *peripheral) SetMTU(mtu uint16) error {
+	return errors.New("Not implemented")
+}
+
+func uuidSlice(uu []UUID) [][]byte {
+	us := [][]byte{}
+	for _, u := range uu {
+		us = append(us, reverse(u.b))
+	}
+	return us
+}
+
+type message struct {
+	id   int
+	args xpc.Dict
+	rspc chan xpc.Dict
+}
+
+func (p *peripheral) sendCmd(id int, args xpc.Dict) {
+	p.reqc <- message{id: id, args: args}
+}
+
+func (p *peripheral) sendReq(id int, args xpc.Dict) xpc.Dict {
+	m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
+	p.reqc <- m
+	return <-m.rspc
+}
+
+func (p *peripheral) loop() {
+	rspc := make(chan message)
+
+	go func() {
+		for {
+			select {
+			case req := <-p.reqc:
+				p.d.sendCBMsg(req.id, req.args)
+				if req.rspc == nil {
+					break
+				}
+				m := <-rspc
+				req.rspc <- m.args
+			case <-p.quitc:
+				return
+			}
+		}
+	}()
+
+	for {
+		select {
+		case rsp := <-p.rspc:
+			// Notification
+			if rsp.id == 71 && rsp.args.GetInt("kCBMsgArgIsNotification", 0) != 0 {
+				// While we're notified with the value's handle, blued reports the characteristic handle.
+				ch := uint16(rsp.args.MustGetInt("kCBMsgArgCharacteristicHandle"))
+				b := rsp.args.MustGetBytes("kCBMsgArgData")
+				f := p.sub.fn(ch)
+				if f == nil {
+					log.Printf("notified by unsubscribed handle")
+					// FIXME: should terminate the connection?
+				} else {
+					go f(b, nil)
+				}
+				break
+			}
+			rspc <- rsp
+		case <-p.quitc:
+			return
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_linux.go
new file mode 100644
index 0000000..43ec067
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/peripheral_linux.go
@@ -0,0 +1,448 @@
+package gatt
+
+import (
+	"bytes"
+	"encoding/binary"
+	"fmt"
+	"io"
+	"log"
+	"net"
+	"strings"
+
+	"github.com/runtimeco/gatt/linux"
+)
+
+type peripheral struct {
+	// NameChanged is called whenever the peripheral GAP device name has changed.
+	NameChanged func(*peripheral)
+
+	// ServicedModified is called when one or more service of a peripheral have changed.
+	// A list of invalid service is provided in the parameter.
+	ServicesModified func(*peripheral, []*Service)
+
+	d    *device
+	svcs []*Service
+
+	sub *subscriber
+
+	mtu uint16
+	l2c io.ReadWriteCloser
+
+	reqc  chan message
+	quitc chan struct{}
+
+	pd *linux.PlatData // platform specific data
+}
+
+func (p *peripheral) Device() Device       { return p.d }
+func (p *peripheral) ID() string           { return strings.ToUpper(net.HardwareAddr(p.pd.Address[:]).String()) }
+func (p *peripheral) Name() string         { return p.pd.Name }
+func (p *peripheral) Services() []*Service { return p.svcs }
+
+func finish(op byte, h uint16, b []byte) bool {
+	done := b[0] == attOpError && b[1] == op && b[2] == byte(h) && b[3] == byte(h>>8)
+	e := attEcode(b[4])
+	if e != attEcodeAttrNotFound {
+		// log.Printf("unexpected protocol error: %s", e)
+		// FIXME: terminate the connection
+	}
+	return done
+}
+
+func (p *peripheral) DiscoverServices(s []UUID) ([]*Service, error) {
+	// TODO: implement the UUID filters
+	// p.pd.Conn.Write([]byte{0x02, 0x87, 0x00}) // MTU
+	done := false
+	start := uint16(0x0001)
+	for !done {
+		op := byte(attOpReadByGroupReq)
+		b := make([]byte, 7)
+		b[0] = op
+		binary.LittleEndian.PutUint16(b[1:3], start)
+		binary.LittleEndian.PutUint16(b[3:5], 0xFFFF)
+		binary.LittleEndian.PutUint16(b[5:7], 0x2800)
+
+		b = p.sendReq(op, b)
+		if finish(op, start, b) {
+			break
+		}
+		b = b[1:]
+		l, b := int(b[0]), b[1:]
+		switch {
+		case l == 6 && (len(b)%6 == 0):
+		case l == 20 && (len(b)%20 == 0):
+		default:
+			return nil, ErrInvalidLength
+		}
+
+		for len(b) != 0 {
+			h := binary.LittleEndian.Uint16(b[:2])
+			endh := binary.LittleEndian.Uint16(b[2:4])
+			s := &Service{
+				uuid: UUID{b[4:l]},
+				h:    h,
+				endh: endh,
+			}
+			p.svcs = append(p.svcs, s)
+			b = b[l:]
+			done = endh == 0xFFFF
+			start = endh + 1
+		}
+	}
+	return p.svcs, nil
+}
+
+func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
+	// TODO
+	return nil, nil
+}
+
+func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
+	// TODO: implement the UUID filters
+	done := false
+	start := s.h
+	var prev *Characteristic
+	for !done {
+		op := byte(attOpReadByTypeReq)
+		b := make([]byte, 7)
+		b[0] = op
+		binary.LittleEndian.PutUint16(b[1:3], start)
+		binary.LittleEndian.PutUint16(b[3:5], s.endh)
+		binary.LittleEndian.PutUint16(b[5:7], 0x2803)
+
+		b = p.sendReq(op, b)
+		if finish(op, start, b) {
+			break
+		}
+		b = b[1:]
+
+		l, b := int(b[0]), b[1:]
+		switch {
+		case l == 7 && (len(b)%7 == 0):
+		case l == 21 && (len(b)%21 == 0):
+		default:
+			return nil, ErrInvalidLength
+		}
+
+		for len(b) != 0 {
+			h := binary.LittleEndian.Uint16(b[:2])
+			props := Property(b[2])
+			vh := binary.LittleEndian.Uint16(b[3:5])
+			u := UUID{b[5:l]}
+			s := searchService(p.svcs, h, vh)
+			if s == nil {
+				log.Printf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
+				return nil, fmt.Errorf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
+			}
+			c := &Characteristic{
+				uuid:  u,
+				svc:   s,
+				props: props,
+				h:     h,
+				vh:    vh,
+			}
+			s.chars = append(s.chars, c)
+			b = b[l:]
+			done = vh == s.endh
+			start = vh + 1
+			if prev != nil {
+				prev.endh = c.h - 1
+			}
+			prev = c
+		}
+	}
+	if len(s.chars) > 1 {
+		s.chars[len(s.chars)-1].endh = s.endh
+	}
+	return s.chars, nil
+}
+
+func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
+	// TODO: implement the UUID filters
+	done := false
+	start := c.vh + 1
+	for !done {
+		if c.endh == 0 {
+			c.endh = c.svc.endh
+		}
+		op := byte(attOpFindInfoReq)
+		b := make([]byte, 5)
+		b[0] = op
+		binary.LittleEndian.PutUint16(b[1:3], start)
+		binary.LittleEndian.PutUint16(b[3:5], c.endh)
+
+		b = p.sendReq(op, b)
+		if finish(attOpFindInfoReq, start, b) {
+			break
+		}
+		b = b[1:]
+
+		var l int
+		f, b := int(b[0]), b[1:]
+		switch {
+		case f == 1 && (len(b)%4 == 0):
+			l = 4
+		case f == 2 && (len(b)%18 == 0):
+			l = 18
+		default:
+			return nil, ErrInvalidLength
+		}
+
+		for len(b) != 0 {
+			h := binary.LittleEndian.Uint16(b[:2])
+			u := UUID{b[2:l]}
+			d := &Descriptor{uuid: u, h: h, char: c}
+			c.descs = append(c.descs, d)
+			if u.Equal(attrClientCharacteristicConfigUUID) {
+				c.cccd = d
+			}
+			b = b[l:]
+			done = h == c.endh
+			start = h + 1
+		}
+	}
+	return c.descs, nil
+}
+
+func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
+	b := make([]byte, 3)
+	op := byte(attOpReadReq)
+	b[0] = op
+	binary.LittleEndian.PutUint16(b[1:3], c.vh)
+
+	b = p.sendReq(op, b)
+	b = b[1:]
+	return b, nil
+}
+
+func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
+	// The spec says that a read blob request should fail if the characteristic
+	// is smaller than mtu - 1.  To simplify the API, the first read is done
+	// with a regular read request.  If the buffer received is equal to mtu -1,
+	// then we read the rest of the data using read blob.
+	firstRead, err := p.ReadCharacteristic(c)
+	if err != nil {
+		return nil, err
+	}
+	if len(firstRead) < int(p.mtu)-1 {
+		return firstRead, nil
+	}
+
+	var buf bytes.Buffer
+	buf.Write(firstRead)
+	off := uint16(len(firstRead))
+	for {
+		b := make([]byte, 5)
+		op := byte(attOpReadBlobReq)
+		b[0] = op
+		binary.LittleEndian.PutUint16(b[1:3], c.vh)
+		binary.LittleEndian.PutUint16(b[3:5], off)
+
+		b = p.sendReq(op, b)
+		b = b[1:]
+		if len(b) == 0 {
+			break
+		}
+		buf.Write(b)
+		off += uint16(len(b))
+		if len(b) < int(p.mtu)-1 {
+			break
+		}
+	}
+	return buf.Bytes(), nil
+}
+
+func (p *peripheral) WriteCharacteristic(c *Characteristic, value []byte, noRsp bool) error {
+	b := make([]byte, 3+len(value))
+	op := byte(attOpWriteReq)
+	b[0] = op
+	if noRsp {
+		b[0] = attOpWriteCmd
+	}
+	binary.LittleEndian.PutUint16(b[1:3], c.vh)
+	copy(b[3:], value)
+
+	if noRsp {
+		p.sendCmd(op, b)
+		return nil
+	}
+	b = p.sendReq(op, b)
+	// TODO: error handling
+	b = b[1:]
+	return nil
+}
+
+func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
+	b := make([]byte, 3)
+	op := byte(attOpReadReq)
+	b[0] = op
+	binary.LittleEndian.PutUint16(b[1:3], d.h)
+
+	b = p.sendReq(op, b)
+	b = b[1:]
+	// TODO: error handling
+	return b, nil
+}
+
+func (p *peripheral) WriteDescriptor(d *Descriptor, value []byte) error {
+	b := make([]byte, 3+len(value))
+	op := byte(attOpWriteReq)
+	b[0] = op
+	binary.LittleEndian.PutUint16(b[1:3], d.h)
+	copy(b[3:], value)
+
+	b = p.sendReq(op, b)
+	b = b[1:]
+	// TODO: error handling
+	return nil
+}
+
+func (p *peripheral) setNotifyValue(c *Characteristic, flag uint16,
+	f func(*Characteristic, []byte, error)) error {
+/*
+	if c.cccd == nil {
+		return errors.New("no cccd") // FIXME
+	}
+	ccc := uint16(0)
+	if f != nil {
+		ccc = flag
+*/
+		p.sub.subscribe(c.vh, func(b []byte, err error) { f(c, b, err) })
+/*
+	}
+	b := make([]byte, 5)
+	op := byte(attOpWriteReq)
+	b[0] = op
+	binary.LittleEndian.PutUint16(b[1:3], c.cccd.h)
+	binary.LittleEndian.PutUint16(b[3:5], ccc)
+
+	b = p.sendReq(op, b)
+	b = b[1:]
+	// TODO: error handling
+	if f == nil {
+		p.sub.unsubscribe(c.vh)
+	}
+*/
+	return nil
+}
+
+func (p *peripheral) SetNotifyValue(c *Characteristic,
+	f func(*Characteristic, []byte, error)) error {
+	return p.setNotifyValue(c, gattCCCNotifyFlag, f)
+}
+
+func (p *peripheral) SetIndicateValue(c *Characteristic,
+	f func(*Characteristic, []byte, error)) error {
+	return p.setNotifyValue(c, gattCCCIndicateFlag, f)
+}
+
+func (p *peripheral) ReadRSSI() int {
+	// TODO: implement
+	return -1
+}
+
+func searchService(ss []*Service, start, end uint16) *Service {
+	for _, s := range ss {
+		if s.h < start && s.endh >= end {
+			return s
+		}
+	}
+	return nil
+}
+
+// TODO: unifiy the message with OS X pots and refactor
+type message struct {
+	op   byte
+	b    []byte
+	rspc chan []byte
+}
+
+func (p *peripheral) sendCmd(op byte, b []byte) {
+	p.reqc <- message{op: op, b: b}
+}
+
+func (p *peripheral) sendReq(op byte, b []byte) []byte {
+	m := message{op: op, b: b, rspc: make(chan []byte)}
+	p.reqc <- m
+	return <-m.rspc
+}
+
+func (p *peripheral) loop() {
+	// Serialize the request.
+	rspc := make(chan []byte)
+
+	// Dequeue request loop
+	go func() {
+		for {
+			select {
+			case req := <-p.reqc:
+				p.l2c.Write(req.b)
+				if req.rspc == nil {
+					break
+				}
+				r := <-rspc
+				switch reqOp, rspOp := req.b[0], r[0]; {
+				case rspOp == attRspFor[reqOp]:
+				case rspOp == attOpError && r[1] == reqOp:
+				default:
+					log.Printf("Request 0x%02x got a mismatched response: 0x%02x", reqOp, rspOp)
+					// FIXME: terminate the connection?
+				}
+				req.rspc <- r
+			case <-p.quitc:
+				return
+			}
+		}
+	}()
+
+	// L2CAP implementations shall support a minimum MTU size of 48 bytes.
+	// The default value is 672 bytes
+	buf := make([]byte, 672)
+
+	// Handling response or notification/indication
+	for {
+		n, err := p.l2c.Read(buf)
+		if n == 0 || err != nil {
+			close(p.quitc)
+			return
+		}
+
+		b := make([]byte, n)
+		copy(b, buf)
+
+		if (b[0] != attOpHandleNotify) && (b[0] != attOpHandleInd) {
+			rspc <- b
+			continue
+		}
+
+		h := binary.LittleEndian.Uint16(b[1:3])
+		f := p.sub.fn(h)
+		if f == nil {
+			log.Printf("notified by unsubscribed handle")
+			// FIXME: terminate the connection?
+		} else {
+			go f(b[3:], nil)
+		}
+
+		if b[0] == attOpHandleInd {
+			// write aknowledgement for indication
+			p.l2c.Write([]byte{attOpHandleCnf})
+		}
+
+	}
+}
+
+func (p *peripheral) SetMTU(mtu uint16) error {
+	b := make([]byte, 3)
+	op := byte(attOpMtuReq)
+	b[0] = op
+	binary.LittleEndian.PutUint16(b[1:3], uint16(mtu))
+
+	b = p.sendReq(op, b)
+	serverMTU := binary.LittleEndian.Uint16(b[1:3])
+	if serverMTU < mtu {
+		mtu = serverMTU
+	}
+	p.mtu = mtu
+	return nil
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/readme.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/readme.md b/newtmgr/vendor/github.com/runtimeco/gatt/readme.md
new file mode 100644
index 0000000..ea3a957
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/readme.md
@@ -0,0 +1,115 @@
+# Package gatt provides a Bluetooth Low Energy GATT implementation.
+
+Gatt (Generic Attribute Profile) is the protocol used to write BLE peripherals (servers) and centrals (clients).
+
+As a peripheral, you can create services, characteristics, and descriptors,
+advertise, accept connections, and handle requests.
+
+As a central, you can scan, connect, discover services, and make requests.
+
+## SETUP
+
+### gatt supports both Linux and OS X.
+
+### On Linux:
+To gain complete and exclusive control of the HCI device, gatt uses
+HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
+Those who must use an older kernel may patch in these relevant commits
+from Marcel Holtmann:
+
+    Bluetooth: Introduce new HCI socket channel for user operation
+    Bluetooth: Introduce user channel flag for HCI devices
+    Bluetooth: Refactor raw socket filter into more readable code
+
+Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
+device no other program may access it.
+
+Before starting a gatt program, make sure that your BLE device is down:
+
+    sudo hciconfig
+    sudo hciconfig hci0 down  # or whatever hci device you want to use
+
+If you have BlueZ 5.14+ (or aren't sure), stop the built-in
+bluetooth server, which interferes with gatt, e.g.:
+
+    sudo service bluetooth stop
+
+Because gatt programs administer network devices, they must
+either be run as root, or be granted appropriate capabilities:
+
+    sudo <executable>
+    # OR
+    sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
+    <executable>
+
+## Usage
+Please see [godoc.org](http://godoc.org/github.com/paypal/gatt) for documentation.
+
+## Examples
+
+### Build and run the examples on a native environment (Linux or OS X)
+
+Go is a compiled language, which means to run the examples you need to build them first.
+
+    # Build the sample server.
+    go build examples/server.go
+    # Start the sample server.
+    sudo ./server
+
+Alternatively, you can use "go run" to build and run the examples in a single step:
+
+    # Build and run the sample server.
+    sudo go run examples/server.go
+
+Discoverer and explorer demonstrates central (client) functions:
+
+    # Discover surrounding peripherals.
+    sudo go run examples/discoverer.go
+
+    # Connect to and explorer a peripheral device.
+    sudo go run examples/explorer.go <peripheral ID>
+
+### Cross-compile and deploy to a target device
+
+    # Build and run the server example on a ARMv5 target device.
+    GOARCH=arm GOARM=5 GOOS=linux go build examples/server.go
+    cp server <target device>
+    # Start the server on the target device
+    sudo ./server
+
+See the server.go, discoverer.go, and explorer.go in the examples/
+directory for writing server or client programs that run on Linux
+and OS X.
+
+Users, especially on Linux platforms, seeking finer-grained control
+over the devices can see the examples/server_lnx.go for the usage
+of Option, which are platform specific.
+
+See the rest of the docs for other options and finer-grained control.
+
+## Note
+Note that some BLE central devices, particularly iOS, may aggressively
+cache results from previous connections. If you change your services or
+characteristics, you may need to reboot the other device to pick up the
+changes. This is a common source of confusion and apparent bugs. For an
+OS X central, see http://stackoverflow.com/questions/20553957.
+
+## Known Issues
+
+Currently OS X vesion  does not support subscribing to indications. 
+Please check [#32](https://github.com/paypal/gatt/issues/32) for the status of this issue.
+
+## REFERENCES
+
+gatt started life as a port of bleno, to which it is indebted:
+https://github.com/sandeepmistry/bleno. If you are having
+problems with gatt, particularly around installation, issues
+filed with bleno might also be helpful references.
+
+To try out your GATT server, it is useful to experiment with a
+generic BLE client. LightBlue is a good choice. It is available
+free for both iOS and OS X.
+
+gatt is similar to [bleno](https://github.com/sandeepmistry/bleno) and [noble](https://github.com/sandeepmistry/noble), which offer BLE GATT implementations for node.js.
+
+Gatt is released under a [BSD-style license](./LICENSE.md).

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/uuid.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/uuid.go b/newtmgr/vendor/github.com/runtimeco/gatt/uuid.go
new file mode 100644
index 0000000..393e548
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/uuid.go
@@ -0,0 +1,86 @@
+package gatt
+
+import (
+	"bytes"
+	"encoding/binary"
+	"encoding/hex"
+	"fmt"
+	"strings"
+)
+
+// A UUID is a BLE UUID.
+type UUID struct {
+	// Hide the bytes, so that we can enforce that they have length 2 or 16,
+	// and that they are immutable. This simplifies the code and API.
+	b []byte
+}
+
+// UUID16 converts a uint16 (such as 0x1800) to a UUID.
+func UUID16(i uint16) UUID {
+	b := make([]byte, 2)
+	binary.LittleEndian.PutUint16(b, i)
+	return UUID{b}
+}
+
+// ParseUUID parses a standard-format UUID string, such
+// as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".
+func ParseUUID(s string) (UUID, error) {
+	s = strings.Replace(s, "-", "", -1)
+	b, err := hex.DecodeString(s)
+	if err != nil {
+		return UUID{}, err
+	}
+	if err := lenErr(len(b)); err != nil {
+		return UUID{}, err
+	}
+	return UUID{reverse(b)}, nil
+}
+
+// MustParseUUID parses a standard-format UUID string,
+// like ParseUUID, but panics in case of error.
+func MustParseUUID(s string) UUID {
+	u, err := ParseUUID(s)
+	if err != nil {
+		panic(err)
+	}
+	return u
+}
+
+// lenErr returns an error if n is an invalid UUID length.
+func lenErr(n int) error {
+	switch n {
+	case 2, 16:
+		return nil
+	}
+	return fmt.Errorf("UUIDs must have length 2 or 16, got %d", n)
+}
+
+// Len returns the length of the UUID, in bytes.
+// BLE UUIDs are either 2 or 16 bytes.
+func (u UUID) Len() int {
+	return len(u.b)
+}
+
+// String hex-encodes a UUID.
+func (u UUID) String() string {
+	return fmt.Sprintf("%x", reverse(u.b))
+}
+
+// Equal returns a boolean reporting whether v represent the same UUID as u.
+func (u UUID) Equal(v UUID) bool {
+	return bytes.Equal(u.b, v.b)
+}
+
+// reverse returns a reversed copy of u.
+func reverse(u []byte) []byte {
+	// Special-case 16 bit UUIDS for speed.
+	l := len(u)
+	if l == 2 {
+		return []byte{u[1], u[0]}
+	}
+	b := make([]byte, l)
+	for i := 0; i < l/2+1; i++ {
+		b[i], b[l-i-1] = u[l-i-1], u[i]
+	}
+	return b
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/xpc/LICENSE
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/xpc/LICENSE b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/LICENSE
new file mode 100644
index 0000000..766a0a5
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) {{{year}}} {{{fullname}}}
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/xpc/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/xpc/doc.go b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/doc.go
new file mode 100644
index 0000000..d292249
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/doc.go
@@ -0,0 +1,8 @@
+// Package xpc provides minimal OS X XPC support required for gatt
+//
+// This is adapted from [goble], by Raffaele Sena.
+//
+//     http://godoc.org/github.com/raff/goble
+//     https://github.com/raff/goble
+
+package xpc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_darwin.go
new file mode 100644
index 0000000..2a85a99
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_darwin.go
@@ -0,0 +1,350 @@
+package xpc
+
+/*
+#include "xpc_wrapper_darwin.h"
+#include "sys/utsname.h"
+*/
+import "C"
+
+import (
+	"errors"
+	"fmt"
+	"log"
+	r "reflect"
+	"unsafe"
+)
+
+type XPC struct {
+	conn C.xpc_connection_t
+}
+
+func (x *XPC) Send(msg interface{}, verbose bool) {
+	// verbose == true converts the type from bool to C._Bool
+	C.XpcSendMessage(x.conn, goToXpc(msg), true, verbose == true)
+}
+
+//
+// minimal XPC support required for BLE
+//
+
+// a dictionary of things
+type Dict map[string]interface{}
+
+func (d Dict) Contains(k string) bool {
+	_, ok := d[k]
+	return ok
+}
+
+func (d Dict) MustGetDict(k string) Dict {
+	return d[k].(Dict)
+}
+
+func (d Dict) MustGetArray(k string) Array {
+	return d[k].(Array)
+}
+
+func (d Dict) MustGetBytes(k string) []byte {
+	return d[k].([]byte)
+}
+
+func (d Dict) MustGetHexBytes(k string) string {
+	return fmt.Sprintf("%x", d[k].([]byte))
+}
+
+func (d Dict) MustGetInt(k string) int {
+	return int(d[k].(int64))
+}
+
+func (d Dict) MustGetUUID(k string) []byte {
+	u := d[k].(UUID)
+	return u[:]
+}
+
+func (d Dict) GetString(k, defv string) string {
+	if v := d[k]; v != nil {
+		//log.Printf("GetString %s %#v\n", k, v)
+		return v.(string)
+	} else {
+		//log.Printf("GetString %s default %#v\n", k, defv)
+		return defv
+	}
+}
+
+func (d Dict) GetBytes(k string, defv []byte) []byte {
+	if v := d[k]; v != nil {
+		//log.Printf("GetBytes %s %#v\n", k, v)
+		return v.([]byte)
+	} else {
+		//log.Printf("GetBytes %s default %#v\n", k, defv)
+		return defv
+	}
+}
+
+func (d Dict) GetInt(k string, defv int) int {
+	if v := d[k]; v != nil {
+		//log.Printf("GetString %s %#v\n", k, v)
+		return int(v.(int64))
+	} else {
+		//log.Printf("GetString %s default %#v\n", k, defv)
+		return defv
+	}
+}
+
+func (d Dict) GetUUID(k string) UUID {
+	return GetUUID(d[k])
+}
+
+// an array of things
+type Array []interface{}
+
+func (a Array) GetUUID(k int) UUID {
+	return GetUUID(a[k])
+}
+
+// a UUID
+type UUID []byte
+
+func MakeUUID(s string) UUID {
+	var sl []byte
+	fmt.Sscanf(s, "%32x", &sl)
+
+	var uuid [16]byte
+	copy(uuid[:], sl)
+	return UUID(uuid[:])
+}
+
+func (uuid UUID) String() string {
+	return fmt.Sprintf("%x", []byte(uuid))
+}
+
+func GetUUID(v interface{}) UUID {
+	if v == nil {
+		return UUID{}
+	}
+
+	if uuid, ok := v.(UUID); ok {
+		return uuid
+	}
+
+	if bytes, ok := v.([]byte); ok {
+		uuid := UUID{}
+
+		for i, b := range bytes {
+			uuid[i] = b
+		}
+
+		return uuid
+	}
+
+	if bytes, ok := v.([]uint8); ok {
+		uuid := UUID{}
+
+		for i, b := range bytes {
+			uuid[i] = b
+		}
+
+		return uuid
+	}
+
+	log.Fatalf("invalid type for UUID: %#v", v)
+	return UUID{}
+}
+
+var (
+	CONNECTION_INVALID     = errors.New("connection invalid")
+	CONNECTION_INTERRUPTED = errors.New("connection interrupted")
+	CONNECTION_TERMINATED  = errors.New("connection terminated")
+
+	TYPE_OF_UUID  = r.TypeOf(UUID{})
+	TYPE_OF_BYTES = r.TypeOf([]byte{})
+)
+
+type XpcEventHandler interface {
+	HandleXpcEvent(event Dict, err error)
+}
+
+func XpcConnect(service string, eh XpcEventHandler) XPC {
+	cservice := C.CString(service)
+	defer C.free(unsafe.Pointer(cservice))
+	return XPC{conn: C.XpcConnect(cservice, unsafe.Pointer(&eh))}
+}
+
+//export handleXpcEvent
+func handleXpcEvent(event C.xpc_object_t, p unsafe.Pointer) {
+	//log.Printf("handleXpcEvent %#v %#v\n", event, p)
+
+	t := C.xpc_get_type(event)
+	eh := *((*XpcEventHandler)(p))
+
+	if t == C.TYPE_ERROR {
+		if event == C.ERROR_CONNECTION_INVALID {
+			// The client process on the other end of the connection has either
+			// crashed or cancelled the connection. After receiving this error,
+			// the connection is in an invalid state, and you do not need to
+			// call xpc_connection_cancel(). Just tear down any associated state
+			// here.
+			//log.Println("connection invalid")
+			eh.HandleXpcEvent(nil, CONNECTION_INVALID)
+		} else if event == C.ERROR_CONNECTION_INTERRUPTED {
+			//log.Println("connection interrupted")
+			eh.HandleXpcEvent(nil, CONNECTION_INTERRUPTED)
+		} else if event == C.ERROR_CONNECTION_TERMINATED {
+			// Handle per-connection termination cleanup.
+			//log.Println("connection terminated")
+			eh.HandleXpcEvent(nil, CONNECTION_TERMINATED)
+		} else {
+			//log.Println("got some error", event)
+			eh.HandleXpcEvent(nil, fmt.Errorf("%v", event))
+		}
+	} else {
+		eh.HandleXpcEvent(xpcToGo(event).(Dict), nil)
+	}
+}
+
+// goToXpc converts a go object to an xpc object
+func goToXpc(o interface{}) C.xpc_object_t {
+	return valueToXpc(r.ValueOf(o))
+}
+
+// valueToXpc converts a go Value to an xpc object
+//
+// note that not all the types are supported, but only the subset required for Blued
+func valueToXpc(val r.Value) C.xpc_object_t {
+	if !val.IsValid() {
+		return nil
+	}
+
+	var xv C.xpc_object_t
+
+	switch val.Kind() {
+	case r.Int, r.Int8, r.Int16, r.Int32, r.Int64:
+		xv = C.xpc_int64_create(C.int64_t(val.Int()))
+
+	case r.Uint, r.Uint8, r.Uint16, r.Uint32:
+		xv = C.xpc_int64_create(C.int64_t(val.Uint()))
+
+	case r.String:
+		xv = C.xpc_string_create(C.CString(val.String()))
+
+	case r.Map:
+		xv = C.xpc_dictionary_create(nil, nil, 0)
+		for _, k := range val.MapKeys() {
+			v := valueToXpc(val.MapIndex(k))
+			C.xpc_dictionary_set_value(xv, C.CString(k.String()), v)
+			if v != nil {
+				C.xpc_release(v)
+			}
+		}
+
+	case r.Array, r.Slice:
+		if val.Type() == TYPE_OF_UUID {
+			// array of bytes
+			var uuid [16]byte
+			r.Copy(r.ValueOf(uuid[:]), val)
+			xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0])))
+		} else if val.Type() == TYPE_OF_BYTES {
+			// slice of bytes
+			xv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len()))
+		} else {
+			xv = C.xpc_array_create(nil, 0)
+			l := val.Len()
+
+			for i := 0; i < l; i++ {
+				v := valueToXpc(val.Index(i))
+				C.xpc_array_append_value(xv, v)
+				if v != nil {
+					C.xpc_release(v)
+				}
+			}
+		}
+
+	case r.Interface, r.Ptr:
+		xv = valueToXpc(val.Elem())
+
+	default:
+		log.Fatalf("unsupported %#v", val.String())
+	}
+
+	return xv
+}
+
+//export arraySet
+func arraySet(u unsafe.Pointer, i C.int, v C.xpc_object_t) {
+	a := *(*Array)(u)
+	a[i] = xpcToGo(v)
+}
+
+//export dictSet
+func dictSet(u unsafe.Pointer, k *C.char, v C.xpc_object_t) {
+	d := *(*Dict)(u)
+	d[C.GoString(k)] = xpcToGo(v)
+}
+
+// xpcToGo converts an xpc object to a go object
+//
+// note that not all the types are supported, but only the subset required for Blued
+func xpcToGo(v C.xpc_object_t) interface{} {
+	t := C.xpc_get_type(v)
+
+	switch t {
+	case C.TYPE_ARRAY:
+		a := make(Array, C.int(C.xpc_array_get_count(v)))
+		C.XpcArrayApply(unsafe.Pointer(&a), v)
+		return a
+
+	case C.TYPE_DATA:
+		return C.GoBytes(C.xpc_data_get_bytes_ptr(v), C.int(C.xpc_data_get_length(v)))
+
+	case C.TYPE_DICT:
+		d := make(Dict)
+		C.XpcDictApply(unsafe.Pointer(&d), v)
+		return d
+
+	case C.TYPE_INT64:
+		return int64(C.xpc_int64_get_value(v))
+
+	case C.TYPE_STRING:
+		return C.GoString(C.xpc_string_get_string_ptr(v))
+
+	case C.TYPE_UUID:
+		a := [16]byte{}
+		C.XpcUUIDGetBytes(unsafe.Pointer(&a), v)
+		return UUID(a[:])
+
+	default:
+		log.Fatalf("unexpected type %#v, value %#v", t, v)
+	}
+
+	return nil
+}
+
+// xpc_release is needed by tests, since they can't use CGO
+func xpc_release(xv C.xpc_object_t) {
+	C.xpc_release(xv)
+}
+
+// this is used to check the OS version
+
+type Utsname struct {
+	Sysname  string
+	Nodename string
+	Release  string
+	Version  string
+	Machine  string
+}
+
+func Uname(utsname *Utsname) error {
+	var cstruct C.struct_utsname
+	if err := C.uname(&cstruct); err != 0 {
+		return errors.New("utsname error")
+	}
+
+	// XXX: this may crash if any value is exactly 256 characters (no 0 terminator)
+	utsname.Sysname = C.GoString(&cstruct.sysname[0])
+	utsname.Nodename = C.GoString(&cstruct.nodename[0])
+	utsname.Release = C.GoString(&cstruct.release[0])
+	utsname.Version = C.GoString(&cstruct.version[0])
+	utsname.Machine = C.GoString(&cstruct.machine[0])
+
+	return nil
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.c
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.c b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.c
new file mode 100644
index 0000000..7bcb83d
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.c
@@ -0,0 +1,85 @@
+#include <dispatch/dispatch.h>
+#include <xpc/xpc.h>
+#include <xpc/connection.h>
+#include <Block.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "_cgo_export.h"
+
+//
+// types and errors are implemented as macros
+// create some real objects to make them accessible to Go
+//
+xpc_type_t TYPE_ERROR = XPC_TYPE_ERROR;
+
+xpc_type_t TYPE_ARRAY = XPC_TYPE_ARRAY;
+xpc_type_t TYPE_DATA = XPC_TYPE_DATA;
+xpc_type_t TYPE_DICT = XPC_TYPE_DICTIONARY;
+xpc_type_t TYPE_INT64 = XPC_TYPE_INT64;
+xpc_type_t TYPE_STRING = XPC_TYPE_STRING;
+xpc_type_t TYPE_UUID = XPC_TYPE_UUID;
+
+xpc_object_t ERROR_CONNECTION_INVALID = (xpc_object_t) XPC_ERROR_CONNECTION_INVALID;
+xpc_object_t ERROR_CONNECTION_INTERRUPTED = (xpc_object_t) XPC_ERROR_CONNECTION_INTERRUPTED;
+xpc_object_t ERROR_CONNECTION_TERMINATED = (xpc_object_t) XPC_ERROR_TERMINATION_IMMINENT;
+
+const ptr_to_uuid_t ptr_to_uuid(void *p) { return (ptr_to_uuid_t)p; }
+
+
+//
+// connect to XPC service
+//
+xpc_connection_t XpcConnect(char *service, void *ctx) {
+    dispatch_queue_t queue = dispatch_queue_create(service, 0);
+    xpc_connection_t conn = xpc_connection_create_mach_service(service, queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
+
+    // making a local copy, that should be made "persistent" with the following Block_copy
+    GoInterface ictx = *((GoInterface*)ctx);
+
+    xpc_connection_set_event_handler(conn,
+        Block_copy(^(xpc_object_t event) {
+            handleXpcEvent(event, (void *)&ictx);
+        })
+    );
+
+    xpc_connection_resume(conn);
+    return conn;
+}
+
+void XpcSendMessage(xpc_connection_t conn, xpc_object_t message, bool release, bool reportDelivery) {
+    xpc_connection_send_message(conn,  message);
+    xpc_connection_send_barrier(conn, ^{
+        // Block is invoked on connection's target queue
+        // when 'message' has been sent.
+        if (reportDelivery) { // maybe this could be a callback
+            puts("message delivered");
+        }
+    });
+    if (release) {
+        xpc_release(message);
+    }
+}
+
+void XpcArrayApply(void *v, xpc_object_t arr) {
+  xpc_array_apply(arr, ^bool(size_t index, xpc_object_t value) {
+    arraySet(v, index, value);
+    return true;
+  });
+}
+
+void XpcDictApply(void *v, xpc_object_t dict) {
+  xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
+    dictSet(v, (char *)key, value);
+    return true;
+  });
+}
+
+void XpcUUIDGetBytes(void *v, xpc_object_t uuid) {
+   const uint8_t *src = xpc_uuid_get_bytes(uuid);
+   uint8_t *dest = (uint8_t *)v;
+
+   for (int i=0; i < sizeof(uuid_t); i++) {
+     dest[i] = src[i];
+   }
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.h
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.h b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.h
new file mode 100644
index 0000000..e2cfb5c
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/xpc/xpc_wrapper_darwin.h
@@ -0,0 +1,32 @@
+#ifndef _XPC_WRAPPER_H_
+#define _XPC_WRAPPER_H_
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <xpc/xpc.h>
+
+extern xpc_type_t TYPE_ERROR;
+
+extern xpc_type_t TYPE_ARRAY;
+extern xpc_type_t TYPE_DATA;
+extern xpc_type_t TYPE_DICT;
+extern xpc_type_t TYPE_INT64;
+extern xpc_type_t TYPE_STRING;
+extern xpc_type_t TYPE_UUID;
+
+extern xpc_object_t ERROR_CONNECTION_INVALID;
+extern xpc_object_t ERROR_CONNECTION_INTERRUPTED;
+extern xpc_object_t ERROR_CONNECTION_TERMINATED;
+
+extern xpc_connection_t XpcConnect(char *, void *);
+extern void XpcSendMessage(xpc_connection_t, xpc_object_t, bool, bool);
+extern void XpcArrayApply(void *, xpc_object_t);
+extern void XpcDictApply(void *, xpc_object_t);
+extern void XpcUUIDGetBytes(void *, xpc_object_t);
+
+// the input type for xpc_uuid_create should be uuid_t but CGO instists on unsigned char *
+// typedef uuid_t * ptr_to_uuid_t;
+typedef unsigned char * ptr_to_uuid_t;
+extern const ptr_to_uuid_t ptr_to_uuid(void *p);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/.gitignore
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/.gitignore b/newtmgr/vendor/github.com/runtimeinc/gatt/.gitignore
deleted file mode 100644
index 7ab0687..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-c.out
-c/*-ble
-sample

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/LICENSE.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/LICENSE.md b/newtmgr/vendor/github.com/runtimeinc/gatt/LICENSE.md
deleted file mode 100644
index 51c07a6..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/LICENSE.md
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2014 PayPal Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-   * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-   * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-   * Neither the name of PayPal Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/adv.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/adv.go b/newtmgr/vendor/github.com/runtimeinc/gatt/adv.go
deleted file mode 100644
index 3b8a747..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/adv.go
+++ /dev/null
@@ -1,234 +0,0 @@
-package gatt
-
-import (
-	"errors"
-	"log"
-)
-
-// MaxEIRPacketLength is the maximum allowed AdvertisingPacket
-// and ScanResponsePacket length.
-const MaxEIRPacketLength = 31
-
-// ErrEIRPacketTooLong is the error returned when an AdvertisingPacket
-// or ScanResponsePacket is too long.
-var ErrEIRPacketTooLong = errors.New("max packet length is 31")
-
-// Advertising data field types
-const (
-	typeFlags             = 0x01 // Flags
-	typeSomeUUID16        = 0x02 // Incomplete List of 16-bit Service Class UUIDs
-	typeAllUUID16         = 0x03 // Complete List of 16-bit Service Class UUIDs
-	typeSomeUUID32        = 0x04 // Incomplete List of 32-bit Service Class UUIDs
-	typeAllUUID32         = 0x05 // Complete List of 32-bit Service Class UUIDs
-	typeSomeUUID128       = 0x06 // Incomplete List of 128-bit Service Class UUIDs
-	typeAllUUID128        = 0x07 // Complete List of 128-bit Service Class UUIDs
-	typeShortName         = 0x08 // Shortened Local Name
-	typeCompleteName      = 0x09 // Complete Local Name
-	typeTxPower           = 0x0A // Tx Power Level
-	typeClassOfDevice     = 0x0D // Class of Device
-	typeSimplePairingC192 = 0x0E // Simple Pairing Hash C-192
-	typeSimplePairingR192 = 0x0F // Simple Pairing Randomizer R-192
-	typeSecManagerTK      = 0x10 // Security Manager TK Value
-	typeSecManagerOOB     = 0x11 // Security Manager Out of Band Flags
-	typeSlaveConnInt      = 0x12 // Slave Connection Interval Range
-	typeServiceSol16      = 0x14 // List of 16-bit Service Solicitation UUIDs
-	typeServiceSol128     = 0x15 // List of 128-bit Service Solicitation UUIDs
-	typeServiceData16     = 0x16 // Service Data - 16-bit UUID
-	typePubTargetAddr     = 0x17 // Public Target Address
-	typeRandTargetAddr    = 0x18 // Random Target Address
-	typeAppearance        = 0x19 // Appearance
-	typeAdvInterval       = 0x1A // Advertising Interval
-	typeLEDeviceAddr      = 0x1B // LE Bluetooth Device Address
-	typeLERole            = 0x1C // LE Role
-	typeServiceSol32      = 0x1F // List of 32-bit Service Solicitation UUIDs
-	typeServiceData32     = 0x20 // Service Data - 32-bit UUID
-	typeServiceData128    = 0x21 // Service Data - 128-bit UUID
-	typeLESecConfirm      = 0x22 // LE Secure Connections Confirmation Value
-	typeLESecRandom       = 0x23 // LE Secure Connections Random Value
-	typeManufacturerData  = 0xFF // Manufacturer Specific Data
-)
-
-// Advertising type flags
-const (
-	flagLimitedDiscoverable = 0x01 // LE Limited Discoverable Mode
-	flagGeneralDiscoverable = 0x02 // LE General Discoverable Mode
-	flagLEOnly              = 0x04 // BR/EDR Not Supported. Bit 37 of LMP Feature Mask Definitions (Page 0)
-	flagBothController      = 0x08 // Simultaneous LE and BR/EDR to Same Device Capable (Controller).
-	flagBothHost            = 0x10 // Simultaneous LE and BR/EDR to Same Device Capable (Host).
-)
-
-// FIXME: check the unmarshalling of this data structure.
-type ServiceData struct {
-	UUID UUID
-	Data []byte
-}
-
-// This is borrowed from core bluetooth.
-// Embedded/Linux folks might be interested in more details.
-type Advertisement struct {
-	LocalName        string
-	ManufacturerData []byte
-	ServiceData      []ServiceData
-	Services         []UUID
-	OverflowService  []UUID
-	TxPowerLevel     int
-	Connectable      bool
-	SolicitedService []UUID
-	AddressType uint8
-	Address     [6]byte
-}
-
-// This is only used in Linux port.
-func (a *Advertisement) unmarshall(b []byte) error {
-
-	// Utility function for creating a list of uuids.
-	uuidList := func(u []UUID, d []byte, w int) []UUID {
-		for len(d) > 0 {
-			u = append(u, UUID{d[:w]})
-			d = d[w:]
-		}
-		return u
-	}
-
-	for len(b) > 0 {
-		if len(b) < 2 {
-			return errors.New("invalid advertise data")
-		}
-		l, t := b[0], b[1]
-		if len(b) < int(1+l) {
-			return errors.New("invalid advertise data")
-		}
-		d := b[2 : 1+l]
-		switch t {
-		case typeFlags:
-			// TODO: should we do anything about the discoverability here?
-		case typeSomeUUID16:
-			a.Services = uuidList(a.Services, d, 2)
-		case typeAllUUID16:
-			a.Services = uuidList(a.Services, d, 2)
-		case typeSomeUUID32:
-			a.Services = uuidList(a.Services, d, 4)
-		case typeAllUUID32:
-			a.Services = uuidList(a.Services, d, 4)
-		case typeSomeUUID128:
-			a.Services = uuidList(a.Services, d, 16)
-		case typeAllUUID128:
-			a.Services = uuidList(a.Services, d, 16)
-		case typeShortName:
-			a.LocalName = string(d)
-		case typeCompleteName:
-			a.LocalName = string(d)
-		case typeTxPower:
-			a.TxPowerLevel = int(d[0])
-		case typeServiceSol16:
-			a.SolicitedService = uuidList(a.SolicitedService, d, 2)
-		case typeServiceSol128:
-			a.SolicitedService = uuidList(a.SolicitedService, d, 16)
-		case typeServiceSol32:
-			a.SolicitedService = uuidList(a.SolicitedService, d, 4)
-		case typeManufacturerData:
-			a.ManufacturerData = make([]byte, len(d))
-			copy(a.ManufacturerData, d)
-		// case typeServiceData16,
-		// case typeServiceData32,
-		// case typeServiceData128:
-		default:
-			log.Printf("DATA: [ % X ]", d)
-		}
-		b = b[1+l:]
-	}
-	return nil
-}
-
-// AdvPacket is an utility to help crafting advertisment or scan response data.
-type AdvPacket struct {
-	b []byte
-}
-
-// Bytes returns an 31-byte array, which contains up to 31 bytes of the packet.
-func (a *AdvPacket) Bytes() [31]byte {
-	b := [31]byte{}
-	copy(b[:], a.b)
-	return b
-}
-
-// Len returns the length of the packets with a maximum of 31.
-func (a *AdvPacket) Len() int {
-	if len(a.b) > 31 {
-		return 31
-	}
-	return len(a.b)
-}
-
-// AppendField appends a BLE advertising packet field.
-// TODO: refuse to append field if it'd make the packet too long.
-func (a *AdvPacket) AppendField(typ byte, b []byte) *AdvPacket {
-	// A field consists of len, typ, b.
-	// Len is 1 byte for typ plus len(b).
-	if len(a.b)+2+len(b) > MaxEIRPacketLength {
-		b = b[:MaxEIRPacketLength-len(a.b)-2]
-	}
-	a.b = append(a.b, byte(len(b)+1))
-	a.b = append(a.b, typ)
-	a.b = append(a.b, b...)
-	return a
-}
-
-// AppendFlags appends a flag field to the packet.
-func (a *AdvPacket) AppendFlags(f byte) *AdvPacket {
-	return a.AppendField(typeFlags, []byte{f})
-}
-
-// AppendFlags appends a name field to the packet.
-// If the name fits in the space, it will be append as a complete name field, otherwise a short name field.
-func (a *AdvPacket) AppendName(n string) *AdvPacket {
-	typ := byte(typeCompleteName)
-	if len(a.b)+2+len(n) > MaxEIRPacketLength {
-		typ = byte(typeShortName)
-	}
-	return a.AppendField(typ, []byte(n))
-}
-
-// AppendManufacturerData appends a manufacturer data field to the packet.
-func (a *AdvPacket) AppendManufacturerData(id uint16, b []byte) *AdvPacket {
-	d := append([]byte{uint8(id), uint8(id >> 8)}, b...)
-	return a.AppendField(typeManufacturerData, d)
-}
-
-// AppendUUIDFit appends a BLE advertised service UUID
-// packet field if it fits in the packet, and reports whether the UUID fit.
-func (a *AdvPacket) AppendUUIDFit(uu []UUID) bool {
-	// Iterate all UUIDs to see if they fit in the packet or not.
-	fit, l := true, len(a.b)
-	for _, u := range uu {
-		if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) {
-			continue
-		}
-		l += 2 + u.Len()
-		if l > MaxEIRPacketLength {
-			fit = false
-			break
-		}
-	}
-
-	// Append the UUIDs until they no longer fit.
-	for _, u := range uu {
-		if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) {
-			continue
-		}
-		if len(a.b)+2+u.Len() > MaxEIRPacketLength {
-			break
-		}
-		switch l = u.Len(); {
-		case l == 2 && fit:
-			a.AppendField(typeAllUUID16, u.b)
-		case l == 16 && fit:
-			a.AppendField(typeAllUUID128, u.b)
-		case l == 2 && !fit:
-			a.AppendField(typeSomeUUID16, u.b)
-		case l == 16 && !fit:
-			a.AppendField(typeSomeUUID128, u.b)
-		}
-	}
-	return fit
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/attr.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/attr.go b/newtmgr/vendor/github.com/runtimeinc/gatt/attr.go
deleted file mode 100644
index d1ae09d..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/attr.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package gatt
-
-import "log"
-
-// attr is a BLE attribute. It is not exported;
-// managing attributes is an implementation detail.
-type attr struct {
-	h      uint16   // attribute handle
-	typ    UUID     // attribute type in UUID
-	props  Property // attripute property
-	secure Property // attribute secure (implementation specific usage)
-	value  []byte   // attribute value
-
-	pvt interface{} // point to the corresponsing Serveice/Characteristic/Descriptor
-}
-
-// A attrRange is a contiguous range of attributes.
-type attrRange struct {
-	aa   []attr
-	base uint16 // handle for first attr in aa
-}
-
-const (
-	tooSmall = -1
-	tooLarge = -2
-)
-
-// idx returns the index into aa corresponding to attr a.
-// If h is too small, idx returns tooSmall (-1).
-// If h is too large, idx returns tooLarge (-2).
-func (r *attrRange) idx(h int) int {
-	if h < int(r.base) {
-		return tooSmall
-	}
-	if int(h) >= int(r.base)+len(r.aa) {
-		return tooLarge
-	}
-	return h - int(r.base)
-}
-
-// At returns attr a.
-func (r *attrRange) At(h uint16) (a attr, ok bool) {
-	i := r.idx(int(h))
-	if i < 0 {
-		return attr{}, false
-	}
-	return r.aa[i], true
-}
-
-// Subrange returns attributes in range [start, end]; it may
-// return an empty slice. Subrange does not panic for
-// out-of-range start or end.
-func (r *attrRange) Subrange(start, end uint16) []attr {
-	startidx := r.idx(int(start))
-	switch startidx {
-	case tooSmall:
-		startidx = 0
-	case tooLarge:
-		return []attr{}
-	}
-
-	endidx := r.idx(int(end) + 1) // [start, end] includes its upper bound!
-	switch endidx {
-	case tooSmall:
-		return []attr{}
-	case tooLarge:
-		endidx = len(r.aa)
-	}
-	return r.aa[startidx:endidx]
-}
-
-func dumpAttributes(aa []attr) {
-	log.Printf("Generating attribute table:")
-	log.Printf("handle\ttype\tprops\tsecure\tpvt\tvalue")
-	for _, a := range aa {
-		log.Printf("0x%04X\t0x%s\t0x%02X\t0x%02x\t%T\t[ % X ]",
-			a.h, a.typ, int(a.props), int(a.secure), a.pvt, a.value)
-	}
-}
-
-func generateAttributes(ss []*Service, base uint16) *attrRange {
-	var aa []attr
-	h := base
-	last := len(ss) - 1
-	for i, s := range ss {
-		var a []attr
-		h, a = generateServiceAttributes(s, h, i == last)
-		aa = append(aa, a...)
-	}
-	dumpAttributes(aa)
-	return &attrRange{aa: aa, base: base}
-}
-
-func generateServiceAttributes(s *Service, h uint16, last bool) (uint16, []attr) {
-	s.h = h
-	// endh set later
-	a := attr{
-		h:     h,
-		typ:   attrPrimaryServiceUUID,
-		value: s.uuid.b,
-		props: CharRead,
-		pvt:   s,
-	}
-	aa := []attr{a}
-	h++
-
-	for _, c := range s.Characteristics() {
-		var a []attr
-		h, a = generateCharAttributes(c, h)
-		aa = append(aa, a...)
-	}
-
-	s.endh = h - 1
-	if last {
-		h = 0xFFFF
-		s.endh = h
-	}
-
-	return h, aa
-}
-
-func generateCharAttributes(c *Characteristic, h uint16) (uint16, []attr) {
-	c.h = h
-	c.vh = h + 1
-	ca := attr{
-		h:     c.h,
-		typ:   attrCharacteristicUUID,
-		value: append([]byte{byte(c.props), byte(c.vh), byte((c.vh) >> 8)}, c.uuid.b...),
-		props: c.props,
-		pvt:   c,
-	}
-	va := attr{
-		h:     c.vh,
-		typ:   c.uuid,
-		value: c.value,
-		props: c.props,
-		pvt:   c,
-	}
-	h += 2
-
-	aa := []attr{ca, va}
-	for _, d := range c.descs {
-		aa = append(aa, generateDescAttributes(d, h))
-		h++
-	}
-
-	return h, aa
-}
-
-func generateDescAttributes(d *Descriptor, h uint16) attr {
-	d.h = h
-	a := attr{
-		h:     h,
-		typ:   d.uuid,
-		value: d.value,
-		props: d.props,
-		pvt:   d,
-	}
-	return a
-}



[04/41] incubator-mynewt-newt git commit: NOTICE; update copyright years to include 2017.

Posted by ma...@apache.org.
NOTICE; update copyright years to include 2017.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/d6502a39
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/d6502a39
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/d6502a39

Branch: refs/heads/mynewt_1_0_0
Commit: d6502a39f2124b7494d68b4c0dc8a962658de349
Parents: a3ddaaa
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Tue Feb 7 12:02:38 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:29:17 2017 -0800

----------------------------------------------------------------------
 NOTICE | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/d6502a39/NOTICE
----------------------------------------------------------------------
diff --git a/NOTICE b/NOTICE
index 94bea73..8648ba9 100644
--- a/NOTICE
+++ b/NOTICE
@@ -1,5 +1,5 @@
 Apache Mynewt (incubating)
-Copyright 2015-2016 The Apache Software Foundation
+Copyright 2015-2017 The Apache Software Foundation
 
 This product includes software developed at
 The Apache Software Foundation (http://www.apache.org/).


[11/41] incubator-mynewt-newt git commit: remove deadcode.

Posted by ma...@apache.org.
remove deadcode.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/2f04e254
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/2f04e254
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/2f04e254

Branch: refs/heads/mynewt_1_0_0
Commit: 2f04e2541e8231327dc637bcdd472977e0266ee8
Parents: b3f044d
Author: Sterling Hughes <st...@runtime.io>
Authored: Sat Feb 11 15:50:10 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:23 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 10 ----------
 1 file changed, 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/2f04e254/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 13937d6..d04691e 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -29,7 +29,6 @@ import (
 	"github.com/spf13/cobra"
 	"mynewt.apache.org/newt/newt/interfaces"
 	"mynewt.apache.org/newt/newt/newtutil"
-	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
 	"mynewt.apache.org/newt/util"
 )
@@ -139,15 +138,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
 
-	dstPkg, err := pkg.LoadLocalPackage(repo, pkgName)
-	if err != nil {
-		os.Chdir(wd)
-		NewtUsage(cmd, err)
-	}
-
-	dstPkg.SetName(pkgName)
-	dstPkg.Save()
-
 	/* If the last element of the package path changes, rename the include
 	 * directory.
 	 */


[32/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
MYNEWT-653 Use runtimeco gatt fork.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/a1553084
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/a1553084
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/a1553084

Branch: refs/heads/mynewt_1_0_0
Commit: a1553084c899135c7764b5307f9252b4ec42ca01
Parents: 351d90a
Author: Christopher Collins <cc...@apache.org>
Authored: Thu Mar 2 19:12:27 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:38:07 2017 -0800

----------------------------------------------------------------------
 newtmgr/Godeps/Godeps.json                      |  32 +-
 .../vendor/github.com/runtimeco/gatt/.gitignore |   3 +
 .../vendor/github.com/runtimeco/gatt/LICENSE.md |  27 +
 newtmgr/vendor/github.com/runtimeco/gatt/adv.go | 234 +++++
 .../vendor/github.com/runtimeco/gatt/attr.go    | 160 +++
 .../vendor/github.com/runtimeco/gatt/central.go | 152 +++
 .../github.com/runtimeco/gatt/central_darwin.go |  70 ++
 .../github.com/runtimeco/gatt/central_linux.go  | 446 +++++++++
 .../vendor/github.com/runtimeco/gatt/common.go  | 399 ++++++++
 .../vendor/github.com/runtimeco/gatt/const.go   | 153 +++
 .../vendor/github.com/runtimeco/gatt/device.go  | 161 +++
 .../github.com/runtimeco/gatt/device_darwin.go  | 513 ++++++++++
 .../github.com/runtimeco/gatt/device_linux.go   | 240 +++++
 newtmgr/vendor/github.com/runtimeco/gatt/doc.go |  88 ++
 .../github.com/runtimeco/gatt/known_uuid.go     | 122 +++
 .../runtimeco/gatt/l2cap_writer_linux.go        | 156 +++
 .../github.com/runtimeco/gatt/linux/cmd/cmd.go  | 995 +++++++++++++++++++
 .../github.com/runtimeco/gatt/linux/const.go    |  21 +
 .../github.com/runtimeco/gatt/linux/device.go   | 109 ++
 .../github.com/runtimeco/gatt/linux/devices.go  |  58 ++
 .../github.com/runtimeco/gatt/linux/doc.go      |   5 +
 .../github.com/runtimeco/gatt/linux/evt/evt.go  | 382 +++++++
 .../runtimeco/gatt/linux/gioctl/LICENSE.md      |  22 +
 .../runtimeco/gatt/linux/gioctl/README.md       |  12 +
 .../runtimeco/gatt/linux/gioctl/ioctl.go        |  57 ++
 .../github.com/runtimeco/gatt/linux/hci.go      | 400 ++++++++
 .../github.com/runtimeco/gatt/linux/l2cap.go    | 174 ++++
 .../runtimeco/gatt/linux/socket/asm.s           |   8 +
 .../runtimeco/gatt/linux/socket/asm_linux_386.s |  33 +
 .../runtimeco/gatt/linux/socket/socket.go       | 121 +++
 .../gatt/linux/socket/socket_common.go          |  24 +
 .../gatt/linux/socket/socket_darwin.go          |   6 +
 .../runtimeco/gatt/linux/socket/socket_linux.go |   7 +
 .../gatt/linux/socket/socket_linux_386.go       |  31 +
 .../runtimeco/gatt/linux/util/util.go           |  16 +
 .../github.com/runtimeco/gatt/option_darwin.go  |  15 +
 .../github.com/runtimeco/gatt/option_linux.go   |  87 ++
 .../github.com/runtimeco/gatt/peripheral.go     | 102 ++
 .../runtimeco/gatt/peripheral_darwin.go         | 277 ++++++
 .../runtimeco/gatt/peripheral_linux.go          | 448 +++++++++
 .../vendor/github.com/runtimeco/gatt/readme.md  | 115 +++
 .../vendor/github.com/runtimeco/gatt/uuid.go    |  86 ++
 .../github.com/runtimeco/gatt/xpc/LICENSE       |  21 +
 .../vendor/github.com/runtimeco/gatt/xpc/doc.go |   8 +
 .../github.com/runtimeco/gatt/xpc/xpc_darwin.go | 350 +++++++
 .../runtimeco/gatt/xpc/xpc_wrapper_darwin.c     |  85 ++
 .../runtimeco/gatt/xpc/xpc_wrapper_darwin.h     |  32 +
 .../github.com/runtimeinc/gatt/.gitignore       |   3 -
 .../github.com/runtimeinc/gatt/LICENSE.md       |  27 -
 .../vendor/github.com/runtimeinc/gatt/adv.go    | 234 -----
 .../vendor/github.com/runtimeinc/gatt/attr.go   | 160 ---
 .../github.com/runtimeinc/gatt/central.go       | 152 ---
 .../runtimeinc/gatt/central_darwin.go           |  70 --
 .../github.com/runtimeinc/gatt/central_linux.go | 446 ---------
 .../vendor/github.com/runtimeinc/gatt/common.go | 399 --------
 .../vendor/github.com/runtimeinc/gatt/const.go  | 153 ---
 .../vendor/github.com/runtimeinc/gatt/device.go | 161 ---
 .../github.com/runtimeinc/gatt/device_darwin.go | 513 ----------
 .../github.com/runtimeinc/gatt/device_linux.go  | 240 -----
 .../vendor/github.com/runtimeinc/gatt/doc.go    |  88 --
 .../github.com/runtimeinc/gatt/known_uuid.go    | 122 ---
 .../runtimeinc/gatt/l2cap_writer_linux.go       | 156 ---
 .../github.com/runtimeinc/gatt/linux/cmd/cmd.go | 995 -------------------
 .../github.com/runtimeinc/gatt/linux/const.go   |  21 -
 .../github.com/runtimeinc/gatt/linux/device.go  | 109 --
 .../github.com/runtimeinc/gatt/linux/devices.go |  58 --
 .../github.com/runtimeinc/gatt/linux/doc.go     |   5 -
 .../github.com/runtimeinc/gatt/linux/evt/evt.go | 382 -------
 .../runtimeinc/gatt/linux/gioctl/LICENSE.md     |  22 -
 .../runtimeinc/gatt/linux/gioctl/README.md      |  12 -
 .../runtimeinc/gatt/linux/gioctl/ioctl.go       |  57 --
 .../github.com/runtimeinc/gatt/linux/hci.go     | 400 --------
 .../github.com/runtimeinc/gatt/linux/l2cap.go   | 174 ----
 .../runtimeinc/gatt/linux/socket/asm.s          |   8 -
 .../gatt/linux/socket/asm_linux_386.s           |  33 -
 .../runtimeinc/gatt/linux/socket/socket.go      | 121 ---
 .../gatt/linux/socket/socket_common.go          |  24 -
 .../gatt/linux/socket/socket_darwin.go          |   6 -
 .../gatt/linux/socket/socket_linux.go           |   7 -
 .../gatt/linux/socket/socket_linux_386.go       |  31 -
 .../runtimeinc/gatt/linux/util/util.go          |  16 -
 .../github.com/runtimeinc/gatt/option_darwin.go |  15 -
 .../github.com/runtimeinc/gatt/option_linux.go  |  87 --
 .../github.com/runtimeinc/gatt/peripheral.go    | 102 --
 .../runtimeinc/gatt/peripheral_darwin.go        | 277 ------
 .../runtimeinc/gatt/peripheral_linux.go         | 448 ---------
 .../vendor/github.com/runtimeinc/gatt/readme.md | 115 ---
 .../vendor/github.com/runtimeinc/gatt/uuid.go   |  86 --
 .../github.com/runtimeinc/gatt/xpc/LICENSE      |  21 -
 .../github.com/runtimeinc/gatt/xpc/doc.go       |   8 -
 .../runtimeinc/gatt/xpc/xpc_darwin.go           | 350 -------
 .../runtimeinc/gatt/xpc/xpc_wrapper_darwin.c    |  85 --
 .../runtimeinc/gatt/xpc/xpc_wrapper_darwin.h    |  32 -
 93 files changed, 7061 insertions(+), 7033 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/Godeps/Godeps.json
----------------------------------------------------------------------
diff --git a/newtmgr/Godeps/Godeps.json b/newtmgr/Godeps/Godeps.json
index b2571e8..b486ebe 100644
--- a/newtmgr/Godeps/Godeps.json
+++ b/newtmgr/Godeps/Godeps.json
@@ -38,8 +38,8 @@
 			"Rev": "f3009df150dadf309fdee4a54ed65c124afad715"
 		},
 		{
-			"ImportPath": "github.com/runtimeinc/gatt",
-			"Rev": "a8b4c64987af1491ef629e5ec45d3fc47df29eb9"
+			"ImportPath": "github.com/runtimeco/gatt",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
 		},
 		{
 			"ImportPath": "github.com/runtimeinc/gatt/linux",
@@ -116,6 +116,34 @@
 			"ImportPath": "mynewt.apache.org/newt/yaml",
 			"Comment": "pre_sterly_refactor-137-gfcecea4",
 			"Rev": "fcecea4b13ab467168e936a51ef01695833644d8"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux/cmd",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/xpc",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux/evt",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux/gioctl",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux/socket",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
+		},
+		{
+			"ImportPath": "github.com/runtimeco/gatt/linux/util",
+			"Rev": "ceaca1e3d4b698ce4f610b8c71ebc5cde9ad40dd"
 		}
 	]
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/.gitignore
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/.gitignore b/newtmgr/vendor/github.com/runtimeco/gatt/.gitignore
new file mode 100644
index 0000000..7ab0687
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/.gitignore
@@ -0,0 +1,3 @@
+c.out
+c/*-ble
+sample

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/LICENSE.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/LICENSE.md b/newtmgr/vendor/github.com/runtimeco/gatt/LICENSE.md
new file mode 100644
index 0000000..51c07a6
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/LICENSE.md
@@ -0,0 +1,27 @@
+Copyright (c) 2014 PayPal Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+   * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+   * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+   * Neither the name of PayPal Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/adv.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/adv.go b/newtmgr/vendor/github.com/runtimeco/gatt/adv.go
new file mode 100644
index 0000000..3b8a747
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/adv.go
@@ -0,0 +1,234 @@
+package gatt
+
+import (
+	"errors"
+	"log"
+)
+
+// MaxEIRPacketLength is the maximum allowed AdvertisingPacket
+// and ScanResponsePacket length.
+const MaxEIRPacketLength = 31
+
+// ErrEIRPacketTooLong is the error returned when an AdvertisingPacket
+// or ScanResponsePacket is too long.
+var ErrEIRPacketTooLong = errors.New("max packet length is 31")
+
+// Advertising data field types
+const (
+	typeFlags             = 0x01 // Flags
+	typeSomeUUID16        = 0x02 // Incomplete List of 16-bit Service Class UUIDs
+	typeAllUUID16         = 0x03 // Complete List of 16-bit Service Class UUIDs
+	typeSomeUUID32        = 0x04 // Incomplete List of 32-bit Service Class UUIDs
+	typeAllUUID32         = 0x05 // Complete List of 32-bit Service Class UUIDs
+	typeSomeUUID128       = 0x06 // Incomplete List of 128-bit Service Class UUIDs
+	typeAllUUID128        = 0x07 // Complete List of 128-bit Service Class UUIDs
+	typeShortName         = 0x08 // Shortened Local Name
+	typeCompleteName      = 0x09 // Complete Local Name
+	typeTxPower           = 0x0A // Tx Power Level
+	typeClassOfDevice     = 0x0D // Class of Device
+	typeSimplePairingC192 = 0x0E // Simple Pairing Hash C-192
+	typeSimplePairingR192 = 0x0F // Simple Pairing Randomizer R-192
+	typeSecManagerTK      = 0x10 // Security Manager TK Value
+	typeSecManagerOOB     = 0x11 // Security Manager Out of Band Flags
+	typeSlaveConnInt      = 0x12 // Slave Connection Interval Range
+	typeServiceSol16      = 0x14 // List of 16-bit Service Solicitation UUIDs
+	typeServiceSol128     = 0x15 // List of 128-bit Service Solicitation UUIDs
+	typeServiceData16     = 0x16 // Service Data - 16-bit UUID
+	typePubTargetAddr     = 0x17 // Public Target Address
+	typeRandTargetAddr    = 0x18 // Random Target Address
+	typeAppearance        = 0x19 // Appearance
+	typeAdvInterval       = 0x1A // Advertising Interval
+	typeLEDeviceAddr      = 0x1B // LE Bluetooth Device Address
+	typeLERole            = 0x1C // LE Role
+	typeServiceSol32      = 0x1F // List of 32-bit Service Solicitation UUIDs
+	typeServiceData32     = 0x20 // Service Data - 32-bit UUID
+	typeServiceData128    = 0x21 // Service Data - 128-bit UUID
+	typeLESecConfirm      = 0x22 // LE Secure Connections Confirmation Value
+	typeLESecRandom       = 0x23 // LE Secure Connections Random Value
+	typeManufacturerData  = 0xFF // Manufacturer Specific Data
+)
+
+// Advertising type flags
+const (
+	flagLimitedDiscoverable = 0x01 // LE Limited Discoverable Mode
+	flagGeneralDiscoverable = 0x02 // LE General Discoverable Mode
+	flagLEOnly              = 0x04 // BR/EDR Not Supported. Bit 37 of LMP Feature Mask Definitions (Page 0)
+	flagBothController      = 0x08 // Simultaneous LE and BR/EDR to Same Device Capable (Controller).
+	flagBothHost            = 0x10 // Simultaneous LE and BR/EDR to Same Device Capable (Host).
+)
+
+// FIXME: check the unmarshalling of this data structure.
+type ServiceData struct {
+	UUID UUID
+	Data []byte
+}
+
+// This is borrowed from core bluetooth.
+// Embedded/Linux folks might be interested in more details.
+type Advertisement struct {
+	LocalName        string
+	ManufacturerData []byte
+	ServiceData      []ServiceData
+	Services         []UUID
+	OverflowService  []UUID
+	TxPowerLevel     int
+	Connectable      bool
+	SolicitedService []UUID
+	AddressType uint8
+	Address     [6]byte
+}
+
+// This is only used in Linux port.
+func (a *Advertisement) unmarshall(b []byte) error {
+
+	// Utility function for creating a list of uuids.
+	uuidList := func(u []UUID, d []byte, w int) []UUID {
+		for len(d) > 0 {
+			u = append(u, UUID{d[:w]})
+			d = d[w:]
+		}
+		return u
+	}
+
+	for len(b) > 0 {
+		if len(b) < 2 {
+			return errors.New("invalid advertise data")
+		}
+		l, t := b[0], b[1]
+		if len(b) < int(1+l) {
+			return errors.New("invalid advertise data")
+		}
+		d := b[2 : 1+l]
+		switch t {
+		case typeFlags:
+			// TODO: should we do anything about the discoverability here?
+		case typeSomeUUID16:
+			a.Services = uuidList(a.Services, d, 2)
+		case typeAllUUID16:
+			a.Services = uuidList(a.Services, d, 2)
+		case typeSomeUUID32:
+			a.Services = uuidList(a.Services, d, 4)
+		case typeAllUUID32:
+			a.Services = uuidList(a.Services, d, 4)
+		case typeSomeUUID128:
+			a.Services = uuidList(a.Services, d, 16)
+		case typeAllUUID128:
+			a.Services = uuidList(a.Services, d, 16)
+		case typeShortName:
+			a.LocalName = string(d)
+		case typeCompleteName:
+			a.LocalName = string(d)
+		case typeTxPower:
+			a.TxPowerLevel = int(d[0])
+		case typeServiceSol16:
+			a.SolicitedService = uuidList(a.SolicitedService, d, 2)
+		case typeServiceSol128:
+			a.SolicitedService = uuidList(a.SolicitedService, d, 16)
+		case typeServiceSol32:
+			a.SolicitedService = uuidList(a.SolicitedService, d, 4)
+		case typeManufacturerData:
+			a.ManufacturerData = make([]byte, len(d))
+			copy(a.ManufacturerData, d)
+		// case typeServiceData16,
+		// case typeServiceData32,
+		// case typeServiceData128:
+		default:
+			log.Printf("DATA: [ % X ]", d)
+		}
+		b = b[1+l:]
+	}
+	return nil
+}
+
+// AdvPacket is an utility to help crafting advertisment or scan response data.
+type AdvPacket struct {
+	b []byte
+}
+
+// Bytes returns an 31-byte array, which contains up to 31 bytes of the packet.
+func (a *AdvPacket) Bytes() [31]byte {
+	b := [31]byte{}
+	copy(b[:], a.b)
+	return b
+}
+
+// Len returns the length of the packets with a maximum of 31.
+func (a *AdvPacket) Len() int {
+	if len(a.b) > 31 {
+		return 31
+	}
+	return len(a.b)
+}
+
+// AppendField appends a BLE advertising packet field.
+// TODO: refuse to append field if it'd make the packet too long.
+func (a *AdvPacket) AppendField(typ byte, b []byte) *AdvPacket {
+	// A field consists of len, typ, b.
+	// Len is 1 byte for typ plus len(b).
+	if len(a.b)+2+len(b) > MaxEIRPacketLength {
+		b = b[:MaxEIRPacketLength-len(a.b)-2]
+	}
+	a.b = append(a.b, byte(len(b)+1))
+	a.b = append(a.b, typ)
+	a.b = append(a.b, b...)
+	return a
+}
+
+// AppendFlags appends a flag field to the packet.
+func (a *AdvPacket) AppendFlags(f byte) *AdvPacket {
+	return a.AppendField(typeFlags, []byte{f})
+}
+
+// AppendFlags appends a name field to the packet.
+// If the name fits in the space, it will be append as a complete name field, otherwise a short name field.
+func (a *AdvPacket) AppendName(n string) *AdvPacket {
+	typ := byte(typeCompleteName)
+	if len(a.b)+2+len(n) > MaxEIRPacketLength {
+		typ = byte(typeShortName)
+	}
+	return a.AppendField(typ, []byte(n))
+}
+
+// AppendManufacturerData appends a manufacturer data field to the packet.
+func (a *AdvPacket) AppendManufacturerData(id uint16, b []byte) *AdvPacket {
+	d := append([]byte{uint8(id), uint8(id >> 8)}, b...)
+	return a.AppendField(typeManufacturerData, d)
+}
+
+// AppendUUIDFit appends a BLE advertised service UUID
+// packet field if it fits in the packet, and reports whether the UUID fit.
+func (a *AdvPacket) AppendUUIDFit(uu []UUID) bool {
+	// Iterate all UUIDs to see if they fit in the packet or not.
+	fit, l := true, len(a.b)
+	for _, u := range uu {
+		if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) {
+			continue
+		}
+		l += 2 + u.Len()
+		if l > MaxEIRPacketLength {
+			fit = false
+			break
+		}
+	}
+
+	// Append the UUIDs until they no longer fit.
+	for _, u := range uu {
+		if u.Equal(attrGAPUUID) || u.Equal(attrGATTUUID) {
+			continue
+		}
+		if len(a.b)+2+u.Len() > MaxEIRPacketLength {
+			break
+		}
+		switch l = u.Len(); {
+		case l == 2 && fit:
+			a.AppendField(typeAllUUID16, u.b)
+		case l == 16 && fit:
+			a.AppendField(typeAllUUID128, u.b)
+		case l == 2 && !fit:
+			a.AppendField(typeSomeUUID16, u.b)
+		case l == 16 && !fit:
+			a.AppendField(typeSomeUUID128, u.b)
+		}
+	}
+	return fit
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/attr.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/attr.go b/newtmgr/vendor/github.com/runtimeco/gatt/attr.go
new file mode 100644
index 0000000..d1ae09d
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/attr.go
@@ -0,0 +1,160 @@
+package gatt
+
+import "log"
+
+// attr is a BLE attribute. It is not exported;
+// managing attributes is an implementation detail.
+type attr struct {
+	h      uint16   // attribute handle
+	typ    UUID     // attribute type in UUID
+	props  Property // attripute property
+	secure Property // attribute secure (implementation specific usage)
+	value  []byte   // attribute value
+
+	pvt interface{} // point to the corresponsing Serveice/Characteristic/Descriptor
+}
+
+// A attrRange is a contiguous range of attributes.
+type attrRange struct {
+	aa   []attr
+	base uint16 // handle for first attr in aa
+}
+
+const (
+	tooSmall = -1
+	tooLarge = -2
+)
+
+// idx returns the index into aa corresponding to attr a.
+// If h is too small, idx returns tooSmall (-1).
+// If h is too large, idx returns tooLarge (-2).
+func (r *attrRange) idx(h int) int {
+	if h < int(r.base) {
+		return tooSmall
+	}
+	if int(h) >= int(r.base)+len(r.aa) {
+		return tooLarge
+	}
+	return h - int(r.base)
+}
+
+// At returns attr a.
+func (r *attrRange) At(h uint16) (a attr, ok bool) {
+	i := r.idx(int(h))
+	if i < 0 {
+		return attr{}, false
+	}
+	return r.aa[i], true
+}
+
+// Subrange returns attributes in range [start, end]; it may
+// return an empty slice. Subrange does not panic for
+// out-of-range start or end.
+func (r *attrRange) Subrange(start, end uint16) []attr {
+	startidx := r.idx(int(start))
+	switch startidx {
+	case tooSmall:
+		startidx = 0
+	case tooLarge:
+		return []attr{}
+	}
+
+	endidx := r.idx(int(end) + 1) // [start, end] includes its upper bound!
+	switch endidx {
+	case tooSmall:
+		return []attr{}
+	case tooLarge:
+		endidx = len(r.aa)
+	}
+	return r.aa[startidx:endidx]
+}
+
+func dumpAttributes(aa []attr) {
+	log.Printf("Generating attribute table:")
+	log.Printf("handle\ttype\tprops\tsecure\tpvt\tvalue")
+	for _, a := range aa {
+		log.Printf("0x%04X\t0x%s\t0x%02X\t0x%02x\t%T\t[ % X ]",
+			a.h, a.typ, int(a.props), int(a.secure), a.pvt, a.value)
+	}
+}
+
+func generateAttributes(ss []*Service, base uint16) *attrRange {
+	var aa []attr
+	h := base
+	last := len(ss) - 1
+	for i, s := range ss {
+		var a []attr
+		h, a = generateServiceAttributes(s, h, i == last)
+		aa = append(aa, a...)
+	}
+	dumpAttributes(aa)
+	return &attrRange{aa: aa, base: base}
+}
+
+func generateServiceAttributes(s *Service, h uint16, last bool) (uint16, []attr) {
+	s.h = h
+	// endh set later
+	a := attr{
+		h:     h,
+		typ:   attrPrimaryServiceUUID,
+		value: s.uuid.b,
+		props: CharRead,
+		pvt:   s,
+	}
+	aa := []attr{a}
+	h++
+
+	for _, c := range s.Characteristics() {
+		var a []attr
+		h, a = generateCharAttributes(c, h)
+		aa = append(aa, a...)
+	}
+
+	s.endh = h - 1
+	if last {
+		h = 0xFFFF
+		s.endh = h
+	}
+
+	return h, aa
+}
+
+func generateCharAttributes(c *Characteristic, h uint16) (uint16, []attr) {
+	c.h = h
+	c.vh = h + 1
+	ca := attr{
+		h:     c.h,
+		typ:   attrCharacteristicUUID,
+		value: append([]byte{byte(c.props), byte(c.vh), byte((c.vh) >> 8)}, c.uuid.b...),
+		props: c.props,
+		pvt:   c,
+	}
+	va := attr{
+		h:     c.vh,
+		typ:   c.uuid,
+		value: c.value,
+		props: c.props,
+		pvt:   c,
+	}
+	h += 2
+
+	aa := []attr{ca, va}
+	for _, d := range c.descs {
+		aa = append(aa, generateDescAttributes(d, h))
+		h++
+	}
+
+	return h, aa
+}
+
+func generateDescAttributes(d *Descriptor, h uint16) attr {
+	d.h = h
+	a := attr{
+		h:     h,
+		typ:   d.uuid,
+		value: d.value,
+		props: d.props,
+		pvt:   d,
+	}
+	return a
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/central.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/central.go b/newtmgr/vendor/github.com/runtimeco/gatt/central.go
new file mode 100644
index 0000000..55bd2c1
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/central.go
@@ -0,0 +1,152 @@
+package gatt
+
+import (
+	"bytes"
+	"errors"
+	"fmt"
+	"sync"
+)
+
+// Central is the interface that represent a remote central device.
+type Central interface {
+	ID() string   // ID returns platform specific ID of the remote central device.
+	Close() error // Close disconnects the connection.
+	MTU() int     // MTU returns the current connection mtu.
+}
+
+type ResponseWriter interface {
+	// Write writes data to return as the characteristic value.
+	Write([]byte) (int, error)
+
+	// SetStatus reports the result of the read operation. See the Status* constants.
+	SetStatus(byte)
+}
+
+// responseWriter is the default implementation of ResponseWriter.
+type responseWriter struct {
+	capacity int
+	buf      *bytes.Buffer
+	status   byte
+}
+
+func newResponseWriter(c int) *responseWriter {
+	return &responseWriter{
+		capacity: c,
+		buf:      new(bytes.Buffer),
+		status:   StatusSuccess,
+	}
+}
+
+func (w *responseWriter) Write(b []byte) (int, error) {
+	if avail := w.capacity - w.buf.Len(); avail < len(b) {
+		return 0, fmt.Errorf("requested write %d bytes, %d available", len(b), avail)
+	}
+	return w.buf.Write(b)
+}
+
+func (w *responseWriter) SetStatus(status byte) { w.status = status }
+func (w *responseWriter) bytes() []byte         { return w.buf.Bytes() }
+
+// A ReadHandler handles GATT read requests.
+type ReadHandler interface {
+	ServeRead(resp ResponseWriter, req *ReadRequest)
+}
+
+// ReadHandlerFunc is an adapter to allow the use of
+// ordinary functions as ReadHandlers. If f is a function
+// with the appropriate signature, ReadHandlerFunc(f) is a
+// ReadHandler that calls f.
+type ReadHandlerFunc func(resp ResponseWriter, req *ReadRequest)
+
+// ServeRead returns f(r, maxlen, offset).
+func (f ReadHandlerFunc) ServeRead(resp ResponseWriter, req *ReadRequest) {
+	f(resp, req)
+}
+
+// A WriteHandler handles GATT write requests.
+// Write and WriteNR requests are presented identically;
+// the server will ensure that a response is sent if appropriate.
+type WriteHandler interface {
+	ServeWrite(r Request, data []byte) (status byte)
+}
+
+// WriteHandlerFunc is an adapter to allow the use of
+// ordinary functions as WriteHandlers. If f is a function
+// with the appropriate signature, WriteHandlerFunc(f) is a
+// WriteHandler that calls f.
+type WriteHandlerFunc func(r Request, data []byte) byte
+
+// ServeWrite returns f(r, data).
+func (f WriteHandlerFunc) ServeWrite(r Request, data []byte) byte {
+	return f(r, data)
+}
+
+// A NotifyHandler handles GATT notification requests.
+// Notifications can be sent using the provided notifier.
+type NotifyHandler interface {
+	ServeNotify(r Request, n Notifier)
+}
+
+// NotifyHandlerFunc is an adapter to allow the use of
+// ordinary functions as NotifyHandlers. If f is a function
+// with the appropriate signature, NotifyHandlerFunc(f) is a
+// NotifyHandler that calls f.
+type NotifyHandlerFunc func(r Request, n Notifier)
+
+// ServeNotify calls f(r, n).
+func (f NotifyHandlerFunc) ServeNotify(r Request, n Notifier) {
+	f(r, n)
+}
+
+// A Notifier provides a means for a GATT server to send
+// notifications about value changes to a connected device.
+// Notifiers are provided by NotifyHandlers.
+type Notifier interface {
+	// Write sends data to the central.
+	Write(data []byte) (int, error)
+
+	// Done reports whether the central has requested not to
+	// receive any more notifications with this notifier.
+	Done() bool
+
+	// Cap returns the maximum number of bytes that may be sent
+	// in a single notification.
+	Cap() int
+}
+
+type notifier struct {
+	central *central
+	a       *attr
+	maxlen  int
+	donemu  sync.RWMutex
+	done    bool
+}
+
+func newNotifier(c *central, a *attr, maxlen int) *notifier {
+	return &notifier{central: c, a: a, maxlen: maxlen}
+}
+
+func (n *notifier) Write(b []byte) (int, error) {
+	n.donemu.RLock()
+	defer n.donemu.RUnlock()
+	if n.done {
+		return 0, errors.New("central stopped notifications")
+	}
+	return n.central.sendNotification(n.a, b)
+}
+
+func (n *notifier) Cap() int {
+	return n.maxlen
+}
+
+func (n *notifier) Done() bool {
+	n.donemu.RLock()
+	defer n.donemu.RUnlock()
+	return n.done
+}
+
+func (n *notifier) stop() {
+	n.donemu.Lock()
+	n.done = true
+	n.donemu.Unlock()
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/central_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/central_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/central_darwin.go
new file mode 100644
index 0000000..47faa2e
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/central_darwin.go
@@ -0,0 +1,70 @@
+package gatt
+
+import (
+	"sync"
+
+	"github.com/runtimeco/gatt/xpc"
+)
+
+type central struct {
+	dev         *device
+	uuid        UUID
+	mtu         int
+	notifiers   map[uint16]*notifier
+	notifiersmu *sync.Mutex
+}
+
+func newCentral(d *device, u UUID) *central {
+	return &central{
+		dev:         d,
+		mtu:         23,
+		uuid:        u,
+		notifiers:   make(map[uint16]*notifier),
+		notifiersmu: &sync.Mutex{},
+	}
+}
+
+func (c *central) ID() string   { return c.uuid.String() }
+func (c *central) Close() error { return nil }
+func (c *central) MTU() int     { return c.mtu }
+
+func (c *central) sendNotification(a *attr, b []byte) (int, error) {
+	data := make([]byte, len(b))
+	copy(data, b) // have to make a copy, why?
+	c.dev.sendCmd(15, xpc.Dict{
+		// "kCBMsgArgUUIDs": [][]byte{reverse(c.uuid.b)}, // connection interrupted
+		// "kCBMsgArgUUIDs": [][]byte{c.uuid.b}, // connection interrupted
+		// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(reverse(c.uuid.b))},
+		// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(c.uuid.b)},
+		// "kCBMsgArgUUIDs": reverse(c.uuid.b),
+		//
+		// FIXME: Sigh... tried to targeting the central, but couldn't get work.
+		// So, broadcast to all subscribed centrals. Either of the following works.
+		// "kCBMsgArgUUIDs": []xpc.UUID{},
+		"kCBMsgArgUUIDs":       [][]byte{},
+		"kCBMsgArgAttributeID": a.h,
+		"kCBMsgArgData":        data,
+	})
+	return len(b), nil
+}
+
+func (c *central) startNotify(a *attr, maxlen int) {
+	c.notifiersmu.Lock()
+	defer c.notifiersmu.Unlock()
+	if _, found := c.notifiers[a.h]; found {
+		return
+	}
+	n := newNotifier(c, a, maxlen)
+	c.notifiers[a.h] = n
+	char := a.pvt.(*Characteristic)
+	go char.nhandler.ServeNotify(Request{Central: c}, n)
+}
+
+func (c *central) stopNotify(a *attr) {
+	c.notifiersmu.Lock()
+	defer c.notifiersmu.Unlock()
+	if n, found := c.notifiers[a.h]; found {
+		n.stop()
+		delete(c.notifiers, a.h)
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/central_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/central_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/central_linux.go
new file mode 100644
index 0000000..3ae6994
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/central_linux.go
@@ -0,0 +1,446 @@
+package gatt
+
+import (
+	"encoding/binary"
+	"io"
+	"net"
+	"sync"
+)
+
+type security int
+
+const (
+	securityLow = iota
+	securityMed
+	securityHigh
+)
+
+type central struct {
+	attrs       *attrRange
+	mtu         uint16
+	addr        net.HardwareAddr
+	security    security
+	l2conn      io.ReadWriteCloser
+	notifiers   map[uint16]*notifier
+	notifiersmu *sync.Mutex
+}
+
+func newCentral(a *attrRange, addr net.HardwareAddr, l2conn io.ReadWriteCloser) *central {
+	return &central{
+		attrs:       a,
+		mtu:         23,
+		addr:        addr,
+		security:    securityLow,
+		l2conn:      l2conn,
+		notifiers:   make(map[uint16]*notifier),
+		notifiersmu: &sync.Mutex{},
+	}
+}
+
+func (c *central) ID() string {
+	return c.addr.String()
+}
+
+func (c *central) Close() error {
+	c.notifiersmu.Lock()
+	defer c.notifiersmu.Unlock()
+	for _, n := range c.notifiers {
+		n.stop()
+	}
+	return c.l2conn.Close()
+}
+
+func (c *central) MTU() int {
+	return int(c.mtu)
+}
+
+func (c *central) loop() {
+	for {
+		// L2CAP implementations shall support a minimum MTU size of 48 bytes.
+		// The default value is 672 bytes
+		b := make([]byte, 672)
+		n, err := c.l2conn.Read(b)
+		if n == 0 || err != nil {
+			c.Close()
+			break
+		}
+		if rsp := c.handleReq(b[:n]); rsp != nil {
+			c.l2conn.Write(rsp)
+		}
+	}
+}
+
+// handleReq dispatches a raw request from the central shim
+// to an appropriate handler, based on its type.
+// It panics if len(b) == 0.
+func (c *central) handleReq(b []byte) []byte {
+	var resp []byte
+	switch reqType, req := b[0], b[1:]; reqType {
+	case attOpMtuReq:
+		resp = c.handleMTU(req)
+	case attOpFindInfoReq:
+		resp = c.handleFindInfo(req)
+	case attOpFindByTypeValueReq:
+		resp = c.handleFindByTypeValue(req)
+	case attOpReadByTypeReq:
+		resp = c.handleReadByType(req)
+	case attOpReadReq:
+		resp = c.handleRead(req)
+	case attOpReadBlobReq:
+		resp = c.handleReadBlob(req)
+	case attOpReadByGroupReq:
+		resp = c.handleReadByGroup(req)
+	case attOpWriteReq, attOpWriteCmd:
+		resp = c.handleWrite(reqType, req)
+	case attOpReadMultiReq, attOpPrepWriteReq, attOpExecWriteReq, attOpSignedWriteCmd:
+		fallthrough
+	default:
+		resp = attErrorRsp(reqType, 0x0000, attEcodeReqNotSupp)
+	}
+	return resp
+}
+
+func (c *central) handleMTU(b []byte) []byte {
+	c.mtu = binary.LittleEndian.Uint16(b[:2])
+	if c.mtu < 23 {
+		c.mtu = 23
+	}
+	if c.mtu >= 256 {
+		c.mtu = 256
+	}
+	return []byte{attOpMtuRsp, uint8(c.mtu), uint8(c.mtu >> 8)}
+}
+
+// REQ: FindInfoReq(0x04), StartHandle, EndHandle
+// RSP: FindInfoRsp(0x05), UUIDFormat, Handle, UUID, Handle, UUID, ...
+func (c *central) handleFindInfo(b []byte) []byte {
+	start, end := readHandleRange(b[:4])
+
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpFindInfoRsp)
+
+	uuidLen := -1
+	for _, a := range c.attrs.Subrange(start, end) {
+		if uuidLen == -1 {
+			uuidLen = a.typ.Len()
+			if uuidLen == 2 {
+				w.WriteByteFit(0x01) // TODO: constants for 16bit vs 128bit uuid magic numbers here
+			} else {
+				w.WriteByteFit(0x02)
+			}
+		}
+		if a.typ.Len() != uuidLen {
+			break
+		}
+		w.Chunk()
+		w.WriteUint16Fit(a.h)
+		w.WriteUUIDFit(a.typ)
+		if ok := w.Commit(); !ok {
+			break
+		}
+	}
+
+	if uuidLen == -1 {
+		return attErrorRsp(attOpFindInfoReq, start, attEcodeAttrNotFound)
+	}
+	return w.Bytes()
+}
+
+// REQ: FindByTypeValueReq(0x06), StartHandle, EndHandle, Type(UUID), Value
+// RSP: FindByTypeValueRsp(0x07), AttrHandle, GroupEndHandle, AttrHandle, GroupEndHandle, ...
+func (c *central) handleFindByTypeValue(b []byte) []byte {
+	start, end := readHandleRange(b[:4])
+	t := UUID{b[4:6]}
+	u := UUID{b[6:]}
+
+	// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
+	// More sepcifically, the "Discover Primary Services By Service UUID" sub-procedure
+	if !t.Equal(attrPrimaryServiceUUID) {
+		return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
+	}
+
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpFindByTypeValueRsp)
+
+	var wrote bool
+	for _, a := range c.attrs.Subrange(start, end) {
+		if !a.typ.Equal(attrPrimaryServiceUUID) {
+			continue
+		}
+		if !(UUID{a.value}.Equal(u)) {
+			continue
+		}
+		s := a.pvt.(*Service)
+		w.Chunk()
+		w.WriteUint16Fit(s.h)
+		w.WriteUint16Fit(s.endh)
+		if ok := w.Commit(); !ok {
+			break
+		}
+		wrote = true
+	}
+	if !wrote {
+		return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
+	}
+
+	return w.Bytes()
+}
+
+// REQ: ReadByType(0x08), StartHandle, EndHandle, Type(UUID)
+// RSP: ReadByType(0x09), LenOfEachDataField, DataField, DataField, ...
+func (c *central) handleReadByType(b []byte) []byte {
+	start, end := readHandleRange(b[:4])
+	t := UUID{b[4:]}
+
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpReadByTypeRsp)
+	uuidLen := -1
+	for _, a := range c.attrs.Subrange(start, end) {
+		if !a.typ.Equal(t) {
+			continue
+		}
+		if (a.secure&CharRead) != 0 && c.security > securityLow {
+			return attErrorRsp(attOpReadByTypeReq, start, attEcodeAuthentication)
+		}
+		v := a.value
+		if v == nil {
+			rsp := newResponseWriter(int(c.mtu - 1))
+			req := &ReadRequest{
+				Request: Request{Central: c},
+				Cap:     int(c.mtu - 1),
+				Offset:  0,
+			}
+			if c, ok := a.pvt.(*Characteristic); ok {
+				c.rhandler.ServeRead(rsp, req)
+			} else if d, ok := a.pvt.(*Descriptor); ok {
+				d.rhandler.ServeRead(rsp, req)
+			}
+			v = rsp.bytes()
+		}
+		if uuidLen == -1 {
+			uuidLen = len(v)
+			w.WriteByteFit(byte(uuidLen) + 2)
+		}
+		if len(v) != uuidLen {
+			break
+		}
+		w.Chunk()
+		w.WriteUint16Fit(a.h)
+		w.WriteFit(v)
+		if ok := w.Commit(); !ok {
+			break
+		}
+	}
+	if uuidLen == -1 {
+		return attErrorRsp(attOpReadByTypeReq, start, attEcodeAttrNotFound)
+	}
+	return w.Bytes()
+}
+
+// REQ: ReadReq(0x0A), Handle
+// RSP: ReadRsp(0x0B), Value
+func (c *central) handleRead(b []byte) []byte {
+	h := binary.LittleEndian.Uint16(b)
+	a, ok := c.attrs.At(h)
+	if !ok {
+		return attErrorRsp(attOpReadReq, h, attEcodeInvalidHandle)
+	}
+	if a.props&CharRead == 0 {
+		return attErrorRsp(attOpReadReq, h, attEcodeReadNotPerm)
+	}
+	if a.secure&CharRead != 0 && c.security > securityLow {
+		return attErrorRsp(attOpReadReq, h, attEcodeAuthentication)
+	}
+	v := a.value
+	if v == nil {
+		req := &ReadRequest{
+			Request: Request{Central: c},
+			Cap:     int(c.mtu - 1),
+			Offset:  0,
+		}
+		rsp := newResponseWriter(int(c.mtu - 1))
+		if c, ok := a.pvt.(*Characteristic); ok {
+			c.rhandler.ServeRead(rsp, req)
+		} else if d, ok := a.pvt.(*Descriptor); ok {
+			d.rhandler.ServeRead(rsp, req)
+		}
+		v = rsp.bytes()
+	}
+
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpReadRsp)
+	w.Chunk()
+	w.WriteFit(v)
+	w.CommitFit()
+	return w.Bytes()
+}
+
+// FIXME: check this, untested, might be broken
+func (c *central) handleReadBlob(b []byte) []byte {
+	h := binary.LittleEndian.Uint16(b)
+	offset := binary.LittleEndian.Uint16(b[2:])
+	a, ok := c.attrs.At(h)
+	if !ok {
+		return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidHandle)
+	}
+	if a.props&CharRead == 0 {
+		return attErrorRsp(attOpReadBlobReq, h, attEcodeReadNotPerm)
+	}
+	if a.secure&CharRead != 0 && c.security > securityLow {
+		return attErrorRsp(attOpReadBlobReq, h, attEcodeAuthentication)
+	}
+	v := a.value
+	if v == nil {
+		req := &ReadRequest{
+			Request: Request{Central: c},
+			Cap:     int(c.mtu - 1),
+			Offset:  int(offset),
+		}
+		rsp := newResponseWriter(int(c.mtu - 1))
+		if c, ok := a.pvt.(*Characteristic); ok {
+			c.rhandler.ServeRead(rsp, req)
+		} else if d, ok := a.pvt.(*Descriptor); ok {
+			d.rhandler.ServeRead(rsp, req)
+		}
+		v = rsp.bytes()
+		offset = 0 // the server has already adjusted for the offset
+	}
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpReadBlobRsp)
+	w.Chunk()
+	w.WriteFit(v)
+	if ok := w.ChunkSeek(offset); !ok {
+		return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidOffset)
+	}
+	w.CommitFit()
+	return w.Bytes()
+}
+
+func (c *central) handleReadByGroup(b []byte) []byte {
+	start, end := readHandleRange(b)
+	t := UUID{b[4:]}
+
+	// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
+	// More specifically, the "Discover All Primary Services" sub-procedure.
+	if !t.Equal(attrPrimaryServiceUUID) {
+		return attErrorRsp(attOpReadByGroupReq, start, attEcodeUnsuppGrpType)
+	}
+
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpReadByGroupRsp)
+	uuidLen := -1
+	for _, a := range c.attrs.Subrange(start, end) {
+		if !a.typ.Equal(attrPrimaryServiceUUID) {
+			continue
+		}
+		if uuidLen == -1 {
+			uuidLen = len(a.value)
+			w.WriteByteFit(byte(uuidLen + 4))
+		}
+		if uuidLen != len(a.value) {
+			break
+		}
+		s := a.pvt.(*Service)
+		w.Chunk()
+		w.WriteUint16Fit(s.h)
+		w.WriteUint16Fit(s.endh)
+		w.WriteFit(a.value)
+		if ok := w.Commit(); !ok {
+			break
+		}
+	}
+	if uuidLen == -1 {
+		return attErrorRsp(attOpReadByGroupReq, start, attEcodeAttrNotFound)
+	}
+	return w.Bytes()
+}
+
+func (c *central) handleWrite(reqType byte, b []byte) []byte {
+	h := binary.LittleEndian.Uint16(b[:2])
+	value := b[2:]
+
+	a, ok := c.attrs.At(h)
+	if !ok {
+		return attErrorRsp(reqType, h, attEcodeInvalidHandle)
+	}
+
+	noRsp := reqType == attOpWriteCmd
+	charFlag := CharWrite
+	if noRsp {
+		charFlag = CharWriteNR
+	}
+	if a.props&charFlag == 0 {
+		return attErrorRsp(reqType, h, attEcodeWriteNotPerm)
+	}
+	if a.secure&charFlag == 0 && c.security > securityLow {
+		return attErrorRsp(reqType, h, attEcodeAuthentication)
+	}
+
+	// Props of Service and Characteristic declration are read only.
+	// So we only need deal with writable descriptors here.
+	// (Characteristic's value is implemented with descriptor)
+	if !a.typ.Equal(attrClientCharacteristicConfigUUID) {
+		// Regular write, not CCC
+		r := Request{Central: c}
+		if c, ok := a.pvt.(*Characteristic); ok {
+			c.whandler.ServeWrite(r, value)
+		} else if d, ok := a.pvt.(*Characteristic); ok {
+			d.whandler.ServeWrite(r, value)
+		}
+		if noRsp {
+			return nil
+		} else {
+			return []byte{attOpWriteRsp}
+		}
+	}
+
+	// CCC/descriptor write
+	if len(value) != 2 {
+		return attErrorRsp(reqType, h, attEcodeInvalAttrValueLen)
+	}
+	ccc := binary.LittleEndian.Uint16(value)
+	// char := a.pvt.(*Descriptor).char
+	if ccc&(gattCCCNotifyFlag|gattCCCIndicateFlag) != 0 {
+		c.startNotify(&a, int(c.mtu-3))
+	} else {
+		c.stopNotify(&a)
+	}
+	if noRsp {
+		return nil
+	}
+	return []byte{attOpWriteRsp}
+}
+
+func (c *central) sendNotification(a *attr, data []byte) (int, error) {
+	w := newL2capWriter(c.mtu)
+	w.WriteByteFit(attOpHandleNotify)
+	w.WriteUint16Fit(a.pvt.(*Descriptor).char.vh)
+	w.WriteFit(data)
+	return c.l2conn.Write(w.Bytes())
+}
+
+func readHandleRange(b []byte) (start, end uint16) {
+	return binary.LittleEndian.Uint16(b), binary.LittleEndian.Uint16(b[2:])
+}
+
+func (c *central) startNotify(a *attr, maxlen int) {
+	c.notifiersmu.Lock()
+	defer c.notifiersmu.Unlock()
+	if _, found := c.notifiers[a.h]; found {
+		return
+	}
+	char := a.pvt.(*Descriptor).char
+	n := newNotifier(c, a, maxlen)
+	c.notifiers[a.h] = n
+	go char.nhandler.ServeNotify(Request{Central: c}, n)
+}
+
+func (c *central) stopNotify(a *attr) {
+	c.notifiersmu.Lock()
+	defer c.notifiersmu.Unlock()
+	// char := a.pvt.(*Characteristic)
+	if n, found := c.notifiers[a.h]; found {
+		n.stop()
+		delete(c.notifiers, a.h)
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/common.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/common.go b/newtmgr/vendor/github.com/runtimeco/gatt/common.go
new file mode 100644
index 0000000..4fa2389
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/common.go
@@ -0,0 +1,399 @@
+package gatt
+
+// Supported statuses for GATT characteristic read/write operations.
+// These correspond to att constants in the BLE spec
+const (
+	StatusSuccess         = 0
+	StatusInvalidOffset   = 1
+	StatusUnexpectedError = 2
+)
+
+// A Request is the context for a request from a connected central device.
+// TODO: Replace this with more general context, such as:
+// http://godoc.org/golang.org/x/net/context
+type Request struct {
+	Central Central
+}
+
+// A ReadRequest is a characteristic read request from a connected device.
+type ReadRequest struct {
+	Request
+	Cap    int // maximum allowed reply length
+	Offset int // request value offset
+}
+
+type Property int
+
+// Characteristic property flags (spec 3.3.3.1)
+const (
+	CharBroadcast   Property = 0x01 // may be brocasted
+	CharRead        Property = 0x02 // may be read
+	CharWriteNR     Property = 0x04 // may be written to, with no reply
+	CharWrite       Property = 0x08 // may be written to, with a reply
+	CharNotify      Property = 0x10 // supports notifications
+	CharIndicate    Property = 0x20 // supports Indications
+	CharSignedWrite Property = 0x40 // supports signed write
+	CharExtended    Property = 0x80 // supports extended properties
+)
+
+func (p Property) String() (result string) {
+	if (p & CharBroadcast) != 0 {
+		result += "broadcast "
+	}
+	if (p & CharRead) != 0 {
+		result += "read "
+	}
+	if (p & CharWriteNR) != 0 {
+		result += "writeWithoutResponse "
+	}
+	if (p & CharWrite) != 0 {
+		result += "write "
+	}
+	if (p & CharNotify) != 0 {
+		result += "notify "
+	}
+	if (p & CharIndicate) != 0 {
+		result += "indicate "
+	}
+	if (p & CharSignedWrite) != 0 {
+		result += "authenticateSignedWrites "
+	}
+	if (p & CharExtended) != 0 {
+		result += "extendedProperties "
+	}
+	return
+}
+
+// A Service is a BLE service.
+type Service struct {
+	uuid  UUID
+	chars []*Characteristic
+
+	h    uint16
+	endh uint16
+}
+
+// NewService creates and initialize a new Service using u as it's UUID.
+func NewService(u UUID) *Service {
+	return &Service{uuid: u}
+}
+
+// AddCharacteristic adds a characteristic to a service.
+// AddCharacteristic panics if the service already contains another
+// characteristic with the same UUID.
+func (s *Service) AddCharacteristic(u UUID) *Characteristic {
+	for _, c := range s.chars {
+		if c.uuid.Equal(u) {
+			panic("service already contains a characteristic with uuid " + u.String())
+		}
+	}
+	c := &Characteristic{uuid: u, svc: s}
+	s.chars = append(s.chars, c)
+	return c
+}
+
+// UUID returns the UUID of the service.
+func (s *Service) UUID() UUID { return s.uuid }
+
+// Name returns the specificatin name of the service according to its UUID.
+// If the UUID is not assigne, Name returns an empty string.
+func (s *Service) Name() string {
+	return knownServices[s.uuid.String()].Name
+}
+
+// Handle returns the Handle of the service.
+func (s *Service) Handle() uint16 { return s.h }
+
+// EndHandle returns the End Handle of the service.
+func (s *Service) EndHandle() uint16 { return s.endh }
+
+// SetHandle sets the Handle of the service.
+func (s *Service) SetHandle(h uint16) { s.h = h }
+
+// SetEndHandle sets the End Handle of the service.
+func (s *Service) SetEndHandle(endh uint16) { s.endh = endh }
+
+// SetCharacteristics sets the Characteristics of the service.
+func (s *Service) SetCharacteristics(chars []*Characteristic) { s.chars = chars }
+
+// Characteristic returns the contained characteristic of this service.
+func (s *Service) Characteristics() []*Characteristic { return s.chars }
+
+// A Characteristic is a BLE characteristic.
+type Characteristic struct {
+	uuid   UUID
+	props  Property // enabled properties
+	secure Property // security enabled properties
+	svc    *Service
+	cccd   *Descriptor
+	descs  []*Descriptor
+
+	value []byte
+
+	// All the following fields are only used in peripheral/server implementation.
+	rhandler ReadHandler
+	whandler WriteHandler
+	nhandler NotifyHandler
+
+	h    uint16
+	vh   uint16
+	endh uint16
+}
+
+// NewCharacteristic creates and returns a Characteristic.
+func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic {
+	c := &Characteristic{
+		uuid:  u,
+		svc:   s,
+		props: props,
+		h:     h,
+		vh:    vh,
+	}
+
+	return c
+}
+
+// Handle returns the Handle of the characteristic.
+func (c *Characteristic) Handle() uint16 { return c.h }
+
+// VHandle returns the Value Handle of the characteristic.
+func (c *Characteristic) VHandle() uint16 { return c.vh }
+
+// EndHandle returns the End Handle of the characteristic.
+func (c *Characteristic) EndHandle() uint16 { return c.endh }
+
+// Descriptor returns the Descriptor of the characteristic.
+func (c *Characteristic) Descriptor() *Descriptor { return c.cccd }
+
+// SetHandle sets the Handle of the characteristic.
+func (c *Characteristic) SetHandle(h uint16) { c.h = h }
+
+// SetVHandle sets the Value Handle of the characteristic.
+func (c *Characteristic) SetVHandle(vh uint16) { c.vh = vh }
+
+// SetEndHandle sets the End Handle of the characteristic.
+func (c *Characteristic) SetEndHandle(endh uint16) { c.endh = endh }
+
+// SetDescriptor sets the Descriptor of the characteristic.
+func (c *Characteristic) SetDescriptor(cccd *Descriptor) { c.cccd = cccd }
+
+// SetDescriptors sets the list of Descriptor of the characteristic.
+func (c *Characteristic) SetDescriptors(descs []*Descriptor) { c.descs = descs }
+
+// UUID returns the UUID of the characteristic.
+func (c *Characteristic) UUID() UUID {
+	return c.uuid
+}
+
+// Name returns the specificatin name of the characteristic.
+// If the UUID is not assigned, Name returns empty string.
+func (c *Characteristic) Name() string {
+	return knownCharacteristics[c.uuid.String()].Name
+}
+
+// Service returns the containing service of this characteristic.
+func (c *Characteristic) Service() *Service {
+	return c.svc
+}
+
+// Properties returns the properties of this characteristic.
+func (c *Characteristic) Properties() Property {
+	return c.props
+}
+
+// Descriptors returns the contained descriptors of this characteristic.
+func (c *Characteristic) Descriptors() []*Descriptor {
+	return c.descs
+}
+
+// AddDescriptor adds a descriptor to a characteristic.
+// AddDescriptor panics if the characteristic already contains another
+// descriptor with the same UUID.
+func (c *Characteristic) AddDescriptor(u UUID) *Descriptor {
+	for _, d := range c.descs {
+		if d.uuid.Equal(u) {
+			panic("service already contains a characteristic with uuid " + u.String())
+		}
+	}
+	d := &Descriptor{uuid: u, char: c}
+	c.descs = append(c.descs, d)
+	return d
+}
+
+// SetValue makes the characteristic support read requests, and returns a
+// static value. SetValue must be called before the containing service is
+// added to a server.
+// SetValue panics if the characteristic has been configured with a ReadHandler.
+func (c *Characteristic) SetValue(b []byte) {
+	if c.rhandler != nil {
+		panic("charactristic has been configured with a read handler")
+	}
+	c.props |= CharRead
+	// c.secure |= CharRead
+	c.value = make([]byte, len(b))
+	copy(c.value, b)
+}
+
+// HandleRead makes the characteristic support read requests, and routes read
+// requests to h. HandleRead must be called before the containing service is
+// added to a server.
+// HandleRead panics if the characteristic has been configured with a static value.
+func (c *Characteristic) HandleRead(h ReadHandler) {
+	if c.value != nil {
+		panic("charactristic has been configured with a static value")
+	}
+	c.props |= CharRead
+	// c.secure |= CharRead
+	c.rhandler = h
+}
+
+// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
+func (c *Characteristic) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
+	c.HandleRead(ReadHandlerFunc(f))
+}
+
+// HandleWrite makes the characteristic support write and write-no-response
+// requests, and routes write requests to h.
+// The WriteHandler does not differentiate between write and write-no-response
+// requests; it is handled automatically.
+// HandleWrite must be called before the containing service is added to a server.
+func (c *Characteristic) HandleWrite(h WriteHandler) {
+	c.props |= CharWrite | CharWriteNR
+	// c.secure |= CharWrite | CharWriteNR
+	c.whandler = h
+}
+
+// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
+func (c *Characteristic) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
+	c.HandleWrite(WriteHandlerFunc(f))
+}
+
+// HandleNotify makes the characteristic support notify requests, and routes
+// notification requests to h. HandleNotify must be called before the
+// containing service is added to a server.
+func (c *Characteristic) HandleNotify(h NotifyHandler) {
+	if c.cccd != nil {
+		return
+	}
+	p := CharNotify | CharIndicate
+	c.props |= p
+	c.nhandler = h
+
+	// add ccc (client characteristic configuration) descriptor
+	secure := Property(0)
+	// If the characteristic requested secure notifications,
+	// then set ccc security to r/w.
+	if c.secure&p != 0 {
+		secure = CharRead | CharWrite
+	}
+	cd := &Descriptor{
+		uuid:   attrClientCharacteristicConfigUUID,
+		props:  CharRead | CharWrite | CharWriteNR,
+		secure: secure,
+		// FIXME: currently, we always return 0, which is inaccurate.
+		// Each connection should have it's own copy of this value.
+		value: []byte{0x00, 0x00},
+		char:  c,
+	}
+	c.cccd = cd
+	c.descs = append(c.descs, cd)
+}
+
+// HandleNotifyFunc calls HandleNotify(NotifyHandlerFunc(f)).
+func (c *Characteristic) HandleNotifyFunc(f func(r Request, n Notifier)) {
+	c.HandleNotify(NotifyHandlerFunc(f))
+}
+
+// TODO
+// func (c *Characteristic) SubscribedCentrals() []Central{
+// }
+
+// Descriptor is a BLE descriptor
+type Descriptor struct {
+	uuid   UUID
+	char   *Characteristic
+	props  Property // enabled properties
+	secure Property // security enabled properties
+
+	h     uint16
+	value []byte
+
+	rhandler ReadHandler
+	whandler WriteHandler
+}
+
+// Handle returns the Handle of the descriptor.
+func (d *Descriptor) Handle() uint16 { return d.h }
+
+// SetHandle sets the Handle of the descriptor.
+func (d *Descriptor) SetHandle(h uint16) { d.h = h }
+
+// NewDescriptor creates and returns a Descriptor.
+func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor {
+	cd := &Descriptor{
+		uuid: u,
+		h:    h,
+		char: char,
+	}
+	return cd
+}
+
+// UUID returns the UUID of the descriptor.
+func (d *Descriptor) UUID() UUID {
+	return d.uuid
+}
+
+// Name returns the specificatin name of the descriptor.
+// If the UUID is not assigned, returns an empty string.
+func (d *Descriptor) Name() string {
+	return knownDescriptors[d.uuid.String()].Name
+}
+
+// Characteristic returns the containing characteristic of the descriptor.
+func (d *Descriptor) Characteristic() *Characteristic {
+	return d.char
+}
+
+// SetValue makes the descriptor support read requests, and returns a static value.
+// SetValue must be called before the containing service is added to a server.
+// SetValue panics if the descriptor has already configured with a ReadHandler.
+func (d *Descriptor) SetValue(b []byte) {
+	if d.rhandler != nil {
+		panic("descriptor has been configured with a read handler")
+	}
+	d.props |= CharRead
+	// d.secure |= CharRead
+	d.value = make([]byte, len(b))
+	copy(d.value, b)
+}
+
+// HandleRead makes the descriptor support read requests, and routes read requests to h.
+// HandleRead must be called before the containing service is added to a server.
+// HandleRead panics if the descriptor has been configured with a static value.
+func (d *Descriptor) HandleRead(h ReadHandler) {
+	if d.value != nil {
+		panic("descriptor has been configured with a static value")
+	}
+	d.props |= CharRead
+	// d.secure |= CharRead
+	d.rhandler = h
+}
+
+// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
+func (d *Descriptor) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
+	d.HandleRead(ReadHandlerFunc(f))
+}
+
+// HandleWrite makes the descriptor support write and write-no-response requests, and routes write requests to h.
+// The WriteHandler does not differentiate between write and write-no-response requests; it is handled automatically.
+// HandleWrite must be called before the containing service is added to a server.
+func (d *Descriptor) HandleWrite(h WriteHandler) {
+	d.props |= CharWrite | CharWriteNR
+	// d.secure |= CharWrite | CharWriteNR
+	d.whandler = h
+}
+
+// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
+func (d *Descriptor) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
+	d.HandleWrite(WriteHandlerFunc(f))
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/const.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/const.go b/newtmgr/vendor/github.com/runtimeco/gatt/const.go
new file mode 100644
index 0000000..4a04b04
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/const.go
@@ -0,0 +1,153 @@
+package gatt
+
+// This file includes constants from the BLE spec.
+
+var (
+	attrGAPUUID  = UUID16(0x1800)
+	attrGATTUUID = UUID16(0x1801)
+
+	attrPrimaryServiceUUID   = UUID16(0x2800)
+	attrSecondaryServiceUUID = UUID16(0x2801)
+	attrIncludeUUID          = UUID16(0x2802)
+	attrCharacteristicUUID   = UUID16(0x2803)
+
+	attrClientCharacteristicConfigUUID = UUID16(0x2902)
+	attrServerCharacteristicConfigUUID = UUID16(0x2903)
+
+	attrDeviceNameUUID        = UUID16(0x2A00)
+	attrAppearanceUUID        = UUID16(0x2A01)
+	attrPeripheralPrivacyUUID = UUID16(0x2A02)
+	attrReconnectionAddrUUID  = UUID16(0x2A03)
+	attrPeferredParamsUUID    = UUID16(0x2A04)
+	attrServiceChangedUUID    = UUID16(0x2A05)
+)
+
+const (
+	gattCCCNotifyFlag   = 0x0001
+	gattCCCIndicateFlag = 0x0002
+)
+
+const (
+	attOpError              = 0x01
+	attOpMtuReq             = 0x02
+	attOpMtuRsp             = 0x03
+	attOpFindInfoReq        = 0x04
+	attOpFindInfoRsp        = 0x05
+	attOpFindByTypeValueReq = 0x06
+	attOpFindByTypeValueRsp = 0x07
+	attOpReadByTypeReq      = 0x08
+	attOpReadByTypeRsp      = 0x09
+	attOpReadReq            = 0x0a
+	attOpReadRsp            = 0x0b
+	attOpReadBlobReq        = 0x0c
+	attOpReadBlobRsp        = 0x0d
+	attOpReadMultiReq       = 0x0e
+	attOpReadMultiRsp       = 0x0f
+	attOpReadByGroupReq     = 0x10
+	attOpReadByGroupRsp     = 0x11
+	attOpWriteReq           = 0x12
+	attOpWriteRsp           = 0x13
+	attOpWriteCmd           = 0x52
+	attOpPrepWriteReq       = 0x16
+	attOpPrepWriteRsp       = 0x17
+	attOpExecWriteReq       = 0x18
+	attOpExecWriteRsp       = 0x19
+	attOpHandleNotify       = 0x1b
+	attOpHandleInd          = 0x1d
+	attOpHandleCnf          = 0x1e
+	attOpSignedWriteCmd     = 0xd2
+)
+
+type attEcode byte
+
+const (
+	attEcodeSuccess           attEcode = 0x00 // Success
+	attEcodeInvalidHandle     attEcode = 0x01 // The attribute handle given was not valid on this server.
+	attEcodeReadNotPerm       attEcode = 0x02 // The attribute cannot be read.
+	attEcodeWriteNotPerm      attEcode = 0x03 // The attribute cannot be written.
+	attEcodeInvalidPDU        attEcode = 0x04 // The attribute PDU was invalid.
+	attEcodeAuthentication    attEcode = 0x05 // The attribute requires authentication before it can be read or written.
+	attEcodeReqNotSupp        attEcode = 0x06 // Attribute server does not support the request received from the client.
+	attEcodeInvalidOffset     attEcode = 0x07 // Offset specified was past the end of the attribute.
+	attEcodeAuthorization     attEcode = 0x08 // The attribute requires authorization before it can be read or written.
+	attEcodePrepQueueFull     attEcode = 0x09 // Too many prepare writes have been queued.
+	attEcodeAttrNotFound      attEcode = 0x0a // No attribute found within the given attribute handle range.
+	attEcodeAttrNotLong       attEcode = 0x0b // The attribute cannot be read or written using the Read Blob Request.
+	attEcodeInsuffEncrKeySize attEcode = 0x0c // The Encryption Key Size used for encrypting this link is insufficient.
+	attEcodeInvalAttrValueLen attEcode = 0x0d // The attribute value length is invalid for the operation.
+	attEcodeUnlikely          attEcode = 0x0e // The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested.
+	attEcodeInsuffEnc         attEcode = 0x0f // The attribute requires encryption before it can be read or written.
+	attEcodeUnsuppGrpType     attEcode = 0x10 // The attribute type is not a supported grouping attribute as defined by a higher layer specification.
+	attEcodeInsuffResources   attEcode = 0x11 // Insufficient Resources to complete the request.
+)
+
+func (a attEcode) Error() string {
+	switch i := int(a); {
+	case i < 0x11:
+		return attEcodeName[a]
+	case i >= 0x12 && i <= 0x7F: // Reserved for future use
+		return "reserved error code"
+	case i >= 0x80 && i <= 0x9F: // Application Error, defined by higher level
+		return "reserved error code"
+	case i >= 0xA0 && i <= 0xDF: // Reserved for future use
+		return "reserved error code"
+	case i >= 0xE0 && i <= 0xFF: // Common profile and service error codes
+		return "profile or service error"
+	default: // can't happen, just make compiler happy
+		return "unkown error"
+	}
+}
+
+var attEcodeName = map[attEcode]string{
+	attEcodeSuccess:           "success",
+	attEcodeInvalidHandle:     "invalid handle",
+	attEcodeReadNotPerm:       "read not permitted",
+	attEcodeWriteNotPerm:      "write not permitted",
+	attEcodeInvalidPDU:        "invalid PDU",
+	attEcodeAuthentication:    "insufficient authentication",
+	attEcodeReqNotSupp:        "request not supported",
+	attEcodeInvalidOffset:     "invalid offset",
+	attEcodeAuthorization:     "insufficient authorization",
+	attEcodePrepQueueFull:     "prepare queue full",
+	attEcodeAttrNotFound:      "attribute not found",
+	attEcodeAttrNotLong:       "attribute not long",
+	attEcodeInsuffEncrKeySize: "insufficient encryption key size",
+	attEcodeInvalAttrValueLen: "invalid attribute value length",
+	attEcodeUnlikely:          "unlikely error",
+	attEcodeInsuffEnc:         "insufficient encryption",
+	attEcodeUnsuppGrpType:     "unsupported group type",
+	attEcodeInsuffResources:   "insufficient resources",
+}
+
+func attErrorRsp(op byte, h uint16, s attEcode) []byte {
+	return attErr{opcode: op, attr: h, status: s}.Marshal()
+}
+
+// attRspFor maps from att request
+// codes to att response codes.
+var attRspFor = map[byte]byte{
+	attOpMtuReq:             attOpMtuRsp,
+	attOpFindInfoReq:        attOpFindInfoRsp,
+	attOpFindByTypeValueReq: attOpFindByTypeValueRsp,
+	attOpReadByTypeReq:      attOpReadByTypeRsp,
+	attOpReadReq:            attOpReadRsp,
+	attOpReadBlobReq:        attOpReadBlobRsp,
+	attOpReadMultiReq:       attOpReadMultiRsp,
+	attOpReadByGroupReq:     attOpReadByGroupRsp,
+	attOpWriteReq:           attOpWriteRsp,
+	attOpPrepWriteReq:       attOpPrepWriteRsp,
+	attOpExecWriteReq:       attOpExecWriteRsp,
+}
+
+type attErr struct {
+	opcode uint8
+	attr   uint16
+	status attEcode
+}
+
+// TODO: Reformulate in a way that lets the caller avoid allocs.
+// Accept a []byte? Write directly to an io.Writer?
+func (e attErr) Marshal() []byte {
+	// little-endian encoding for attr
+	return []byte{attOpError, e.opcode, byte(e.attr), byte(e.attr >> 8), byte(e.status)}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/device.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/device.go b/newtmgr/vendor/github.com/runtimeco/gatt/device.go
new file mode 100644
index 0000000..eba96cf
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/device.go
@@ -0,0 +1,161 @@
+package gatt
+
+import "errors"
+
+var notImplemented = errors.New("not implemented")
+
+type State int
+
+const (
+	StateUnknown      State = 0
+	StateResetting    State = 1
+	StateUnsupported  State = 2
+	StateUnauthorized State = 3
+	StatePoweredOff   State = 4
+	StatePoweredOn    State = 5
+)
+
+func (s State) String() string {
+	str := []string{
+		"Unknown",
+		"Resetting",
+		"Unsupported",
+		"Unauthorized",
+		"PoweredOff",
+		"PoweredOn",
+	}
+	return str[int(s)]
+}
+
+// Device defines the interface for a BLE device.
+// Since an interface can't define fields(properties). To implement the
+// callback support for cerntain events, deviceHandler is defined and
+// implementation of Device on different platforms should embed it in
+// order to keep have keep compatible in API level.
+// Package users can use the Handler to set these handlers.
+type Device interface {
+	Init(stateChanged func(Device, State)) error
+
+	// Advertise advertise AdvPacket
+	Advertise(a *AdvPacket) error
+
+	// AdvertiseNameAndServices advertises device name, and specified service UUIDs.
+	// It tres to fit the UUIDs in the advertising packet as much as possible.
+	// If name doesn't fit in the advertising packet, it will be put in scan response.
+	AdvertiseNameAndServices(name string, ss []UUID) error
+
+	// AdvertiseIBeaconData advertise iBeacon with given manufacturer data.
+	AdvertiseIBeaconData(b []byte) error
+
+	// AdvertisingIbeacon advertises iBeacon with specified parameters.
+	AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error
+
+	// StopAdvertising stops advertising.
+	StopAdvertising() error
+
+	// RemoveAllServices removes all services that are currently in the database.
+	RemoveAllServices() error
+
+	// Add Service add a service to database.
+	AddService(s *Service) error
+
+	// SetServices set the specified service to the database.
+	// It removes all currently added services, if any.
+	SetServices(ss []*Service) error
+
+	// Scan discovers surounding remote peripherals that have the Service UUID specified in ss.
+	// If ss is set to nil, all devices scanned are reported.
+	// dup specifies weather duplicated advertisement should be reported or not.
+	// When a remote peripheral is discovered, the PeripheralDiscovered Handler is called.
+	Scan(ss []UUID, dup bool)
+
+	// StopScanning stops scanning.
+	StopScanning()
+
+	// Connect connects to a remote peripheral.
+	Connect(p Peripheral)
+
+	// CancelConnection disconnects a remote peripheral.
+	CancelConnection(p Peripheral)
+
+	// Handle registers the specified handlers.
+	Handle(h ...Handler)
+
+	// Stop HCI Connection
+        Stop() error
+
+	// Option sets the options specified.
+	Option(o ...Option) error
+}
+
+// deviceHandler is the handlers(callbacks) of the Device.
+type deviceHandler struct {
+	// stateChanged is called when the device states changes.
+	stateChanged func(d Device, s State)
+
+	// connect is called when a remote central device connects to the device.
+	centralConnected func(c Central)
+
+	// disconnect is called when a remote central device disconnects to the device.
+	centralDisconnected func(c Central)
+
+	// peripheralDiscovered is called when a remote peripheral device is found during scan procedure.
+	peripheralDiscovered func(p Peripheral, a *Advertisement, rssi int)
+
+	// peripheralConnected is called when a remote peripheral is conneted.
+	peripheralConnected func(p Peripheral, err error)
+
+	// peripheralConnected is called when a remote peripheral is disconneted.
+	peripheralDisconnected func(p Peripheral, err error)
+}
+
+// A Handler is a self-referential function, which registers the options specified.
+// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
+type Handler func(Device)
+
+// Handle registers the specified handlers.
+func (d *device) Handle(hh ...Handler) {
+	for _, h := range hh {
+		h(d)
+	}
+}
+
+// CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.
+func CentralConnected(f func(Central)) Handler {
+	return func(d Device) { d.(*device).centralConnected = f }
+}
+
+// CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.
+func CentralDisconnected(f func(Central)) Handler {
+	return func(d Device) { d.(*device).centralDisconnected = f }
+}
+
+// PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.
+func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler {
+	return func(d Device) { d.(*device).peripheralDiscovered = f }
+}
+
+// PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.
+func PeripheralConnected(f func(Peripheral, error)) Handler {
+	return func(d Device) { d.(*device).peripheralConnected = f }
+}
+
+// PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.
+func PeripheralDisconnected(f func(Peripheral, error)) Handler {
+	return func(d Device) { d.(*device).peripheralDisconnected = f }
+}
+
+// An Option is a self-referential function, which sets the option specified.
+// Most Options are platform-specific, which gives more fine-grained control over the device at a cost of losing portibility.
+// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
+type Option func(Device) error
+
+// Option sets the options specified.
+// Some options can only be set before the device is initialized; they are best used with NewDevice instead of Option.
+func (d *device) Option(opts ...Option) error {
+	var err error
+	for _, opt := range opts {
+		err = opt(d)
+	}
+	return err
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/device_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/device_darwin.go b/newtmgr/vendor/github.com/runtimeco/gatt/device_darwin.go
new file mode 100644
index 0000000..acf4431
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/device_darwin.go
@@ -0,0 +1,513 @@
+package gatt
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"log"
+	"sync"
+	"time"
+
+	"github.com/runtimeco/gatt/xpc"
+)
+
+const (
+	peripheralDiscovered   = 37
+	peripheralConnected    = 38
+	peripheralDisconnected = 40
+	// below constants for Yosemite
+	rssiRead                   = 55
+	includedServicesDiscovered = 63
+	serviceDiscovered          = 56
+	characteristicsDiscovered  = 64
+	characteristicRead         = 71
+	characteristicWritten      = 72
+	notificationValueSet       = 74
+	descriptorsDiscovered      = 76
+	descriptorRead             = 79
+	descriptorWritten          = 80
+)
+
+type device struct {
+	deviceHandler
+
+	conn xpc.XPC
+
+	role int // 1: peripheralManager (server), 0: centralManager (client)
+
+	reqc chan message
+	rspc chan message
+
+	// Only used in client/centralManager implementation
+	plist   map[string]*peripheral
+	plistmu *sync.Mutex
+
+	// Only used in server/peripheralManager implementation
+
+	attrN int
+	attrs map[int]*attr
+
+	subscribers map[string]*central
+}
+
+func NewDevice(opts ...Option) (Device, error) {
+	d := &device{
+		reqc:    make(chan message),
+		rspc:    make(chan message),
+		plist:   map[string]*peripheral{},
+		plistmu: &sync.Mutex{},
+
+		attrN: 1,
+		attrs: make(map[int]*attr),
+
+		subscribers: make(map[string]*central),
+	}
+	d.Option(opts...)
+	d.conn = xpc.XpcConnect("com.apple.blued", d)
+	return d, nil
+}
+
+func (d *device) Init(f func(Device, State)) error {
+	go d.loop()
+	rsp := d.sendReq(1, xpc.Dict{
+		"kCBMsgArgName":    fmt.Sprintf("gopher-%v", time.Now().Unix()),
+		"kCBMsgArgOptions": xpc.Dict{"kCBInitOptionShowPowerAlert": 1},
+		"kCBMsgArgType":    d.role,
+	})
+	d.stateChanged = f
+	go d.stateChanged(d, State(rsp.MustGetInt("kCBMsgArgState")))
+	return nil
+}
+
+func (d *device) Advertise(a *AdvPacket) error {
+	rsp := d.sendReq(8, xpc.Dict{
+		"kCBAdvDataAppleMfgData": a.b, // not a.Bytes(). should be slice
+	})
+
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return errors.New("FIXME: Advertise error")
+	}
+	return nil
+}
+
+func (d *device) AdvertiseNameAndServices(name string, ss []UUID) error {
+	us := uuidSlice(ss)
+	rsp := d.sendReq(8, xpc.Dict{
+		"kCBAdvDataLocalName":    name,
+		"kCBAdvDataServiceUUIDs": us},
+	)
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return errors.New("FIXME: Advertise error")
+	}
+	return nil
+}
+
+func (d *device) AdvertiseIBeaconData(data []byte) error {
+	var utsname xpc.Utsname
+	xpc.Uname(&utsname)
+
+	var rsp xpc.Dict
+
+	if utsname.Release >= "14." {
+		l := len(data)
+		buf := bytes.NewBuffer([]byte{byte(l + 5), 0xFF, 0x4C, 0x00, 0x02, byte(l)})
+		buf.Write(data)
+		rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleMfgData": buf.Bytes()})
+	} else {
+		rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleBeaconKey": data})
+	}
+
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return errors.New("FIXME: Advertise error")
+	}
+
+	return nil
+}
+
+func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
+	b := make([]byte, 21)
+	copy(b, reverse(u.b))                     // Big endian
+	binary.BigEndian.PutUint16(b[16:], major) // Big endian
+	binary.BigEndian.PutUint16(b[18:], minor) // Big endian
+	b[20] = uint8(pwr)                        // Measured Tx Power
+	return d.AdvertiseIBeaconData(b)
+}
+
+func (d *device) StopAdvertising() error {
+	rsp := d.sendReq(9, nil)
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return errors.New("FIXME: Stop Advertise error")
+	}
+	return nil
+}
+
+func (d *device) RemoveAllServices() error {
+	d.sendCmd(12, nil)
+	return nil
+}
+
+func (d *device) AddService(s *Service) error {
+	if s.uuid.Equal(attrGAPUUID) || s.uuid.Equal(attrGATTUUID) {
+		// skip GATT and GAP services
+		return nil
+	}
+
+	xs := xpc.Dict{
+		"kCBMsgArgAttributeID":     d.attrN,
+		"kCBMsgArgAttributeIDs":    []int{},
+		"kCBMsgArgCharacteristics": nil,
+		"kCBMsgArgType":            1, // 1 => primary, 0 => excluded
+		"kCBMsgArgUUID":            reverse(s.uuid.b),
+	}
+	d.attrN++
+
+	xcs := xpc.Array{}
+	for _, c := range s.Characteristics() {
+		props := 0
+		perm := 0
+		if c.props&CharRead != 0 {
+			props |= 0x02
+			if CharRead&c.secure != 0 {
+				perm |= 0x04
+			} else {
+				perm |= 0x01
+			}
+		}
+		if c.props&CharWriteNR != 0 {
+			props |= 0x04
+			if c.secure&CharWriteNR != 0 {
+				perm |= 0x08
+			} else {
+				perm |= 0x02
+			}
+		}
+		if c.props&CharWrite != 0 {
+			props |= 0x08
+			if c.secure&CharWrite != 0 {
+				perm |= 0x08
+			} else {
+				perm |= 0x02
+			}
+		}
+		if c.props&CharNotify != 0 {
+			if c.secure&CharNotify != 0 {
+				props |= 0x100
+			} else {
+				props |= 0x10
+			}
+		}
+		if c.props&CharIndicate != 0 {
+			if c.secure&CharIndicate != 0 {
+				props |= 0x200
+			} else {
+				props |= 0x20
+			}
+		}
+
+		xc := xpc.Dict{
+			"kCBMsgArgAttributeID":              d.attrN,
+			"kCBMsgArgUUID":                     reverse(c.uuid.b),
+			"kCBMsgArgAttributePermissions":     perm,
+			"kCBMsgArgCharacteristicProperties": props,
+			"kCBMsgArgData":                     c.value,
+		}
+		d.attrs[d.attrN] = &attr{h: uint16(d.attrN), value: c.value, pvt: c}
+		d.attrN++
+
+		xds := xpc.Array{}
+		for _, d := range c.Descriptors() {
+			if d.uuid.Equal(attrClientCharacteristicConfigUUID) {
+				// skip CCCD
+				continue
+			}
+			xd := xpc.Dict{
+				"kCBMsgArgData": d.value,
+				"kCBMsgArgUUID": reverse(d.uuid.b),
+			}
+			xds = append(xds, xd)
+		}
+		xc["kCBMsgArgDescriptors"] = xds
+		xcs = append(xcs, xc)
+	}
+	xs["kCBMsgArgCharacteristics"] = xcs
+
+	rsp := d.sendReq(10, xs)
+	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
+		return errors.New("FIXME: Add Srvice error")
+	}
+	return nil
+}
+
+func (d *device) SetServices(ss []*Service) error {
+	d.RemoveAllServices()
+	for _, s := range ss {
+		d.AddService(s)
+	}
+	return nil
+}
+
+func (d *device) Scan(ss []UUID, dup bool) {
+	args := xpc.Dict{
+		"kCBMsgArgUUIDs": uuidSlice(ss),
+		"kCBMsgArgOptions": xpc.Dict{
+			"kCBScanOptionAllowDuplicates": map[bool]int{true: 1, false: 0}[dup],
+		},
+	}
+	d.sendCmd(29, args)
+}
+
+func (d *device) StopScanning() {
+	d.sendCmd(30, nil)
+}
+
+func (d *device) Connect(p Peripheral) {
+	pp := p.(*peripheral)
+	d.plist[pp.id.String()] = pp
+	d.sendCmd(31,
+		xpc.Dict{
+			"kCBMsgArgDeviceUUID": pp.id,
+			"kCBMsgArgOptions": xpc.Dict{
+				"kCBConnectOptionNotifyOnDisconnection": 1,
+			},
+		})
+}
+
+func (d *device) respondToRequest(id int, args xpc.Dict) {
+
+	switch id {
+	case 19: // ReadRequest
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		t := args.MustGetInt("kCBMsgArgTransactionID")
+		a := args.MustGetInt("kCBMsgArgAttributeID")
+		o := args.MustGetInt("kCBMsgArgOffset")
+
+		attr := d.attrs[a]
+		v := attr.value
+		if v == nil {
+			c := newCentral(d, u)
+			req := &ReadRequest{
+				Request: Request{Central: c},
+				Cap:     int(c.mtu - 1),
+				Offset:  o,
+			}
+			rsp := newResponseWriter(int(c.mtu - 1))
+			if c, ok := attr.pvt.(*Characteristic); ok {
+				c.rhandler.ServeRead(rsp, req)
+				v = rsp.bytes()
+			}
+		}
+
+		d.sendCmd(13, xpc.Dict{
+			"kCBMsgArgAttributeID":   a,
+			"kCBMsgArgData":          v,
+			"kCBMsgArgTransactionID": t,
+			"kCBMsgArgResult":        0,
+		})
+
+	case 20: // WriteRequest
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		t := args.MustGetInt("kCBMsgArgTransactionID")
+		a := 0
+		noRsp := false
+		xxws := args.MustGetArray("kCBMsgArgATTWrites")
+		for _, xxw := range xxws {
+			xw := xxw.(xpc.Dict)
+			if a == 0 {
+				a = xw.MustGetInt("kCBMsgArgAttributeID")
+			}
+			o := xw.MustGetInt("kCBMsgArgOffset")
+			i := xw.MustGetInt("kCBMsgArgIgnoreResponse")
+			b := xw.MustGetBytes("kCBMsgArgData")
+			_ = o
+			attr := d.attrs[a]
+			c := newCentral(d, u)
+			r := Request{Central: c}
+			attr.pvt.(*Characteristic).whandler.ServeWrite(r, b)
+			if i == 1 {
+				noRsp = true
+			}
+
+		}
+		if noRsp {
+			break
+		}
+		d.sendCmd(13, xpc.Dict{
+			"kCBMsgArgAttributeID":   a,
+			"kCBMsgArgData":          nil,
+			"kCBMsgArgTransactionID": t,
+			"kCBMsgArgResult":        0,
+		})
+
+	case 21: // subscribed
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		a := args.MustGetInt("kCBMsgArgAttributeID")
+		attr := d.attrs[a]
+		c := newCentral(d, u)
+		d.subscribers[u.String()] = c
+		c.startNotify(attr, c.mtu)
+
+	case 22: // unubscribed
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		a := args.MustGetInt("kCBMsgArgAttributeID")
+		attr := d.attrs[a]
+		if c := d.subscribers[u.String()]; c != nil {
+			c.stopNotify(attr)
+		}
+
+	case 23: // notificationSent
+	}
+}
+
+/*
+ * OSX GATT library currently doesn't work for Mynewt, so adding this stub to keep
+ * it buildable for OSX.
+ */
+func (d *device) Stop() error {
+	return nil
+}
+
+func (d *device) CancelConnection(p Peripheral) {
+	d.sendCmd(32, xpc.Dict{"kCBMsgArgDeviceUUID": p.(*peripheral).id})
+}
+
+// process device events and asynchronous errors
+// (implements XpcEventHandler)
+func (d *device) HandleXpcEvent(event xpc.Dict, err error) {
+	if err != nil {
+		log.Println("error:", err)
+		return
+	}
+
+	id := event.MustGetInt("kCBMsgId")
+	args := event.MustGetDict("kCBMsgArgs")
+	//log.Printf(">> %d, %v", id, args)
+
+	switch id {
+	case // device event
+		6,  // StateChanged
+		16, // AdvertisingStarted
+		17, // AdvertisingStopped
+		18: // ServiceAdded
+		d.rspc <- message{id: id, args: args}
+
+	case
+		19, // ReadRequest
+		20, // WriteRequest
+		21, // Subscribe
+		22, // Unubscribe
+		23: // Confirmation
+		d.respondToRequest(id, args)
+
+	case peripheralDiscovered:
+		xa := args.MustGetDict("kCBMsgArgAdvertisementData")
+		if len(xa) == 0 {
+			return
+		}
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		a := &Advertisement{
+			LocalName:        xa.GetString("kCBAdvDataLocalName", args.GetString("kCBMsgArgName", "")),
+			TxPowerLevel:     xa.GetInt("kCBAdvDataTxPowerLevel", 0),
+			ManufacturerData: xa.GetBytes("kCBAdvDataManufacturerData", nil),
+		}
+
+		rssi := args.MustGetInt("kCBMsgArgRssi")
+
+		if xu, ok := xa["kCBAdvDataServiceUUIDs"]; ok {
+			for _, xs := range xu.(xpc.Array) {
+				s := UUID{reverse(xs.([]byte))}
+				a.Services = append(a.Services, s)
+			}
+		}
+		if xsds, ok := xa["kCBAdvDataServiceData"]; ok {
+			xsd := xsds.(xpc.Array)
+			for i := 0; i < len(xsd); i += 2 {
+				sd := ServiceData{
+					UUID: UUID{xsd[i].([]byte)},
+					Data: xsd[i+1].([]byte),
+				}
+				a.ServiceData = append(a.ServiceData, sd)
+			}
+		}
+		if d.peripheralDiscovered != nil {
+			go d.peripheralDiscovered(&peripheral{id: xpc.UUID(u.b), d: d}, a, rssi)
+		}
+
+	case peripheralConnected:
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		p := &peripheral{
+			id:    xpc.UUID(u.b),
+			d:     d,
+			reqc:  make(chan message),
+			rspc:  make(chan message),
+			quitc: make(chan struct{}),
+			sub:   newSubscriber(),
+		}
+		d.plistmu.Lock()
+		d.plist[u.String()] = p
+		d.plistmu.Unlock()
+		go p.loop()
+
+		if d.peripheralConnected != nil {
+			go d.peripheralConnected(p, nil)
+		}
+
+	case peripheralDisconnected:
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		d.plistmu.Lock()
+		p := d.plist[u.String()]
+		delete(d.plist, u.String())
+		d.plistmu.Unlock()
+		if d.peripheralDisconnected != nil {
+			d.peripheralDisconnected(p, nil) // TODO: Get Result as error?
+		}
+		close(p.quitc)
+
+	case // Peripheral events
+		rssiRead,
+		serviceDiscovered,
+		includedServicesDiscovered,
+		characteristicsDiscovered,
+		characteristicRead,
+		characteristicWritten,
+		notificationValueSet,
+		descriptorsDiscovered,
+		descriptorRead,
+		descriptorWritten:
+
+		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
+		d.plistmu.Lock()
+		p := d.plist[u.String()]
+		d.plistmu.Unlock()
+		p.rspc <- message{id: id, args: args}
+
+	default:
+		log.Printf("Unhandled event: %#v", event)
+	}
+}
+
+func (d *device) sendReq(id int, args xpc.Dict) xpc.Dict {
+	m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
+	d.reqc <- m
+	return <-m.rspc
+}
+
+func (d *device) sendCmd(id int, args xpc.Dict) {
+	d.reqc <- message{id: id, args: args}
+}
+
+func (d *device) loop() {
+	for req := range d.reqc {
+		d.sendCBMsg(req.id, req.args)
+		if req.rspc == nil {
+			continue
+		}
+		m := <-d.rspc
+		req.rspc <- m.args
+	}
+}
+
+func (d *device) sendCBMsg(id int, args xpc.Dict) {
+	// log.Printf("<< %d, %v", id, args)
+	d.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, false)
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeco/gatt/device_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeco/gatt/device_linux.go b/newtmgr/vendor/github.com/runtimeco/gatt/device_linux.go
new file mode 100644
index 0000000..4c989e1
--- /dev/null
+++ b/newtmgr/vendor/github.com/runtimeco/gatt/device_linux.go
@@ -0,0 +1,240 @@
+package gatt
+
+import (
+	"encoding/binary"
+	"net"
+
+	"github.com/runtimeco/gatt/linux"
+	"github.com/runtimeco/gatt/linux/cmd"
+)
+
+type device struct {
+	deviceHandler
+
+	hci   *linux.HCI
+	state State
+
+	// All the following fields are only used peripheralManager (server) implementation.
+	svcs  []*Service
+	attrs *attrRange
+
+	devID   int
+	chkLE   bool
+	maxConn int
+
+	advData   *cmd.LESetAdvertisingData
+	scanResp  *cmd.LESetScanResponseData
+	advParam  *cmd.LESetAdvertisingParameters
+	scanParam *cmd.LESetScanParameters
+}
+
+func NewDevice(opts ...Option) (Device, error) {
+	d := &device{
+		maxConn: 1,    // Support 1 connection at a time.
+		devID:   -1,   // Find an available HCI device.
+		chkLE:   true, // Check if the device supports LE.
+
+		advParam: &cmd.LESetAdvertisingParameters{
+			AdvertisingIntervalMin:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
+			AdvertisingIntervalMax:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
+			AdvertisingType:         0x00,      // [0x00]: ADV_IND, 0x01: DIRECT(HIGH), 0x02: SCAN, 0x03: NONCONN, 0x04: DIRECT(LOW)
+			OwnAddressType:          0x00,      // [0x00]: public, 0x01: random
+			DirectAddressType:       0x00,      // [0x00]: public, 0x01: random
+			DirectAddress:           [6]byte{}, // Public or Random Address of the device to be connected
+			AdvertisingChannelMap:   0x7,       // [0x07] 0x01: ch37, 0x2: ch38, 0x4: ch39
+			AdvertisingFilterPolicy: 0x00,
+		},
+		scanParam: &cmd.LESetScanParameters{
+			LEScanType:           0x01,   // [0x00]: passive, 0x01: active
+			LEScanInterval:       0x0010, // [0x10]: 0.625ms * 16
+			LEScanWindow:         0x0010, // [0x10]: 0.625ms * 16
+			OwnAddressType:       0x00,   // [0x00]: public, 0x01: random
+			ScanningFilterPolicy: 0x00,   // [0x00]: accept all, 0x01: ignore non-white-listed.
+		},
+	}
+
+	d.Option(opts...)
+	h, err := linux.NewHCI(d.devID, d.chkLE, d.maxConn)
+	if err != nil {
+		return nil, err
+	}
+
+	d.hci = h
+	return d, nil
+}
+
+func (d *device) Init(f func(Device, State)) error {
+	d.hci.AcceptMasterHandler = func(pd *linux.PlatData) {
+		a := pd.Address
+		c := newCentral(d.attrs, net.HardwareAddr([]byte{a[5], a[4], a[3], a[2], a[1], a[0]}), pd.Conn)
+		if d.centralConnected != nil {
+			d.centralConnected(c)
+		}
+		c.loop()
+		if d.centralDisconnected != nil {
+			d.centralDisconnected(c)
+		}
+	}
+	d.hci.AcceptSlaveHandler = func(pd *linux.PlatData) {
+		p := &peripheral{
+			d:     d,
+			pd:    pd,
+			l2c:   pd.Conn,
+			reqc:  make(chan message),
+			quitc: make(chan struct{}),
+			sub:   newSubscriber(),
+		}
+		if d.peripheralConnected != nil {
+			go d.peripheralConnected(p, nil)
+		}
+		p.loop()
+		if d.peripheralDisconnected != nil {
+			d.peripheralDisconnected(p, nil)
+		}
+	}
+	d.hci.AdvertisementHandler = func(pd *linux.PlatData) {
+		a := &Advertisement{}
+		a.unmarshall(pd.Data)
+		a.Connectable = pd.Connectable
+	        a.Address = pd.Address
+		a.AddressType = pd.AddressType
+		p := &peripheral{pd: pd, d: d}
+		if d.peripheralDiscovered != nil {
+			pd.Name = a.LocalName
+			d.peripheralDiscovered(p, a, int(pd.RSSI))
+		}
+	}
+	d.state = StatePoweredOn
+	d.stateChanged = f
+	go d.stateChanged(d, d.state)
+	return nil
+}
+
+func (d *device) Stop() error {
+	d.state = StatePoweredOff
+	defer d.stateChanged(d, d.state)
+	return d.hci.Close()
+}
+
+func (d *device) AddService(s *Service) error {
+	d.svcs = append(d.svcs, s)
+	d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
+	return nil
+}
+
+func (d *device) RemoveAllServices() error {
+	d.svcs = nil
+	d.attrs = nil
+	return nil
+}
+
+func (d *device) SetServices(s []*Service) error {
+	d.RemoveAllServices()
+	d.svcs = append(d.svcs, s...)
+	d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
+	return nil
+}
+
+func (d *device) Advertise(a *AdvPacket) error {
+	d.advData = &cmd.LESetAdvertisingData{
+		AdvertisingDataLength: uint8(a.Len()),
+		AdvertisingData:       a.Bytes(),
+	}
+
+	if err := d.update(); err != nil {
+		return err
+	}
+
+	return d.hci.SetAdvertiseEnable(true)
+}
+
+func (d *device) AdvertiseNameAndServices(name string, uu []UUID) error {
+	a := &AdvPacket{}
+	a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
+	a.AppendUUIDFit(uu)
+
+	if len(a.b)+len(name)+2 < MaxEIRPacketLength {
+		a.AppendName(name)
+		d.scanResp = nil
+	} else {
+		a := &AdvPacket{}
+		a.AppendName(name)
+		d.scanResp = &cmd.LESetScanResponseData{
+			ScanResponseDataLength: uint8(a.Len()),
+			ScanResponseData:       a.Bytes(),
+		}
+	}
+
+	return d.Advertise(a)
+}
+
+func (d *device) AdvertiseIBeaconData(b []byte) error {
+	a := &AdvPacket{}
+	a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
+	a.AppendManufacturerData(0x004C, b)
+	d.advData = &cmd.LESetAdvertisingData{
+		AdvertisingDataLength: uint8(a.Len()),
+		AdvertisingData:       a.Bytes(),
+	}
+
+	return d.Advertise(a)
+}
+
+func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
+	b := make([]byte, 23)
+	b[0] = 0x02                               // Data type: iBeacon
+	b[1] = 0x15                               // Data length: 21 bytes
+	copy(b[2:], reverse(u.b))                 // Big endian
+	binary.BigEndian.PutUint16(b[18:], major) // Big endian
+	binary.BigEndian.PutUint16(b[20:], minor) // Big endian
+	b[22] = uint8(pwr)                        // Measured Tx Power
+	return d.AdvertiseIBeaconData(b)
+}
+
+func (d *device) StopAdvertising() error {
+	return d.hci.SetAdvertiseEnable(false)
+}
+
+func (d *device) Scan(ss []UUID, dup bool) {
+	// TODO: filter
+	d.hci.SetScanEnable(true, dup)
+}
+
+func (d *device) StopScanning() {
+	d.hci.SetScanEnable(false, true)
+}
+
+func (d *device) Connect(p Peripheral) {
+	d.hci.Connect(p.(*peripheral).pd)
+}
+
+func (d *device) CancelConnection(p Peripheral) {
+	d.hci.CancelConnection(p.(*peripheral).pd)
+}
+
+func (d *device) SendHCIRawCommand(c cmd.CmdParam) ([]byte, error) {
+	return d.hci.SendRawCommand(c)
+}
+
+// Flush pending advertising settings to the device.
+func (d *device) update() error {
+	if d.advParam != nil {
+		if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil {
+			return err
+		}
+		d.advParam = nil
+	}
+	if d.scanResp != nil {
+		if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil {
+			return err
+		}
+		d.scanResp = nil
+	}
+	if d.advData != nil {
+		if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil {
+			return err
+		}
+		d.advData = nil
+	}
+	return nil
+}


[41/41] incubator-mynewt-newt git commit: newt; update version string to be 1.0.0-rc1. Blinky tag to fetch is mynewt_1_0_0_rc1_tag.

Posted by ma...@apache.org.
newt; update version string to be 1.0.0-rc1.
Blinky tag to fetch is mynewt_1_0_0_rc1_tag.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/50d5f1f1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/50d5f1f1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/50d5f1f1

Branch: refs/heads/mynewt_1_0_0
Commit: 50d5f1f102377e416b62ffbb9422277a20da4294
Parents: db27018
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Mon Mar 6 13:42:11 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:42:11 2017 -0800

----------------------------------------------------------------------
 newt/newtutil/newtutil.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/50d5f1f1/newt/newtutil/newtutil.go
----------------------------------------------------------------------
diff --git a/newt/newtutil/newtutil.go b/newt/newtutil/newtutil.go
index 6a981ec..962fd28 100644
--- a/newt/newtutil/newtutil.go
+++ b/newt/newtutil/newtutil.go
@@ -34,8 +34,8 @@ import (
 	"mynewt.apache.org/newt/viper"
 )
 
-var NewtVersionStr string = "Apache Newt (incubating) version: 1.0.0.b2"
-var NewtBlinkyTag string = "mynewt_1_0_0_b2_rc1_tag"
+var NewtVersionStr string = "Apache Newt (incubating) version: 1.0.0-rc1"
+var NewtBlinkyTag string = "mynewt_1_0_0_rc1_tag"
 var NewtNumJobs int
 var NewtForce bool
 


[29/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/central.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/central.go b/newtmgr/vendor/github.com/runtimeinc/gatt/central.go
deleted file mode 100644
index 55bd2c1..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/central.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package gatt
-
-import (
-	"bytes"
-	"errors"
-	"fmt"
-	"sync"
-)
-
-// Central is the interface that represent a remote central device.
-type Central interface {
-	ID() string   // ID returns platform specific ID of the remote central device.
-	Close() error // Close disconnects the connection.
-	MTU() int     // MTU returns the current connection mtu.
-}
-
-type ResponseWriter interface {
-	// Write writes data to return as the characteristic value.
-	Write([]byte) (int, error)
-
-	// SetStatus reports the result of the read operation. See the Status* constants.
-	SetStatus(byte)
-}
-
-// responseWriter is the default implementation of ResponseWriter.
-type responseWriter struct {
-	capacity int
-	buf      *bytes.Buffer
-	status   byte
-}
-
-func newResponseWriter(c int) *responseWriter {
-	return &responseWriter{
-		capacity: c,
-		buf:      new(bytes.Buffer),
-		status:   StatusSuccess,
-	}
-}
-
-func (w *responseWriter) Write(b []byte) (int, error) {
-	if avail := w.capacity - w.buf.Len(); avail < len(b) {
-		return 0, fmt.Errorf("requested write %d bytes, %d available", len(b), avail)
-	}
-	return w.buf.Write(b)
-}
-
-func (w *responseWriter) SetStatus(status byte) { w.status = status }
-func (w *responseWriter) bytes() []byte         { return w.buf.Bytes() }
-
-// A ReadHandler handles GATT read requests.
-type ReadHandler interface {
-	ServeRead(resp ResponseWriter, req *ReadRequest)
-}
-
-// ReadHandlerFunc is an adapter to allow the use of
-// ordinary functions as ReadHandlers. If f is a function
-// with the appropriate signature, ReadHandlerFunc(f) is a
-// ReadHandler that calls f.
-type ReadHandlerFunc func(resp ResponseWriter, req *ReadRequest)
-
-// ServeRead returns f(r, maxlen, offset).
-func (f ReadHandlerFunc) ServeRead(resp ResponseWriter, req *ReadRequest) {
-	f(resp, req)
-}
-
-// A WriteHandler handles GATT write requests.
-// Write and WriteNR requests are presented identically;
-// the server will ensure that a response is sent if appropriate.
-type WriteHandler interface {
-	ServeWrite(r Request, data []byte) (status byte)
-}
-
-// WriteHandlerFunc is an adapter to allow the use of
-// ordinary functions as WriteHandlers. If f is a function
-// with the appropriate signature, WriteHandlerFunc(f) is a
-// WriteHandler that calls f.
-type WriteHandlerFunc func(r Request, data []byte) byte
-
-// ServeWrite returns f(r, data).
-func (f WriteHandlerFunc) ServeWrite(r Request, data []byte) byte {
-	return f(r, data)
-}
-
-// A NotifyHandler handles GATT notification requests.
-// Notifications can be sent using the provided notifier.
-type NotifyHandler interface {
-	ServeNotify(r Request, n Notifier)
-}
-
-// NotifyHandlerFunc is an adapter to allow the use of
-// ordinary functions as NotifyHandlers. If f is a function
-// with the appropriate signature, NotifyHandlerFunc(f) is a
-// NotifyHandler that calls f.
-type NotifyHandlerFunc func(r Request, n Notifier)
-
-// ServeNotify calls f(r, n).
-func (f NotifyHandlerFunc) ServeNotify(r Request, n Notifier) {
-	f(r, n)
-}
-
-// A Notifier provides a means for a GATT server to send
-// notifications about value changes to a connected device.
-// Notifiers are provided by NotifyHandlers.
-type Notifier interface {
-	// Write sends data to the central.
-	Write(data []byte) (int, error)
-
-	// Done reports whether the central has requested not to
-	// receive any more notifications with this notifier.
-	Done() bool
-
-	// Cap returns the maximum number of bytes that may be sent
-	// in a single notification.
-	Cap() int
-}
-
-type notifier struct {
-	central *central
-	a       *attr
-	maxlen  int
-	donemu  sync.RWMutex
-	done    bool
-}
-
-func newNotifier(c *central, a *attr, maxlen int) *notifier {
-	return &notifier{central: c, a: a, maxlen: maxlen}
-}
-
-func (n *notifier) Write(b []byte) (int, error) {
-	n.donemu.RLock()
-	defer n.donemu.RUnlock()
-	if n.done {
-		return 0, errors.New("central stopped notifications")
-	}
-	return n.central.sendNotification(n.a, b)
-}
-
-func (n *notifier) Cap() int {
-	return n.maxlen
-}
-
-func (n *notifier) Done() bool {
-	n.donemu.RLock()
-	defer n.donemu.RUnlock()
-	return n.done
-}
-
-func (n *notifier) stop() {
-	n.donemu.Lock()
-	n.done = true
-	n.donemu.Unlock()
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/central_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/central_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/central_darwin.go
deleted file mode 100644
index e5eed0a..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/central_darwin.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package gatt
-
-import (
-	"sync"
-
-	"github.com/runtimeinc/gatt/xpc"
-)
-
-type central struct {
-	dev         *device
-	uuid        UUID
-	mtu         int
-	notifiers   map[uint16]*notifier
-	notifiersmu *sync.Mutex
-}
-
-func newCentral(d *device, u UUID) *central {
-	return &central{
-		dev:         d,
-		mtu:         23,
-		uuid:        u,
-		notifiers:   make(map[uint16]*notifier),
-		notifiersmu: &sync.Mutex{},
-	}
-}
-
-func (c *central) ID() string   { return c.uuid.String() }
-func (c *central) Close() error { return nil }
-func (c *central) MTU() int     { return c.mtu }
-
-func (c *central) sendNotification(a *attr, b []byte) (int, error) {
-	data := make([]byte, len(b))
-	copy(data, b) // have to make a copy, why?
-	c.dev.sendCmd(15, xpc.Dict{
-		// "kCBMsgArgUUIDs": [][]byte{reverse(c.uuid.b)}, // connection interrupted
-		// "kCBMsgArgUUIDs": [][]byte{c.uuid.b}, // connection interrupted
-		// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(reverse(c.uuid.b))},
-		// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(c.uuid.b)},
-		// "kCBMsgArgUUIDs": reverse(c.uuid.b),
-		//
-		// FIXME: Sigh... tried to targeting the central, but couldn't get work.
-		// So, broadcast to all subscribed centrals. Either of the following works.
-		// "kCBMsgArgUUIDs": []xpc.UUID{},
-		"kCBMsgArgUUIDs":       [][]byte{},
-		"kCBMsgArgAttributeID": a.h,
-		"kCBMsgArgData":        data,
-	})
-	return len(b), nil
-}
-
-func (c *central) startNotify(a *attr, maxlen int) {
-	c.notifiersmu.Lock()
-	defer c.notifiersmu.Unlock()
-	if _, found := c.notifiers[a.h]; found {
-		return
-	}
-	n := newNotifier(c, a, maxlen)
-	c.notifiers[a.h] = n
-	char := a.pvt.(*Characteristic)
-	go char.nhandler.ServeNotify(Request{Central: c}, n)
-}
-
-func (c *central) stopNotify(a *attr) {
-	c.notifiersmu.Lock()
-	defer c.notifiersmu.Unlock()
-	if n, found := c.notifiers[a.h]; found {
-		n.stop()
-		delete(c.notifiers, a.h)
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/central_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/central_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/central_linux.go
deleted file mode 100644
index 3ae6994..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/central_linux.go
+++ /dev/null
@@ -1,446 +0,0 @@
-package gatt
-
-import (
-	"encoding/binary"
-	"io"
-	"net"
-	"sync"
-)
-
-type security int
-
-const (
-	securityLow = iota
-	securityMed
-	securityHigh
-)
-
-type central struct {
-	attrs       *attrRange
-	mtu         uint16
-	addr        net.HardwareAddr
-	security    security
-	l2conn      io.ReadWriteCloser
-	notifiers   map[uint16]*notifier
-	notifiersmu *sync.Mutex
-}
-
-func newCentral(a *attrRange, addr net.HardwareAddr, l2conn io.ReadWriteCloser) *central {
-	return &central{
-		attrs:       a,
-		mtu:         23,
-		addr:        addr,
-		security:    securityLow,
-		l2conn:      l2conn,
-		notifiers:   make(map[uint16]*notifier),
-		notifiersmu: &sync.Mutex{},
-	}
-}
-
-func (c *central) ID() string {
-	return c.addr.String()
-}
-
-func (c *central) Close() error {
-	c.notifiersmu.Lock()
-	defer c.notifiersmu.Unlock()
-	for _, n := range c.notifiers {
-		n.stop()
-	}
-	return c.l2conn.Close()
-}
-
-func (c *central) MTU() int {
-	return int(c.mtu)
-}
-
-func (c *central) loop() {
-	for {
-		// L2CAP implementations shall support a minimum MTU size of 48 bytes.
-		// The default value is 672 bytes
-		b := make([]byte, 672)
-		n, err := c.l2conn.Read(b)
-		if n == 0 || err != nil {
-			c.Close()
-			break
-		}
-		if rsp := c.handleReq(b[:n]); rsp != nil {
-			c.l2conn.Write(rsp)
-		}
-	}
-}
-
-// handleReq dispatches a raw request from the central shim
-// to an appropriate handler, based on its type.
-// It panics if len(b) == 0.
-func (c *central) handleReq(b []byte) []byte {
-	var resp []byte
-	switch reqType, req := b[0], b[1:]; reqType {
-	case attOpMtuReq:
-		resp = c.handleMTU(req)
-	case attOpFindInfoReq:
-		resp = c.handleFindInfo(req)
-	case attOpFindByTypeValueReq:
-		resp = c.handleFindByTypeValue(req)
-	case attOpReadByTypeReq:
-		resp = c.handleReadByType(req)
-	case attOpReadReq:
-		resp = c.handleRead(req)
-	case attOpReadBlobReq:
-		resp = c.handleReadBlob(req)
-	case attOpReadByGroupReq:
-		resp = c.handleReadByGroup(req)
-	case attOpWriteReq, attOpWriteCmd:
-		resp = c.handleWrite(reqType, req)
-	case attOpReadMultiReq, attOpPrepWriteReq, attOpExecWriteReq, attOpSignedWriteCmd:
-		fallthrough
-	default:
-		resp = attErrorRsp(reqType, 0x0000, attEcodeReqNotSupp)
-	}
-	return resp
-}
-
-func (c *central) handleMTU(b []byte) []byte {
-	c.mtu = binary.LittleEndian.Uint16(b[:2])
-	if c.mtu < 23 {
-		c.mtu = 23
-	}
-	if c.mtu >= 256 {
-		c.mtu = 256
-	}
-	return []byte{attOpMtuRsp, uint8(c.mtu), uint8(c.mtu >> 8)}
-}
-
-// REQ: FindInfoReq(0x04), StartHandle, EndHandle
-// RSP: FindInfoRsp(0x05), UUIDFormat, Handle, UUID, Handle, UUID, ...
-func (c *central) handleFindInfo(b []byte) []byte {
-	start, end := readHandleRange(b[:4])
-
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpFindInfoRsp)
-
-	uuidLen := -1
-	for _, a := range c.attrs.Subrange(start, end) {
-		if uuidLen == -1 {
-			uuidLen = a.typ.Len()
-			if uuidLen == 2 {
-				w.WriteByteFit(0x01) // TODO: constants for 16bit vs 128bit uuid magic numbers here
-			} else {
-				w.WriteByteFit(0x02)
-			}
-		}
-		if a.typ.Len() != uuidLen {
-			break
-		}
-		w.Chunk()
-		w.WriteUint16Fit(a.h)
-		w.WriteUUIDFit(a.typ)
-		if ok := w.Commit(); !ok {
-			break
-		}
-	}
-
-	if uuidLen == -1 {
-		return attErrorRsp(attOpFindInfoReq, start, attEcodeAttrNotFound)
-	}
-	return w.Bytes()
-}
-
-// REQ: FindByTypeValueReq(0x06), StartHandle, EndHandle, Type(UUID), Value
-// RSP: FindByTypeValueRsp(0x07), AttrHandle, GroupEndHandle, AttrHandle, GroupEndHandle, ...
-func (c *central) handleFindByTypeValue(b []byte) []byte {
-	start, end := readHandleRange(b[:4])
-	t := UUID{b[4:6]}
-	u := UUID{b[6:]}
-
-	// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
-	// More sepcifically, the "Discover Primary Services By Service UUID" sub-procedure
-	if !t.Equal(attrPrimaryServiceUUID) {
-		return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
-	}
-
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpFindByTypeValueRsp)
-
-	var wrote bool
-	for _, a := range c.attrs.Subrange(start, end) {
-		if !a.typ.Equal(attrPrimaryServiceUUID) {
-			continue
-		}
-		if !(UUID{a.value}.Equal(u)) {
-			continue
-		}
-		s := a.pvt.(*Service)
-		w.Chunk()
-		w.WriteUint16Fit(s.h)
-		w.WriteUint16Fit(s.endh)
-		if ok := w.Commit(); !ok {
-			break
-		}
-		wrote = true
-	}
-	if !wrote {
-		return attErrorRsp(attOpFindByTypeValueReq, start, attEcodeAttrNotFound)
-	}
-
-	return w.Bytes()
-}
-
-// REQ: ReadByType(0x08), StartHandle, EndHandle, Type(UUID)
-// RSP: ReadByType(0x09), LenOfEachDataField, DataField, DataField, ...
-func (c *central) handleReadByType(b []byte) []byte {
-	start, end := readHandleRange(b[:4])
-	t := UUID{b[4:]}
-
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpReadByTypeRsp)
-	uuidLen := -1
-	for _, a := range c.attrs.Subrange(start, end) {
-		if !a.typ.Equal(t) {
-			continue
-		}
-		if (a.secure&CharRead) != 0 && c.security > securityLow {
-			return attErrorRsp(attOpReadByTypeReq, start, attEcodeAuthentication)
-		}
-		v := a.value
-		if v == nil {
-			rsp := newResponseWriter(int(c.mtu - 1))
-			req := &ReadRequest{
-				Request: Request{Central: c},
-				Cap:     int(c.mtu - 1),
-				Offset:  0,
-			}
-			if c, ok := a.pvt.(*Characteristic); ok {
-				c.rhandler.ServeRead(rsp, req)
-			} else if d, ok := a.pvt.(*Descriptor); ok {
-				d.rhandler.ServeRead(rsp, req)
-			}
-			v = rsp.bytes()
-		}
-		if uuidLen == -1 {
-			uuidLen = len(v)
-			w.WriteByteFit(byte(uuidLen) + 2)
-		}
-		if len(v) != uuidLen {
-			break
-		}
-		w.Chunk()
-		w.WriteUint16Fit(a.h)
-		w.WriteFit(v)
-		if ok := w.Commit(); !ok {
-			break
-		}
-	}
-	if uuidLen == -1 {
-		return attErrorRsp(attOpReadByTypeReq, start, attEcodeAttrNotFound)
-	}
-	return w.Bytes()
-}
-
-// REQ: ReadReq(0x0A), Handle
-// RSP: ReadRsp(0x0B), Value
-func (c *central) handleRead(b []byte) []byte {
-	h := binary.LittleEndian.Uint16(b)
-	a, ok := c.attrs.At(h)
-	if !ok {
-		return attErrorRsp(attOpReadReq, h, attEcodeInvalidHandle)
-	}
-	if a.props&CharRead == 0 {
-		return attErrorRsp(attOpReadReq, h, attEcodeReadNotPerm)
-	}
-	if a.secure&CharRead != 0 && c.security > securityLow {
-		return attErrorRsp(attOpReadReq, h, attEcodeAuthentication)
-	}
-	v := a.value
-	if v == nil {
-		req := &ReadRequest{
-			Request: Request{Central: c},
-			Cap:     int(c.mtu - 1),
-			Offset:  0,
-		}
-		rsp := newResponseWriter(int(c.mtu - 1))
-		if c, ok := a.pvt.(*Characteristic); ok {
-			c.rhandler.ServeRead(rsp, req)
-		} else if d, ok := a.pvt.(*Descriptor); ok {
-			d.rhandler.ServeRead(rsp, req)
-		}
-		v = rsp.bytes()
-	}
-
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpReadRsp)
-	w.Chunk()
-	w.WriteFit(v)
-	w.CommitFit()
-	return w.Bytes()
-}
-
-// FIXME: check this, untested, might be broken
-func (c *central) handleReadBlob(b []byte) []byte {
-	h := binary.LittleEndian.Uint16(b)
-	offset := binary.LittleEndian.Uint16(b[2:])
-	a, ok := c.attrs.At(h)
-	if !ok {
-		return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidHandle)
-	}
-	if a.props&CharRead == 0 {
-		return attErrorRsp(attOpReadBlobReq, h, attEcodeReadNotPerm)
-	}
-	if a.secure&CharRead != 0 && c.security > securityLow {
-		return attErrorRsp(attOpReadBlobReq, h, attEcodeAuthentication)
-	}
-	v := a.value
-	if v == nil {
-		req := &ReadRequest{
-			Request: Request{Central: c},
-			Cap:     int(c.mtu - 1),
-			Offset:  int(offset),
-		}
-		rsp := newResponseWriter(int(c.mtu - 1))
-		if c, ok := a.pvt.(*Characteristic); ok {
-			c.rhandler.ServeRead(rsp, req)
-		} else if d, ok := a.pvt.(*Descriptor); ok {
-			d.rhandler.ServeRead(rsp, req)
-		}
-		v = rsp.bytes()
-		offset = 0 // the server has already adjusted for the offset
-	}
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpReadBlobRsp)
-	w.Chunk()
-	w.WriteFit(v)
-	if ok := w.ChunkSeek(offset); !ok {
-		return attErrorRsp(attOpReadBlobReq, h, attEcodeInvalidOffset)
-	}
-	w.CommitFit()
-	return w.Bytes()
-}
-
-func (c *central) handleReadByGroup(b []byte) []byte {
-	start, end := readHandleRange(b)
-	t := UUID{b[4:]}
-
-	// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
-	// More specifically, the "Discover All Primary Services" sub-procedure.
-	if !t.Equal(attrPrimaryServiceUUID) {
-		return attErrorRsp(attOpReadByGroupReq, start, attEcodeUnsuppGrpType)
-	}
-
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpReadByGroupRsp)
-	uuidLen := -1
-	for _, a := range c.attrs.Subrange(start, end) {
-		if !a.typ.Equal(attrPrimaryServiceUUID) {
-			continue
-		}
-		if uuidLen == -1 {
-			uuidLen = len(a.value)
-			w.WriteByteFit(byte(uuidLen + 4))
-		}
-		if uuidLen != len(a.value) {
-			break
-		}
-		s := a.pvt.(*Service)
-		w.Chunk()
-		w.WriteUint16Fit(s.h)
-		w.WriteUint16Fit(s.endh)
-		w.WriteFit(a.value)
-		if ok := w.Commit(); !ok {
-			break
-		}
-	}
-	if uuidLen == -1 {
-		return attErrorRsp(attOpReadByGroupReq, start, attEcodeAttrNotFound)
-	}
-	return w.Bytes()
-}
-
-func (c *central) handleWrite(reqType byte, b []byte) []byte {
-	h := binary.LittleEndian.Uint16(b[:2])
-	value := b[2:]
-
-	a, ok := c.attrs.At(h)
-	if !ok {
-		return attErrorRsp(reqType, h, attEcodeInvalidHandle)
-	}
-
-	noRsp := reqType == attOpWriteCmd
-	charFlag := CharWrite
-	if noRsp {
-		charFlag = CharWriteNR
-	}
-	if a.props&charFlag == 0 {
-		return attErrorRsp(reqType, h, attEcodeWriteNotPerm)
-	}
-	if a.secure&charFlag == 0 && c.security > securityLow {
-		return attErrorRsp(reqType, h, attEcodeAuthentication)
-	}
-
-	// Props of Service and Characteristic declration are read only.
-	// So we only need deal with writable descriptors here.
-	// (Characteristic's value is implemented with descriptor)
-	if !a.typ.Equal(attrClientCharacteristicConfigUUID) {
-		// Regular write, not CCC
-		r := Request{Central: c}
-		if c, ok := a.pvt.(*Characteristic); ok {
-			c.whandler.ServeWrite(r, value)
-		} else if d, ok := a.pvt.(*Characteristic); ok {
-			d.whandler.ServeWrite(r, value)
-		}
-		if noRsp {
-			return nil
-		} else {
-			return []byte{attOpWriteRsp}
-		}
-	}
-
-	// CCC/descriptor write
-	if len(value) != 2 {
-		return attErrorRsp(reqType, h, attEcodeInvalAttrValueLen)
-	}
-	ccc := binary.LittleEndian.Uint16(value)
-	// char := a.pvt.(*Descriptor).char
-	if ccc&(gattCCCNotifyFlag|gattCCCIndicateFlag) != 0 {
-		c.startNotify(&a, int(c.mtu-3))
-	} else {
-		c.stopNotify(&a)
-	}
-	if noRsp {
-		return nil
-	}
-	return []byte{attOpWriteRsp}
-}
-
-func (c *central) sendNotification(a *attr, data []byte) (int, error) {
-	w := newL2capWriter(c.mtu)
-	w.WriteByteFit(attOpHandleNotify)
-	w.WriteUint16Fit(a.pvt.(*Descriptor).char.vh)
-	w.WriteFit(data)
-	return c.l2conn.Write(w.Bytes())
-}
-
-func readHandleRange(b []byte) (start, end uint16) {
-	return binary.LittleEndian.Uint16(b), binary.LittleEndian.Uint16(b[2:])
-}
-
-func (c *central) startNotify(a *attr, maxlen int) {
-	c.notifiersmu.Lock()
-	defer c.notifiersmu.Unlock()
-	if _, found := c.notifiers[a.h]; found {
-		return
-	}
-	char := a.pvt.(*Descriptor).char
-	n := newNotifier(c, a, maxlen)
-	c.notifiers[a.h] = n
-	go char.nhandler.ServeNotify(Request{Central: c}, n)
-}
-
-func (c *central) stopNotify(a *attr) {
-	c.notifiersmu.Lock()
-	defer c.notifiersmu.Unlock()
-	// char := a.pvt.(*Characteristic)
-	if n, found := c.notifiers[a.h]; found {
-		n.stop()
-		delete(c.notifiers, a.h)
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/common.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/common.go b/newtmgr/vendor/github.com/runtimeinc/gatt/common.go
deleted file mode 100644
index 4fa2389..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/common.go
+++ /dev/null
@@ -1,399 +0,0 @@
-package gatt
-
-// Supported statuses for GATT characteristic read/write operations.
-// These correspond to att constants in the BLE spec
-const (
-	StatusSuccess         = 0
-	StatusInvalidOffset   = 1
-	StatusUnexpectedError = 2
-)
-
-// A Request is the context for a request from a connected central device.
-// TODO: Replace this with more general context, such as:
-// http://godoc.org/golang.org/x/net/context
-type Request struct {
-	Central Central
-}
-
-// A ReadRequest is a characteristic read request from a connected device.
-type ReadRequest struct {
-	Request
-	Cap    int // maximum allowed reply length
-	Offset int // request value offset
-}
-
-type Property int
-
-// Characteristic property flags (spec 3.3.3.1)
-const (
-	CharBroadcast   Property = 0x01 // may be brocasted
-	CharRead        Property = 0x02 // may be read
-	CharWriteNR     Property = 0x04 // may be written to, with no reply
-	CharWrite       Property = 0x08 // may be written to, with a reply
-	CharNotify      Property = 0x10 // supports notifications
-	CharIndicate    Property = 0x20 // supports Indications
-	CharSignedWrite Property = 0x40 // supports signed write
-	CharExtended    Property = 0x80 // supports extended properties
-)
-
-func (p Property) String() (result string) {
-	if (p & CharBroadcast) != 0 {
-		result += "broadcast "
-	}
-	if (p & CharRead) != 0 {
-		result += "read "
-	}
-	if (p & CharWriteNR) != 0 {
-		result += "writeWithoutResponse "
-	}
-	if (p & CharWrite) != 0 {
-		result += "write "
-	}
-	if (p & CharNotify) != 0 {
-		result += "notify "
-	}
-	if (p & CharIndicate) != 0 {
-		result += "indicate "
-	}
-	if (p & CharSignedWrite) != 0 {
-		result += "authenticateSignedWrites "
-	}
-	if (p & CharExtended) != 0 {
-		result += "extendedProperties "
-	}
-	return
-}
-
-// A Service is a BLE service.
-type Service struct {
-	uuid  UUID
-	chars []*Characteristic
-
-	h    uint16
-	endh uint16
-}
-
-// NewService creates and initialize a new Service using u as it's UUID.
-func NewService(u UUID) *Service {
-	return &Service{uuid: u}
-}
-
-// AddCharacteristic adds a characteristic to a service.
-// AddCharacteristic panics if the service already contains another
-// characteristic with the same UUID.
-func (s *Service) AddCharacteristic(u UUID) *Characteristic {
-	for _, c := range s.chars {
-		if c.uuid.Equal(u) {
-			panic("service already contains a characteristic with uuid " + u.String())
-		}
-	}
-	c := &Characteristic{uuid: u, svc: s}
-	s.chars = append(s.chars, c)
-	return c
-}
-
-// UUID returns the UUID of the service.
-func (s *Service) UUID() UUID { return s.uuid }
-
-// Name returns the specificatin name of the service according to its UUID.
-// If the UUID is not assigne, Name returns an empty string.
-func (s *Service) Name() string {
-	return knownServices[s.uuid.String()].Name
-}
-
-// Handle returns the Handle of the service.
-func (s *Service) Handle() uint16 { return s.h }
-
-// EndHandle returns the End Handle of the service.
-func (s *Service) EndHandle() uint16 { return s.endh }
-
-// SetHandle sets the Handle of the service.
-func (s *Service) SetHandle(h uint16) { s.h = h }
-
-// SetEndHandle sets the End Handle of the service.
-func (s *Service) SetEndHandle(endh uint16) { s.endh = endh }
-
-// SetCharacteristics sets the Characteristics of the service.
-func (s *Service) SetCharacteristics(chars []*Characteristic) { s.chars = chars }
-
-// Characteristic returns the contained characteristic of this service.
-func (s *Service) Characteristics() []*Characteristic { return s.chars }
-
-// A Characteristic is a BLE characteristic.
-type Characteristic struct {
-	uuid   UUID
-	props  Property // enabled properties
-	secure Property // security enabled properties
-	svc    *Service
-	cccd   *Descriptor
-	descs  []*Descriptor
-
-	value []byte
-
-	// All the following fields are only used in peripheral/server implementation.
-	rhandler ReadHandler
-	whandler WriteHandler
-	nhandler NotifyHandler
-
-	h    uint16
-	vh   uint16
-	endh uint16
-}
-
-// NewCharacteristic creates and returns a Characteristic.
-func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic {
-	c := &Characteristic{
-		uuid:  u,
-		svc:   s,
-		props: props,
-		h:     h,
-		vh:    vh,
-	}
-
-	return c
-}
-
-// Handle returns the Handle of the characteristic.
-func (c *Characteristic) Handle() uint16 { return c.h }
-
-// VHandle returns the Value Handle of the characteristic.
-func (c *Characteristic) VHandle() uint16 { return c.vh }
-
-// EndHandle returns the End Handle of the characteristic.
-func (c *Characteristic) EndHandle() uint16 { return c.endh }
-
-// Descriptor returns the Descriptor of the characteristic.
-func (c *Characteristic) Descriptor() *Descriptor { return c.cccd }
-
-// SetHandle sets the Handle of the characteristic.
-func (c *Characteristic) SetHandle(h uint16) { c.h = h }
-
-// SetVHandle sets the Value Handle of the characteristic.
-func (c *Characteristic) SetVHandle(vh uint16) { c.vh = vh }
-
-// SetEndHandle sets the End Handle of the characteristic.
-func (c *Characteristic) SetEndHandle(endh uint16) { c.endh = endh }
-
-// SetDescriptor sets the Descriptor of the characteristic.
-func (c *Characteristic) SetDescriptor(cccd *Descriptor) { c.cccd = cccd }
-
-// SetDescriptors sets the list of Descriptor of the characteristic.
-func (c *Characteristic) SetDescriptors(descs []*Descriptor) { c.descs = descs }
-
-// UUID returns the UUID of the characteristic.
-func (c *Characteristic) UUID() UUID {
-	return c.uuid
-}
-
-// Name returns the specificatin name of the characteristic.
-// If the UUID is not assigned, Name returns empty string.
-func (c *Characteristic) Name() string {
-	return knownCharacteristics[c.uuid.String()].Name
-}
-
-// Service returns the containing service of this characteristic.
-func (c *Characteristic) Service() *Service {
-	return c.svc
-}
-
-// Properties returns the properties of this characteristic.
-func (c *Characteristic) Properties() Property {
-	return c.props
-}
-
-// Descriptors returns the contained descriptors of this characteristic.
-func (c *Characteristic) Descriptors() []*Descriptor {
-	return c.descs
-}
-
-// AddDescriptor adds a descriptor to a characteristic.
-// AddDescriptor panics if the characteristic already contains another
-// descriptor with the same UUID.
-func (c *Characteristic) AddDescriptor(u UUID) *Descriptor {
-	for _, d := range c.descs {
-		if d.uuid.Equal(u) {
-			panic("service already contains a characteristic with uuid " + u.String())
-		}
-	}
-	d := &Descriptor{uuid: u, char: c}
-	c.descs = append(c.descs, d)
-	return d
-}
-
-// SetValue makes the characteristic support read requests, and returns a
-// static value. SetValue must be called before the containing service is
-// added to a server.
-// SetValue panics if the characteristic has been configured with a ReadHandler.
-func (c *Characteristic) SetValue(b []byte) {
-	if c.rhandler != nil {
-		panic("charactristic has been configured with a read handler")
-	}
-	c.props |= CharRead
-	// c.secure |= CharRead
-	c.value = make([]byte, len(b))
-	copy(c.value, b)
-}
-
-// HandleRead makes the characteristic support read requests, and routes read
-// requests to h. HandleRead must be called before the containing service is
-// added to a server.
-// HandleRead panics if the characteristic has been configured with a static value.
-func (c *Characteristic) HandleRead(h ReadHandler) {
-	if c.value != nil {
-		panic("charactristic has been configured with a static value")
-	}
-	c.props |= CharRead
-	// c.secure |= CharRead
-	c.rhandler = h
-}
-
-// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
-func (c *Characteristic) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
-	c.HandleRead(ReadHandlerFunc(f))
-}
-
-// HandleWrite makes the characteristic support write and write-no-response
-// requests, and routes write requests to h.
-// The WriteHandler does not differentiate between write and write-no-response
-// requests; it is handled automatically.
-// HandleWrite must be called before the containing service is added to a server.
-func (c *Characteristic) HandleWrite(h WriteHandler) {
-	c.props |= CharWrite | CharWriteNR
-	// c.secure |= CharWrite | CharWriteNR
-	c.whandler = h
-}
-
-// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
-func (c *Characteristic) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
-	c.HandleWrite(WriteHandlerFunc(f))
-}
-
-// HandleNotify makes the characteristic support notify requests, and routes
-// notification requests to h. HandleNotify must be called before the
-// containing service is added to a server.
-func (c *Characteristic) HandleNotify(h NotifyHandler) {
-	if c.cccd != nil {
-		return
-	}
-	p := CharNotify | CharIndicate
-	c.props |= p
-	c.nhandler = h
-
-	// add ccc (client characteristic configuration) descriptor
-	secure := Property(0)
-	// If the characteristic requested secure notifications,
-	// then set ccc security to r/w.
-	if c.secure&p != 0 {
-		secure = CharRead | CharWrite
-	}
-	cd := &Descriptor{
-		uuid:   attrClientCharacteristicConfigUUID,
-		props:  CharRead | CharWrite | CharWriteNR,
-		secure: secure,
-		// FIXME: currently, we always return 0, which is inaccurate.
-		// Each connection should have it's own copy of this value.
-		value: []byte{0x00, 0x00},
-		char:  c,
-	}
-	c.cccd = cd
-	c.descs = append(c.descs, cd)
-}
-
-// HandleNotifyFunc calls HandleNotify(NotifyHandlerFunc(f)).
-func (c *Characteristic) HandleNotifyFunc(f func(r Request, n Notifier)) {
-	c.HandleNotify(NotifyHandlerFunc(f))
-}
-
-// TODO
-// func (c *Characteristic) SubscribedCentrals() []Central{
-// }
-
-// Descriptor is a BLE descriptor
-type Descriptor struct {
-	uuid   UUID
-	char   *Characteristic
-	props  Property // enabled properties
-	secure Property // security enabled properties
-
-	h     uint16
-	value []byte
-
-	rhandler ReadHandler
-	whandler WriteHandler
-}
-
-// Handle returns the Handle of the descriptor.
-func (d *Descriptor) Handle() uint16 { return d.h }
-
-// SetHandle sets the Handle of the descriptor.
-func (d *Descriptor) SetHandle(h uint16) { d.h = h }
-
-// NewDescriptor creates and returns a Descriptor.
-func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor {
-	cd := &Descriptor{
-		uuid: u,
-		h:    h,
-		char: char,
-	}
-	return cd
-}
-
-// UUID returns the UUID of the descriptor.
-func (d *Descriptor) UUID() UUID {
-	return d.uuid
-}
-
-// Name returns the specificatin name of the descriptor.
-// If the UUID is not assigned, returns an empty string.
-func (d *Descriptor) Name() string {
-	return knownDescriptors[d.uuid.String()].Name
-}
-
-// Characteristic returns the containing characteristic of the descriptor.
-func (d *Descriptor) Characteristic() *Characteristic {
-	return d.char
-}
-
-// SetValue makes the descriptor support read requests, and returns a static value.
-// SetValue must be called before the containing service is added to a server.
-// SetValue panics if the descriptor has already configured with a ReadHandler.
-func (d *Descriptor) SetValue(b []byte) {
-	if d.rhandler != nil {
-		panic("descriptor has been configured with a read handler")
-	}
-	d.props |= CharRead
-	// d.secure |= CharRead
-	d.value = make([]byte, len(b))
-	copy(d.value, b)
-}
-
-// HandleRead makes the descriptor support read requests, and routes read requests to h.
-// HandleRead must be called before the containing service is added to a server.
-// HandleRead panics if the descriptor has been configured with a static value.
-func (d *Descriptor) HandleRead(h ReadHandler) {
-	if d.value != nil {
-		panic("descriptor has been configured with a static value")
-	}
-	d.props |= CharRead
-	// d.secure |= CharRead
-	d.rhandler = h
-}
-
-// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
-func (d *Descriptor) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
-	d.HandleRead(ReadHandlerFunc(f))
-}
-
-// HandleWrite makes the descriptor support write and write-no-response requests, and routes write requests to h.
-// The WriteHandler does not differentiate between write and write-no-response requests; it is handled automatically.
-// HandleWrite must be called before the containing service is added to a server.
-func (d *Descriptor) HandleWrite(h WriteHandler) {
-	d.props |= CharWrite | CharWriteNR
-	// d.secure |= CharWrite | CharWriteNR
-	d.whandler = h
-}
-
-// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
-func (d *Descriptor) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
-	d.HandleWrite(WriteHandlerFunc(f))
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/const.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/const.go b/newtmgr/vendor/github.com/runtimeinc/gatt/const.go
deleted file mode 100644
index 4a04b04..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/const.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package gatt
-
-// This file includes constants from the BLE spec.
-
-var (
-	attrGAPUUID  = UUID16(0x1800)
-	attrGATTUUID = UUID16(0x1801)
-
-	attrPrimaryServiceUUID   = UUID16(0x2800)
-	attrSecondaryServiceUUID = UUID16(0x2801)
-	attrIncludeUUID          = UUID16(0x2802)
-	attrCharacteristicUUID   = UUID16(0x2803)
-
-	attrClientCharacteristicConfigUUID = UUID16(0x2902)
-	attrServerCharacteristicConfigUUID = UUID16(0x2903)
-
-	attrDeviceNameUUID        = UUID16(0x2A00)
-	attrAppearanceUUID        = UUID16(0x2A01)
-	attrPeripheralPrivacyUUID = UUID16(0x2A02)
-	attrReconnectionAddrUUID  = UUID16(0x2A03)
-	attrPeferredParamsUUID    = UUID16(0x2A04)
-	attrServiceChangedUUID    = UUID16(0x2A05)
-)
-
-const (
-	gattCCCNotifyFlag   = 0x0001
-	gattCCCIndicateFlag = 0x0002
-)
-
-const (
-	attOpError              = 0x01
-	attOpMtuReq             = 0x02
-	attOpMtuRsp             = 0x03
-	attOpFindInfoReq        = 0x04
-	attOpFindInfoRsp        = 0x05
-	attOpFindByTypeValueReq = 0x06
-	attOpFindByTypeValueRsp = 0x07
-	attOpReadByTypeReq      = 0x08
-	attOpReadByTypeRsp      = 0x09
-	attOpReadReq            = 0x0a
-	attOpReadRsp            = 0x0b
-	attOpReadBlobReq        = 0x0c
-	attOpReadBlobRsp        = 0x0d
-	attOpReadMultiReq       = 0x0e
-	attOpReadMultiRsp       = 0x0f
-	attOpReadByGroupReq     = 0x10
-	attOpReadByGroupRsp     = 0x11
-	attOpWriteReq           = 0x12
-	attOpWriteRsp           = 0x13
-	attOpWriteCmd           = 0x52
-	attOpPrepWriteReq       = 0x16
-	attOpPrepWriteRsp       = 0x17
-	attOpExecWriteReq       = 0x18
-	attOpExecWriteRsp       = 0x19
-	attOpHandleNotify       = 0x1b
-	attOpHandleInd          = 0x1d
-	attOpHandleCnf          = 0x1e
-	attOpSignedWriteCmd     = 0xd2
-)
-
-type attEcode byte
-
-const (
-	attEcodeSuccess           attEcode = 0x00 // Success
-	attEcodeInvalidHandle     attEcode = 0x01 // The attribute handle given was not valid on this server.
-	attEcodeReadNotPerm       attEcode = 0x02 // The attribute cannot be read.
-	attEcodeWriteNotPerm      attEcode = 0x03 // The attribute cannot be written.
-	attEcodeInvalidPDU        attEcode = 0x04 // The attribute PDU was invalid.
-	attEcodeAuthentication    attEcode = 0x05 // The attribute requires authentication before it can be read or written.
-	attEcodeReqNotSupp        attEcode = 0x06 // Attribute server does not support the request received from the client.
-	attEcodeInvalidOffset     attEcode = 0x07 // Offset specified was past the end of the attribute.
-	attEcodeAuthorization     attEcode = 0x08 // The attribute requires authorization before it can be read or written.
-	attEcodePrepQueueFull     attEcode = 0x09 // Too many prepare writes have been queued.
-	attEcodeAttrNotFound      attEcode = 0x0a // No attribute found within the given attribute handle range.
-	attEcodeAttrNotLong       attEcode = 0x0b // The attribute cannot be read or written using the Read Blob Request.
-	attEcodeInsuffEncrKeySize attEcode = 0x0c // The Encryption Key Size used for encrypting this link is insufficient.
-	attEcodeInvalAttrValueLen attEcode = 0x0d // The attribute value length is invalid for the operation.
-	attEcodeUnlikely          attEcode = 0x0e // The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested.
-	attEcodeInsuffEnc         attEcode = 0x0f // The attribute requires encryption before it can be read or written.
-	attEcodeUnsuppGrpType     attEcode = 0x10 // The attribute type is not a supported grouping attribute as defined by a higher layer specification.
-	attEcodeInsuffResources   attEcode = 0x11 // Insufficient Resources to complete the request.
-)
-
-func (a attEcode) Error() string {
-	switch i := int(a); {
-	case i < 0x11:
-		return attEcodeName[a]
-	case i >= 0x12 && i <= 0x7F: // Reserved for future use
-		return "reserved error code"
-	case i >= 0x80 && i <= 0x9F: // Application Error, defined by higher level
-		return "reserved error code"
-	case i >= 0xA0 && i <= 0xDF: // Reserved for future use
-		return "reserved error code"
-	case i >= 0xE0 && i <= 0xFF: // Common profile and service error codes
-		return "profile or service error"
-	default: // can't happen, just make compiler happy
-		return "unkown error"
-	}
-}
-
-var attEcodeName = map[attEcode]string{
-	attEcodeSuccess:           "success",
-	attEcodeInvalidHandle:     "invalid handle",
-	attEcodeReadNotPerm:       "read not permitted",
-	attEcodeWriteNotPerm:      "write not permitted",
-	attEcodeInvalidPDU:        "invalid PDU",
-	attEcodeAuthentication:    "insufficient authentication",
-	attEcodeReqNotSupp:        "request not supported",
-	attEcodeInvalidOffset:     "invalid offset",
-	attEcodeAuthorization:     "insufficient authorization",
-	attEcodePrepQueueFull:     "prepare queue full",
-	attEcodeAttrNotFound:      "attribute not found",
-	attEcodeAttrNotLong:       "attribute not long",
-	attEcodeInsuffEncrKeySize: "insufficient encryption key size",
-	attEcodeInvalAttrValueLen: "invalid attribute value length",
-	attEcodeUnlikely:          "unlikely error",
-	attEcodeInsuffEnc:         "insufficient encryption",
-	attEcodeUnsuppGrpType:     "unsupported group type",
-	attEcodeInsuffResources:   "insufficient resources",
-}
-
-func attErrorRsp(op byte, h uint16, s attEcode) []byte {
-	return attErr{opcode: op, attr: h, status: s}.Marshal()
-}
-
-// attRspFor maps from att request
-// codes to att response codes.
-var attRspFor = map[byte]byte{
-	attOpMtuReq:             attOpMtuRsp,
-	attOpFindInfoReq:        attOpFindInfoRsp,
-	attOpFindByTypeValueReq: attOpFindByTypeValueRsp,
-	attOpReadByTypeReq:      attOpReadByTypeRsp,
-	attOpReadReq:            attOpReadRsp,
-	attOpReadBlobReq:        attOpReadBlobRsp,
-	attOpReadMultiReq:       attOpReadMultiRsp,
-	attOpReadByGroupReq:     attOpReadByGroupRsp,
-	attOpWriteReq:           attOpWriteRsp,
-	attOpPrepWriteReq:       attOpPrepWriteRsp,
-	attOpExecWriteReq:       attOpExecWriteRsp,
-}
-
-type attErr struct {
-	opcode uint8
-	attr   uint16
-	status attEcode
-}
-
-// TODO: Reformulate in a way that lets the caller avoid allocs.
-// Accept a []byte? Write directly to an io.Writer?
-func (e attErr) Marshal() []byte {
-	// little-endian encoding for attr
-	return []byte{attOpError, e.opcode, byte(e.attr), byte(e.attr >> 8), byte(e.status)}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/device.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/device.go b/newtmgr/vendor/github.com/runtimeinc/gatt/device.go
deleted file mode 100644
index eba96cf..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/device.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package gatt
-
-import "errors"
-
-var notImplemented = errors.New("not implemented")
-
-type State int
-
-const (
-	StateUnknown      State = 0
-	StateResetting    State = 1
-	StateUnsupported  State = 2
-	StateUnauthorized State = 3
-	StatePoweredOff   State = 4
-	StatePoweredOn    State = 5
-)
-
-func (s State) String() string {
-	str := []string{
-		"Unknown",
-		"Resetting",
-		"Unsupported",
-		"Unauthorized",
-		"PoweredOff",
-		"PoweredOn",
-	}
-	return str[int(s)]
-}
-
-// Device defines the interface for a BLE device.
-// Since an interface can't define fields(properties). To implement the
-// callback support for cerntain events, deviceHandler is defined and
-// implementation of Device on different platforms should embed it in
-// order to keep have keep compatible in API level.
-// Package users can use the Handler to set these handlers.
-type Device interface {
-	Init(stateChanged func(Device, State)) error
-
-	// Advertise advertise AdvPacket
-	Advertise(a *AdvPacket) error
-
-	// AdvertiseNameAndServices advertises device name, and specified service UUIDs.
-	// It tres to fit the UUIDs in the advertising packet as much as possible.
-	// If name doesn't fit in the advertising packet, it will be put in scan response.
-	AdvertiseNameAndServices(name string, ss []UUID) error
-
-	// AdvertiseIBeaconData advertise iBeacon with given manufacturer data.
-	AdvertiseIBeaconData(b []byte) error
-
-	// AdvertisingIbeacon advertises iBeacon with specified parameters.
-	AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error
-
-	// StopAdvertising stops advertising.
-	StopAdvertising() error
-
-	// RemoveAllServices removes all services that are currently in the database.
-	RemoveAllServices() error
-
-	// Add Service add a service to database.
-	AddService(s *Service) error
-
-	// SetServices set the specified service to the database.
-	// It removes all currently added services, if any.
-	SetServices(ss []*Service) error
-
-	// Scan discovers surounding remote peripherals that have the Service UUID specified in ss.
-	// If ss is set to nil, all devices scanned are reported.
-	// dup specifies weather duplicated advertisement should be reported or not.
-	// When a remote peripheral is discovered, the PeripheralDiscovered Handler is called.
-	Scan(ss []UUID, dup bool)
-
-	// StopScanning stops scanning.
-	StopScanning()
-
-	// Connect connects to a remote peripheral.
-	Connect(p Peripheral)
-
-	// CancelConnection disconnects a remote peripheral.
-	CancelConnection(p Peripheral)
-
-	// Handle registers the specified handlers.
-	Handle(h ...Handler)
-
-	// Stop HCI Connection
-        Stop() error
-
-	// Option sets the options specified.
-	Option(o ...Option) error
-}
-
-// deviceHandler is the handlers(callbacks) of the Device.
-type deviceHandler struct {
-	// stateChanged is called when the device states changes.
-	stateChanged func(d Device, s State)
-
-	// connect is called when a remote central device connects to the device.
-	centralConnected func(c Central)
-
-	// disconnect is called when a remote central device disconnects to the device.
-	centralDisconnected func(c Central)
-
-	// peripheralDiscovered is called when a remote peripheral device is found during scan procedure.
-	peripheralDiscovered func(p Peripheral, a *Advertisement, rssi int)
-
-	// peripheralConnected is called when a remote peripheral is conneted.
-	peripheralConnected func(p Peripheral, err error)
-
-	// peripheralConnected is called when a remote peripheral is disconneted.
-	peripheralDisconnected func(p Peripheral, err error)
-}
-
-// A Handler is a self-referential function, which registers the options specified.
-// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
-type Handler func(Device)
-
-// Handle registers the specified handlers.
-func (d *device) Handle(hh ...Handler) {
-	for _, h := range hh {
-		h(d)
-	}
-}
-
-// CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.
-func CentralConnected(f func(Central)) Handler {
-	return func(d Device) { d.(*device).centralConnected = f }
-}
-
-// CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.
-func CentralDisconnected(f func(Central)) Handler {
-	return func(d Device) { d.(*device).centralDisconnected = f }
-}
-
-// PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.
-func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler {
-	return func(d Device) { d.(*device).peripheralDiscovered = f }
-}
-
-// PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.
-func PeripheralConnected(f func(Peripheral, error)) Handler {
-	return func(d Device) { d.(*device).peripheralConnected = f }
-}
-
-// PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.
-func PeripheralDisconnected(f func(Peripheral, error)) Handler {
-	return func(d Device) { d.(*device).peripheralDisconnected = f }
-}
-
-// An Option is a self-referential function, which sets the option specified.
-// Most Options are platform-specific, which gives more fine-grained control over the device at a cost of losing portibility.
-// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
-type Option func(Device) error
-
-// Option sets the options specified.
-// Some options can only be set before the device is initialized; they are best used with NewDevice instead of Option.
-func (d *device) Option(opts ...Option) error {
-	var err error
-	for _, opt := range opts {
-		err = opt(d)
-	}
-	return err
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/device_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/device_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/device_darwin.go
deleted file mode 100644
index 5401057..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/device_darwin.go
+++ /dev/null
@@ -1,513 +0,0 @@
-package gatt
-
-import (
-	"bytes"
-	"encoding/binary"
-	"errors"
-	"fmt"
-	"log"
-	"sync"
-	"time"
-
-	"github.com/runtimeinc/gatt/xpc"
-)
-
-const (
-	peripheralDiscovered   = 37
-	peripheralConnected    = 38
-	peripheralDisconnected = 40
-	// below constants for Yosemite
-	rssiRead                   = 55
-	includedServicesDiscovered = 63
-	serviceDiscovered          = 56
-	characteristicsDiscovered  = 64
-	characteristicRead         = 71
-	characteristicWritten      = 72
-	notificationValueSet       = 74
-	descriptorsDiscovered      = 76
-	descriptorRead             = 79
-	descriptorWritten          = 80
-)
-
-type device struct {
-	deviceHandler
-
-	conn xpc.XPC
-
-	role int // 1: peripheralManager (server), 0: centralManager (client)
-
-	reqc chan message
-	rspc chan message
-
-	// Only used in client/centralManager implementation
-	plist   map[string]*peripheral
-	plistmu *sync.Mutex
-
-	// Only used in server/peripheralManager implementation
-
-	attrN int
-	attrs map[int]*attr
-
-	subscribers map[string]*central
-}
-
-func NewDevice(opts ...Option) (Device, error) {
-	d := &device{
-		reqc:    make(chan message),
-		rspc:    make(chan message),
-		plist:   map[string]*peripheral{},
-		plistmu: &sync.Mutex{},
-
-		attrN: 1,
-		attrs: make(map[int]*attr),
-
-		subscribers: make(map[string]*central),
-	}
-	d.Option(opts...)
-	d.conn = xpc.XpcConnect("com.apple.blued", d)
-	return d, nil
-}
-
-func (d *device) Init(f func(Device, State)) error {
-	go d.loop()
-	rsp := d.sendReq(1, xpc.Dict{
-		"kCBMsgArgName":    fmt.Sprintf("gopher-%v", time.Now().Unix()),
-		"kCBMsgArgOptions": xpc.Dict{"kCBInitOptionShowPowerAlert": 1},
-		"kCBMsgArgType":    d.role,
-	})
-	d.stateChanged = f
-	go d.stateChanged(d, State(rsp.MustGetInt("kCBMsgArgState")))
-	return nil
-}
-
-func (d *device) Advertise(a *AdvPacket) error {
-	rsp := d.sendReq(8, xpc.Dict{
-		"kCBAdvDataAppleMfgData": a.b, // not a.Bytes(). should be slice
-	})
-
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return errors.New("FIXME: Advertise error")
-	}
-	return nil
-}
-
-func (d *device) AdvertiseNameAndServices(name string, ss []UUID) error {
-	us := uuidSlice(ss)
-	rsp := d.sendReq(8, xpc.Dict{
-		"kCBAdvDataLocalName":    name,
-		"kCBAdvDataServiceUUIDs": us},
-	)
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return errors.New("FIXME: Advertise error")
-	}
-	return nil
-}
-
-func (d *device) AdvertiseIBeaconData(data []byte) error {
-	var utsname xpc.Utsname
-	xpc.Uname(&utsname)
-
-	var rsp xpc.Dict
-
-	if utsname.Release >= "14." {
-		l := len(data)
-		buf := bytes.NewBuffer([]byte{byte(l + 5), 0xFF, 0x4C, 0x00, 0x02, byte(l)})
-		buf.Write(data)
-		rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleMfgData": buf.Bytes()})
-	} else {
-		rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleBeaconKey": data})
-	}
-
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return errors.New("FIXME: Advertise error")
-	}
-
-	return nil
-}
-
-func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
-	b := make([]byte, 21)
-	copy(b, reverse(u.b))                     // Big endian
-	binary.BigEndian.PutUint16(b[16:], major) // Big endian
-	binary.BigEndian.PutUint16(b[18:], minor) // Big endian
-	b[20] = uint8(pwr)                        // Measured Tx Power
-	return d.AdvertiseIBeaconData(b)
-}
-
-func (d *device) StopAdvertising() error {
-	rsp := d.sendReq(9, nil)
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return errors.New("FIXME: Stop Advertise error")
-	}
-	return nil
-}
-
-func (d *device) RemoveAllServices() error {
-	d.sendCmd(12, nil)
-	return nil
-}
-
-func (d *device) AddService(s *Service) error {
-	if s.uuid.Equal(attrGAPUUID) || s.uuid.Equal(attrGATTUUID) {
-		// skip GATT and GAP services
-		return nil
-	}
-
-	xs := xpc.Dict{
-		"kCBMsgArgAttributeID":     d.attrN,
-		"kCBMsgArgAttributeIDs":    []int{},
-		"kCBMsgArgCharacteristics": nil,
-		"kCBMsgArgType":            1, // 1 => primary, 0 => excluded
-		"kCBMsgArgUUID":            reverse(s.uuid.b),
-	}
-	d.attrN++
-
-	xcs := xpc.Array{}
-	for _, c := range s.Characteristics() {
-		props := 0
-		perm := 0
-		if c.props&CharRead != 0 {
-			props |= 0x02
-			if CharRead&c.secure != 0 {
-				perm |= 0x04
-			} else {
-				perm |= 0x01
-			}
-		}
-		if c.props&CharWriteNR != 0 {
-			props |= 0x04
-			if c.secure&CharWriteNR != 0 {
-				perm |= 0x08
-			} else {
-				perm |= 0x02
-			}
-		}
-		if c.props&CharWrite != 0 {
-			props |= 0x08
-			if c.secure&CharWrite != 0 {
-				perm |= 0x08
-			} else {
-				perm |= 0x02
-			}
-		}
-		if c.props&CharNotify != 0 {
-			if c.secure&CharNotify != 0 {
-				props |= 0x100
-			} else {
-				props |= 0x10
-			}
-		}
-		if c.props&CharIndicate != 0 {
-			if c.secure&CharIndicate != 0 {
-				props |= 0x200
-			} else {
-				props |= 0x20
-			}
-		}
-
-		xc := xpc.Dict{
-			"kCBMsgArgAttributeID":              d.attrN,
-			"kCBMsgArgUUID":                     reverse(c.uuid.b),
-			"kCBMsgArgAttributePermissions":     perm,
-			"kCBMsgArgCharacteristicProperties": props,
-			"kCBMsgArgData":                     c.value,
-		}
-		d.attrs[d.attrN] = &attr{h: uint16(d.attrN), value: c.value, pvt: c}
-		d.attrN++
-
-		xds := xpc.Array{}
-		for _, d := range c.Descriptors() {
-			if d.uuid.Equal(attrClientCharacteristicConfigUUID) {
-				// skip CCCD
-				continue
-			}
-			xd := xpc.Dict{
-				"kCBMsgArgData": d.value,
-				"kCBMsgArgUUID": reverse(d.uuid.b),
-			}
-			xds = append(xds, xd)
-		}
-		xc["kCBMsgArgDescriptors"] = xds
-		xcs = append(xcs, xc)
-	}
-	xs["kCBMsgArgCharacteristics"] = xcs
-
-	rsp := d.sendReq(10, xs)
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return errors.New("FIXME: Add Srvice error")
-	}
-	return nil
-}
-
-func (d *device) SetServices(ss []*Service) error {
-	d.RemoveAllServices()
-	for _, s := range ss {
-		d.AddService(s)
-	}
-	return nil
-}
-
-func (d *device) Scan(ss []UUID, dup bool) {
-	args := xpc.Dict{
-		"kCBMsgArgUUIDs": uuidSlice(ss),
-		"kCBMsgArgOptions": xpc.Dict{
-			"kCBScanOptionAllowDuplicates": map[bool]int{true: 1, false: 0}[dup],
-		},
-	}
-	d.sendCmd(29, args)
-}
-
-func (d *device) StopScanning() {
-	d.sendCmd(30, nil)
-}
-
-func (d *device) Connect(p Peripheral) {
-	pp := p.(*peripheral)
-	d.plist[pp.id.String()] = pp
-	d.sendCmd(31,
-		xpc.Dict{
-			"kCBMsgArgDeviceUUID": pp.id,
-			"kCBMsgArgOptions": xpc.Dict{
-				"kCBConnectOptionNotifyOnDisconnection": 1,
-			},
-		})
-}
-
-func (d *device) respondToRequest(id int, args xpc.Dict) {
-
-	switch id {
-	case 19: // ReadRequest
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		t := args.MustGetInt("kCBMsgArgTransactionID")
-		a := args.MustGetInt("kCBMsgArgAttributeID")
-		o := args.MustGetInt("kCBMsgArgOffset")
-
-		attr := d.attrs[a]
-		v := attr.value
-		if v == nil {
-			c := newCentral(d, u)
-			req := &ReadRequest{
-				Request: Request{Central: c},
-				Cap:     int(c.mtu - 1),
-				Offset:  o,
-			}
-			rsp := newResponseWriter(int(c.mtu - 1))
-			if c, ok := attr.pvt.(*Characteristic); ok {
-				c.rhandler.ServeRead(rsp, req)
-				v = rsp.bytes()
-			}
-		}
-
-		d.sendCmd(13, xpc.Dict{
-			"kCBMsgArgAttributeID":   a,
-			"kCBMsgArgData":          v,
-			"kCBMsgArgTransactionID": t,
-			"kCBMsgArgResult":        0,
-		})
-
-	case 20: // WriteRequest
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		t := args.MustGetInt("kCBMsgArgTransactionID")
-		a := 0
-		noRsp := false
-		xxws := args.MustGetArray("kCBMsgArgATTWrites")
-		for _, xxw := range xxws {
-			xw := xxw.(xpc.Dict)
-			if a == 0 {
-				a = xw.MustGetInt("kCBMsgArgAttributeID")
-			}
-			o := xw.MustGetInt("kCBMsgArgOffset")
-			i := xw.MustGetInt("kCBMsgArgIgnoreResponse")
-			b := xw.MustGetBytes("kCBMsgArgData")
-			_ = o
-			attr := d.attrs[a]
-			c := newCentral(d, u)
-			r := Request{Central: c}
-			attr.pvt.(*Characteristic).whandler.ServeWrite(r, b)
-			if i == 1 {
-				noRsp = true
-			}
-
-		}
-		if noRsp {
-			break
-		}
-		d.sendCmd(13, xpc.Dict{
-			"kCBMsgArgAttributeID":   a,
-			"kCBMsgArgData":          nil,
-			"kCBMsgArgTransactionID": t,
-			"kCBMsgArgResult":        0,
-		})
-
-	case 21: // subscribed
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		a := args.MustGetInt("kCBMsgArgAttributeID")
-		attr := d.attrs[a]
-		c := newCentral(d, u)
-		d.subscribers[u.String()] = c
-		c.startNotify(attr, c.mtu)
-
-	case 22: // unubscribed
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		a := args.MustGetInt("kCBMsgArgAttributeID")
-		attr := d.attrs[a]
-		if c := d.subscribers[u.String()]; c != nil {
-			c.stopNotify(attr)
-		}
-
-	case 23: // notificationSent
-	}
-}
-
-/*
- * OSX GATT library currently doesn't work for Mynewt, so adding this stub to keep
- * it buildable for OSX.
- */
-func (d *device) Stop() error {
-	return nil
-}
-
-func (d *device) CancelConnection(p Peripheral) {
-	d.sendCmd(32, xpc.Dict{"kCBMsgArgDeviceUUID": p.(*peripheral).id})
-}
-
-// process device events and asynchronous errors
-// (implements XpcEventHandler)
-func (d *device) HandleXpcEvent(event xpc.Dict, err error) {
-	if err != nil {
-		log.Println("error:", err)
-		return
-	}
-
-	id := event.MustGetInt("kCBMsgId")
-	args := event.MustGetDict("kCBMsgArgs")
-	//log.Printf(">> %d, %v", id, args)
-
-	switch id {
-	case // device event
-		6,  // StateChanged
-		16, // AdvertisingStarted
-		17, // AdvertisingStopped
-		18: // ServiceAdded
-		d.rspc <- message{id: id, args: args}
-
-	case
-		19, // ReadRequest
-		20, // WriteRequest
-		21, // Subscribe
-		22, // Unubscribe
-		23: // Confirmation
-		d.respondToRequest(id, args)
-
-	case peripheralDiscovered:
-		xa := args.MustGetDict("kCBMsgArgAdvertisementData")
-		if len(xa) == 0 {
-			return
-		}
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		a := &Advertisement{
-			LocalName:        xa.GetString("kCBAdvDataLocalName", args.GetString("kCBMsgArgName", "")),
-			TxPowerLevel:     xa.GetInt("kCBAdvDataTxPowerLevel", 0),
-			ManufacturerData: xa.GetBytes("kCBAdvDataManufacturerData", nil),
-		}
-
-		rssi := args.MustGetInt("kCBMsgArgRssi")
-
-		if xu, ok := xa["kCBAdvDataServiceUUIDs"]; ok {
-			for _, xs := range xu.(xpc.Array) {
-				s := UUID{reverse(xs.([]byte))}
-				a.Services = append(a.Services, s)
-			}
-		}
-		if xsds, ok := xa["kCBAdvDataServiceData"]; ok {
-			xsd := xsds.(xpc.Array)
-			for i := 0; i < len(xsd); i += 2 {
-				sd := ServiceData{
-					UUID: UUID{xsd[i].([]byte)},
-					Data: xsd[i+1].([]byte),
-				}
-				a.ServiceData = append(a.ServiceData, sd)
-			}
-		}
-		if d.peripheralDiscovered != nil {
-			go d.peripheralDiscovered(&peripheral{id: xpc.UUID(u.b), d: d}, a, rssi)
-		}
-
-	case peripheralConnected:
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		p := &peripheral{
-			id:    xpc.UUID(u.b),
-			d:     d,
-			reqc:  make(chan message),
-			rspc:  make(chan message),
-			quitc: make(chan struct{}),
-			sub:   newSubscriber(),
-		}
-		d.plistmu.Lock()
-		d.plist[u.String()] = p
-		d.plistmu.Unlock()
-		go p.loop()
-
-		if d.peripheralConnected != nil {
-			go d.peripheralConnected(p, nil)
-		}
-
-	case peripheralDisconnected:
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		d.plistmu.Lock()
-		p := d.plist[u.String()]
-		delete(d.plist, u.String())
-		d.plistmu.Unlock()
-		if d.peripheralDisconnected != nil {
-			d.peripheralDisconnected(p, nil) // TODO: Get Result as error?
-		}
-		close(p.quitc)
-
-	case // Peripheral events
-		rssiRead,
-		serviceDiscovered,
-		includedServicesDiscovered,
-		characteristicsDiscovered,
-		characteristicRead,
-		characteristicWritten,
-		notificationValueSet,
-		descriptorsDiscovered,
-		descriptorRead,
-		descriptorWritten:
-
-		u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
-		d.plistmu.Lock()
-		p := d.plist[u.String()]
-		d.plistmu.Unlock()
-		p.rspc <- message{id: id, args: args}
-
-	default:
-		log.Printf("Unhandled event: %#v", event)
-	}
-}
-
-func (d *device) sendReq(id int, args xpc.Dict) xpc.Dict {
-	m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
-	d.reqc <- m
-	return <-m.rspc
-}
-
-func (d *device) sendCmd(id int, args xpc.Dict) {
-	d.reqc <- message{id: id, args: args}
-}
-
-func (d *device) loop() {
-	for req := range d.reqc {
-		d.sendCBMsg(req.id, req.args)
-		if req.rspc == nil {
-			continue
-		}
-		m := <-d.rspc
-		req.rspc <- m.args
-	}
-}
-
-func (d *device) sendCBMsg(id int, args xpc.Dict) {
-	// log.Printf("<< %d, %v", id, args)
-	d.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, false)
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/device_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/device_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/device_linux.go
deleted file mode 100644
index d723e40..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/device_linux.go
+++ /dev/null
@@ -1,240 +0,0 @@
-package gatt
-
-import (
-	"encoding/binary"
-	"net"
-
-	"github.com/runtimeinc/gatt/linux"
-	"github.com/runtimeinc/gatt/linux/cmd"
-)
-
-type device struct {
-	deviceHandler
-
-	hci   *linux.HCI
-	state State
-
-	// All the following fields are only used peripheralManager (server) implementation.
-	svcs  []*Service
-	attrs *attrRange
-
-	devID   int
-	chkLE   bool
-	maxConn int
-
-	advData   *cmd.LESetAdvertisingData
-	scanResp  *cmd.LESetScanResponseData
-	advParam  *cmd.LESetAdvertisingParameters
-	scanParam *cmd.LESetScanParameters
-}
-
-func NewDevice(opts ...Option) (Device, error) {
-	d := &device{
-		maxConn: 1,    // Support 1 connection at a time.
-		devID:   -1,   // Find an available HCI device.
-		chkLE:   true, // Check if the device supports LE.
-
-		advParam: &cmd.LESetAdvertisingParameters{
-			AdvertisingIntervalMin:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
-			AdvertisingIntervalMax:  0x800,     // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
-			AdvertisingType:         0x00,      // [0x00]: ADV_IND, 0x01: DIRECT(HIGH), 0x02: SCAN, 0x03: NONCONN, 0x04: DIRECT(LOW)
-			OwnAddressType:          0x00,      // [0x00]: public, 0x01: random
-			DirectAddressType:       0x00,      // [0x00]: public, 0x01: random
-			DirectAddress:           [6]byte{}, // Public or Random Address of the device to be connected
-			AdvertisingChannelMap:   0x7,       // [0x07] 0x01: ch37, 0x2: ch38, 0x4: ch39
-			AdvertisingFilterPolicy: 0x00,
-		},
-		scanParam: &cmd.LESetScanParameters{
-			LEScanType:           0x01,   // [0x00]: passive, 0x01: active
-			LEScanInterval:       0x0010, // [0x10]: 0.625ms * 16
-			LEScanWindow:         0x0010, // [0x10]: 0.625ms * 16
-			OwnAddressType:       0x00,   // [0x00]: public, 0x01: random
-			ScanningFilterPolicy: 0x00,   // [0x00]: accept all, 0x01: ignore non-white-listed.
-		},
-	}
-
-	d.Option(opts...)
-	h, err := linux.NewHCI(d.devID, d.chkLE, d.maxConn)
-	if err != nil {
-		return nil, err
-	}
-
-	d.hci = h
-	return d, nil
-}
-
-func (d *device) Init(f func(Device, State)) error {
-	d.hci.AcceptMasterHandler = func(pd *linux.PlatData) {
-		a := pd.Address
-		c := newCentral(d.attrs, net.HardwareAddr([]byte{a[5], a[4], a[3], a[2], a[1], a[0]}), pd.Conn)
-		if d.centralConnected != nil {
-			d.centralConnected(c)
-		}
-		c.loop()
-		if d.centralDisconnected != nil {
-			d.centralDisconnected(c)
-		}
-	}
-	d.hci.AcceptSlaveHandler = func(pd *linux.PlatData) {
-		p := &peripheral{
-			d:     d,
-			pd:    pd,
-			l2c:   pd.Conn,
-			reqc:  make(chan message),
-			quitc: make(chan struct{}),
-			sub:   newSubscriber(),
-		}
-		if d.peripheralConnected != nil {
-			go d.peripheralConnected(p, nil)
-		}
-		p.loop()
-		if d.peripheralDisconnected != nil {
-			d.peripheralDisconnected(p, nil)
-		}
-	}
-	d.hci.AdvertisementHandler = func(pd *linux.PlatData) {
-		a := &Advertisement{}
-		a.unmarshall(pd.Data)
-		a.Connectable = pd.Connectable
-	        a.Address = pd.Address
-		a.AddressType = pd.AddressType
-		p := &peripheral{pd: pd, d: d}
-		if d.peripheralDiscovered != nil {
-			pd.Name = a.LocalName
-			d.peripheralDiscovered(p, a, int(pd.RSSI))
-		}
-	}
-	d.state = StatePoweredOn
-	d.stateChanged = f
-	go d.stateChanged(d, d.state)
-	return nil
-}
-
-func (d *device) Stop() error {
-	d.state = StatePoweredOff
-	defer d.stateChanged(d, d.state)
-	return d.hci.Close()
-}
-
-func (d *device) AddService(s *Service) error {
-	d.svcs = append(d.svcs, s)
-	d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
-	return nil
-}
-
-func (d *device) RemoveAllServices() error {
-	d.svcs = nil
-	d.attrs = nil
-	return nil
-}
-
-func (d *device) SetServices(s []*Service) error {
-	d.RemoveAllServices()
-	d.svcs = append(d.svcs, s...)
-	d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
-	return nil
-}
-
-func (d *device) Advertise(a *AdvPacket) error {
-	d.advData = &cmd.LESetAdvertisingData{
-		AdvertisingDataLength: uint8(a.Len()),
-		AdvertisingData:       a.Bytes(),
-	}
-
-	if err := d.update(); err != nil {
-		return err
-	}
-
-	return d.hci.SetAdvertiseEnable(true)
-}
-
-func (d *device) AdvertiseNameAndServices(name string, uu []UUID) error {
-	a := &AdvPacket{}
-	a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
-	a.AppendUUIDFit(uu)
-
-	if len(a.b)+len(name)+2 < MaxEIRPacketLength {
-		a.AppendName(name)
-		d.scanResp = nil
-	} else {
-		a := &AdvPacket{}
-		a.AppendName(name)
-		d.scanResp = &cmd.LESetScanResponseData{
-			ScanResponseDataLength: uint8(a.Len()),
-			ScanResponseData:       a.Bytes(),
-		}
-	}
-
-	return d.Advertise(a)
-}
-
-func (d *device) AdvertiseIBeaconData(b []byte) error {
-	a := &AdvPacket{}
-	a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
-	a.AppendManufacturerData(0x004C, b)
-	d.advData = &cmd.LESetAdvertisingData{
-		AdvertisingDataLength: uint8(a.Len()),
-		AdvertisingData:       a.Bytes(),
-	}
-
-	return d.Advertise(a)
-}
-
-func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
-	b := make([]byte, 23)
-	b[0] = 0x02                               // Data type: iBeacon
-	b[1] = 0x15                               // Data length: 21 bytes
-	copy(b[2:], reverse(u.b))                 // Big endian
-	binary.BigEndian.PutUint16(b[18:], major) // Big endian
-	binary.BigEndian.PutUint16(b[20:], minor) // Big endian
-	b[22] = uint8(pwr)                        // Measured Tx Power
-	return d.AdvertiseIBeaconData(b)
-}
-
-func (d *device) StopAdvertising() error {
-	return d.hci.SetAdvertiseEnable(false)
-}
-
-func (d *device) Scan(ss []UUID, dup bool) {
-	// TODO: filter
-	d.hci.SetScanEnable(true, dup)
-}
-
-func (d *device) StopScanning() {
-	d.hci.SetScanEnable(false, true)
-}
-
-func (d *device) Connect(p Peripheral) {
-	d.hci.Connect(p.(*peripheral).pd)
-}
-
-func (d *device) CancelConnection(p Peripheral) {
-	d.hci.CancelConnection(p.(*peripheral).pd)
-}
-
-func (d *device) SendHCIRawCommand(c cmd.CmdParam) ([]byte, error) {
-	return d.hci.SendRawCommand(c)
-}
-
-// Flush pending advertising settings to the device.
-func (d *device) update() error {
-	if d.advParam != nil {
-		if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil {
-			return err
-		}
-		d.advParam = nil
-	}
-	if d.scanResp != nil {
-		if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil {
-			return err
-		}
-		d.scanResp = nil
-	}
-	if d.advData != nil {
-		if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil {
-			return err
-		}
-		d.advData = nil
-	}
-	return nil
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/doc.go b/newtmgr/vendor/github.com/runtimeinc/gatt/doc.go
deleted file mode 100644
index c34a3e9..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/doc.go
+++ /dev/null
@@ -1,88 +0,0 @@
-// Package gatt provides a Bluetooth Low Energy gatt implementation.
-//
-// Gatt (Generic Attribute Profile) is the protocol used to write
-// BLE peripherals (servers) and centrals (clients).
-//
-// STATUS
-//
-// This package is a work in progress. The API will change.
-//
-// As a peripheral, you can create services, characteristics, and descriptors,
-// advertise, accept connections, and handle requests.
-// As a central, you can scan, connect, discover services, and make requests.
-//
-// SETUP
-//
-// gatt supports both Linux and OS X.
-//
-// On Linux:
-// To gain complete and exclusive control of the HCI device, gatt uses
-// HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
-// Those who must use an older kernel may patch in these relevant commits
-// from Marcel Holtmann:
-//
-//     Bluetooth: Introduce new HCI socket channel for user operation
-//     Bluetooth: Introduce user channel flag for HCI devices
-//     Bluetooth: Refactor raw socket filter into more readable code
-//
-// Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
-// device no other program may access it.
-//
-// Before starting a gatt program, make sure that your BLE device is down:
-//
-//     sudo hciconfig
-//     sudo hciconfig hci0 down  # or whatever hci device you want to use
-//
-// If you have BlueZ 5.14+ (or aren't sure), stop the built-in
-// bluetooth server, which interferes with gatt, e.g.:
-//
-//     sudo service bluetooth stop
-//
-// Because gatt programs administer network devices, they must
-// either be run as root, or be granted appropriate capabilities:
-//
-//     sudo <executable>
-//     # OR
-//     sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
-//     <executable>
-//
-// USAGE
-//
-//     # Start a simple server.
-//     sudo go run example/server.go
-//
-//     # Discover surrounding peripherals.
-//     sudo go run example/discoverer.go
-//
-//     # Connect to and explorer a peripheral device.
-//     sudo go run example/explorer.go <peripheral ID>
-//
-// See the server.go, discoverer.go, and explorer.go in the examples/
-// directory for writing server or client programs that run on Linux
-// and OS X.
-//
-// Users, especially on Linux platforms, seeking finer-grained control
-// over the devices can see the examples/server_lnx.go for the usage
-// of Option, which are platform specific.
-//
-// See the rest of the docs for other options and finer-grained control.
-//
-// Note that some BLE central devices, particularly iOS, may aggressively
-// cache results from previous connections. If you change your services or
-// characteristics, you may need to reboot the other device to pick up the
-// changes. This is a common source of confusion and apparent bugs. For an
-// OS X central, see http://stackoverflow.com/questions/20553957.
-//
-//
-// REFERENCES
-//
-// gatt started life as a port of bleno, to which it is indebted:
-// https://github.com/sandeepmistry/bleno. If you are having
-// problems with gatt, particularly around installation, issues
-// filed with bleno might also be helpful references.
-//
-// To try out your GATT server, it is useful to experiment with a
-// generic BLE client. LightBlue is a good choice. It is available
-// free for both iOS and OS X.
-//
-package gatt

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/known_uuid.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/known_uuid.go b/newtmgr/vendor/github.com/runtimeinc/gatt/known_uuid.go
deleted file mode 100644
index 2146af5..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/known_uuid.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package gatt
-
-// A dictionary of known service names and type (keyed by service uuid)
-var knownServices = map[string]struct{ Name, Type string }{
-	"1800": {Name: "Generic Access", Type: "org.bluetooth.service.generic_access"},
-	"1801": {Name: "Generic Attribute", Type: "org.bluetooth.service.generic_attribute"},
-	"1802": {Name: "Immediate Alert", Type: "org.bluetooth.service.immediate_alert"},
-	"1803": {Name: "Link Loss", Type: "org.bluetooth.service.link_loss"},
-	"1804": {Name: "Tx Power", Type: "org.bluetooth.service.tx_power"},
-	"1805": {Name: "Current Time Service", Type: "org.bluetooth.service.current_time"},
-	"1806": {Name: "Reference Time Update Service", Type: "org.bluetooth.service.reference_time_update"},
-	"1807": {Name: "Next DST Change Service", Type: "org.bluetooth.service.next_dst_change"},
-	"1808": {Name: "Glucose", Type: "org.bluetooth.service.glucose"},
-	"1809": {Name: "Health Thermometer", Type: "org.bluetooth.service.health_thermometer"},
-	"180a": {Name: "Device Information", Type: "org.bluetooth.service.device_information"},
-	"180d": {Name: "Heart Rate", Type: "org.bluetooth.service.heart_rate"},
-	"180e": {Name: "Phone Alert Status Service", Type: "org.bluetooth.service.phone_alert_service"},
-	"180f": {Name: "Battery Service", Type: "org.bluetooth.service.battery_service"},
-	"1810": {Name: "Blood Pressure", Type: "org.bluetooth.service.blood_pressuer"},
-	"1811": {Name: "Alert Notification Service", Type: "org.bluetooth.service.alert_notification"},
-	"1812": {Name: "Human Interface Device", Type: "org.bluetooth.service.human_interface_device"},
-	"1813": {Name: "Scan Parameters", Type: "org.bluetooth.service.scan_parameters"},
-	"1814": {Name: "Running Speed and Cadence", Type: "org.bluetooth.service.running_speed_and_cadence"},
-	"1815": {Name: "Cycling Speed and Cadence", Type: "org.bluetooth.service.cycling_speed_and_cadence"},
-}
-
-// A dictionary of known descriptor names and type (keyed by attribute uuid)
-var knownAttributes = map[string]struct{ Name, Type string }{
-	"2800": {Name: "Primary Service", Type: "org.bluetooth.attribute.gatt.primary_service_declaration"},
-	"2801": {Name: "Secondary Service", Type: "org.bluetooth.attribute.gatt.secondary_service_declaration"},
-	"2802": {Name: "Include", Type: "org.bluetooth.attribute.gatt.include_declaration"},
-	"2803": {Name: "Characteristic", Type: "org.bluetooth.attribute.gatt.characteristic_declaration"},
-}
-
-// A dictionary of known descriptor names and type (keyed by descriptor uuid)
-var knownDescriptors = map[string]struct{ Name, Type string }{
-	"2900": {Name: "Characteristic Extended Properties", Type: "org.bluetooth.descriptor.gatt.characteristic_extended_properties"},
-	"2901": {Name: "Characteristic User Description", Type: "org.bluetooth.descriptor.gatt.characteristic_user_description"},
-	"2902": {Name: "Client Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.client_characteristic_configuration"},
-	"2903": {Name: "Server Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.server_characteristic_configuration"},
-	"2904": {Name: "Characteristic Presentation Format", Type: "org.bluetooth.descriptor.gatt.characteristic_presentation_format"},
-	"2905": {Name: "Characteristic Aggregate Format", Type: "org.bluetooth.descriptor.gatt.characteristic_aggregate_format"},
-	"2906": {Name: "Valid Range", Type: "org.bluetooth.descriptor.valid_range"},
-	"2907": {Name: "External Report Reference", Type: "org.bluetooth.descriptor.external_report_reference"},
-	"2908": {Name: "Report Reference", Type: "org.bluetooth.descriptor.report_reference"},
-}
-
-// A dictionary of known characteristic names and type (keyed by characteristic uuid)
-var knownCharacteristics = map[string]struct{ Name, Type string }{
-	"2a00": {Name: "Device Name", Type: "org.bluetooth.characteristic.gap.device_name"},
-	"2a01": {Name: "Appearance", Type: "org.bluetooth.characteristic.gap.appearance"},
-	"2a02": {Name: "Peripheral Privacy Flag", Type: "org.bluetooth.characteristic.gap.peripheral_privacy_flag"},
-	"2a03": {Name: "Reconnection Address", Type: "org.bluetooth.characteristic.gap.reconnection_address"},
-	"2a04": {Name: "Peripheral Preferred Connection Parameters", Type: "org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters"},
-	"2a05": {Name: "Service Changed", Type: "org.bluetooth.characteristic.gatt.service_changed"},
-	"2a06": {Name: "Alert Level", Type: "org.bluetooth.characteristic.alert_level"},
-	"2a07": {Name: "Tx Power Level", Type: "org.bluetooth.characteristic.tx_power_level"},
-	"2a08": {Name: "Date Time", Type: "org.bluetooth.characteristic.date_time"},
-	"2a09": {Name: "Day of Week", Type: "org.bluetooth.characteristic.day_of_week"},
-	"2a0a": {Name: "Day Date Time", Type: "org.bluetooth.characteristic.day_date_time"},
-	"2a0c": {Name: "Exact Time 256", Type: "org.bluetooth.characteristic.exact_time_256"},
-	"2a0d": {Name: "DST Offset", Type: "org.bluetooth.characteristic.dst_offset"},
-	"2a0e": {Name: "Time Zone", Type: "org.bluetooth.characteristic.time_zone"},
-	"2a0f": {Name: "Local Time Information", Type: "org.bluetooth.characteristic.local_time_information"},
-	"2a11": {Name: "Time with DST", Type: "org.bluetooth.characteristic.time_with_dst"},
-	"2a12": {Name: "Time Accuracy", Type: "org.bluetooth.characteristic.time_accuracy"},
-	"2a13": {Name: "Time Source", Type: "org.bluetooth.characteristic.time_source"},
-	"2a14": {Name: "Reference Time Information", Type: "org.bluetooth.characteristic.reference_time_information"},
-	"2a16": {Name: "Time Update Control Point", Type: "org.bluetooth.characteristic.time_update_control_point"},
-	"2a17": {Name: "Time Update State", Type: "org.bluetooth.characteristic.time_update_state"},
-	"2a18": {Name: "Glucose Measurement", Type: "org.bluetooth.characteristic.glucose_measurement"},
-	"2a19": {Name: "Battery Level", Type: "org.bluetooth.characteristic.battery_level"},
-	"2a1c": {Name: "Temperature Measurement", Type: "org.bluetooth.characteristic.temperature_measurement"},
-	"2a1d": {Name: "Temperature Type", Type: "org.bluetooth.characteristic.temperature_type"},
-	"2a1e": {Name: "Intermediate Temperature", Type: "org.bluetooth.characteristic.intermediate_temperature"},
-	"2a21": {Name: "Measurement Interval", Type: "org.bluetooth.characteristic.measurement_interval"},
-	"2a22": {Name: "Boot Keyboard Input Report", Type: "org.bluetooth.characteristic.boot_keyboard_input_report"},
-	"2a23": {Name: "System ID", Type: "org.bluetooth.characteristic.system_id"},
-	"2a24": {Name: "Model Number String", Type: "org.bluetooth.characteristic.model_number_string"},
-	"2a25": {Name: "Serial Number String", Type: "org.bluetooth.characteristic.serial_number_string"},
-	"2a26": {Name: "Firmware Revision String", Type: "org.bluetooth.characteristic.firmware_revision_string"},
-	"2a27": {Name: "Hardware Revision String", Type: "org.bluetooth.characteristic.hardware_revision_string"},
-	"2a28": {Name: "Software Revision String", Type: "org.bluetooth.characteristic.software_revision_string"},
-	"2a29": {Name: "Manufacturer Name String", Type: "org.bluetooth.characteristic.manufacturer_name_string"},
-	"2a2a": {Name: "IEEE 11073-20601 Regulatory Certification Data List", Type: "org.bluetooth.characteristic.ieee_11073-20601_regulatory_certification_data_list"},
-	"2a2b": {Name: "Current Time", Type: "org.bluetooth.characteristic.current_time"},
-	"2a31": {Name: "Scan Refresh", Type: "org.bluetooth.characteristic.scan_refresh"},
-	"2a32": {Name: "Boot Keyboard Output Report", Type: "org.bluetooth.characteristic.boot_keyboard_output_report"},
-	"2a33": {Name: "Boot Mouse Input Report", Type: "org.bluetooth.characteristic.boot_mouse_input_report"},
-	"2a34": {Name: "Glucose Measurement Context", Type: "org.bluetooth.characteristic.glucose_measurement_context"},
-	"2a35": {Name: "Blood Pressure Measurement", Type: "org.bluetooth.characteristic.blood_pressure_measurement"},
-	"2a36": {Name: "Intermediate Cuff Pressure", Type: "org.bluetooth.characteristic.intermediate_blood_pressure"},
-	"2a37": {Name: "Heart Rate Measurement", Type: "org.bluetooth.characteristic.heart_rate_measurement"},
-	"2a38": {Name: "Body Sensor Location", Type: "org.bluetooth.characteristic.body_sensor_location"},
-	"2a39": {Name: "Heart Rate Control Point", Type: "org.bluetooth.characteristic.heart_rate_control_point"},
-	"2a3f": {Name: "Alert Status", Type: "org.bluetooth.characteristic.alert_status"},
-	"2a40": {Name: "Ringer Control Point", Type: "org.bluetooth.characteristic.ringer_control_point"},
-	"2a41": {Name: "Ringer Setting", Type: "org.bluetooth.characteristic.ringer_setting"},
-	"2a42": {Name: "Alert Category ID Bit Mask", Type: "org.bluetooth.characteristic.alert_category_id_bit_mask"},
-	"2a43": {Name: "Alert Category ID", Type: "org.bluetooth.characteristic.alert_category_id"},
-	"2a44": {Name: "Alert Notification Control Point", Type: "org.bluetooth.characteristic.alert_notification_control_point"},
-	"2a45": {Name: "Unread Alert Status", Type: "org.bluetooth.characteristic.unread_alert_status"},
-	"2a46": {Name: "New Alert", Type: "org.bluetooth.characteristic.new_alert"},
-	"2a47": {Name: "Supported New Alert Category", Type: "org.bluetooth.characteristic.supported_new_alert_category"},
-	"2a48": {Name: "Supported Unread Alert Category", Type: "org.bluetooth.characteristic.supported_unread_alert_category"},
-	"2a49": {Name: "Blood Pressure Feature", Type: "org.bluetooth.characteristic.blood_pressure_feature"},
-	"2a4a": {Name: "HID Information", Type: "org.bluetooth.characteristic.hid_information"},
-	"2a4b": {Name: "Report Map", Type: "org.bluetooth.characteristic.report_map"},
-	"2a4c": {Name: "HID Control Point", Type: "org.bluetooth.characteristic.hid_control_point"},
-	"2a4d": {Name: "Report", Type: "org.bluetooth.characteristic.report"},
-	"2a4e": {Name: "Protocol Mode", Type: "org.bluetooth.characteristic.protocol_mode"},
-	"2a4f": {Name: "Scan Interval Window", Type: "org.bluetooth.characteristic.scan_interval_window"},
-	"2a50": {Name: "PnP ID", Type: "org.bluetooth.characteristic.pnp_id"},
-	"2a51": {Name: "Glucose Feature", Type: "org.bluetooth.characteristic.glucose_feature"},
-	"2a52": {Name: "Record Access Control Point", Type: "org.bluetooth.characteristic.record_access_control_point"},
-	"2a53": {Name: "RSC Measurement", Type: "org.bluetooth.characteristic.rsc_measurement"},
-	"2a54": {Name: "RSC Feature", Type: "org.bluetooth.characteristic.rsc_feature"},
-	"2a55": {Name: "SC Control Point", Type: "org.bluetooth.characteristic.sc_control_point"},
-	"2a5b": {Name: "CSC Measurement", Type: "org.bluetooth.characteristic.csc_measurement"},
-	"2a5c": {Name: "CSC Feature", Type: "org.bluetooth.characteristic.csc_feature"},
-	"2a5d": {Name: "Sensor Location", Type: "org.bluetooth.characteristic.sensor_location"},
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/l2cap_writer_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/l2cap_writer_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/l2cap_writer_linux.go
deleted file mode 100644
index f5cecaf..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/l2cap_writer_linux.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package gatt
-
-import "encoding/binary"
-
-// l2capWriter helps create l2cap responses.
-// It is not meant to be used with large writes.
-// TODO: benchmark the number of allocs here.
-// Reduce by letting WriteByteFit, WriteUint16Fit, etc.
-// extend b/chunk and write into it directly.
-type l2capWriter struct {
-	mtu     int
-	b       []byte
-	chunk   []byte
-	chunked bool
-}
-
-func newL2capWriter(mtu uint16) *l2capWriter {
-	return &l2capWriter{mtu: int(mtu), b: make([]byte, 0, mtu)}
-}
-
-// Chunk starts writing a new chunk. This chunk
-// is not committed until Commit is called.
-// Chunk panics if another chunk has already been
-// started and not committed.
-func (w *l2capWriter) Chunk() {
-	if w.chunked {
-		panic("l2capWriter: chunk called twice without committing")
-	}
-	w.chunked = true
-	if w.chunk == nil {
-		w.chunk = make([]byte, 0, w.mtu)
-	}
-}
-
-// Commit writes the current chunk and reports whether the
-// write succeeded. The write succeeds iff there is enough room.
-// Commit panics if no chunk has been started.
-func (w *l2capWriter) Commit() bool {
-	if !w.chunked {
-		panic("l2capWriter: commit without starting a chunk")
-	}
-	var success bool
-	if len(w.b)+len(w.chunk) <= w.mtu {
-		success = true
-		w.b = append(w.b, w.chunk...)
-	}
-	w.chunk = w.chunk[:0]
-	w.chunked = false
-	return success
-}
-
-// CommitFit writes as much of the current chunk as possible,
-// truncating as needed.
-// CommitFit panics if no chunk has been started.
-func (w *l2capWriter) CommitFit() {
-	if !w.chunked {
-		panic("l2capWriter: CommitFit without starting a chunk")
-	}
-	writeable := w.mtu - len(w.b)
-	if writeable > len(w.chunk) {
-		writeable = len(w.chunk)
-	}
-	w.b = append(w.b, w.chunk[:writeable]...)
-	w.chunk = w.chunk[:0]
-	w.chunked = false
-}
-
-// WriteByteFit writes b.
-// It reports whether the write succeeded,
-// using the criteria of WriteFit.
-func (w *l2capWriter) WriteByteFit(b byte) bool {
-	return w.WriteFit([]byte{b})
-}
-
-// WriteUint16Fit writes v using BLE (LittleEndian) encoding.
-// It reports whether the write succeeded, using the
-// criteria of WriteFit.
-func (w *l2capWriter) WriteUint16Fit(v uint16) bool {
-	b := make([]byte, 2)
-	binary.LittleEndian.PutUint16(b, v)
-	return w.WriteFit(b)
-}
-
-// WriteUUIDFit writes uuid using BLE (reversed) encoding.
-// It reports whether the write succeeded, using the
-// criteria of WriteFit.
-func (w *l2capWriter) WriteUUIDFit(u UUID) bool {
-	return w.WriteFit(u.b)
-}
-
-// Writeable returns the number of bytes from b
-// that would be written if pad bytes were written,
-// then as much of b as fits were written. When
-// writing to a chunk, any amount of bytes may be
-// written.
-func (w *l2capWriter) Writeable(pad int, b []byte) int {
-	if w.chunked {
-		return len(b)
-	}
-	avail := w.mtu - len(w.b) - pad
-	if avail > len(b) {
-		return len(b)
-	}
-	if avail < 0 {
-		return 0
-	}
-	return avail
-}
-
-// WriteFit writes as much of b as fits.
-// It reports whether the write succeeded without
-// truncation. A write succeeds without truncation
-// iff a chunk write is in progress or the entire
-// contents were written (without exceeding the mtu).
-func (w *l2capWriter) WriteFit(b []byte) bool {
-	if w.chunked {
-		w.chunk = append(w.chunk, b...)
-		return true
-	}
-	avail := w.mtu - len(w.b)
-	if avail >= len(b) {
-		w.b = append(w.b, b...)
-		return true
-	}
-	w.b = append(w.b, b[:avail]...)
-	return false
-}
-
-// ChunkSeek discards the first offset bytes from the
-// current chunk. It reports whether there were at least
-// offset bytes available to discard.
-// It panics if a chunked write is not in progress.
-func (w *l2capWriter) ChunkSeek(offset uint16) bool {
-	if !w.chunked {
-		panic("l2capWriter: ChunkSeek requested without chunked write in progress")
-	}
-	if len(w.chunk) < int(offset) {
-		w.chunk = w.chunk[:0]
-		return false
-	}
-	w.chunk = w.chunk[offset:]
-	return true
-}
-
-// Bytes returns the written bytes.
-// It will panic if a chunked write
-// is in progress.
-// It is meant to be used when writing
-// is completed. It does not return a copy.
-// Don't abuse this, it's not worth it.
-func (w *l2capWriter) Bytes() []byte {
-	if w.chunked {
-		panic("l2capWriter: Bytes requested while chunked write in progress")
-	}
-	return w.b
-}


[07/41] incubator-mynewt-newt git commit: MYNEWT-623; allow user to override "github.com" as repo location. Override is done using repository variable "server".

Posted by ma...@apache.org.
MYNEWT-623; allow user to override "github.com" as repo location.
Override is done using repository variable "server".


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/3e4102b1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/3e4102b1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/3e4102b1

Branch: refs/heads/mynewt_1_0_0
Commit: 3e4102b1c51ae5591c80153e6fd45fa550040918
Parents: df3061f
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Sat Feb 11 12:39:36 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:30:52 2017 -0800

----------------------------------------------------------------------
 newt/downloader/downloader.go | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/3e4102b1/newt/downloader/downloader.go
----------------------------------------------------------------------
diff --git a/newt/downloader/downloader.go b/newt/downloader/downloader.go
index bd763f5..06557dd 100644
--- a/newt/downloader/downloader.go
+++ b/newt/downloader/downloader.go
@@ -47,8 +47,9 @@ type GenericDownloader struct {
 
 type GithubDownloader struct {
 	GenericDownloader
-	User string
-	Repo string
+	Server string
+	User   string
+	Repo   string
 
 	// Github access token for private repositories.
 	Token string
@@ -117,8 +118,12 @@ func (gd *GenericDownloader) TempDir() (string, error) {
 }
 
 func (gd *GithubDownloader) FetchFile(name string, dest string) error {
-	url := fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s?ref=%s",
-		gd.User, gd.Repo, name, gd.Branch())
+	server := "github.com"
+	if gd.Server != "" {
+		server = gd.Server
+	}
+	url := fmt.Sprintf("https://api.%s/repos/%s/%s/contents/%s?ref=%s",
+		server, gd.User, gd.Repo, name, gd.Branch())
 
 	req, err := http.NewRequest("GET", url, nil)
 	req.Header.Add("Accept", "application/vnd.github.v3.raw")
@@ -174,8 +179,12 @@ func (gd *GithubDownloader) DownloadRepo(commit string) (string, error) {
 
 	// Currently only the master branch is supported.
 	branch := "master"
+	server := "github.com"
 
-	url := fmt.Sprintf("https://github.com/%s/%s.git", gd.User, gd.Repo)
+	if gd.Server != "" {
+		server = gd.Server
+	}
+	url := fmt.Sprintf("https://%s/%s/%s.git", server, gd.User, gd.Repo)
 	util.StatusMessage(util.VERBOSITY_VERBOSE, "Downloading "+
 		"repository %s (branch: %s; commit: %s) at %s\n", gd.Repo, branch,
 		commit, url)
@@ -265,6 +274,7 @@ func LoadDownloader(repoName string, repoVars map[string]string) (
 	case "github":
 		gd := NewGithubDownloader()
 
+		gd.Server = repoVars["server"]
 		gd.User = repoVars["user"]
 		gd.Repo = repoVars["repo"]
 


[13/41] incubator-mynewt-newt git commit: use defer to exit function instead of calling os.Chdir() in exit path

Posted by ma...@apache.org.
use defer to exit function instead of calling os.Chdir() in exit path


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/85bc49bf
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/85bc49bf
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/85bc49bf

Branch: refs/heads/mynewt_1_0_0
Commit: 85bc49bfaa1aaa7df9f63e4c0557a48cc365fd06
Parents: f497cab
Author: Sterling Hughes <st...@runtime.io>
Authored: Mon Feb 13 18:27:19 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:39 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 11 ++---------
 1 file changed, 2 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/85bc49bf/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 75e9a00..4fdecca 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -63,6 +63,7 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	if err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
+	defer os.Chdir(wd)
 
 	if err := os.Chdir(proj.Path() + "/"); err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
@@ -73,7 +74,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	 */
 	srcRepoName, srcName, err := newtutil.ParsePackageString(srcLoc)
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -84,7 +84,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 
 	srcPkg, err := proj.ResolvePackage(srcRepo, srcName)
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -94,7 +93,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	 */
 	repoName, pkgName, err := newtutil.ParsePackageString(dstLoc)
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -104,7 +102,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 		dstPath += "repos/" + repoName + "/"
 		repo = proj.FindRepo(repoName)
 		if repo == nil {
-			os.Chdir(wd)
 			NewtUsage(cmd, util.NewNewtError("Destination repo "+
 				repoName+" does not exist"))
 		}
@@ -112,7 +109,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	dstPath += pkgName + "/"
 
 	if util.NodeExist(dstPath) {
-		os.Chdir(wd)
 		NewtUsage(cmd, util.NewNewtError("Cannot overwrite existing package, "+
 			"use pkg delete first"))
 	}
@@ -121,14 +117,12 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 		srcLoc, dstLoc)
 
 	if err := util.MoveDir(srcPkg.BasePath(), dstPath); err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
 	/* Replace the package name in the pkg.yml file */
 	pkgData, err := ioutil.ReadFile(dstPath + "/pkg.yml")
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -146,8 +140,6 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 		util.MoveDir(dstPath+"/include/"+path.Base(srcPkg.Name()),
 			dstPath+"/include/"+path.Base(pkgName))
 	}
-
-	os.Chdir(wd)
 }
 
 func pkgRemoveCmd(cmd *cobra.Command, args []string) {
@@ -162,6 +154,7 @@ func pkgRemoveCmd(cmd *cobra.Command, args []string) {
 	if err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
+	defer os.Chdir(wd)
 
 	if err := os.Chdir(proj.Path() + "/"); err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))


[27/41] incubator-mynewt-newt git commit: MYNEWT-653 Use runtimeco gatt fork.

Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/linux/util/util.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/util/util.go b/newtmgr/vendor/github.com/runtimeinc/gatt/linux/util/util.go
deleted file mode 100644
index 4933008..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/linux/util/util.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package util
-
-import "encoding/binary"
-
-type order struct{ binary.ByteOrder }
-
-var Order = order{binary.LittleEndian}
-
-func (o order) Int8(b []byte) int8   { return int8(b[0]) }
-func (o order) Uint8(b []byte) uint8 { return b[0] }
-func (o order) MAC(b []byte) [6]byte { return [6]byte{b[5], b[4], b[3], b[2], b[1], b[0]} }
-
-func (o order) PutUint8(b []byte, v uint8) { b[0] = v }
-func (o order) PutMAC(b []byte, m [6]byte) {
-	b[0], b[1], b[2], b[3], b[4], b[5] = m[5], m[4], m[3], m[2], m[1], m[0]
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/option_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/option_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/option_darwin.go
deleted file mode 100644
index 617db21..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/option_darwin.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package gatt
-
-const (
-	CentralManager    = 0 // Client functions (default)
-	PeripheralManager = 1 // Server functions
-)
-
-// MacDeviceRole specify the XPC connection type to connect blued.
-// THis option can only be used with NewDevice on OS X implementation.
-func MacDeviceRole(r int) Option {
-	return func(d Device) error {
-		d.(*device).role = r
-		return nil
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/option_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/option_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/option_linux.go
deleted file mode 100644
index fe8065b..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/option_linux.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package gatt
-
-import (
-	"errors"
-	"io"
-
-	"github.com/runtimeinc/gatt/linux/cmd"
-)
-
-// LnxDeviceID specifies which HCI device to use.
-// If n is set to -1, all the available HCI devices will be probed.
-// If chk is set to true, LnxDeviceID checks the LE support in the feature list of the HCI device.
-// This is to filter devices that does not support LE. In case some LE driver that doesn't correctly
-// set the LE support in its feature list, user can turn off the check.
-// This option can only be used with NewDevice on Linux implementation.
-func LnxDeviceID(n int, chk bool) Option {
-	return func(d Device) error {
-		d.(*device).devID = n
-		d.(*device).chkLE = chk
-		return nil
-	}
-}
-
-// LnxMaxConnections is an optional parameter.
-// If set, it overrides the default max connections supported.
-// This option can only be used with NewDevice on Linux implementation.
-func LnxMaxConnections(n int) Option {
-	return func(d Device) error {
-		d.(*device).maxConn = n
-		return nil
-	}
-}
-
-// LnxSetAdvertisingEnable sets the advertising data to the HCI device.
-// This option can be used with Option on Linux implementation.
-func LnxSetAdvertisingEnable(en bool) Option {
-	return func(d Device) error {
-		dd := d.(*device)
-		if dd == nil {
-			return errors.New("device is not initialized")
-		}
-		if err := dd.update(); err != nil {
-			return err
-		}
-		return dd.hci.SetAdvertiseEnable(en)
-	}
-}
-
-// LnxSetAdvertisingData sets the advertising data to the HCI device.
-// This option can be used with NewDevice or Option on Linux implementation.
-func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option {
-	return func(d Device) error {
-		d.(*device).advData = c
-		return nil
-	}
-}
-
-// LnxSetScanResponseData sets the scan response data to the HXI device.
-// This option can be used with NewDevice or Option on Linux implementation.
-func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option {
-	return func(d Device) error {
-		d.(*device).scanResp = c
-		return nil
-	}
-}
-
-// LnxSetAdvertisingParameters sets the advertising parameters to the HCI device.
-// This option can be used with NewDevice or Option on Linux implementation.
-func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option {
-	return func(d Device) error {
-		d.(*device).advParam = c
-		return nil
-	}
-}
-
-// LnxSendHCIRawCommand sends a raw command to the HCI device
-// This option can be used with NewDevice or Option on Linux implementation.
-func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option {
-	return func(d Device) error {
-		b, err := d.(*device).SendHCIRawCommand(c)
-		if rsp == nil {
-			return err
-		}
-		rsp.Write(b)
-		return err
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral.go b/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral.go
deleted file mode 100644
index 36ad578..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package gatt
-
-import (
-	"errors"
-	"sync"
-)
-
-// Peripheral is the interface that represent a remote peripheral device.
-type Peripheral interface {
-	// Device returns the underlying device.
-	Device() Device
-
-	// ID is the platform specific unique ID of the remote peripheral, e.g. MAC for Linux, Peripheral UUID for MacOS.
-	ID() string
-
-	// Name returns the name of the remote peripheral.
-	// This can be the advertised name, if exists, or the GAP device name, which takes priority
-	Name() string
-
-	// Services returnns the services of the remote peripheral which has been discovered.
-	Services() []*Service
-
-	// DiscoverServices discover the specified services of the remote peripheral.
-	// If the specified services is set to nil, all the available services of the remote peripheral are returned.
-	DiscoverServices(s []UUID) ([]*Service, error)
-
-	// DiscoverIncludedServices discovers the specified included services of a service.
-	// If the specified services is set to nil, all the included services of the service are returned.
-	DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error)
-
-	// DiscoverCharacteristics discovers the specified characteristics of a service.
-	// If the specified characterstics is set to nil, all the characteristic of the service are returned.
-	DiscoverCharacteristics(c []UUID, s *Service) ([]*Characteristic, error)
-
-	// DiscoverDescriptors discovers the descriptors of a characteristic.
-	// If the specified descriptors is set to nil, all the descriptors of the characteristic are returned.
-	DiscoverDescriptors(d []UUID, c *Characteristic) ([]*Descriptor, error)
-
-	// ReadCharacteristic retrieves the value of a specified characteristic.
-	ReadCharacteristic(c *Characteristic) ([]byte, error)
-
-	// ReadLongCharacteristic retrieves the value of a specified characteristic that is longer than the
-	// MTU.
-	ReadLongCharacteristic(c *Characteristic) ([]byte, error)
-
-	// ReadDescriptor retrieves the value of a specified characteristic descriptor.
-	ReadDescriptor(d *Descriptor) ([]byte, error)
-
-	// WriteCharacteristic writes the value of a characteristic.
-	WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error
-
-	// WriteDescriptor writes the value of a characteristic descriptor.
-	WriteDescriptor(d *Descriptor, b []byte) error
-
-	// SetNotifyValue sets notifications for the value of a specified characteristic.
-	SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
-
-	// SetIndicateValue sets indications for the value of a specified characteristic.
-	SetIndicateValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
-
-	// ReadRSSI retrieves the current RSSI value for the remote peripheral.
-	ReadRSSI() int
-
-	// SetMTU sets the mtu for the remote peripheral.
-	SetMTU(mtu uint16) error
-}
-
-type subscriber struct {
-	sub map[uint16]subscribefn
-	mu  *sync.Mutex
-}
-
-type subscribefn func([]byte, error)
-
-func newSubscriber() *subscriber {
-	return &subscriber{
-		sub: make(map[uint16]subscribefn),
-		mu:  &sync.Mutex{},
-	}
-}
-
-func (s *subscriber) subscribe(h uint16, f subscribefn) {
-	s.mu.Lock()
-	s.sub[h] = f
-	s.mu.Unlock()
-}
-
-func (s *subscriber) unsubscribe(h uint16) {
-	s.mu.Lock()
-	delete(s.sub, h)
-	s.mu.Unlock()
-}
-
-func (s *subscriber) fn(h uint16) subscribefn {
-	s.mu.Lock()
-	defer s.mu.Unlock()
-	return s.sub[h]
-}
-
-var (
-	ErrInvalidLength = errors.New("invalid length")
-)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_darwin.go
deleted file mode 100644
index 69f9b36..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_darwin.go
+++ /dev/null
@@ -1,277 +0,0 @@
-package gatt
-
-import (
-	"errors"
-	"log"
-
-	"github.com/runtimeinc/gatt/xpc"
-)
-
-type peripheral struct {
-	// NameChanged is called whenever the peripheral GAP Device name has changed.
-	NameChanged func(Peripheral)
-
-	// ServicesModified is called when one or more service of a peripheral have changed.
-	// A list of invalid service is provided in the parameter.
-	ServicesModified func(Peripheral, []*Service)
-
-	d    *device
-	svcs []*Service
-
-	sub *subscriber
-
-	id   xpc.UUID
-	name string
-
-	reqc  chan message
-	rspc  chan message
-	quitc chan struct{}
-}
-
-func NewPeripheral(u UUID) Peripheral { return &peripheral{id: xpc.UUID(u.b)} }
-
-func (p *peripheral) Device() Device       { return p.d }
-func (p *peripheral) ID() string           { return p.id.String() }
-func (p *peripheral) Name() string         { return p.name }
-func (p *peripheral) Services() []*Service { return p.svcs }
-
-func (p *peripheral) DiscoverServices(ss []UUID) ([]*Service, error) {
-	rsp := p.sendReq(45, xpc.Dict{
-		"kCBMsgArgDeviceUUID": p.id,
-		"kCBMsgArgUUIDs":      uuidSlice(ss),
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return nil, attEcode(res)
-	}
-	svcs := []*Service{}
-	for _, xss := range rsp["kCBMsgArgServices"].(xpc.Array) {
-		xs := xss.(xpc.Dict)
-		u := MustParseUUID(xs.MustGetHexBytes("kCBMsgArgUUID"))
-		h := uint16(xs.MustGetInt("kCBMsgArgServiceStartHandle"))
-		endh := uint16(xs.MustGetInt("kCBMsgArgServiceEndHandle"))
-		svcs = append(svcs, &Service{uuid: u, h: h, endh: endh})
-	}
-	p.svcs = svcs
-	return svcs, nil
-}
-
-func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
-	rsp := p.sendReq(60, xpc.Dict{
-		"kCBMsgArgDeviceUUID":         p.id,
-		"kCBMsgArgServiceStartHandle": s.h,
-		"kCBMsgArgServiceEndHandle":   s.endh,
-		"kCBMsgArgUUIDs":              uuidSlice(ss),
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return nil, attEcode(res)
-	}
-	// TODO
-	return nil, notImplemented
-}
-
-func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
-	rsp := p.sendReq(62, xpc.Dict{
-		"kCBMsgArgDeviceUUID":         p.id,
-		"kCBMsgArgServiceStartHandle": s.h,
-		"kCBMsgArgServiceEndHandle":   s.endh,
-		"kCBMsgArgUUIDs":              uuidSlice(cs),
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return nil, attEcode(res)
-	}
-	for _, xcs := range rsp.MustGetArray("kCBMsgArgCharacteristics") {
-		xc := xcs.(xpc.Dict)
-		u := MustParseUUID(xc.MustGetHexBytes("kCBMsgArgUUID"))
-		ch := uint16(xc.MustGetInt("kCBMsgArgCharacteristicHandle"))
-		vh := uint16(xc.MustGetInt("kCBMsgArgCharacteristicValueHandle"))
-		props := Property(xc.MustGetInt("kCBMsgArgCharacteristicProperties"))
-		c := &Characteristic{uuid: u, svc: s, props: props, h: ch, vh: vh}
-		s.chars = append(s.chars, c)
-	}
-	return s.chars, nil
-}
-
-func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
-	rsp := p.sendReq(70, xpc.Dict{
-		"kCBMsgArgDeviceUUID":                p.id,
-		"kCBMsgArgCharacteristicHandle":      c.h,
-		"kCBMsgArgCharacteristicValueHandle": c.vh,
-		"kCBMsgArgUUIDs":                     uuidSlice(ds),
-	})
-	for _, xds := range rsp.MustGetArray("kCBMsgArgDescriptors") {
-		xd := xds.(xpc.Dict)
-		u := MustParseUUID(xd.MustGetHexBytes("kCBMsgArgUUID"))
-		h := uint16(xd.MustGetInt("kCBMsgArgDescriptorHandle"))
-		d := &Descriptor{uuid: u, char: c, h: h}
-		c.descs = append(c.descs, d)
-	}
-	return c.descs, nil
-}
-
-func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
-	rsp := p.sendReq(65, xpc.Dict{
-		"kCBMsgArgDeviceUUID":                p.id,
-		"kCBMsgArgCharacteristicHandle":      c.h,
-		"kCBMsgArgCharacteristicValueHandle": c.vh,
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return nil, attEcode(res)
-	}
-	b := rsp.MustGetBytes("kCBMsgArgData")
-	return b, nil
-}
-
-func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
-	return nil, errors.New("Not implemented")
-}
-
-func (p *peripheral) WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error {
-	args := xpc.Dict{
-		"kCBMsgArgDeviceUUID":                p.id,
-		"kCBMsgArgCharacteristicHandle":      c.h,
-		"kCBMsgArgCharacteristicValueHandle": c.vh,
-		"kCBMsgArgData":                      b,
-		"kCBMsgArgType":                      map[bool]int{false: 0, true: 1}[noRsp],
-	}
-	if noRsp {
-		p.sendCmd(66, args)
-		return nil
-	}
-	rsp := p.sendReq(65, args)
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return attEcode(res)
-	}
-	return nil
-}
-
-func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
-	rsp := p.sendReq(77, xpc.Dict{
-		"kCBMsgArgDeviceUUID":       p.id,
-		"kCBMsgArgDescriptorHandle": d.h,
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return nil, attEcode(res)
-	}
-	b := rsp.MustGetBytes("kCBMsgArgData")
-	return b, nil
-}
-
-func (p *peripheral) WriteDescriptor(d *Descriptor, b []byte) error {
-	rsp := p.sendReq(78, xpc.Dict{
-		"kCBMsgArgDeviceUUID":       p.id,
-		"kCBMsgArgDescriptorHandle": d.h,
-		"kCBMsgArgData":             b,
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return attEcode(res)
-	}
-	return nil
-}
-
-func (p *peripheral) SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error {
-	set := 1
-	if f == nil {
-		set = 0
-	}
-	// To avoid race condition, registeration is handled before requesting the server.
-	if f != nil {
-		// Note: when notified, core bluetooth reports characteristic handle, not value's handle.
-		p.sub.subscribe(c.h, func(b []byte, err error) { f(c, b, err) })
-	}
-	rsp := p.sendReq(68, xpc.Dict{
-		"kCBMsgArgDeviceUUID":                p.id,
-		"kCBMsgArgCharacteristicHandle":      c.h,
-		"kCBMsgArgCharacteristicValueHandle": c.vh,
-		"kCBMsgArgState":                     set,
-	})
-	if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
-		return attEcode(res)
-	}
-	// To avoid race condition, unregisteration is handled after server responses.
-	if f == nil {
-		p.sub.unsubscribe(c.h)
-	}
-	return nil
-}
-
-func (p *peripheral) SetIndicateValue(c *Characteristic,
-	f func(*Characteristic, []byte, error)) error {
-	// TODO: Implement set indications logic for darwin (https://github.com/runtimeinc/gatt/issues/32)
-	return nil
-}
-
-func (p *peripheral) ReadRSSI() int {
-	rsp := p.sendReq(43, xpc.Dict{"kCBMsgArgDeviceUUID": p.id})
-	return rsp.MustGetInt("kCBMsgArgData")
-}
-
-func (p *peripheral) SetMTU(mtu uint16) error {
-	return errors.New("Not implemented")
-}
-
-func uuidSlice(uu []UUID) [][]byte {
-	us := [][]byte{}
-	for _, u := range uu {
-		us = append(us, reverse(u.b))
-	}
-	return us
-}
-
-type message struct {
-	id   int
-	args xpc.Dict
-	rspc chan xpc.Dict
-}
-
-func (p *peripheral) sendCmd(id int, args xpc.Dict) {
-	p.reqc <- message{id: id, args: args}
-}
-
-func (p *peripheral) sendReq(id int, args xpc.Dict) xpc.Dict {
-	m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
-	p.reqc <- m
-	return <-m.rspc
-}
-
-func (p *peripheral) loop() {
-	rspc := make(chan message)
-
-	go func() {
-		for {
-			select {
-			case req := <-p.reqc:
-				p.d.sendCBMsg(req.id, req.args)
-				if req.rspc == nil {
-					break
-				}
-				m := <-rspc
-				req.rspc <- m.args
-			case <-p.quitc:
-				return
-			}
-		}
-	}()
-
-	for {
-		select {
-		case rsp := <-p.rspc:
-			// Notification
-			if rsp.id == 71 && rsp.args.GetInt("kCBMsgArgIsNotification", 0) != 0 {
-				// While we're notified with the value's handle, blued reports the characteristic handle.
-				ch := uint16(rsp.args.MustGetInt("kCBMsgArgCharacteristicHandle"))
-				b := rsp.args.MustGetBytes("kCBMsgArgData")
-				f := p.sub.fn(ch)
-				if f == nil {
-					log.Printf("notified by unsubscribed handle")
-					// FIXME: should terminate the connection?
-				} else {
-					go f(b, nil)
-				}
-				break
-			}
-			rspc <- rsp
-		case <-p.quitc:
-			return
-		}
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_linux.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_linux.go b/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_linux.go
deleted file mode 100644
index a8a819c..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/peripheral_linux.go
+++ /dev/null
@@ -1,448 +0,0 @@
-package gatt
-
-import (
-	"bytes"
-	"encoding/binary"
-	"fmt"
-	"io"
-	"log"
-	"net"
-	"strings"
-
-	"github.com/runtimeinc/gatt/linux"
-)
-
-type peripheral struct {
-	// NameChanged is called whenever the peripheral GAP device name has changed.
-	NameChanged func(*peripheral)
-
-	// ServicedModified is called when one or more service of a peripheral have changed.
-	// A list of invalid service is provided in the parameter.
-	ServicesModified func(*peripheral, []*Service)
-
-	d    *device
-	svcs []*Service
-
-	sub *subscriber
-
-	mtu uint16
-	l2c io.ReadWriteCloser
-
-	reqc  chan message
-	quitc chan struct{}
-
-	pd *linux.PlatData // platform specific data
-}
-
-func (p *peripheral) Device() Device       { return p.d }
-func (p *peripheral) ID() string           { return strings.ToUpper(net.HardwareAddr(p.pd.Address[:]).String()) }
-func (p *peripheral) Name() string         { return p.pd.Name }
-func (p *peripheral) Services() []*Service { return p.svcs }
-
-func finish(op byte, h uint16, b []byte) bool {
-	done := b[0] == attOpError && b[1] == op && b[2] == byte(h) && b[3] == byte(h>>8)
-	e := attEcode(b[4])
-	if e != attEcodeAttrNotFound {
-		// log.Printf("unexpected protocol error: %s", e)
-		// FIXME: terminate the connection
-	}
-	return done
-}
-
-func (p *peripheral) DiscoverServices(s []UUID) ([]*Service, error) {
-	// TODO: implement the UUID filters
-	// p.pd.Conn.Write([]byte{0x02, 0x87, 0x00}) // MTU
-	done := false
-	start := uint16(0x0001)
-	for !done {
-		op := byte(attOpReadByGroupReq)
-		b := make([]byte, 7)
-		b[0] = op
-		binary.LittleEndian.PutUint16(b[1:3], start)
-		binary.LittleEndian.PutUint16(b[3:5], 0xFFFF)
-		binary.LittleEndian.PutUint16(b[5:7], 0x2800)
-
-		b = p.sendReq(op, b)
-		if finish(op, start, b) {
-			break
-		}
-		b = b[1:]
-		l, b := int(b[0]), b[1:]
-		switch {
-		case l == 6 && (len(b)%6 == 0):
-		case l == 20 && (len(b)%20 == 0):
-		default:
-			return nil, ErrInvalidLength
-		}
-
-		for len(b) != 0 {
-			h := binary.LittleEndian.Uint16(b[:2])
-			endh := binary.LittleEndian.Uint16(b[2:4])
-			s := &Service{
-				uuid: UUID{b[4:l]},
-				h:    h,
-				endh: endh,
-			}
-			p.svcs = append(p.svcs, s)
-			b = b[l:]
-			done = endh == 0xFFFF
-			start = endh + 1
-		}
-	}
-	return p.svcs, nil
-}
-
-func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
-	// TODO
-	return nil, nil
-}
-
-func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
-	// TODO: implement the UUID filters
-	done := false
-	start := s.h
-	var prev *Characteristic
-	for !done {
-		op := byte(attOpReadByTypeReq)
-		b := make([]byte, 7)
-		b[0] = op
-		binary.LittleEndian.PutUint16(b[1:3], start)
-		binary.LittleEndian.PutUint16(b[3:5], s.endh)
-		binary.LittleEndian.PutUint16(b[5:7], 0x2803)
-
-		b = p.sendReq(op, b)
-		if finish(op, start, b) {
-			break
-		}
-		b = b[1:]
-
-		l, b := int(b[0]), b[1:]
-		switch {
-		case l == 7 && (len(b)%7 == 0):
-		case l == 21 && (len(b)%21 == 0):
-		default:
-			return nil, ErrInvalidLength
-		}
-
-		for len(b) != 0 {
-			h := binary.LittleEndian.Uint16(b[:2])
-			props := Property(b[2])
-			vh := binary.LittleEndian.Uint16(b[3:5])
-			u := UUID{b[5:l]}
-			s := searchService(p.svcs, h, vh)
-			if s == nil {
-				log.Printf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
-				return nil, fmt.Errorf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
-			}
-			c := &Characteristic{
-				uuid:  u,
-				svc:   s,
-				props: props,
-				h:     h,
-				vh:    vh,
-			}
-			s.chars = append(s.chars, c)
-			b = b[l:]
-			done = vh == s.endh
-			start = vh + 1
-			if prev != nil {
-				prev.endh = c.h - 1
-			}
-			prev = c
-		}
-	}
-	if len(s.chars) > 1 {
-		s.chars[len(s.chars)-1].endh = s.endh
-	}
-	return s.chars, nil
-}
-
-func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
-	// TODO: implement the UUID filters
-	done := false
-	start := c.vh + 1
-	for !done {
-		if c.endh == 0 {
-			c.endh = c.svc.endh
-		}
-		op := byte(attOpFindInfoReq)
-		b := make([]byte, 5)
-		b[0] = op
-		binary.LittleEndian.PutUint16(b[1:3], start)
-		binary.LittleEndian.PutUint16(b[3:5], c.endh)
-
-		b = p.sendReq(op, b)
-		if finish(attOpFindInfoReq, start, b) {
-			break
-		}
-		b = b[1:]
-
-		var l int
-		f, b := int(b[0]), b[1:]
-		switch {
-		case f == 1 && (len(b)%4 == 0):
-			l = 4
-		case f == 2 && (len(b)%18 == 0):
-			l = 18
-		default:
-			return nil, ErrInvalidLength
-		}
-
-		for len(b) != 0 {
-			h := binary.LittleEndian.Uint16(b[:2])
-			u := UUID{b[2:l]}
-			d := &Descriptor{uuid: u, h: h, char: c}
-			c.descs = append(c.descs, d)
-			if u.Equal(attrClientCharacteristicConfigUUID) {
-				c.cccd = d
-			}
-			b = b[l:]
-			done = h == c.endh
-			start = h + 1
-		}
-	}
-	return c.descs, nil
-}
-
-func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
-	b := make([]byte, 3)
-	op := byte(attOpReadReq)
-	b[0] = op
-	binary.LittleEndian.PutUint16(b[1:3], c.vh)
-
-	b = p.sendReq(op, b)
-	b = b[1:]
-	return b, nil
-}
-
-func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
-	// The spec says that a read blob request should fail if the characteristic
-	// is smaller than mtu - 1.  To simplify the API, the first read is done
-	// with a regular read request.  If the buffer received is equal to mtu -1,
-	// then we read the rest of the data using read blob.
-	firstRead, err := p.ReadCharacteristic(c)
-	if err != nil {
-		return nil, err
-	}
-	if len(firstRead) < int(p.mtu)-1 {
-		return firstRead, nil
-	}
-
-	var buf bytes.Buffer
-	buf.Write(firstRead)
-	off := uint16(len(firstRead))
-	for {
-		b := make([]byte, 5)
-		op := byte(attOpReadBlobReq)
-		b[0] = op
-		binary.LittleEndian.PutUint16(b[1:3], c.vh)
-		binary.LittleEndian.PutUint16(b[3:5], off)
-
-		b = p.sendReq(op, b)
-		b = b[1:]
-		if len(b) == 0 {
-			break
-		}
-		buf.Write(b)
-		off += uint16(len(b))
-		if len(b) < int(p.mtu)-1 {
-			break
-		}
-	}
-	return buf.Bytes(), nil
-}
-
-func (p *peripheral) WriteCharacteristic(c *Characteristic, value []byte, noRsp bool) error {
-	b := make([]byte, 3+len(value))
-	op := byte(attOpWriteReq)
-	b[0] = op
-	if noRsp {
-		b[0] = attOpWriteCmd
-	}
-	binary.LittleEndian.PutUint16(b[1:3], c.vh)
-	copy(b[3:], value)
-
-	if noRsp {
-		p.sendCmd(op, b)
-		return nil
-	}
-	b = p.sendReq(op, b)
-	// TODO: error handling
-	b = b[1:]
-	return nil
-}
-
-func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
-	b := make([]byte, 3)
-	op := byte(attOpReadReq)
-	b[0] = op
-	binary.LittleEndian.PutUint16(b[1:3], d.h)
-
-	b = p.sendReq(op, b)
-	b = b[1:]
-	// TODO: error handling
-	return b, nil
-}
-
-func (p *peripheral) WriteDescriptor(d *Descriptor, value []byte) error {
-	b := make([]byte, 3+len(value))
-	op := byte(attOpWriteReq)
-	b[0] = op
-	binary.LittleEndian.PutUint16(b[1:3], d.h)
-	copy(b[3:], value)
-
-	b = p.sendReq(op, b)
-	b = b[1:]
-	// TODO: error handling
-	return nil
-}
-
-func (p *peripheral) setNotifyValue(c *Characteristic, flag uint16,
-	f func(*Characteristic, []byte, error)) error {
-/*
-	if c.cccd == nil {
-		return errors.New("no cccd") // FIXME
-	}
-	ccc := uint16(0)
-	if f != nil {
-		ccc = flag
-*/
-		p.sub.subscribe(c.vh, func(b []byte, err error) { f(c, b, err) })
-/*
-	}
-	b := make([]byte, 5)
-	op := byte(attOpWriteReq)
-	b[0] = op
-	binary.LittleEndian.PutUint16(b[1:3], c.cccd.h)
-	binary.LittleEndian.PutUint16(b[3:5], ccc)
-
-	b = p.sendReq(op, b)
-	b = b[1:]
-	// TODO: error handling
-	if f == nil {
-		p.sub.unsubscribe(c.vh)
-	}
-*/
-	return nil
-}
-
-func (p *peripheral) SetNotifyValue(c *Characteristic,
-	f func(*Characteristic, []byte, error)) error {
-	return p.setNotifyValue(c, gattCCCNotifyFlag, f)
-}
-
-func (p *peripheral) SetIndicateValue(c *Characteristic,
-	f func(*Characteristic, []byte, error)) error {
-	return p.setNotifyValue(c, gattCCCIndicateFlag, f)
-}
-
-func (p *peripheral) ReadRSSI() int {
-	// TODO: implement
-	return -1
-}
-
-func searchService(ss []*Service, start, end uint16) *Service {
-	for _, s := range ss {
-		if s.h < start && s.endh >= end {
-			return s
-		}
-	}
-	return nil
-}
-
-// TODO: unifiy the message with OS X pots and refactor
-type message struct {
-	op   byte
-	b    []byte
-	rspc chan []byte
-}
-
-func (p *peripheral) sendCmd(op byte, b []byte) {
-	p.reqc <- message{op: op, b: b}
-}
-
-func (p *peripheral) sendReq(op byte, b []byte) []byte {
-	m := message{op: op, b: b, rspc: make(chan []byte)}
-	p.reqc <- m
-	return <-m.rspc
-}
-
-func (p *peripheral) loop() {
-	// Serialize the request.
-	rspc := make(chan []byte)
-
-	// Dequeue request loop
-	go func() {
-		for {
-			select {
-			case req := <-p.reqc:
-				p.l2c.Write(req.b)
-				if req.rspc == nil {
-					break
-				}
-				r := <-rspc
-				switch reqOp, rspOp := req.b[0], r[0]; {
-				case rspOp == attRspFor[reqOp]:
-				case rspOp == attOpError && r[1] == reqOp:
-				default:
-					log.Printf("Request 0x%02x got a mismatched response: 0x%02x", reqOp, rspOp)
-					// FIXME: terminate the connection?
-				}
-				req.rspc <- r
-			case <-p.quitc:
-				return
-			}
-		}
-	}()
-
-	// L2CAP implementations shall support a minimum MTU size of 48 bytes.
-	// The default value is 672 bytes
-	buf := make([]byte, 672)
-
-	// Handling response or notification/indication
-	for {
-		n, err := p.l2c.Read(buf)
-		if n == 0 || err != nil {
-			close(p.quitc)
-			return
-		}
-
-		b := make([]byte, n)
-		copy(b, buf)
-
-		if (b[0] != attOpHandleNotify) && (b[0] != attOpHandleInd) {
-			rspc <- b
-			continue
-		}
-
-		h := binary.LittleEndian.Uint16(b[1:3])
-		f := p.sub.fn(h)
-		if f == nil {
-			log.Printf("notified by unsubscribed handle")
-			// FIXME: terminate the connection?
-		} else {
-			go f(b[3:], nil)
-		}
-
-		if b[0] == attOpHandleInd {
-			// write aknowledgement for indication
-			p.l2c.Write([]byte{attOpHandleCnf})
-		}
-
-	}
-}
-
-func (p *peripheral) SetMTU(mtu uint16) error {
-	b := make([]byte, 3)
-	op := byte(attOpMtuReq)
-	b[0] = op
-	binary.LittleEndian.PutUint16(b[1:3], uint16(mtu))
-
-	b = p.sendReq(op, b)
-	serverMTU := binary.LittleEndian.Uint16(b[1:3])
-	if serverMTU < mtu {
-		mtu = serverMTU
-	}
-	p.mtu = mtu
-	return nil
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/readme.md
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/readme.md b/newtmgr/vendor/github.com/runtimeinc/gatt/readme.md
deleted file mode 100644
index ea3a957..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/readme.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Package gatt provides a Bluetooth Low Energy GATT implementation.
-
-Gatt (Generic Attribute Profile) is the protocol used to write BLE peripherals (servers) and centrals (clients).
-
-As a peripheral, you can create services, characteristics, and descriptors,
-advertise, accept connections, and handle requests.
-
-As a central, you can scan, connect, discover services, and make requests.
-
-## SETUP
-
-### gatt supports both Linux and OS X.
-
-### On Linux:
-To gain complete and exclusive control of the HCI device, gatt uses
-HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
-Those who must use an older kernel may patch in these relevant commits
-from Marcel Holtmann:
-
-    Bluetooth: Introduce new HCI socket channel for user operation
-    Bluetooth: Introduce user channel flag for HCI devices
-    Bluetooth: Refactor raw socket filter into more readable code
-
-Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
-device no other program may access it.
-
-Before starting a gatt program, make sure that your BLE device is down:
-
-    sudo hciconfig
-    sudo hciconfig hci0 down  # or whatever hci device you want to use
-
-If you have BlueZ 5.14+ (or aren't sure), stop the built-in
-bluetooth server, which interferes with gatt, e.g.:
-
-    sudo service bluetooth stop
-
-Because gatt programs administer network devices, they must
-either be run as root, or be granted appropriate capabilities:
-
-    sudo <executable>
-    # OR
-    sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
-    <executable>
-
-## Usage
-Please see [godoc.org](http://godoc.org/github.com/paypal/gatt) for documentation.
-
-## Examples
-
-### Build and run the examples on a native environment (Linux or OS X)
-
-Go is a compiled language, which means to run the examples you need to build them first.
-
-    # Build the sample server.
-    go build examples/server.go
-    # Start the sample server.
-    sudo ./server
-
-Alternatively, you can use "go run" to build and run the examples in a single step:
-
-    # Build and run the sample server.
-    sudo go run examples/server.go
-
-Discoverer and explorer demonstrates central (client) functions:
-
-    # Discover surrounding peripherals.
-    sudo go run examples/discoverer.go
-
-    # Connect to and explorer a peripheral device.
-    sudo go run examples/explorer.go <peripheral ID>
-
-### Cross-compile and deploy to a target device
-
-    # Build and run the server example on a ARMv5 target device.
-    GOARCH=arm GOARM=5 GOOS=linux go build examples/server.go
-    cp server <target device>
-    # Start the server on the target device
-    sudo ./server
-
-See the server.go, discoverer.go, and explorer.go in the examples/
-directory for writing server or client programs that run on Linux
-and OS X.
-
-Users, especially on Linux platforms, seeking finer-grained control
-over the devices can see the examples/server_lnx.go for the usage
-of Option, which are platform specific.
-
-See the rest of the docs for other options and finer-grained control.
-
-## Note
-Note that some BLE central devices, particularly iOS, may aggressively
-cache results from previous connections. If you change your services or
-characteristics, you may need to reboot the other device to pick up the
-changes. This is a common source of confusion and apparent bugs. For an
-OS X central, see http://stackoverflow.com/questions/20553957.
-
-## Known Issues
-
-Currently OS X vesion  does not support subscribing to indications. 
-Please check [#32](https://github.com/paypal/gatt/issues/32) for the status of this issue.
-
-## REFERENCES
-
-gatt started life as a port of bleno, to which it is indebted:
-https://github.com/sandeepmistry/bleno. If you are having
-problems with gatt, particularly around installation, issues
-filed with bleno might also be helpful references.
-
-To try out your GATT server, it is useful to experiment with a
-generic BLE client. LightBlue is a good choice. It is available
-free for both iOS and OS X.
-
-gatt is similar to [bleno](https://github.com/sandeepmistry/bleno) and [noble](https://github.com/sandeepmistry/noble), which offer BLE GATT implementations for node.js.
-
-Gatt is released under a [BSD-style license](./LICENSE.md).

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/uuid.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/uuid.go b/newtmgr/vendor/github.com/runtimeinc/gatt/uuid.go
deleted file mode 100644
index 393e548..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/uuid.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package gatt
-
-import (
-	"bytes"
-	"encoding/binary"
-	"encoding/hex"
-	"fmt"
-	"strings"
-)
-
-// A UUID is a BLE UUID.
-type UUID struct {
-	// Hide the bytes, so that we can enforce that they have length 2 or 16,
-	// and that they are immutable. This simplifies the code and API.
-	b []byte
-}
-
-// UUID16 converts a uint16 (such as 0x1800) to a UUID.
-func UUID16(i uint16) UUID {
-	b := make([]byte, 2)
-	binary.LittleEndian.PutUint16(b, i)
-	return UUID{b}
-}
-
-// ParseUUID parses a standard-format UUID string, such
-// as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".
-func ParseUUID(s string) (UUID, error) {
-	s = strings.Replace(s, "-", "", -1)
-	b, err := hex.DecodeString(s)
-	if err != nil {
-		return UUID{}, err
-	}
-	if err := lenErr(len(b)); err != nil {
-		return UUID{}, err
-	}
-	return UUID{reverse(b)}, nil
-}
-
-// MustParseUUID parses a standard-format UUID string,
-// like ParseUUID, but panics in case of error.
-func MustParseUUID(s string) UUID {
-	u, err := ParseUUID(s)
-	if err != nil {
-		panic(err)
-	}
-	return u
-}
-
-// lenErr returns an error if n is an invalid UUID length.
-func lenErr(n int) error {
-	switch n {
-	case 2, 16:
-		return nil
-	}
-	return fmt.Errorf("UUIDs must have length 2 or 16, got %d", n)
-}
-
-// Len returns the length of the UUID, in bytes.
-// BLE UUIDs are either 2 or 16 bytes.
-func (u UUID) Len() int {
-	return len(u.b)
-}
-
-// String hex-encodes a UUID.
-func (u UUID) String() string {
-	return fmt.Sprintf("%x", reverse(u.b))
-}
-
-// Equal returns a boolean reporting whether v represent the same UUID as u.
-func (u UUID) Equal(v UUID) bool {
-	return bytes.Equal(u.b, v.b)
-}
-
-// reverse returns a reversed copy of u.
-func reverse(u []byte) []byte {
-	// Special-case 16 bit UUIDS for speed.
-	l := len(u)
-	if l == 2 {
-		return []byte{u[1], u[0]}
-	}
-	b := make([]byte, l)
-	for i := 0; i < l/2+1; i++ {
-		b[i], b[l-i-1] = u[l-i-1], u[i]
-	}
-	return b
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/LICENSE
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/LICENSE b/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/LICENSE
deleted file mode 100644
index 766a0a5..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) {{{year}}} {{{fullname}}}
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/doc.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/doc.go b/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/doc.go
deleted file mode 100644
index d292249..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/doc.go
+++ /dev/null
@@ -1,8 +0,0 @@
-// Package xpc provides minimal OS X XPC support required for gatt
-//
-// This is adapted from [goble], by Raffaele Sena.
-//
-//     http://godoc.org/github.com/raff/goble
-//     https://github.com/raff/goble
-
-package xpc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_darwin.go
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_darwin.go b/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_darwin.go
deleted file mode 100644
index 2a85a99..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_darwin.go
+++ /dev/null
@@ -1,350 +0,0 @@
-package xpc
-
-/*
-#include "xpc_wrapper_darwin.h"
-#include "sys/utsname.h"
-*/
-import "C"
-
-import (
-	"errors"
-	"fmt"
-	"log"
-	r "reflect"
-	"unsafe"
-)
-
-type XPC struct {
-	conn C.xpc_connection_t
-}
-
-func (x *XPC) Send(msg interface{}, verbose bool) {
-	// verbose == true converts the type from bool to C._Bool
-	C.XpcSendMessage(x.conn, goToXpc(msg), true, verbose == true)
-}
-
-//
-// minimal XPC support required for BLE
-//
-
-// a dictionary of things
-type Dict map[string]interface{}
-
-func (d Dict) Contains(k string) bool {
-	_, ok := d[k]
-	return ok
-}
-
-func (d Dict) MustGetDict(k string) Dict {
-	return d[k].(Dict)
-}
-
-func (d Dict) MustGetArray(k string) Array {
-	return d[k].(Array)
-}
-
-func (d Dict) MustGetBytes(k string) []byte {
-	return d[k].([]byte)
-}
-
-func (d Dict) MustGetHexBytes(k string) string {
-	return fmt.Sprintf("%x", d[k].([]byte))
-}
-
-func (d Dict) MustGetInt(k string) int {
-	return int(d[k].(int64))
-}
-
-func (d Dict) MustGetUUID(k string) []byte {
-	u := d[k].(UUID)
-	return u[:]
-}
-
-func (d Dict) GetString(k, defv string) string {
-	if v := d[k]; v != nil {
-		//log.Printf("GetString %s %#v\n", k, v)
-		return v.(string)
-	} else {
-		//log.Printf("GetString %s default %#v\n", k, defv)
-		return defv
-	}
-}
-
-func (d Dict) GetBytes(k string, defv []byte) []byte {
-	if v := d[k]; v != nil {
-		//log.Printf("GetBytes %s %#v\n", k, v)
-		return v.([]byte)
-	} else {
-		//log.Printf("GetBytes %s default %#v\n", k, defv)
-		return defv
-	}
-}
-
-func (d Dict) GetInt(k string, defv int) int {
-	if v := d[k]; v != nil {
-		//log.Printf("GetString %s %#v\n", k, v)
-		return int(v.(int64))
-	} else {
-		//log.Printf("GetString %s default %#v\n", k, defv)
-		return defv
-	}
-}
-
-func (d Dict) GetUUID(k string) UUID {
-	return GetUUID(d[k])
-}
-
-// an array of things
-type Array []interface{}
-
-func (a Array) GetUUID(k int) UUID {
-	return GetUUID(a[k])
-}
-
-// a UUID
-type UUID []byte
-
-func MakeUUID(s string) UUID {
-	var sl []byte
-	fmt.Sscanf(s, "%32x", &sl)
-
-	var uuid [16]byte
-	copy(uuid[:], sl)
-	return UUID(uuid[:])
-}
-
-func (uuid UUID) String() string {
-	return fmt.Sprintf("%x", []byte(uuid))
-}
-
-func GetUUID(v interface{}) UUID {
-	if v == nil {
-		return UUID{}
-	}
-
-	if uuid, ok := v.(UUID); ok {
-		return uuid
-	}
-
-	if bytes, ok := v.([]byte); ok {
-		uuid := UUID{}
-
-		for i, b := range bytes {
-			uuid[i] = b
-		}
-
-		return uuid
-	}
-
-	if bytes, ok := v.([]uint8); ok {
-		uuid := UUID{}
-
-		for i, b := range bytes {
-			uuid[i] = b
-		}
-
-		return uuid
-	}
-
-	log.Fatalf("invalid type for UUID: %#v", v)
-	return UUID{}
-}
-
-var (
-	CONNECTION_INVALID     = errors.New("connection invalid")
-	CONNECTION_INTERRUPTED = errors.New("connection interrupted")
-	CONNECTION_TERMINATED  = errors.New("connection terminated")
-
-	TYPE_OF_UUID  = r.TypeOf(UUID{})
-	TYPE_OF_BYTES = r.TypeOf([]byte{})
-)
-
-type XpcEventHandler interface {
-	HandleXpcEvent(event Dict, err error)
-}
-
-func XpcConnect(service string, eh XpcEventHandler) XPC {
-	cservice := C.CString(service)
-	defer C.free(unsafe.Pointer(cservice))
-	return XPC{conn: C.XpcConnect(cservice, unsafe.Pointer(&eh))}
-}
-
-//export handleXpcEvent
-func handleXpcEvent(event C.xpc_object_t, p unsafe.Pointer) {
-	//log.Printf("handleXpcEvent %#v %#v\n", event, p)
-
-	t := C.xpc_get_type(event)
-	eh := *((*XpcEventHandler)(p))
-
-	if t == C.TYPE_ERROR {
-		if event == C.ERROR_CONNECTION_INVALID {
-			// The client process on the other end of the connection has either
-			// crashed or cancelled the connection. After receiving this error,
-			// the connection is in an invalid state, and you do not need to
-			// call xpc_connection_cancel(). Just tear down any associated state
-			// here.
-			//log.Println("connection invalid")
-			eh.HandleXpcEvent(nil, CONNECTION_INVALID)
-		} else if event == C.ERROR_CONNECTION_INTERRUPTED {
-			//log.Println("connection interrupted")
-			eh.HandleXpcEvent(nil, CONNECTION_INTERRUPTED)
-		} else if event == C.ERROR_CONNECTION_TERMINATED {
-			// Handle per-connection termination cleanup.
-			//log.Println("connection terminated")
-			eh.HandleXpcEvent(nil, CONNECTION_TERMINATED)
-		} else {
-			//log.Println("got some error", event)
-			eh.HandleXpcEvent(nil, fmt.Errorf("%v", event))
-		}
-	} else {
-		eh.HandleXpcEvent(xpcToGo(event).(Dict), nil)
-	}
-}
-
-// goToXpc converts a go object to an xpc object
-func goToXpc(o interface{}) C.xpc_object_t {
-	return valueToXpc(r.ValueOf(o))
-}
-
-// valueToXpc converts a go Value to an xpc object
-//
-// note that not all the types are supported, but only the subset required for Blued
-func valueToXpc(val r.Value) C.xpc_object_t {
-	if !val.IsValid() {
-		return nil
-	}
-
-	var xv C.xpc_object_t
-
-	switch val.Kind() {
-	case r.Int, r.Int8, r.Int16, r.Int32, r.Int64:
-		xv = C.xpc_int64_create(C.int64_t(val.Int()))
-
-	case r.Uint, r.Uint8, r.Uint16, r.Uint32:
-		xv = C.xpc_int64_create(C.int64_t(val.Uint()))
-
-	case r.String:
-		xv = C.xpc_string_create(C.CString(val.String()))
-
-	case r.Map:
-		xv = C.xpc_dictionary_create(nil, nil, 0)
-		for _, k := range val.MapKeys() {
-			v := valueToXpc(val.MapIndex(k))
-			C.xpc_dictionary_set_value(xv, C.CString(k.String()), v)
-			if v != nil {
-				C.xpc_release(v)
-			}
-		}
-
-	case r.Array, r.Slice:
-		if val.Type() == TYPE_OF_UUID {
-			// array of bytes
-			var uuid [16]byte
-			r.Copy(r.ValueOf(uuid[:]), val)
-			xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0])))
-		} else if val.Type() == TYPE_OF_BYTES {
-			// slice of bytes
-			xv = C.xpc_data_create(unsafe.Pointer(val.Pointer()), C.size_t(val.Len()))
-		} else {
-			xv = C.xpc_array_create(nil, 0)
-			l := val.Len()
-
-			for i := 0; i < l; i++ {
-				v := valueToXpc(val.Index(i))
-				C.xpc_array_append_value(xv, v)
-				if v != nil {
-					C.xpc_release(v)
-				}
-			}
-		}
-
-	case r.Interface, r.Ptr:
-		xv = valueToXpc(val.Elem())
-
-	default:
-		log.Fatalf("unsupported %#v", val.String())
-	}
-
-	return xv
-}
-
-//export arraySet
-func arraySet(u unsafe.Pointer, i C.int, v C.xpc_object_t) {
-	a := *(*Array)(u)
-	a[i] = xpcToGo(v)
-}
-
-//export dictSet
-func dictSet(u unsafe.Pointer, k *C.char, v C.xpc_object_t) {
-	d := *(*Dict)(u)
-	d[C.GoString(k)] = xpcToGo(v)
-}
-
-// xpcToGo converts an xpc object to a go object
-//
-// note that not all the types are supported, but only the subset required for Blued
-func xpcToGo(v C.xpc_object_t) interface{} {
-	t := C.xpc_get_type(v)
-
-	switch t {
-	case C.TYPE_ARRAY:
-		a := make(Array, C.int(C.xpc_array_get_count(v)))
-		C.XpcArrayApply(unsafe.Pointer(&a), v)
-		return a
-
-	case C.TYPE_DATA:
-		return C.GoBytes(C.xpc_data_get_bytes_ptr(v), C.int(C.xpc_data_get_length(v)))
-
-	case C.TYPE_DICT:
-		d := make(Dict)
-		C.XpcDictApply(unsafe.Pointer(&d), v)
-		return d
-
-	case C.TYPE_INT64:
-		return int64(C.xpc_int64_get_value(v))
-
-	case C.TYPE_STRING:
-		return C.GoString(C.xpc_string_get_string_ptr(v))
-
-	case C.TYPE_UUID:
-		a := [16]byte{}
-		C.XpcUUIDGetBytes(unsafe.Pointer(&a), v)
-		return UUID(a[:])
-
-	default:
-		log.Fatalf("unexpected type %#v, value %#v", t, v)
-	}
-
-	return nil
-}
-
-// xpc_release is needed by tests, since they can't use CGO
-func xpc_release(xv C.xpc_object_t) {
-	C.xpc_release(xv)
-}
-
-// this is used to check the OS version
-
-type Utsname struct {
-	Sysname  string
-	Nodename string
-	Release  string
-	Version  string
-	Machine  string
-}
-
-func Uname(utsname *Utsname) error {
-	var cstruct C.struct_utsname
-	if err := C.uname(&cstruct); err != 0 {
-		return errors.New("utsname error")
-	}
-
-	// XXX: this may crash if any value is exactly 256 characters (no 0 terminator)
-	utsname.Sysname = C.GoString(&cstruct.sysname[0])
-	utsname.Nodename = C.GoString(&cstruct.nodename[0])
-	utsname.Release = C.GoString(&cstruct.release[0])
-	utsname.Version = C.GoString(&cstruct.version[0])
-	utsname.Machine = C.GoString(&cstruct.machine[0])
-
-	return nil
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.c
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.c b/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.c
deleted file mode 100644
index 7bcb83d..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.c
+++ /dev/null
@@ -1,85 +0,0 @@
-#include <dispatch/dispatch.h>
-#include <xpc/xpc.h>
-#include <xpc/connection.h>
-#include <Block.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-#include "_cgo_export.h"
-
-//
-// types and errors are implemented as macros
-// create some real objects to make them accessible to Go
-//
-xpc_type_t TYPE_ERROR = XPC_TYPE_ERROR;
-
-xpc_type_t TYPE_ARRAY = XPC_TYPE_ARRAY;
-xpc_type_t TYPE_DATA = XPC_TYPE_DATA;
-xpc_type_t TYPE_DICT = XPC_TYPE_DICTIONARY;
-xpc_type_t TYPE_INT64 = XPC_TYPE_INT64;
-xpc_type_t TYPE_STRING = XPC_TYPE_STRING;
-xpc_type_t TYPE_UUID = XPC_TYPE_UUID;
-
-xpc_object_t ERROR_CONNECTION_INVALID = (xpc_object_t) XPC_ERROR_CONNECTION_INVALID;
-xpc_object_t ERROR_CONNECTION_INTERRUPTED = (xpc_object_t) XPC_ERROR_CONNECTION_INTERRUPTED;
-xpc_object_t ERROR_CONNECTION_TERMINATED = (xpc_object_t) XPC_ERROR_TERMINATION_IMMINENT;
-
-const ptr_to_uuid_t ptr_to_uuid(void *p) { return (ptr_to_uuid_t)p; }
-
-
-//
-// connect to XPC service
-//
-xpc_connection_t XpcConnect(char *service, void *ctx) {
-    dispatch_queue_t queue = dispatch_queue_create(service, 0);
-    xpc_connection_t conn = xpc_connection_create_mach_service(service, queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
-
-    // making a local copy, that should be made "persistent" with the following Block_copy
-    GoInterface ictx = *((GoInterface*)ctx);
-
-    xpc_connection_set_event_handler(conn,
-        Block_copy(^(xpc_object_t event) {
-            handleXpcEvent(event, (void *)&ictx);
-        })
-    );
-
-    xpc_connection_resume(conn);
-    return conn;
-}
-
-void XpcSendMessage(xpc_connection_t conn, xpc_object_t message, bool release, bool reportDelivery) {
-    xpc_connection_send_message(conn,  message);
-    xpc_connection_send_barrier(conn, ^{
-        // Block is invoked on connection's target queue
-        // when 'message' has been sent.
-        if (reportDelivery) { // maybe this could be a callback
-            puts("message delivered");
-        }
-    });
-    if (release) {
-        xpc_release(message);
-    }
-}
-
-void XpcArrayApply(void *v, xpc_object_t arr) {
-  xpc_array_apply(arr, ^bool(size_t index, xpc_object_t value) {
-    arraySet(v, index, value);
-    return true;
-  });
-}
-
-void XpcDictApply(void *v, xpc_object_t dict) {
-  xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
-    dictSet(v, (char *)key, value);
-    return true;
-  });
-}
-
-void XpcUUIDGetBytes(void *v, xpc_object_t uuid) {
-   const uint8_t *src = xpc_uuid_get_bytes(uuid);
-   uint8_t *dest = (uint8_t *)v;
-
-   for (int i=0; i < sizeof(uuid_t); i++) {
-     dest[i] = src[i];
-   }
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a1553084/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.h
----------------------------------------------------------------------
diff --git a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.h b/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.h
deleted file mode 100644
index e2cfb5c..0000000
--- a/newtmgr/vendor/github.com/runtimeinc/gatt/xpc/xpc_wrapper_darwin.h
+++ /dev/null
@@ -1,32 +0,0 @@
-#ifndef _XPC_WRAPPER_H_
-#define _XPC_WRAPPER_H_
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <xpc/xpc.h>
-
-extern xpc_type_t TYPE_ERROR;
-
-extern xpc_type_t TYPE_ARRAY;
-extern xpc_type_t TYPE_DATA;
-extern xpc_type_t TYPE_DICT;
-extern xpc_type_t TYPE_INT64;
-extern xpc_type_t TYPE_STRING;
-extern xpc_type_t TYPE_UUID;
-
-extern xpc_object_t ERROR_CONNECTION_INVALID;
-extern xpc_object_t ERROR_CONNECTION_INTERRUPTED;
-extern xpc_object_t ERROR_CONNECTION_TERMINATED;
-
-extern xpc_connection_t XpcConnect(char *, void *);
-extern void XpcSendMessage(xpc_connection_t, xpc_object_t, bool, bool);
-extern void XpcArrayApply(void *, xpc_object_t);
-extern void XpcDictApply(void *, xpc_object_t);
-extern void XpcUUIDGetBytes(void *, xpc_object_t);
-
-// the input type for xpc_uuid_create should be uuid_t but CGO instists on unsigned char *
-// typedef uuid_t * ptr_to_uuid_t;
-typedef unsigned char * ptr_to_uuid_t;
-extern const ptr_to_uuid_t ptr_to_uuid(void *p);
-
-#endif


[33/41] incubator-mynewt-newt git commit: Add back "newt complete" and remove from help text. 1) Added "newt complete" support back. 2) Make the command hidden so it is not in the list of "Available Commands" in newt help. 3) Removed "newt complete" help

Posted by ma...@apache.org.
Add back "newt complete" and remove from help text.
1) Added "newt complete" support back.
2) Make the command hidden so it is not in the list of "Available Commands" in newt help.
3) Removed "newt complete" help text.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/31e23b2c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/31e23b2c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/31e23b2c

Branch: refs/heads/mynewt_1_0_0
Commit: 31e23b2cf1029aafa0060f36ee9f3d6167fd87ce
Parents: a155308
Author: cwanda <wa...@happycity.com>
Authored: Thu Mar 2 20:25:57 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:38:18 2017 -0800

----------------------------------------------------------------------
 newt/cli/complete_cmd.go | 14 +++++---------
 newt/newt.go             |  1 +
 2 files changed, 6 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/31e23b2c/newt/cli/complete_cmd.go
----------------------------------------------------------------------
diff --git a/newt/cli/complete_cmd.go b/newt/cli/complete_cmd.go
index 272f928..ae3d39e 100644
--- a/newt/cli/complete_cmd.go
+++ b/newt/cli/complete_cmd.go
@@ -237,17 +237,13 @@ func completeRunCmd(cmd *cobra.Command, args []string) {
 }
 
 func AddCompleteCommands(cmd *cobra.Command) {
-	completeShortHelp := "Performs Bash Autocompletion (-C)"
-
-	completeLongHelp := completeShortHelp + ".\n\n" +
-		" this command reads environment variables COMP_LINE and COMP_POINT " +
-		" and will send completion options out stdout as one option per line  "
 
 	completeCmd := &cobra.Command{
-		Use:   "complete",
-		Short: completeShortHelp,
-		Long:  completeLongHelp,
-		Run:   completeRunCmd,
+		Use:    "complete",
+		Short:  "",
+		Long:   "",
+		Run:    completeRunCmd,
+		Hidden: true,
 	}
 
 	/* silence errors on the complete command because we have partial flags */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/31e23b2c/newt/newt.go
----------------------------------------------------------------------
diff --git a/newt/newt.go b/newt/newt.go
index a09e57c..0dc8808 100644
--- a/newt/newt.go
+++ b/newt/newt.go
@@ -140,6 +140,7 @@ func main() {
 	cmd := newtCmd()
 
 	cli.AddBuildCommands(cmd)
+	cli.AddCompleteCommands(cmd)
 	cli.AddImageCommands(cmd)
 	cli.AddPackageCommands(cmd)
 	cli.AddProjectCommands(cmd)


[40/41] incubator-mynewt-newt git commit: 1) Updated newtmgr crash Usage text: crash test argument required. 2) Updated datetime.go - Moved datetime format examples from error message to Help Text examples. 3) Minor formatting for image.go help text 4

Posted by ma...@apache.org.
1) Updated newtmgr crash Usage text: crash test argument required.
2) Updated datetime.go - Moved datetime format examples from error message
   to Help Text examples.
3) Minor formatting for image.go help text
4) Update newtmgr stat command help text:
    a) added stat_name argument in newtmgr stat usage text
    b) updated list subcommand help text to say list of "Stat names" instead
       "statistics".
5) Added more help text  to newtmgr conn show command.
6) Updated help text for newtmgr log command.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/db270181
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/db270181
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/db270181

Branch: refs/heads/mynewt_1_0_0
Commit: db270181256ad97798028fcde1444a6763f3a406
Parents: 4204776
Author: cwanda <wa...@happycity.com>
Authored: Sun Mar 5 04:58:23 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:39:39 2017 -0800

----------------------------------------------------------------------
 newtmgr/cli/connprofile.go |  9 +++++++--
 newtmgr/cli/crash.go       |  4 ++--
 newtmgr/cli/datetime.go    | 34 +++++++++++++++++++++++-----------
 newtmgr/cli/image.go       |  6 +++---
 newtmgr/cli/logs.go        |  2 +-
 newtmgr/cli/runtest.go     | 13 +++++++++----
 newtmgr/cli/stats.go       |  6 ++++--
 7 files changed, 49 insertions(+), 25 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/connprofile.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/connprofile.go b/newtmgr/cli/connprofile.go
index 06d70e0..547d185 100644
--- a/newtmgr/cli/connprofile.go
+++ b/newtmgr/cli/connprofile.go
@@ -190,7 +190,7 @@ func connProfileCmd() *cobra.Command {
 	}
 
 	addCmd := &cobra.Command{
-		Use:   "add <conn_profile> [varname=value ...] ",
+		Use:   "add <conn_profile> <varname=value ...> ",
 		Short: "Add a newtmgr connection profile",
 		Run:   connProfileAddCmd,
 	}
@@ -203,9 +203,14 @@ func connProfileCmd() *cobra.Command {
 	}
 	cpCmd.AddCommand(deleCmd)
 
+	connShowHelpText := "Show information for the conn_profile connection "
+	connShowHelpText += "profile or for all\nconnection profiles "
+	connShowHelpText += "if conn_profile is not specified.\n"
+
 	showCmd := &cobra.Command{
-		Use:   "show",
+		Use:   "show [conn_profile]",
 		Short: "Show newtmgr connection profiles",
+		Long:  connShowHelpText,
 		Run:   connProfileShowCmd,
 	}
 	cpCmd.AddCommand(showCmd)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/crash.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/crash.go b/newtmgr/cli/crash.go
index 941b6de..553572b 100644
--- a/newtmgr/cli/crash.go
+++ b/newtmgr/cli/crash.go
@@ -87,8 +87,8 @@ func crashCmd() *cobra.Command {
 	crashEx := "   newtmgr -c olimex crash div0\n"
 
 	crashCmd := &cobra.Command{
-		Use:     "crash [div0|jump0|ref0|assert|wdog] -c <conn_profile>",
-		Short:   "Send crash command to a device",
+		Use:     "crash <div0|jump0|ref0|assert|wdog> -c <conn_profile>",
+		Short:   "Send a crash command to a device",
 		Example: crashEx,
 		Run:     crashRunCmd,
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/datetime.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/datetime.go b/newtmgr/cli/datetime.go
index 34fd471..c71cb1b 100644
--- a/newtmgr/cli/datetime.go
+++ b/newtmgr/cli/datetime.go
@@ -61,14 +61,7 @@ func dateTimeCmd(cmd *cobra.Command, args []string) {
 		nmUsage(cmd, err)
 	}
 
-	err_str := "Command: datetime\n" +
-		"For writing datetime <argument>\n" +
-		"Need to specify a datetime in RFC 3339 format\n" +
-		"2016-03-02T22:44:00                  UTC time (implicit)\n" +
-		"2016-03-02T22:44:00Z                 UTC time (explicit)\n" +
-		"2016-03-02T22:44:00-08:00            PST timezone\n" +
-		"2016-03-02T22:44:00.1                fractional seconds\n" +
-		"2016-03-02T22:44:00.101+05:30        fractional seconds with timezone\n"
+	err_str := "Need to specify a datetime in RFC 3339 format\n"
 
 	if len(args) > 1 {
 		nmUsage(cmd, util.NewNewtError(err_str))
@@ -85,10 +78,29 @@ func dateTimeCmd(cmd *cobra.Command, args []string) {
 }
 
 func dTimeCmd() *cobra.Command {
+	dateTimeHelpText := "Display or set datetime on a device. "
+	dateTimeHelpText += "Specify a datetime-value\n"
+	dateTimeHelpText += "to set the datetime on the device.\n\n"
+	dateTimeHelpText += "Must specify datetime-value in RFC 3339 format.\n"
+
+	dateTimeEx := "newtmgr datetime -c myserial\n"
+	dateTimeEx += "newtmgr datetime 2016-03-02T22:44:00 -c myserial"
+	dateTimeEx += "             (implicit UTC) \n"
+	dateTimeEx += "newtmgr datetime 2016-03-02T22:44:00Z -c myserial"
+	dateTimeEx += "            (explicit UTC)\n"
+	dateTimeEx += "newtmgr datetime 2016-03-02T22:44:00-08:00 -c myserial"
+	dateTimeEx += "       (PST)\n"
+	dateTimeEx += "newtmgr datetime 2016-03-02T22:44:00.1 -c myserial"
+	dateTimeEx += "           (fractional secs)\n"
+	dateTimeEx += "newtmgr datetime 2016-03-02T22:44:00.101+05:30 -c myserial"
+	dateTimeEx += "   (fractional secs + timezone)\n"
+
 	dateTCmd := &cobra.Command{
-		Use:   "datetime -c <conn_profile>",
-		Short: "Manage datetime on a device",
-		Run:   dateTimeCmd,
+		Use:     "datetime [datetime-value] -c <conn_profile>",
+		Short:   "Manage datetime on a device",
+		Long:    dateTimeHelpText,
+		Example: dateTimeEx,
+		Run:     dateTimeCmd,
 	}
 
 	return dateTCmd

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/image.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/image.go b/newtmgr/cli/image.go
index 7457df8..b32ce60 100644
--- a/newtmgr/cli/image.go
+++ b/newtmgr/cli/image.go
@@ -578,19 +578,19 @@ func imageCmd() *cobra.Command {
 	coreEx += "  newtmgr -c olimex image coredownload --offset 10 -n 10 core\n"
 
 	coreDownloadCmd := &cobra.Command{
-		Use:     "coredownload <core_filename> -c <conn_profile>",
+		Use:     "coredownload <core-filename> -c <conn_profile>",
 		Short:   "Download core from a device",
 		Example: coreEx,
 		Run:     coreDownloadCmd,
 	}
-	coreDownloadCmd.Flags().BoolVarP(&coreElfify, "elfify", "e", false, "Creat an elf file")
+	coreDownloadCmd.Flags().BoolVarP(&coreElfify, "elfify", "e", false, "Create an ELF file")
 	coreDownloadCmd.Flags().Uint32Var(&coreOffset, "offset", 0, "Start offset")
 	coreDownloadCmd.Flags().Uint32VarP(&coreNumBytes, "bytes", "n", 0, "Number of bytes of the core to download")
 	imageCmd.AddCommand(coreDownloadCmd)
 
 	coreConvertCmd := &cobra.Command{
 		Use:   "coreconvert <core-filename> <elf-filename>",
-		Short: "Convert core to elf",
+		Short: "Convert core to ELF",
 		Run:   coreConvertCmd,
 	}
 	imageCmd.AddCommand(coreConvertCmd)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/logs.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/logs.go b/newtmgr/cli/logs.go
index 775402a..d36e076 100644
--- a/newtmgr/cli/logs.go
+++ b/newtmgr/cli/logs.go
@@ -327,7 +327,7 @@ func logsClearCmd(cmd *cobra.Command, args []string) {
 func logsCmd() *cobra.Command {
 	logsCmd := &cobra.Command{
 		Use:   "log",
-		Short: "Handle logs on a device",
+		Short: "Manage logs on a device",
 		Run: func(cmd *cobra.Command, args []string) {
 			cmd.HelpFunc()(cmd, args)
 		},

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/runtest.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/runtest.go b/newtmgr/cli/runtest.go
index 60070ee..f9d70a8 100644
--- a/newtmgr/cli/runtest.go
+++ b/newtmgr/cli/runtest.go
@@ -29,7 +29,7 @@ import (
 func runCmd() *cobra.Command {
 	runCmd := &cobra.Command{
 		Use:   "run",
-		Short: "Run procedures on a device",
+		Short: "Run test procedures on a device",
 		Run: func(cmd *cobra.Command, args []string) {
 			cmd.HelpFunc()(cmd, args)
 		},
@@ -37,9 +37,14 @@ func runCmd() *cobra.Command {
 
 	runtestEx := "  newtmgr -c conn run test all 201612161220"
 
+	runTestHelpText := "Run tests on a device. Specify a testname to run a "
+	runTestHelpText += "specific test. All tests are\nrun if \"all\" or no "
+	runTestHelpText += "testname is specified. If a token-value is "
+	runTestHelpText += "specified, the\nvalue is output on the log messages.\n"
 	runTestCmd := &cobra.Command{
-		Use:     "test [all | testname] [token] -c <conn_profile>",
-		Short:   "Run commands a device - \"token\" output on log messages",
+		Use:     "test [all | testname] [token-value] -c <conn_profile>",
+		Short:   "Run tests on a device",
+		Long:    runTestHelpText,
 		Example: runtestEx,
 		Run:     runTestCmd,
 	}
@@ -47,7 +52,7 @@ func runCmd() *cobra.Command {
 
 	runListCmd := &cobra.Command{
 		Use:   "list -c <conn_profile>",
-		Short: "List registered commands on a device",
+		Short: "List registered tests on a device",
 		Run:   runListCmd,
 	}
 	runCmd.AddCommand(runListCmd)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/db270181/newtmgr/cli/stats.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/stats.go b/newtmgr/cli/stats.go
index be94973..920076a 100644
--- a/newtmgr/cli/stats.go
+++ b/newtmgr/cli/stats.go
@@ -110,15 +110,17 @@ func statsRunCmd(cmd *cobra.Command, args []string) {
 }
 
 func statsCmd() *cobra.Command {
+	statsHelpText := "Read statistics for the specified stats_name from a device"
 	statsCmd := &cobra.Command{
-		Use:   "stat ",
+		Use:   "stat [stats_name] -c <conn_profile>",
 		Short: "Read statistics from a device",
+		Long:  statsHelpText,
 		Run:   statsRunCmd,
 	}
 
 	ListCmd := &cobra.Command{
 		Use:   "list -c <conn_profile>",
-		Short: "Read list of statistics from a device",
+		Short: "Read the list of Stats names from a device",
 		Run:   statsListRunCmd,
 	}
 


[24/41] incubator-mynewt-newt git commit: newt; add target.syscfg to build's manifest file.

Posted by ma...@apache.org.
newt; add target.syscfg to build's manifest file.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/52d031e7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/52d031e7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/52d031e7

Branch: refs/heads/mynewt_1_0_0
Commit: 52d031e7fa37c29074816430bde5d1641b932a20
Parents: af2b279
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Tue Feb 28 16:58:58 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:37:10 2017 -0800

----------------------------------------------------------------------
 newt/builder/targetbuild.go | 7 +++++++
 1 file changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/52d031e7/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index f6bc2f6..2576764 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -570,6 +570,13 @@ func (t *TargetBuilder) createManifest() error {
 	for _, k := range keys {
 		manifest.TgtVars = append(manifest.TgtVars, k+"="+vars[k])
 	}
+	syscfgKV := t.GetTarget().Package().SyscfgV.GetStringMapString("syscfg.vals")
+	if len(syscfgKV) > 0 {
+		tgtSyscfg := fmt.Sprintf("target.syscfg=%s",
+			syscfg.KeyValueToStr(syscfgKV))
+		manifest.TgtVars = append(manifest.TgtVars, tgtSyscfg)
+	}
+
 	file, err := os.Create(t.AppBuilder.ManifestPath())
 	if err != nil {
 		return util.FmtNewtError("Cannot create manifest file %s: %s",


[03/41] incubator-mynewt-newt git commit: MYNEWT-558 newt - depgraph dup nodes in split tgts

Posted by ma...@apache.org.
MYNEWT-558 newt - depgraph dup nodes in split tgts


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/a3ddaaab
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/a3ddaaab
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/a3ddaaab

Branch: refs/heads/mynewt_1_0_0
Commit: a3ddaaabbc25a1548c177604824c67eb58961206
Parents: 0369efc
Author: Christopher Collins <cc...@apache.org>
Authored: Mon Feb 6 17:34:12 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:29:06 2017 -0800

----------------------------------------------------------------------
 newt/builder/buildutil.go   |  4 ++--
 newt/builder/depgraph.go    | 48 ----------------------------------------
 newt/builder/targetbuild.go |  4 ++--
 newt/resolve/resolve.go     | 24 ++++++++------------
 4 files changed, 13 insertions(+), 67 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a3ddaaab/newt/builder/buildutil.go
----------------------------------------------------------------------
diff --git a/newt/builder/buildutil.go b/newt/builder/buildutil.go
index 15ab0c2..61e5b65 100644
--- a/newt/builder/buildutil.go
+++ b/newt/builder/buildutil.go
@@ -106,7 +106,7 @@ func logDepInfo(res *resolve.Resolution) {
 	}
 
 	// Log dependency graph.
-	dg, err := joinedDepGraph(res.Sets())
+	dg, err := depGraph(res.MasterSet)
 	if err != nil {
 		log.Debugf("Error while constructing dependency graph: %s\n",
 			err.Error())
@@ -115,7 +115,7 @@ func logDepInfo(res *resolve.Resolution) {
 	}
 
 	// Log reverse dependency graph.
-	rdg, err := joinedRevdepGraph(res.Sets())
+	rdg, err := revdepGraph(res.MasterSet)
 	if err != nil {
 		log.Debugf("Error while constructing reverse dependency graph: %s\n",
 			err.Error())

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a3ddaaab/newt/builder/depgraph.go
----------------------------------------------------------------------
diff --git a/newt/builder/depgraph.go b/newt/builder/depgraph.go
index f38906c..6fc8a19 100644
--- a/newt/builder/depgraph.go
+++ b/newt/builder/depgraph.go
@@ -89,54 +89,6 @@ func revdepGraph(rs *resolve.ResolveSet) (DepGraph, error) {
 	return graphMapToDepGraph(revGm), nil
 }
 
-func mergeDepGraphs(graphs ...DepGraph) DepGraph {
-	gm := graphMap{}
-
-	for _, graph := range graphs {
-		for parent, children := range graph {
-			if gm[parent] == nil {
-				gm[parent] = map[*resolve.ResolveDep]struct{}{}
-			}
-
-			for _, child := range children {
-				graphMapAdd(gm, parent, child)
-			}
-		}
-	}
-
-	dg := graphMapToDepGraph(gm)
-
-	return dg
-}
-
-func joinedDepGraph(rss []*resolve.ResolveSet) (DepGraph, error) {
-	finalGraph := DepGraph{}
-
-	for _, rs := range rss {
-		graph, err := depGraph(rs)
-		if err != nil {
-			return nil, err
-		}
-		finalGraph = mergeDepGraphs(finalGraph, graph)
-	}
-
-	return finalGraph, nil
-}
-
-func joinedRevdepGraph(rss []*resolve.ResolveSet) (DepGraph, error) {
-	finalGraph := DepGraph{}
-
-	for _, rs := range rss {
-		graph, err := revdepGraph(rs)
-		if err != nil {
-			return nil, err
-		}
-		finalGraph = mergeDepGraphs(finalGraph, graph)
-	}
-
-	return finalGraph, nil
-}
-
 func depString(dep *resolve.ResolveDep) string {
 	s := fmt.Sprintf("%s", dep.Rpkg.Lpkg.FullName())
 	if dep.Api != "" {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a3ddaaab/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index 2bea6ef..64710db 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -669,7 +669,7 @@ func (t *TargetBuilder) CreateDepGraph() (DepGraph, error) {
 		return nil, err
 	}
 
-	return joinedDepGraph(t.res.Sets())
+	return depGraph(t.res.MasterSet)
 }
 
 func (t *TargetBuilder) CreateRevdepGraph() (DepGraph, error) {
@@ -677,5 +677,5 @@ func (t *TargetBuilder) CreateRevdepGraph() (DepGraph, error) {
 		return nil, err
 	}
 
-	return joinedRevdepGraph(t.res.Sets())
+	return revdepGraph(t.res.MasterSet)
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/a3ddaaab/newt/resolve/resolve.go
----------------------------------------------------------------------
diff --git a/newt/resolve/resolve.go b/newt/resolve/resolve.go
index c4a1d38..8a675c0 100644
--- a/newt/resolve/resolve.go
+++ b/newt/resolve/resolve.go
@@ -78,8 +78,12 @@ type Resolution struct {
 	UnsatisfiedApis map[string][]*ResolvePackage
 
 	LpkgRpkgMap map[*pkg.LocalPackage]*ResolvePackage
-	LoaderSet   *ResolveSet
-	AppSet      *ResolveSet
+
+	// Contains all dependencies; union of loader and app.
+	MasterSet *ResolveSet
+
+	LoaderSet *ResolveSet
+	AppSet    *ResolveSet
 }
 
 func newResolver(
@@ -112,25 +116,13 @@ func newResolution() *Resolution {
 		UnsatisfiedApis: map[string][]*ResolvePackage{},
 	}
 
+	r.MasterSet = &ResolveSet{Res: r}
 	r.LoaderSet = &ResolveSet{Res: r}
 	r.AppSet = &ResolveSet{Res: r}
 
 	return r
 }
 
-func (res *Resolution) Sets() []*ResolveSet {
-	rss := []*ResolveSet{}
-
-	if res.LoaderSet != nil {
-		rss = append(rss, res.LoaderSet)
-	}
-	if res.AppSet != nil {
-		rss = append(rss, res.AppSet)
-	}
-
-	return rss
-}
-
 func NewResolvePkg(lpkg *pkg.LocalPackage) *ResolvePackage {
 	return &ResolvePackage{
 		Lpkg:      lpkg,
@@ -542,6 +534,8 @@ func ResolveFull(
 
 	res.LpkgRpkgMap = r.pkgMap
 
+	res.MasterSet.Rpkgs = r.rpkgSlice()
+
 	// If there is no loader, then the set of all packages is just the app
 	// packages.  We already resolved the necessary dependency information when
 	// syscfg was calculated above.


[02/41] incubator-mynewt-newt git commit: gofmt

Posted by ma...@apache.org.
gofmt


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/0369efcb
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/0369efcb
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/0369efcb

Branch: refs/heads/mynewt_1_0_0
Commit: 0369efcbe1d44eb19a59b93a71bf66a228bac630
Parents: 4c0c1b1
Author: Christopher Collins <cc...@apache.org>
Authored: Sun Feb 5 11:51:48 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:28:55 2017 -0800

----------------------------------------------------------------------
 newt/pkg/localpackage.go | 2 +-
 newt/sysinit/sysinit.go  | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/0369efcb/newt/pkg/localpackage.go
----------------------------------------------------------------------
diff --git a/newt/pkg/localpackage.go b/newt/pkg/localpackage.go
index 8c935b1..da7ac65 100644
--- a/newt/pkg/localpackage.go
+++ b/newt/pkg/localpackage.go
@@ -327,7 +327,7 @@ func (pkg *LocalPackage) Load() error {
 		stage, err := strconv.ParseInt(stageStr, 10, 64)
 		if err != nil {
 			return util.NewNewtError(fmt.Sprintf("Parsing pkg %s config: %s",
-			                                     pkg.FullName(), err.Error()))
+				pkg.FullName(), err.Error()))
 		}
 		pkg.init[name] = int(stage)
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/0369efcb/newt/sysinit/sysinit.go
----------------------------------------------------------------------
diff --git a/newt/sysinit/sysinit.go b/newt/sysinit/sysinit.go
index ddcc68b..29dc082 100644
--- a/newt/sysinit/sysinit.go
+++ b/newt/sysinit/sysinit.go
@@ -48,8 +48,8 @@ func buildStageMap(pkgs []*pkg.LocalPackage) map[int][]*initFunc {
 		for name, stage := range p.Init() {
 			initFunc := &initFunc{
 				stage: stage,
-				name: name,
-				pkg: p,
+				name:  name,
+				pkg:   p,
 			}
 			sm[stage] = append(sm[stage], initFunc)
 		}
@@ -63,7 +63,7 @@ func writePrototypes(pkgs []*pkg.LocalPackage, w io.Writer) {
 	for _, p := range sorted {
 		init := p.Init()
 		for name, _ := range init {
-			fmt.Fprintf(w, "void %s(void);\n", name);
+			fmt.Fprintf(w, "void %s(void);\n", name)
 		}
 	}
 }


[12/41] incubator-mynewt-newt git commit: add the pkg remove command to newt

Posted by ma...@apache.org.
add the pkg remove command to newt


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/f497cab9
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/f497cab9
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/f497cab9

Branch: refs/heads/mynewt_1_0_0
Commit: f497cab99381fc00e4462d00fed45b5bba94819f
Parents: 2f04e25
Author: Sterling Hughes <st...@runtime.io>
Authored: Sat Feb 11 16:29:02 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:31 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 72 +++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 69 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/f497cab9/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index d04691e..75e9a00 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -29,6 +29,7 @@ import (
 	"github.com/spf13/cobra"
 	"mynewt.apache.org/newt/newt/interfaces"
 	"mynewt.apache.org/newt/newt/newtutil"
+	"mynewt.apache.org/newt/newt/pkg"
 	"mynewt.apache.org/newt/newt/project"
 	"mynewt.apache.org/newt/util"
 )
@@ -60,11 +61,11 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 
 	wd, err := os.Getwd()
 	if err != nil {
-		NewtUsage(cmd, util.NewNewtError(err.Error()))
+		NewtUsage(cmd, util.ChildNewtError(err))
 	}
 
 	if err := os.Chdir(proj.Path() + "/"); err != nil {
-		NewtUsage(cmd, util.NewNewtError(err.Error()))
+		NewtUsage(cmd, util.ChildNewtError(err))
 	}
 
 	/* Find source package, defaulting search to the local project if no
@@ -149,12 +150,64 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	os.Chdir(wd)
 }
 
+func pkgRemoveCmd(cmd *cobra.Command, args []string) {
+	if len(args) != 1 {
+		NewtUsage(cmd, util.NewNewtError("Must specify a package name to delete"))
+	}
+
+	proj := TryGetProject()
+	interfaces.SetProject(proj)
+
+	wd, err := os.Getwd()
+	if err != nil {
+		NewtUsage(cmd, util.ChildNewtError(err))
+	}
+
+	if err := os.Chdir(proj.Path() + "/"); err != nil {
+		NewtUsage(cmd, util.ChildNewtError(err))
+	}
+	/* Resolve package, and get path from package to ensure we're being asked
+	 * to remove a valid path.
+	 */
+	repoName, pkgName, err := newtutil.ParsePackageString(args[0])
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	repo := proj.LocalRepo()
+	if repoName != "" {
+		repo = proj.FindRepo(repoName)
+		if repo == nil {
+			os.Chdir(wd)
+			NewtUsage(cmd, util.NewNewtError("Destination repo "+
+				repoName+" does not exist"))
+		}
+	}
+
+	pkg, err := pkg.LoadLocalPackage(repo, pkgName)
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	util.StatusMessage(util.VERBOSITY_DEFAULT, "Removing package %s\n",
+		args[0])
+
+	if err := os.RemoveAll(pkg.BasePath()); err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, util.ChildNewtError(err))
+	}
+
+	os.Chdir(wd)
+}
+
 func AddPackageCommands(cmd *cobra.Command) {
 	/* Add the base package command, on top of which other commands are
 	 * keyed
 	 */
 	pkgHelpText := "Commands for creating and manipulating packages"
-	pkgHelpEx := "newt pkg new --type=pkg libs/mylib"
+	pkgHelpEx := "  newt pkg new --type=pkg libs/mylib"
 
 	pkgCmd := &cobra.Command{
 		Use:     "pkg",
@@ -197,4 +250,17 @@ func AddPackageCommands(cmd *cobra.Command) {
 	}
 
 	pkgCmd.AddCommand(moveCmd)
+
+	removeCmdHelpText := ""
+	removeCmdHelpEx := ""
+
+	removeCmd := &cobra.Command{
+		Use:     "remove",
+		Short:   "Remove a package",
+		Long:    removeCmdHelpText,
+		Example: removeCmdHelpEx,
+		Run:     pkgRemoveCmd,
+	}
+
+	pkgCmd.AddCommand(removeCmd)
 }


[23/41] incubator-mynewt-newt git commit: newt; move targetSyscfgKVxxx() routines to be inside syscfg package.

Posted by ma...@apache.org.
newt; move targetSyscfgKVxxx() routines to be inside syscfg package.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/af2b279c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/af2b279c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/af2b279c

Branch: refs/heads/mynewt_1_0_0
Commit: af2b279c1bfb9548ea25e17489464c877aaf55ea
Parents: 91f6e0b
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Tue Feb 28 16:58:21 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:37:01 2017 -0800

----------------------------------------------------------------------
 newt/cli/target_cmds.go | 54 ++------------------------------------------
 newt/syscfg/syscfg.go   | 50 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 52 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/af2b279c/newt/cli/target_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/target_cmds.go b/newt/cli/target_cmds.go
index 8888847..a6ea7df 100644
--- a/newt/cli/target_cmds.go
+++ b/newt/cli/target_cmds.go
@@ -121,7 +121,7 @@ func targetShowCmd(cmd *cobra.Command, args []string) {
 		}
 
 		// A few variables come from the base package rather than the target.
-		kvPairs["syscfg"] = targetSyscfgKVToStr(
+		kvPairs["syscfg"] = syscfg.KeyValueToStr(
 			target.Package().SyscfgV.GetStringMapString("syscfg.vals"))
 		kvPairs["cflags"] = pkgVarSliceString(target.Package(), "pkg.cflags")
 		kvPairs["lflags"] = pkgVarSliceString(target.Package(), "pkg.lflags")
@@ -142,56 +142,6 @@ func targetShowCmd(cmd *cobra.Command, args []string) {
 	}
 }
 
-func targetSyscfgKVFromStr(str string) (map[string]string, error) {
-	vals := map[string]string{}
-
-	if strings.TrimSpace(str) == "" {
-		return vals, nil
-	}
-
-	// Separate syscfg vals are delimited by ':'.
-	fields := strings.Split(str, ":")
-
-	// Key-value pairs are delimited by '='.  If no '=' is present, assume the
-	// string is the key name and the value is 1.
-	for _, f := range fields {
-		if _, err := util.AtoiNoOct(f); err == nil {
-			return nil, util.FmtNewtError(
-				"Invalid setting name \"%s\"; must not be a number", f)
-		}
-
-		kv := strings.SplitN(f, "=", 2)
-		switch len(kv) {
-		case 1:
-			vals[f] = "1"
-		case 2:
-			vals[kv[0]] = kv[1]
-		}
-	}
-
-	return vals, nil
-}
-
-func targetSyscfgKVToStr(syscfgKv map[string]string) string {
-	str := ""
-
-	names := make([]string, 0, len(syscfgKv))
-	for k, _ := range syscfgKv {
-		names = append(names, k)
-	}
-	sort.Strings(names)
-
-	for i, name := range names {
-		if i != 0 {
-			str += ":"
-		}
-
-		str += fmt.Sprintf("%s=%s", name, syscfgKv[name])
-	}
-
-	return str
-}
-
 func targetSetCmd(cmd *cobra.Command, args []string) {
 	if len(args) < 2 {
 		NewtUsage(cmd,
@@ -234,7 +184,7 @@ func targetSetCmd(cmd *cobra.Command, args []string) {
 		// instead of the target.
 		if kv[0] == "target.syscfg" {
 			t.Package().SyscfgV = viper.New()
-			kv, err := targetSyscfgKVFromStr(kv[1])
+			kv, err := syscfg.KeyValueFromStr(kv[1])
 			if err != nil {
 				NewtUsage(cmd, err)
 			}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/af2b279c/newt/syscfg/syscfg.go
----------------------------------------------------------------------
diff --git a/newt/syscfg/syscfg.go b/newt/syscfg/syscfg.go
index f5cef0e..cac298e 100644
--- a/newt/syscfg/syscfg.go
+++ b/newt/syscfg/syscfg.go
@@ -993,3 +993,53 @@ func EnsureWritten(cfg Cfg, includeDir string) error {
 
 	return nil
 }
+
+func KeyValueFromStr(str string) (map[string]string, error) {
+	vals := map[string]string{}
+
+	if strings.TrimSpace(str) == "" {
+		return vals, nil
+	}
+
+	// Separate syscfg vals are delimited by ':'.
+	fields := strings.Split(str, ":")
+
+	// Key-value pairs are delimited by '='.  If no '=' is present, assume the
+	// string is the key name and the value is 1.
+	for _, f := range fields {
+		if _, err := util.AtoiNoOct(f); err == nil {
+			return nil, util.FmtNewtError(
+				"Invalid setting name \"%s\"; must not be a number", f)
+		}
+
+		kv := strings.SplitN(f, "=", 2)
+		switch len(kv) {
+		case 1:
+			vals[f] = "1"
+		case 2:
+			vals[kv[0]] = kv[1]
+		}
+	}
+
+	return vals, nil
+}
+
+func KeyValueToStr(syscfgKv map[string]string) string {
+	str := ""
+
+	names := make([]string, 0, len(syscfgKv))
+	for k, _ := range syscfgKv {
+		names = append(names, k)
+	}
+	sort.Strings(names)
+
+	for i, name := range names {
+		if i != 0 {
+			str += ":"
+		}
+
+		str += fmt.Sprintf("%s=%s", name, syscfgKv[name])
+	}
+
+	return str
+}


[37/41] incubator-mynewt-newt git commit: 1) Fixed runtime exception when no argument is given to the "newtmgr conn add" and the "newtmgr conn delete" 2) Updated help texts.

Posted by ma...@apache.org.
1) Fixed runtime exception when no argument is given to the
    "newtmgr conn add" and the "newtmgr conn delete"
2) Updated help texts.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/18c35bfe
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/18c35bfe
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/18c35bfe

Branch: refs/heads/mynewt_1_0_0
Commit: 18c35bfe47ff9aaeaf007efe04a8ac06a1366f6a
Parents: b6b9599
Author: cwanda <wa...@happycity.com>
Authored: Fri Mar 3 00:23:44 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:39:05 2017 -0800

----------------------------------------------------------------------
 newtmgr/cli/commands.go    |  11 ++-
 newtmgr/cli/config.go      |   7 +-
 newtmgr/cli/connprofile.go |  14 ++-
 newtmgr/cli/crash.go       |   4 +-
 newtmgr/cli/datetime.go    |   4 +-
 newtmgr/cli/echo.go        |   4 +-
 newtmgr/cli/fs.go          |  10 +--
 newtmgr/cli/image.go       |  28 +++---
 newtmgr/cli/logs.go        |  22 ++---
 newtmgr/cli/mpstats.go     |   4 +-
 newtmgr/cli/reset.go       |   4 +-
 newtmgr/cli/runtest.go     | 192 ++++++++++++++++++++--------------------
 newtmgr/cli/stats.go       |   8 +-
 newtmgr/cli/taskstats.go   |   6 +-
 14 files changed, 167 insertions(+), 151 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/commands.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/commands.go b/newtmgr/cli/commands.go
index e8f6c4e..8a5d526 100644
--- a/newtmgr/cli/commands.go
+++ b/newtmgr/cli/commands.go
@@ -29,12 +29,13 @@ import (
 
 var ConnProfileName string
 var NewtmgrLogLevel log.Level
+var NewtmgrHelp bool
 
 func Commands() *cobra.Command {
 	logLevelStr := ""
 	nmCmd := &cobra.Command{
 		Use:   "newtmgr",
-		Short: "Newtmgr helps you manage remote instances of the Mynewt OS.",
+		Short: "Newtmgr helps you manage devices running the Mynewt OS",
 		PersistentPreRun: func(cmd *cobra.Command, args []string) {
 			NewtmgrLogLevel, err := log.ParseLevel(logLevelStr)
 			err = util.Init(NewtmgrLogLevel, "", util.VERBOSITY_DEFAULT)
@@ -48,14 +49,18 @@ func Commands() *cobra.Command {
 	}
 
 	nmCmd.PersistentFlags().StringVarP(&ConnProfileName, "conn", "c", "",
-		"connection profile to use.")
+		"connection profile to use")
 
 	nmCmd.PersistentFlags().StringVarP(&logLevelStr, "loglevel", "l", "info",
-		"log level to use (default INFO.)")
+		"log level to use")
 
 	nmCmd.PersistentFlags().BoolVarP(&nmutil.TraceLogEnabled, "trace", "t",
 		false, "print all bytes transmitted and received")
 
+	// Add the help flag so it shows up under Global Flags
+	nmCmd.PersistentFlags().BoolVarP(&NewtmgrHelp, "help", "h",
+		false, "Help for newtmgr commands")
+
 	nmCmd.AddCommand(configCmd())
 	nmCmd.AddCommand(connProfileCmd())
 	nmCmd.AddCommand(crashCmd())

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/config.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/config.go b/newtmgr/cli/config.go
index 20f819d..a70d320 100644
--- a/newtmgr/cli/config.go
+++ b/newtmgr/cli/config.go
@@ -72,9 +72,12 @@ func configRunCmd(cmd *cobra.Command, args []string) {
 }
 
 func configCmd() *cobra.Command {
+	configCmdLongHelp := "Read or write a config value for <var-name> variable on " +
+		"a device.\nSpecify a var-value to write a value to a device.\n"
 	statsCmd := &cobra.Command{
-		Use:   "config",
-		Short: "Read or write config value on target",
+		Use:   "config <var-name> [var-value] -c <conn_profile>",
+		Short: "Read or write a config value on a device",
+		Long:  configCmdLongHelp,
 		Run:   configRunCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/connprofile.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/connprofile.go b/newtmgr/cli/connprofile.go
index fa90088..06d70e0 100644
--- a/newtmgr/cli/connprofile.go
+++ b/newtmgr/cli/connprofile.go
@@ -62,6 +62,11 @@ func connProfileAddCmd(cmd *cobra.Command, args []string) {
 		nmUsage(cmd, err)
 	}
 
+	// Connection Profile name required
+	if len(args) == 0 {
+		nmUsage(cmd, util.NewNewtError("Need connection profile name"))
+	}
+
 	name := args[0]
 	cp, err := config.NewConnProfile(name)
 	if err != nil {
@@ -161,6 +166,11 @@ func connProfileDelCmd(cmd *cobra.Command, args []string) {
 		nmUsage(cmd, err)
 	}
 
+	// Connection Profile name required
+	if len(args) == 0 {
+		nmUsage(cmd, util.NewNewtError("Need connection profile name"))
+	}
+
 	name := args[0]
 
 	if err := cpm.DeleteConnProfile(name); err != nil {
@@ -180,14 +190,14 @@ func connProfileCmd() *cobra.Command {
 	}
 
 	addCmd := &cobra.Command{
-		Use:   "add",
+		Use:   "add <conn_profile> [varname=value ...] ",
 		Short: "Add a newtmgr connection profile",
 		Run:   connProfileAddCmd,
 	}
 	cpCmd.AddCommand(addCmd)
 
 	deleCmd := &cobra.Command{
-		Use:   "delete",
+		Use:   "delete <conn_profile>",
 		Short: "Delete a newtmgr connection profile",
 		Run:   connProfileDelCmd,
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/crash.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/crash.go b/newtmgr/cli/crash.go
index 9f740db..941b6de 100644
--- a/newtmgr/cli/crash.go
+++ b/newtmgr/cli/crash.go
@@ -87,8 +87,8 @@ func crashCmd() *cobra.Command {
 	crashEx := "   newtmgr -c olimex crash div0\n"
 
 	crashCmd := &cobra.Command{
-		Use:     "crash [div0|jump0|ref0|assert|wdog]",
-		Short:   "Send crash command to remote endpoint using newtmgr",
+		Use:     "crash [div0|jump0|ref0|assert|wdog] -c <conn_profile>",
+		Short:   "Send crash command to a device",
 		Example: crashEx,
 		Run:     crashRunCmd,
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/datetime.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/datetime.go b/newtmgr/cli/datetime.go
index c04122f..34fd471 100644
--- a/newtmgr/cli/datetime.go
+++ b/newtmgr/cli/datetime.go
@@ -86,8 +86,8 @@ func dateTimeCmd(cmd *cobra.Command, args []string) {
 
 func dTimeCmd() *cobra.Command {
 	dateTCmd := &cobra.Command{
-		Use:   "datetime",
-		Short: "Manage datetime on the device",
+		Use:   "datetime -c <conn_profile>",
+		Short: "Manage datetime on a device",
 		Run:   dateTimeCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/echo.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/echo.go b/newtmgr/cli/echo.go
index 3503255..bfb15c6 100644
--- a/newtmgr/cli/echo.go
+++ b/newtmgr/cli/echo.go
@@ -67,8 +67,8 @@ func echoRunCmd(cmd *cobra.Command, args []string) {
 
 func echoCmd() *cobra.Command {
 	echoCmd := &cobra.Command{
-		Use:   "echo",
-		Short: "Send data to remote endpoint using newtmgr, and receive data back",
+		Use:   "echo <text> -c <conn_profile>",
+		Short: "Send data to a device and display the echoed back data",
 		Run:   echoRunCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/fs.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/fs.go b/newtmgr/cli/fs.go
index bdcb062..ade8870 100644
--- a/newtmgr/cli/fs.go
+++ b/newtmgr/cli/fs.go
@@ -186,7 +186,7 @@ func fsDownloadCmd(cmd *cobra.Command, args []string) {
 func fsCmd() *cobra.Command {
 	fsCmd := &cobra.Command{
 		Use:   "fs",
-		Short: "Access files on device",
+		Short: "Access files on a device",
 		Run: func(cmd *cobra.Command, args []string) {
 			cmd.HelpFunc()(cmd, args)
 		},
@@ -195,8 +195,8 @@ func fsCmd() *cobra.Command {
 	uploadEx := "  newtmgr -c olimex fs upload sample.lua /sample.lua\n"
 
 	uploadCmd := &cobra.Command{
-		Use:     "upload <src-filename> <dst-filename>",
-		Short:   "Upload file to target",
+		Use:     "upload <src-filename> <dst-filename> -c <conn_profile>",
+		Short:   "Upload file to a device",
 		Example: uploadEx,
 		Run:     fsUploadCmd,
 	}
@@ -205,8 +205,8 @@ func fsCmd() *cobra.Command {
 	downloadEx := "  newtmgr -c olimex image download /cfg/mfg mfg.txt\n"
 
 	downloadCmd := &cobra.Command{
-		Use:     "download <src-filename> <dst-filename>",
-		Short:   "Download file from target",
+		Use:     "download <src-filename> <dst-filename> -c <conn_profile>",
+		Short:   "Download file from a device",
 		Example: downloadEx,
 		Run:     fsDownloadCmd,
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/image.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/image.go b/newtmgr/cli/image.go
index 8a3f692..7457df8 100644
--- a/newtmgr/cli/image.go
+++ b/newtmgr/cli/image.go
@@ -524,7 +524,7 @@ func coreEraseCmd(cmd *cobra.Command, args []string) {
 func imageCmd() *cobra.Command {
 	imageCmd := &cobra.Command{
 		Use:   "image",
-		Short: "Manage images on remote instance",
+		Short: "Manage images on a device",
 		Run: func(cmd *cobra.Command, args []string) {
 			cmd.HelpFunc()(cmd, args)
 		},
@@ -532,7 +532,7 @@ func imageCmd() *cobra.Command {
 
 	listCmd := &cobra.Command{
 		Use:   "list",
-		Short: "Show target images",
+		Short: "Show images on a device",
 		Run:   imageStateListCmd,
 	}
 	imageCmd.AddCommand(listCmd)
@@ -545,7 +545,7 @@ func imageCmd() *cobra.Command {
 	imageCmd.AddCommand(testCmd)
 
 	confirmCmd := &cobra.Command{
-		Use:   "confirm [hex-image-hash]",
+		Use:   "confirm [hex-image-hash] -c <conn_profile>",
 		Short: "Permanently run image",
 		Long: "If a hash is specified, permanently switch to the " +
 			"corresponding image.  If no hash is specified, the current " +
@@ -554,12 +554,11 @@ func imageCmd() *cobra.Command {
 	}
 	imageCmd.AddCommand(confirmCmd)
 
-	uploadEx := "  newtmgr -c olimex image upload <image_file\n"
-	uploadEx += "  newtmgr -c olimex image upload bin/slinky_zero/apps/slinky.img\n"
+	uploadEx := "  newtmgr -c olimex image upload bin/slinky_zero/apps/slinky.img\n"
 
 	uploadCmd := &cobra.Command{
-		Use:     "upload",
-		Short:   "Upload image to target",
+		Use:     "upload <image-file> -c <conn_profile>",
+		Short:   "Upload image to a device",
 		Example: uploadEx,
 		Run:     imageUploadCmd,
 	}
@@ -568,20 +567,19 @@ func imageCmd() *cobra.Command {
 	coreListEx := "  newtmgr -c olimex image corelist\n"
 
 	coreListCmd := &cobra.Command{
-		Use:     "corelist",
-		Short:   "List core(s) on target",
+		Use:     "corelist -c <conn_profile>",
+		Short:   "List core(s) on a device",
 		Example: coreListEx,
 		Run:     coreListCmd,
 	}
 	imageCmd.AddCommand(coreListCmd)
 
-	coreEx := "  newtmgr -c olimex image coredownload -e <filename>\n"
-	coreEx += "  newtmgr -c olimex image coredownload -e core\n"
+	coreEx := "  newtmgr -c olimex image coredownload -e core\n"
 	coreEx += "  newtmgr -c olimex image coredownload --offset 10 -n 10 core\n"
 
 	coreDownloadCmd := &cobra.Command{
-		Use:     "coredownload",
-		Short:   "Download core from target",
+		Use:     "coredownload <core_filename> -c <conn_profile>",
+		Short:   "Download core from a device",
 		Example: coreEx,
 		Run:     coreDownloadCmd,
 	}
@@ -600,8 +598,8 @@ func imageCmd() *cobra.Command {
 	coreEraseEx := "  newtmgr -c olimex image coreerase\n"
 
 	coreEraseCmd := &cobra.Command{
-		Use:     "coreerase",
-		Short:   "Erase core on target",
+		Use:     "coreerase -c <conn_profile>",
+		Short:   "Erase core on a device",
 		Example: coreEraseEx,
 		Run:     coreEraseCmd,
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/logs.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/logs.go b/newtmgr/cli/logs.go
index 7eb90c2..775402a 100644
--- a/newtmgr/cli/logs.go
+++ b/newtmgr/cli/logs.go
@@ -327,44 +327,44 @@ func logsClearCmd(cmd *cobra.Command, args []string) {
 func logsCmd() *cobra.Command {
 	logsCmd := &cobra.Command{
 		Use:   "log",
-		Short: "Handles logs on remote instance",
+		Short: "Handle logs on a device",
 		Run: func(cmd *cobra.Command, args []string) {
 			cmd.HelpFunc()(cmd, args)
 		},
 	}
 
 	showCmd := &cobra.Command{
-		Use:   "show [log-name] [min-index] [min-timestamp]",
-		Short: "Show logs on target",
+		Use:   "show [log-name] [min-index] [min-timestamp] -c <conn_profile>",
+		Short: "Show the logs on a device",
 		Run:   logsShowCmd,
 	}
 	logsCmd.AddCommand(showCmd)
 
 	clearCmd := &cobra.Command{
-		Use:   "clear",
-		Short: "Clear logs on target",
+		Use:   "clear -c <conn_profile>",
+		Short: "Clear the logs on a device",
 		Run:   logsClearCmd,
 	}
 	logsCmd.AddCommand(clearCmd)
 
 	moduleListCmd := &cobra.Command{
-		Use:   "module_list",
-		Short: "Module List Command",
+		Use:   "module_list -c <conn_profile>",
+		Short: "Show the log module names",
 		Run:   logsModuleListCmd,
 	}
 	logsCmd.AddCommand(moduleListCmd)
 
 	levelListCmd := &cobra.Command{
-		Use:   "level_list",
-		Short: "Level List Command",
+		Use:   "level_list -c <conn_profile>",
+		Short: "Show the log levels",
 		Run:   logsLevelListCmd,
 	}
 
 	logsCmd.AddCommand(levelListCmd)
 
 	ListCmd := &cobra.Command{
-		Use:   "list",
-		Short: "Log List Command",
+		Use:   "list -c <conn_profile>",
+		Short: "Show the log names",
 		Run:   logsListCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/mpstats.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/mpstats.go b/newtmgr/cli/mpstats.go
index 3789dc4..278ca2c 100644
--- a/newtmgr/cli/mpstats.go
+++ b/newtmgr/cli/mpstats.go
@@ -74,8 +74,8 @@ func mempoolStatsRunCmd(cmd *cobra.Command, args []string) {
 
 func mempoolStatsCmd() *cobra.Command {
 	mempoolStatsCmd := &cobra.Command{
-		Use:   "mpstats",
-		Short: "Read statistics from a remote endpoint",
+		Use:   "mpstats -c <conn_profile>",
+		Short: "Read memory pool statistics from a device",
 		Run:   mempoolStatsRunCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/reset.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/reset.go b/newtmgr/cli/reset.go
index 77a9578..e5a9b55 100644
--- a/newtmgr/cli/reset.go
+++ b/newtmgr/cli/reset.go
@@ -57,8 +57,8 @@ func resetRunCmd(cmd *cobra.Command, args []string) {
 
 func resetCmd() *cobra.Command {
 	resetCmd := &cobra.Command{
-		Use:   "reset",
-		Short: "Send reset request to remote endpoint using newtmgr",
+		Use:   "reset -c <conn_profile>",
+		Short: "Send reset request to a device",
 		Run:   resetRunCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/runtest.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/runtest.go b/newtmgr/cli/runtest.go
index 47f0c87..60070ee 100644
--- a/newtmgr/cli/runtest.go
+++ b/newtmgr/cli/runtest.go
@@ -28,118 +28,118 @@ import (
 
 func runCmd() *cobra.Command {
 	runCmd := &cobra.Command{
-		Use:     "run",
-		Short:   "Run procedures on remote device",
+		Use:   "run",
+		Short: "Run procedures on a device",
 		Run: func(cmd *cobra.Command, args []string) {
-                cmd.HelpFunc()(cmd, args)
-        },
+			cmd.HelpFunc()(cmd, args)
+		},
 	}
 
-    runtestEx :="  newtmgr -c conn run test all 201612161220"
+	runtestEx := "  newtmgr -c conn run test all 201612161220"
 
 	runTestCmd := &cobra.Command{
-		Use:     "test [all | testname] [token]",
-        Short:   "Run commands on remote device - \"token\" output on log messages",
-        Example: runtestEx,
+		Use:     "test [all | testname] [token] -c <conn_profile>",
+		Short:   "Run commands a device - \"token\" output on log messages",
+		Example: runtestEx,
 		Run:     runTestCmd,
 	}
-    runCmd.AddCommand(runTestCmd)
+	runCmd.AddCommand(runTestCmd)
 
 	runListCmd := &cobra.Command{
-		Use:     "list",
-		Short:   "List registered commands on remote device",
-		Run:     runListCmd,
+		Use:   "list -c <conn_profile>",
+		Short: "List registered commands on a device",
+		Run:   runListCmd,
 	}
-    runCmd.AddCommand(runListCmd)
+	runCmd.AddCommand(runListCmd)
 
 	return runCmd
 }
 
 func runTestCmd(cmd *cobra.Command, args []string) {
-    runner, err := getTargetCmdRunner()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-    defer runner.Conn.Close()
-
-    req, err := protocol.NewRunTestReq()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    if len(args) > 0 {
-        req.Testname = args[0]
-        if len(args) > 1 {
-            req.Token = args[1]
-        } else {
-            req.Token = ""
-        }
-    } else {
-        /*
-         * If nothing specified, turn on "all" by default
-         * There is no default token.
-         */
-        req.Testname = "all"
-        req.Token = ""
-    }
-
-    nmr, err := req.Encode()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    if err := runner.WriteReq(nmr); err != nil {
-        nmUsage(cmd, err)
-    }
-
-    rsp, err := runner.ReadResp()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    decodedResponse, err := protocol.DecodeRunTestResponse(rsp.Data)
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    if decodedResponse.ReturnCode != 0 {
-        fmt.Printf("Return Code = %d\n", decodedResponse.ReturnCode)
-    }
+	runner, err := getTargetCmdRunner()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+	defer runner.Conn.Close()
+
+	req, err := protocol.NewRunTestReq()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	if len(args) > 0 {
+		req.Testname = args[0]
+		if len(args) > 1 {
+			req.Token = args[1]
+		} else {
+			req.Token = ""
+		}
+	} else {
+		/*
+		 * If nothing specified, turn on "all" by default
+		 * There is no default token.
+		 */
+		req.Testname = "all"
+		req.Token = ""
+	}
+
+	nmr, err := req.Encode()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	if err := runner.WriteReq(nmr); err != nil {
+		nmUsage(cmd, err)
+	}
+
+	rsp, err := runner.ReadResp()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	decodedResponse, err := protocol.DecodeRunTestResponse(rsp.Data)
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	if decodedResponse.ReturnCode != 0 {
+		fmt.Printf("Return Code = %d\n", decodedResponse.ReturnCode)
+	}
 }
 
 func runListCmd(cmd *cobra.Command, args []string) {
-    runner, err := getTargetCmdRunner()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    defer runner.Conn.Close()
-    req, err := protocol.NewRunListReq()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    nmr, err := req.Encode()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    if err := runner.WriteReq(nmr); err != nil {
-        nmUsage(cmd, err)
-    }
-
-    rsp, err := runner.ReadResp()
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    decodedResponse, err := protocol.DecodeRunListResponse(rsp.Data)
-    if err != nil {
-        nmUsage(cmd, err)
-    }
-
-    fmt.Println(decodedResponse.List)
-    if decodedResponse.ReturnCode != 0 {
-        fmt.Printf("Return Code = %d\n", decodedResponse.ReturnCode)
-    }
+	runner, err := getTargetCmdRunner()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	defer runner.Conn.Close()
+	req, err := protocol.NewRunListReq()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	nmr, err := req.Encode()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	if err := runner.WriteReq(nmr); err != nil {
+		nmUsage(cmd, err)
+	}
+
+	rsp, err := runner.ReadResp()
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	decodedResponse, err := protocol.DecodeRunListResponse(rsp.Data)
+	if err != nil {
+		nmUsage(cmd, err)
+	}
+
+	fmt.Println(decodedResponse.List)
+	if decodedResponse.ReturnCode != 0 {
+		fmt.Printf("Return Code = %d\n", decodedResponse.ReturnCode)
+	}
 }

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/stats.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/stats.go b/newtmgr/cli/stats.go
index eb2ee57..be94973 100644
--- a/newtmgr/cli/stats.go
+++ b/newtmgr/cli/stats.go
@@ -111,14 +111,14 @@ func statsRunCmd(cmd *cobra.Command, args []string) {
 
 func statsCmd() *cobra.Command {
 	statsCmd := &cobra.Command{
-		Use:   "stat",
-		Short: "Read statistics from a remote endpoint",
+		Use:   "stat ",
+		Short: "Read statistics from a device",
 		Run:   statsRunCmd,
 	}
 
 	ListCmd := &cobra.Command{
-		Use:   "list",
-		Short: "Read list of statistics from a remote endpoint",
+		Use:   "list -c <conn_profile>",
+		Short: "Read list of statistics from a device",
 		Run:   statsListRunCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/18c35bfe/newtmgr/cli/taskstats.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/taskstats.go b/newtmgr/cli/taskstats.go
index 17122c7..76cda8a 100644
--- a/newtmgr/cli/taskstats.go
+++ b/newtmgr/cli/taskstats.go
@@ -61,7 +61,7 @@ func taskStatsRunCmd(cmd *cobra.Command, args []string) {
 	if tsrsp.ReturnCode == 0 {
 		fmt.Printf("  %8s %3s %3s %8s %8s %8s %8s %8s %8s\n",
 			"task", "pri", "tid", "runtime", "csw", "stksz",
-			"stkuse", "last_checkin", "next_checkin");
+			"stkuse", "last_checkin", "next_checkin")
 		for k, info := range tsrsp.Tasks {
 			fmt.Printf("  %8s %3d %3d %8d %8d %8d %8d %8d %8d\n",
 				k,
@@ -79,8 +79,8 @@ func taskStatsRunCmd(cmd *cobra.Command, args []string) {
 
 func taskStatsCmd() *cobra.Command {
 	taskStatsCmd := &cobra.Command{
-		Use:   "taskstats",
-		Short: "Read statistics from a remote endpoint",
+		Use:   "taskstats -c <conn_profile>",
+		Short: "Read task statistics from a device",
 		Run:   taskStatsRunCmd,
 	}
 


[10/41] incubator-mynewt-newt git commit: search and replace package name instead of rewriting package

Posted by ma...@apache.org.
search and replace package name instead of rewriting package


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/b3f044d2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/b3f044d2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/b3f044d2

Branch: refs/heads/mynewt_1_0_0
Commit: b3f044d2911a82fb4a4b0f096a705947d4218828
Parents: d419f2a
Author: Sterling Hughes <st...@runtime.io>
Authored: Sat Feb 11 15:48:37 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:12 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/b3f044d2/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 0b05f05..13937d6 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -20,8 +20,10 @@
 package cli
 
 import (
+	"io/ioutil"
 	"os"
 	"path"
+	"regexp"
 	"strings"
 
 	"github.com/spf13/cobra"
@@ -123,6 +125,20 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 		NewtUsage(cmd, err)
 	}
 
+	/* Replace the package name in the pkg.yml file */
+	pkgData, err := ioutil.ReadFile(dstPath + "/pkg.yml")
+	if err != nil {
+		os.Chdir(wd)
+		NewtUsage(cmd, err)
+	}
+
+	re := regexp.MustCompile(regexp.QuoteMeta(srcName))
+	res := re.ReplaceAllString(string(pkgData), pkgName)
+
+	if err := ioutil.WriteFile(dstPath+"/pkg.yml", []byte(res), 0666); err != nil {
+		NewtUsage(cmd, util.ChildNewtError(err))
+	}
+
 	dstPkg, err := pkg.LoadLocalPackage(repo, pkgName)
 	if err != nil {
 		os.Chdir(wd)


[36/41] incubator-mynewt-newt git commit: MYNEWT-651; fix go formatting.

Posted by ma...@apache.org.
MYNEWT-651; fix go formatting.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/b6b95992
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/b6b95992
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/b6b95992

Branch: refs/heads/mynewt_1_0_0
Commit: b6b95992195edfe58f99cfa3d460905cec6fbe85
Parents: 8b843ab
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Mar 2 15:37:47 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:38:51 2017 -0800

----------------------------------------------------------------------
 newt/builder/size.go |  2 +-
 newt/image/image.go  | 10 +++++-----
 2 files changed, 6 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/b6b95992/newt/builder/size.go
----------------------------------------------------------------------
diff --git a/newt/builder/size.go b/newt/builder/size.go
index 70b4dc2..7cdcc45 100644
--- a/newt/builder/size.go
+++ b/newt/builder/size.go
@@ -405,7 +405,7 @@ func (t *TargetBuilder) Size() error {
 
 func (b *Builder) FindPkgNameByArName(arName string) string {
 	for rpkg, bpkg := range b.PkgMap {
-		if (b.ArchivePath(bpkg) == arName) {
+		if b.ArchivePath(bpkg) == arName {
 			return rpkg.Lpkg.FullName()
 		}
 	}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/b6b95992/newt/image/image.go
----------------------------------------------------------------------
diff --git a/newt/image/image.go b/newt/image/image.go
index 82ce3e4..dd09b16 100644
--- a/newt/image/image.go
+++ b/newt/image/image.go
@@ -730,7 +730,7 @@ func NewImageManifestSizeCollector() *ImageManifestSizeCollector {
 }
 
 func (c *ImageManifestSizeCollector) AddPkg(pkg string) *ImageManifestSizePkg {
-	p := &ImageManifestSizePkg {
+	p := &ImageManifestSizePkg{
 		Name: pkg,
 	}
 	c.Pkgs = append(c.Pkgs, p)
@@ -739,7 +739,7 @@ func (c *ImageManifestSizeCollector) AddPkg(pkg string) *ImageManifestSizePkg {
 }
 
 func (c *ImageManifestSizePkg) AddSymbol(file string, sym string, area string,
-					symSz uint32) {
+	symSz uint32) {
 	f := c.addFile(file)
 	s := f.addSym(sym)
 	s.addArea(area, symSz)
@@ -751,7 +751,7 @@ func (p *ImageManifestSizePkg) addFile(file string) *ImageManifestSizeFile {
 			return f
 		}
 	}
-	f := &ImageManifestSizeFile {
+	f := &ImageManifestSizeFile{
 		Name: file,
 	}
 	p.Files = append(p.Files, f)
@@ -760,7 +760,7 @@ func (p *ImageManifestSizePkg) addFile(file string) *ImageManifestSizeFile {
 }
 
 func (f *ImageManifestSizeFile) addSym(sym string) *ImageManifestSizeSym {
-	s := &ImageManifestSizeSym {
+	s := &ImageManifestSizeSym{
 		Name: sym,
 	}
 	f.Syms = append(f.Syms, s)
@@ -769,7 +769,7 @@ func (f *ImageManifestSizeFile) addSym(sym string) *ImageManifestSizeSym {
 }
 
 func (s *ImageManifestSizeSym) addArea(area string, areaSz uint32) {
-	a := &ImageManifestSizeArea {
+	a := &ImageManifestSizeArea{
 		Name: area,
 		Size: areaSz,
 	}


[16/41] incubator-mynewt-newt git commit: MYNEWT-557 Warning override of undefined settings Added support to newt build command to print out warning message for override of undefined settings.

Posted by ma...@apache.org.
MYNEWT-557 Warning override of undefined settings
Added support to newt build command to print out warning message for override of undefined settings.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/c2e1b6c2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/c2e1b6c2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/c2e1b6c2

Branch: refs/heads/mynewt_1_0_0
Commit: c2e1b6c23ef06b21f79ac6c14aad956028872cca
Parents: e5b84cf
Author: cwanda <wa...@happycity.com>
Authored: Fri Feb 3 16:45:58 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:35:36 2017 -0800

----------------------------------------------------------------------
 newt/builder/targetbuild.go | 7 +++++++
 1 file changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/c2e1b6c2/newt/builder/targetbuild.go
----------------------------------------------------------------------
diff --git a/newt/builder/targetbuild.go b/newt/builder/targetbuild.go
index 64710db..b8ac724 100644
--- a/newt/builder/targetbuild.go
+++ b/newt/builder/targetbuild.go
@@ -188,6 +188,13 @@ func (t *TargetBuilder) validateAndWriteCfg() error {
 		return util.NewNewtError(errText)
 	}
 
+	warningText := strings.TrimSpace(t.res.WarningText())
+	if warningText != "" {
+		for _, line := range strings.Split(warningText, "\n") {
+			log.Warn(line)
+		}
+	}
+
 	if err := syscfg.EnsureWritten(t.res.Cfg,
 		GeneratedIncludeDir(t.target.Name())); err != nil {
 


[38/41] incubator-mynewt-newt git commit: Modified Newtmgr help text. It now says "Newtmgr helps you manage remote devices running the Mynewt OS"

Posted by ma...@apache.org.
Modified Newtmgr help text.
It now says "Newtmgr helps you manage remote devices running the Mynewt OS"


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/0c35824d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/0c35824d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/0c35824d

Branch: refs/heads/mynewt_1_0_0
Commit: 0c35824d6cb68720742fa45db4592221ba32e139
Parents: 18c35bf
Author: cwanda <wa...@happycity.com>
Authored: Fri Mar 3 17:52:28 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:39:17 2017 -0800

----------------------------------------------------------------------
 newtmgr/cli/commands.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/0c35824d/newtmgr/cli/commands.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/commands.go b/newtmgr/cli/commands.go
index 8a5d526..2c957a7 100644
--- a/newtmgr/cli/commands.go
+++ b/newtmgr/cli/commands.go
@@ -35,7 +35,7 @@ func Commands() *cobra.Command {
 	logLevelStr := ""
 	nmCmd := &cobra.Command{
 		Use:   "newtmgr",
-		Short: "Newtmgr helps you manage devices running the Mynewt OS",
+		Short: "Newtmgr helps you manage remote devices running the Mynewt OS",
 		PersistentPreRun: func(cmd *cobra.Command, args []string) {
 			NewtmgrLogLevel, err := log.ParseLevel(logLevelStr)
 			err = util.Init(NewtmgrLogLevel, "", util.VERBOSITY_DEFAULT)


[35/41] incubator-mynewt-newt git commit: MYNEWT-651; was using uppercase names in json for memory region data.

Posted by ma...@apache.org.
MYNEWT-651; was using uppercase names in json for memory region data.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/8b843ab4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/8b843ab4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/8b843ab4

Branch: refs/heads/mynewt_1_0_0
Commit: 8b843ab4a4fa843e033981f64e942aa76201ee58
Parents: 9691f96
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Thu Mar 2 13:40:00 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:38:38 2017 -0800

----------------------------------------------------------------------
 newt/image/image.go | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/8b843ab4/newt/image/image.go
----------------------------------------------------------------------
diff --git a/newt/image/image.go b/newt/image/image.go
index 38715e3..82ce3e4 100644
--- a/newt/image/image.go
+++ b/newt/image/image.go
@@ -119,8 +119,8 @@ const (
  * Data that's going to go to build manifest file
  */
 type ImageManifestSizeArea struct {
-	Name string
-	Size uint32
+	Name string `json:"name"`
+	Size uint32 `json:"size"`
 }
 
 type ImageManifestSizeSym struct {


[15/41] incubator-mynewt-newt git commit: newt - Remove obsolete pkg.features setting.

Posted by ma...@apache.org.
newt - Remove obsolete pkg.features setting.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/e5b84cfd
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/e5b84cfd
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/e5b84cfd

Branch: refs/heads/mynewt_1_0_0
Commit: e5b84cfd04887f3963d2a6a0d3789b91774630f1
Parents: c93b4e2
Author: Christopher Collins <cc...@apache.org>
Authored: Sun Feb 5 23:19:11 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:34:12 2017 -0800

----------------------------------------------------------------------
 newt/pkg/localpackage.go | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/e5b84cfd/newt/pkg/localpackage.go
----------------------------------------------------------------------
diff --git a/newt/pkg/localpackage.go b/newt/pkg/localpackage.go
index da7ac65..3ce55e6 100644
--- a/newt/pkg/localpackage.go
+++ b/newt/pkg/localpackage.go
@@ -289,7 +289,6 @@ func (pkg *LocalPackage) Save() error {
 
 	file.WriteString(pkg.sequenceString("pkg.aflags"))
 	file.WriteString(pkg.sequenceString("pkg.cflags"))
-	file.WriteString(pkg.sequenceString("pkg.features"))
 	file.WriteString(pkg.sequenceString("pkg.lflags"))
 
 	return nil


[18/41] incubator-mynewt-newt git commit: newt: More detailed size report command

Posted by ma...@apache.org.
newt: More detailed size report command

This patch improves the output of the size command. New flags
were added for this purpose:

Flags:
  -F, --flash   Print FLASH statistics
  -R, --ram     Print RAM statistics

The size statistics are broken down into a tree-like structure, where
the leaves are symbols and branches are folders and files. For
each tree element there its size in bytes and percentage contribution
to the total size of the memory region.

Path                           Size       %
=============================================
(...)
libc                             32     0.49%
  baselibc                       32     0.49%
    src                          32     0.49%
      malloc.c                   32     0.49%
        __malloc_head            24     0.37%
        malloc_lock               4     0.06%
        malloc_unlock             4     0.06%
(...)

Moreover, there is more memory region info available after specifying
verbose flag(-v):

Mem FLASH: 0x00008000-0x00042000
Mem RAM:   0x20000000-0x20010000

Mem: FLASH
Name                       Size
.ARM.extab                    0
.ARM.exidx                   24
.imghdr                      32
.text                     18624
Total                     18680

Mem: RAM
Name                       Size
.bss                       5656
.stack_dummy                432
.vector_relocation          216
.data                       256
.bssnz                        0
Total                      6560


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/6493620b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/6493620b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/6493620b

Branch: refs/heads/mynewt_1_0_0
Commit: 6493620b088701568d663fae65f67e9b418259f9
Parents: ffdbc54
Author: Micha\u0142 Narajowski <mi...@codecoup.pl>
Authored: Tue Feb 7 12:34:37 2017 +0100
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:36:01 2017 -0800

----------------------------------------------------------------------
 newt/builder/size.go        |  34 +++-
 newt/builder/size_report.go | 332 +++++++++++++++++++++++++++++++++++++++
 newt/builder/symbol_tree.go | 194 +++++++++++++++++++++++
 newt/cli/build_cmds.go      |  18 ++-
 4 files changed, 574 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/6493620b/newt/builder/size.go
----------------------------------------------------------------------
diff --git a/newt/builder/size.go b/newt/builder/size.go
index 970db2d..5ce2939 100644
--- a/newt/builder/size.go
+++ b/newt/builder/size.go
@@ -106,8 +106,8 @@ func MakePkgSize(name string, memSections map[string]*MemSection) *PkgSize {
 /*
  * Go through GCC generated mapfile, and collect info about symbol sizes
  */
-func ParseMapFileSizes(fileName string) (map[string]*PkgSize, map[string]*MemSection,
-	error) {
+func ParseMapFileSizes(fileName string) (map[string]*PkgSize,
+	map[string]*MemSection, error) {
 	var state int = 0
 
 	file, err := os.Open(fileName)
@@ -375,3 +375,33 @@ func (b *Builder) Size() error {
 
 	return nil
 }
+
+func (t *TargetBuilder) SizeReport(ram, flash bool) error {
+
+	err := t.PrepBuild()
+
+	if err != nil {
+		return err
+	}
+
+	fmt.Printf("Size of Application Image: %s\n", t.AppBuilder.buildName)
+	err = t.AppBuilder.SizeReport(ram, flash)
+
+	if err == nil {
+		if t.LoaderBuilder != nil {
+			fmt.Printf("Size of Loader Image: %s\n", t.LoaderBuilder.buildName)
+			err = t.LoaderBuilder.SizeReport(ram, flash)
+		}
+	}
+
+	return err
+}
+
+func (b *Builder) SizeReport(ram, flash bool) error {
+	srcBase := b.targetBuilder.GetTarget().App().Repo().Path() + "/"
+	err := SizeReport(b.AppElfPath(), srcBase, ram, flash)
+	if err != nil {
+		return util.NewNewtError(err.Error())
+	}
+	return nil
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/6493620b/newt/builder/size_report.go
----------------------------------------------------------------------
diff --git a/newt/builder/size_report.go b/newt/builder/size_report.go
new file mode 100644
index 0000000..5c9fa02
--- /dev/null
+++ b/newt/builder/size_report.go
@@ -0,0 +1,332 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package builder
+
+import (
+	"bufio"
+	"fmt"
+	"mynewt.apache.org/newt/util"
+	"os"
+	"os/exec"
+	"strconv"
+	"strings"
+)
+
+func runNmCommand(elfFilePath string) ([]byte, error) {
+	var (
+		cmdOut []byte
+		err    error
+	)
+	cmdName := "arm-none-eabi-nm"
+	cmdArgs := []string{elfFilePath, "-S", "-l", "--size-sort", "--radix=d"}
+
+	if cmdOut, err = exec.Command(cmdName, cmdArgs...).Output(); err != nil {
+		fmt.Fprintln(os.Stderr, "There was an error running nm command: ", err)
+		os.Exit(1)
+	}
+
+	return cmdOut, err
+}
+
+func runObjdumpCommand(elfFilePath string, params string) ([]byte, error) {
+	var (
+		cmdOut []byte
+		err    error
+	)
+	cmdName := "arm-none-eabi-objdump"
+	cmdArgs := []string{params, elfFilePath}
+	if cmdOut, err = exec.Command(cmdName, cmdArgs...).Output(); err != nil {
+		fmt.Fprintln(os.Stderr, "There was an error running objdump command: ",
+			err)
+		os.Exit(1)
+	}
+
+	return cmdOut, err
+}
+
+func loadSymbolsAndPaths(elfFilePath, pathToStrip string) (map[string]string,
+	error) {
+	symbolsPath := make(map[string]string)
+
+	nmOut, err := runNmCommand(elfFilePath)
+	if err != nil {
+		return nil, err
+	}
+
+	lines := strings.Split(string(nmOut), "\n")
+
+	for _, line := range lines {
+		fields := strings.Fields(strings.Replace(line, "\t", " ", -1))
+		if len(fields) < 4 {
+			continue
+		}
+		var path string
+
+		if len(fields) < 5 {
+			path = "(other)"
+		} else {
+			path = strings.Split(fields[4], ":")[0]
+		}
+		if pathToStrip != "" {
+			if strings.Contains(path, pathToStrip) {
+				path = strings.Replace(path, pathToStrip, "", -1)
+			} else {
+				path = "(other)"
+			}
+		}
+		symbolsPath[fields[3]] = path
+	}
+	return symbolsPath, nil
+}
+
+func MakeSymbol(name string, section string, size uint64) *Symbol {
+	symbol := &Symbol{
+		name,
+		section,
+		size,
+	}
+	return symbol
+}
+
+type MemoryRegion struct {
+	Name         string
+	Offset       uint64
+	EndOff       uint64
+	TotalSize    uint64
+	SectionNames map[string]struct{}
+	NamesSizes   map[string]uint64
+}
+
+func MakeMemoryRegion() *MemoryRegion {
+	section := &MemoryRegion{
+		"", 0, 0, 0,
+		make(map[string]struct{}),
+		make(map[string]uint64),
+	}
+	return section
+}
+
+func (m *MemoryRegion) PartOf(addr uint64) bool {
+	return addr >= m.Offset && addr < m.EndOff
+}
+
+func loadSymbolsAndSections(elfFilePath string) (map[string]*Symbol, error) {
+	objdumpOut, err := runObjdumpCommand(elfFilePath, "-tw")
+	if err != nil {
+		return nil, err
+	}
+
+	lines := strings.Split(string(objdumpOut), "\n")
+	symbols := make(map[string]*Symbol)
+	for _, line := range lines {
+		fields := strings.Fields(strings.Replace(line, "\t", " ", -1))
+
+		if len(fields) == 5 {
+			size, err := strconv.ParseUint(fields[3], 16, 64)
+			if err != nil {
+				continue
+			}
+			symbols[fields[4]] = MakeSymbol(fields[4], fields[2], size)
+		} else if len(fields) == 6 {
+			size, err := strconv.ParseUint(fields[4], 16, 64)
+			if err != nil {
+				continue
+			}
+			symbols[fields[5]] = MakeSymbol(fields[5], fields[3], size)
+		}
+
+	}
+
+	return symbols, nil
+}
+
+func generateMemoryRegions(elfFilePath string) (*MemoryRegion, *MemoryRegion,
+	error) {
+
+	mapFile := elfFilePath + ".map"
+	flashRegion, ramRegion, err := parseMapFileRegions(mapFile)
+	if err != nil {
+		return nil, nil, err
+	}
+
+	objdumpOut, err := runObjdumpCommand(elfFilePath, "-hw")
+	if err != nil {
+		return nil, nil, err
+	}
+
+	lines := strings.Split(string(objdumpOut), "\n")
+	for _, line := range lines {
+		fields := strings.Fields(line)
+		if len(fields) < 7 {
+			continue
+		}
+		size, err := strconv.ParseUint(fields[2], 16, 64)
+		if err != nil {
+			continue
+		}
+		address, err := strconv.ParseUint(fields[3], 16, 64)
+		if err != nil {
+			continue
+		}
+
+		if flashRegion.PartOf(address) {
+			flashRegion.TotalSize += size
+			flashRegion.SectionNames[fields[1]] = struct{}{}
+			flashRegion.NamesSizes[fields[1]] = size
+			continue
+		}
+
+		if ramRegion.PartOf(address) {
+			ramRegion.TotalSize += size
+			ramRegion.SectionNames[fields[1]] = struct{}{}
+			ramRegion.NamesSizes[fields[1]] = size
+			continue
+		}
+	}
+
+	return flashRegion, ramRegion, nil
+}
+
+/*
+ * Go through GCC generated mapfile, and collect info about symbol sizes
+ */
+func parseMapFileRegions(fileName string) (*MemoryRegion, *MemoryRegion,
+	error) {
+	var state int = 0
+
+	file, err := os.Open(fileName)
+	if err != nil {
+		return nil, nil, err
+	}
+
+	flashRegion := MakeMemoryRegion()
+	ramRegion := MakeMemoryRegion()
+
+	scanner := bufio.NewScanner(file)
+	for scanner.Scan() {
+		switch state {
+		case 0:
+			if strings.Contains(scanner.Text(), "Memory Configuration") {
+				state = 1
+			}
+		case 1:
+			if strings.Contains(scanner.Text(), "Origin") {
+				state = 2
+			}
+		case 2:
+			if strings.Contains(scanner.Text(), "*default*") {
+				state = 3
+				continue
+			}
+			array := strings.Fields(scanner.Text())
+			offset, err := strconv.ParseUint(array[1], 0, 64)
+			if err != nil {
+				continue
+			}
+			size, err := strconv.ParseUint(array[2], 0, 64)
+			if err != nil {
+				continue
+			}
+			if strings.EqualFold(array[0], "flash") {
+				flashRegion.Name = array[0]
+				flashRegion.Offset = offset
+				flashRegion.EndOff = offset + size
+			} else if strings.EqualFold(array[0], "ram") {
+				ramRegion.Name = array[0]
+				ramRegion.Offset = offset
+				ramRegion.EndOff = offset + size
+			}
+		case 3:
+			fallthrough
+		default:
+			return flashRegion, ramRegion, nil
+		}
+
+	}
+	return flashRegion, flashRegion, nil
+}
+
+func logMemoryRegionStats(flashRegion, ramRegion *MemoryRegion) {
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-10s 0x%08x-0x%08x\n",
+		"Mem FLASH:", flashRegion.Offset, flashRegion.EndOff)
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-10s 0x%08x-0x%08x\n",
+		"Mem RAM:", ramRegion.Offset, ramRegion.EndOff)
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "\n")
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "Mem: FLASH\n")
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10s\n", "Name", "Size")
+	for sectionName, size := range flashRegion.NamesSizes {
+		util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10d\n",
+			sectionName, size)
+	}
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10d\n", "Total",
+		flashRegion.TotalSize)
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "\n")
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "Mem: RAM\n")
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10s\n", "Name", "Size")
+	for sectionName, size := range ramRegion.NamesSizes {
+		util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10d\n",
+			sectionName, size)
+	}
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "%-20s %10d\n", "Total",
+		ramRegion.TotalSize)
+	util.StatusMessage(util.VERBOSITY_VERBOSE, "\n")
+}
+
+func SizeReport(elfFilePath, srcBase string, ram bool, flash bool) error {
+	symbolsPath, err := loadSymbolsAndPaths(elfFilePath, srcBase)
+	if err != nil {
+		return err
+	}
+	loadedSectionSizes, err := loadSymbolsAndSections(elfFilePath)
+	if err != nil {
+		return err
+	}
+	flashRegion, ramRegion, err := generateMemoryRegions(elfFilePath)
+	if err != nil {
+		return err
+	}
+
+	logMemoryRegionStats(flashRegion, ramRegion)
+
+	startPath := "."
+
+	if flash {
+		flashNodes := newFolder(startPath)
+		for _, symbol := range loadedSectionSizes {
+			if _, ok := flashRegion.SectionNames[symbol.Section]; ok {
+				flashNodes.addSymbol(symbol, symbolsPath[symbol.Name])
+			}
+		}
+		fmt.Println("FLASH report:")
+		fmt.Printf("%v", flashNodes.ToString(flashRegion.TotalSize))
+	}
+
+	if ram {
+		ramNodes := newFolder(startPath)
+		for _, symbol := range loadedSectionSizes {
+			if _, ok := ramRegion.SectionNames[symbol.Section]; ok {
+				ramNodes.addSymbol(symbol, symbolsPath[symbol.Name])
+			}
+		}
+		fmt.Println("RAM report:")
+		fmt.Printf("%v", ramNodes.ToString(ramRegion.TotalSize))
+	}
+	return nil
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/6493620b/newt/builder/symbol_tree.go
----------------------------------------------------------------------
diff --git a/newt/builder/symbol_tree.go b/newt/builder/symbol_tree.go
new file mode 100644
index 0000000..ea6202b
--- /dev/null
+++ b/newt/builder/symbol_tree.go
@@ -0,0 +1,194 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package builder
+
+import (
+	"fmt"
+	"sort"
+	"strings"
+)
+
+type Symbol struct {
+	Name    string
+	Section string
+	Size    uint64
+}
+
+type File struct {
+	Name    string
+	Symbols map[string]*Symbol
+}
+
+type Folder struct {
+	Name    string
+	Files   map[string]*File
+	Folders map[string]*Folder
+}
+
+func newFolder(name string) *Folder {
+	return &Folder{name, make(map[string]*File), make(map[string]*Folder)}
+}
+
+func newFile(name string) *File {
+	return &File{name, make(map[string]*Symbol)}
+}
+
+func (f *File) sumSize() uint64 {
+	var sum uint64
+	for _, symbol := range f.Symbols {
+		sum += symbol.Size
+	}
+	return sum
+}
+
+func (f *Folder) sumSize() uint64 {
+	var sum uint64
+	for _, folder := range f.Folders {
+		sum += folder.sumSize()
+	}
+
+	for _, file := range f.Files {
+		sum += file.sumSize()
+	}
+	return sum
+}
+
+func (f *Folder) getFolder(name string) *Folder {
+	if nextF, ok := f.Folders[name]; ok {
+		return nextF
+	} else {
+		f.Folders[name] = newFolder(name)
+		return f.Folders[name]
+	}
+	return &Folder{} // cannot happen
+}
+
+func (f *Folder) getFile(name string) *File {
+	if nextF, ok := f.Files[name]; ok {
+		return nextF
+	} else {
+		f.Files[name] = newFile(name)
+		return f.Files[name]
+	}
+	return &File{} // cannot happen
+}
+
+func (f *File) getSymbol(name string) *Symbol {
+	if nextF, ok := f.Symbols[name]; ok {
+		return nextF
+	} else {
+		f.Symbols[name] = &Symbol{name, "", 0}
+		return f.Symbols[name]
+	}
+	return &Symbol{} // cannot happen
+}
+
+func (f *Folder) addFolder(path []string) *Folder {
+	if len(path) == 1 {
+		// last segment == new folder
+		return f.getFolder(path[0])
+	} else {
+		return f.getFolder(path[0]).addFolder(path[1:])
+	}
+}
+
+func (f *Folder) addFile(path []string) *File {
+	if len(path) == 1 {
+		// last segment == file
+		return f.getFile(path[0])
+	} else {
+		return f.getFolder(path[0]).addFile(path[1:])
+	}
+}
+
+func (f *Folder) addSymbol(symbol *Symbol, path string) *Symbol {
+	segments := strings.Split(path, "/")
+	file := f.addFile(segments)
+	sym := file.getSymbol(symbol.Name)
+	sym.Section = symbol.Section
+	sym.Size += symbol.Size
+	return sym
+}
+
+func (f *File) String(indent string, level int, total uint64) string {
+	var str string
+	if f.sumSize() <= 0 {
+		return ""
+	}
+	size := f.sumSize()
+	percent := 100 * float64(size) / float64(total)
+	str += fmt.Sprintf("%-80s %20d %8.2f%%\n", strings.Repeat(indent, level)+
+		f.Name, size, percent)
+
+	var sorted []string
+	for symName := range f.Symbols {
+		sorted = append(sorted, symName)
+	}
+	sort.Strings(sorted)
+	for _, sym := range sorted {
+		size := f.Symbols[sym].Size
+		percent := 100 * float64(size) / float64(total)
+		if f.Symbols[sym].Size > 0 {
+			str += fmt.Sprintf("%-80s %20d %8.2f%%\n",
+				strings.Repeat(indent, level+1)+
+					f.Symbols[sym].Name,
+				size, percent)
+		}
+	}
+	return str
+}
+
+func (f *Folder) StringRec(indent string, level int, total uint64) string {
+	var str string
+
+	var sorted []string
+	for folderName := range f.Folders {
+		sorted = append(sorted, folderName)
+	}
+	for fileName := range f.Files {
+		sorted = append(sorted, fileName)
+	}
+	sort.Strings(sorted)
+
+	for _, name := range sorted {
+		if folder, ok := f.Folders[name]; ok {
+			size := folder.sumSize()
+			percent := 100 * float64(size) / float64(total)
+			str += fmt.Sprintf("%-80s %20d %8.2f%%\n",
+				strings.Repeat(indent, level)+folder.Name, size, percent)
+			str += folder.StringRec(indent, level+1, total)
+		} else {
+			str += f.Files[name].String(indent, level, total)
+		}
+	}
+	return str
+}
+
+func (f *Folder) ToString(total uint64) string {
+	indent := "  "
+	var str string
+	str += fmt.Sprintf("%-90s %10s %9s\n", "Path", "Size", "%")
+	str += strings.Repeat("=", 111) + "\n"
+	str += f.StringRec(indent, 0, total)
+	str += strings.Repeat("=", 111) + "\n"
+	str += fmt.Sprintf("%90s %10d\n",
+		"Total symbol size (i.e. excluding padding, etc.)", f.sumSize())
+	return str
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/6493620b/newt/cli/build_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/build_cmds.go b/newt/cli/build_cmds.go
index 43cf47e..f0789db 100644
--- a/newt/cli/build_cmds.go
+++ b/newt/cli/build_cmds.go
@@ -358,7 +358,7 @@ func debugRunCmd(cmd *cobra.Command, args []string) {
 	}
 }
 
-func sizeRunCmd(cmd *cobra.Command, args []string) {
+func sizeRunCmd(cmd *cobra.Command, args []string, ram bool, flash bool) {
 	if len(args) < 1 {
 		NewtUsage(cmd, util.NewNewtError("Must specify target"))
 	}
@@ -375,6 +375,13 @@ func sizeRunCmd(cmd *cobra.Command, args []string) {
 		NewtUsage(nil, err)
 	}
 
+	if ram || flash {
+		if err := b.SizeReport(ram, flash); err != nil {
+			NewtUsage(cmd, err)
+		}
+		return
+	}
+
 	if err := b.Size(); err != nil {
 		NewtUsage(cmd, err)
 	}
@@ -452,13 +459,20 @@ func AddBuildCommands(cmd *cobra.Command) {
 	sizeHelpText := "Calculate the size of target components specified by " +
 		"<target-name>."
 
+	var ram, flash bool
 	sizeCmd := &cobra.Command{
 		Use:   "size <target-name>",
 		Short: "Size of target components",
 		Long:  sizeHelpText,
-		Run:   sizeRunCmd,
+		Run: func(cmd *cobra.Command, args []string) {
+			sizeRunCmd(cmd, args, ram, flash)
+		},
 	}
 
+	sizeCmd.Flags().BoolVarP(&ram, "ram", "R", false, "Print RAM statistics")
+	sizeCmd.Flags().BoolVarP(&flash, "flash", "F", false,
+		"Print FLASH statistics")
+
 	cmd.AddCommand(sizeCmd)
 	AddTabCompleteFn(sizeCmd, targetList)
 }


[05/41] incubator-mynewt-newt git commit: MYNEWT-622; use util to generate error message.

Posted by ma...@apache.org.
MYNEWT-622; use util to generate error message.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/3868c59b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/3868c59b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/3868c59b

Branch: refs/heads/mynewt_1_0_0
Commit: 3868c59ba62c261d5af5eb0844ccc128a78e1f5e
Parents: d6502a3
Author: Marko Kiiskila <ma...@runtime.io>
Authored: Sat Feb 11 12:01:30 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:29:58 2017 -0800

----------------------------------------------------------------------
 newtmgr/cli/image.go | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/3868c59b/newtmgr/cli/image.go
----------------------------------------------------------------------
diff --git a/newtmgr/cli/image.go b/newtmgr/cli/image.go
index 10ac1f0..8a3f692 100644
--- a/newtmgr/cli/image.go
+++ b/newtmgr/cli/image.go
@@ -21,7 +21,6 @@ package cli
 
 import (
 	"encoding/hex"
-	"errors"
 	"fmt"
 	"io/ioutil"
 	"os"
@@ -390,7 +389,7 @@ func coreConvertCmd(cmd *cobra.Command, args []string) {
 
 func coreDownloadCmd(cmd *cobra.Command, args []string) {
 	if len(args) < 1 {
-		nmUsage(cmd, errors.New("Need to specify target filename to download"))
+		nmUsage(cmd, util.NewNewtError("Need to specify filename for core"))
 		return
 	}
 


[20/41] incubator-mynewt-newt git commit: newt: limit output width in size command to 80 columns

Posted by ma...@apache.org.
newt: limit output width in size command to 80 columns


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/65aab9c6
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/65aab9c6
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/65aab9c6

Branch: refs/heads/mynewt_1_0_0
Commit: 65aab9c6d70efee78da82a52fbbe1d625741bacd
Parents: f7f8ad8
Author: Micha\u0142 Narajowski <mi...@codecoup.pl>
Authored: Mon Feb 27 12:00:08 2017 +0100
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:36:21 2017 -0800

----------------------------------------------------------------------
 newt/builder/symbol_tree.go | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/65aab9c6/newt/builder/symbol_tree.go
----------------------------------------------------------------------
diff --git a/newt/builder/symbol_tree.go b/newt/builder/symbol_tree.go
index ea6202b..2318da1 100644
--- a/newt/builder/symbol_tree.go
+++ b/newt/builder/symbol_tree.go
@@ -127,6 +127,8 @@ func (f *Folder) addSymbol(symbol *Symbol, path string) *Symbol {
 	return sym
 }
 
+var outputFormatting string = "%-59s %9d %8.2f%%\n"
+
 func (f *File) String(indent string, level int, total uint64) string {
 	var str string
 	if f.sumSize() <= 0 {
@@ -134,7 +136,7 @@ func (f *File) String(indent string, level int, total uint64) string {
 	}
 	size := f.sumSize()
 	percent := 100 * float64(size) / float64(total)
-	str += fmt.Sprintf("%-80s %20d %8.2f%%\n", strings.Repeat(indent, level)+
+	str += fmt.Sprintf(outputFormatting, strings.Repeat(indent, level)+
 		f.Name, size, percent)
 
 	var sorted []string
@@ -146,9 +148,8 @@ func (f *File) String(indent string, level int, total uint64) string {
 		size := f.Symbols[sym].Size
 		percent := 100 * float64(size) / float64(total)
 		if f.Symbols[sym].Size > 0 {
-			str += fmt.Sprintf("%-80s %20d %8.2f%%\n",
-				strings.Repeat(indent, level+1)+
-					f.Symbols[sym].Name,
+			str += fmt.Sprintf(outputFormatting,
+				strings.Repeat(indent, level+1)+ f.Symbols[sym].Name,
 				size, percent)
 		}
 	}
@@ -171,7 +172,7 @@ func (f *Folder) StringRec(indent string, level int, total uint64) string {
 		if folder, ok := f.Folders[name]; ok {
 			size := folder.sumSize()
 			percent := 100 * float64(size) / float64(total)
-			str += fmt.Sprintf("%-80s %20d %8.2f%%\n",
+			str += fmt.Sprintf(outputFormatting,
 				strings.Repeat(indent, level)+folder.Name, size, percent)
 			str += folder.StringRec(indent, level+1, total)
 		} else {
@@ -184,11 +185,11 @@ func (f *Folder) StringRec(indent string, level int, total uint64) string {
 func (f *Folder) ToString(total uint64) string {
 	indent := "  "
 	var str string
-	str += fmt.Sprintf("%-90s %10s %9s\n", "Path", "Size", "%")
-	str += strings.Repeat("=", 111) + "\n"
+	str += fmt.Sprintf("%-59s %9s %9s\n", "Path", "Size", "%")
+	str += strings.Repeat("=", 79) + "\n"
 	str += f.StringRec(indent, 0, total)
-	str += strings.Repeat("=", 111) + "\n"
-	str += fmt.Sprintf("%90s %10d\n",
-		"Total symbol size (i.e. excluding padding, etc.)", f.sumSize())
+	str += strings.Repeat("=", 79) + "\n"
+	str += fmt.Sprintf("%-59s %9d %9s\n",
+		"Total symbol size (i.e. excluding padding, etc.)", f.sumSize(), "")
 	return str
 }


[22/41] incubator-mynewt-newt git commit: 1) Updated help text 2) Changed pkg clone to pkg copy (document has been updated) 3) Removed features from newt vals command. 4) Removed newt complete command.

Posted by ma...@apache.org.
1) Updated help text
2) Changed pkg clone to pkg copy (document has been updated)
3) Removed features from newt vals command.
4) Removed newt complete command.


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/91f6e0be
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/91f6e0be
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/91f6e0be

Branch: refs/heads/mynewt_1_0_0
Commit: 91f6e0be851c8d45e89aa1eea20aea437554a499
Parents: 188d8b6
Author: cwanda <wa...@happycity.com>
Authored: Mon Feb 27 22:53:46 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:36:51 2017 -0800

----------------------------------------------------------------------
 newt/cli/build_cmds.go  | 14 +++++++-------
 newt/cli/image_cmds.go  | 12 ++++++------
 newt/cli/mfg_cmds.go    |  2 +-
 newt/cli/pkg_cmds.go    | 24 ++++++++++++------------
 newt/cli/run_cmds.go    |  4 ++--
 newt/cli/target_cmds.go | 31 +++++++++++++++++--------------
 newt/cli/vals_cmds.go   |  2 +-
 newt/cli/vars.go        |  3 ---
 newt/newt.go            |  8 +++++---
 9 files changed, 51 insertions(+), 49 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/build_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/build_cmds.go b/newt/cli/build_cmds.go
index f0789db..5fb7944 100644
--- a/newt/cli/build_cmds.go
+++ b/newt/cli/build_cmds.go
@@ -390,7 +390,7 @@ func sizeRunCmd(cmd *cobra.Command, args []string, ram bool, flash bool) {
 func AddBuildCommands(cmd *cobra.Command) {
 	buildCmd := &cobra.Command{
 		Use:   "build <target-name> [target-names...]",
-		Short: "Builds one or more targets.",
+		Short: "Build one or more targets",
 		Run:   buildRunCmd,
 	}
 
@@ -401,7 +401,7 @@ func AddBuildCommands(cmd *cobra.Command) {
 
 	cleanCmd := &cobra.Command{
 		Use:   "clean <target-name> [target-names...] | all",
-		Short: "Deletes build artifacts for one or more targets.",
+		Short: "Delete build artifacts for one or more targets",
 		Run:   cleanRunCmd,
 	}
 
@@ -424,7 +424,7 @@ func AddBuildCommands(cmd *cobra.Command) {
 		return append(testablePkgList(), "all", "allexcept")
 	})
 
-	loadHelpText := "Load app image to target for <target-name>."
+	loadHelpText := "Load application image on to the board for <target-name>"
 
 	loadCmd := &cobra.Command{
 		Use:   "load <target-name>",
@@ -437,9 +437,9 @@ func AddBuildCommands(cmd *cobra.Command) {
 	AddTabCompleteFn(loadCmd, targetList)
 
 	loadCmd.PersistentFlags().StringVarP(&extraJtagCmd, "extrajtagcmd", "", "",
-		"extra commands to send to JTAG software")
+		"Extra commands to send to JTAG software")
 
-	debugHelpText := "Open debugger session for <target-name>."
+	debugHelpText := "Open a debugger session for <target-name>"
 
 	debugCmd := &cobra.Command{
 		Use:   "debug <target-name>",
@@ -449,9 +449,9 @@ func AddBuildCommands(cmd *cobra.Command) {
 	}
 
 	debugCmd.PersistentFlags().StringVarP(&extraJtagCmd, "extrajtagcmd", "",
-		"", "extra commands to send to JTAG software")
+		"", "Extra commands to send to JTAG software")
 	debugCmd.PersistentFlags().BoolVarP(&noGDB_flag, "noGDB", "n", false,
-		"don't start GDB from command line")
+		"Do not start GDB from command line")
 
 	cmd.AddCommand(debugCmd)
 	AddTabCompleteFn(debugCmd, targetList)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/image_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/image_cmds.go b/newt/cli/image_cmds.go
index 722c8ca..991c4c5 100644
--- a/newt/cli/image_cmds.go
+++ b/newt/cli/image_cmds.go
@@ -69,16 +69,16 @@ func createImageRunCmd(cmd *cobra.Command, args []string) {
 }
 
 func AddImageCommands(cmd *cobra.Command) {
-	createImageHelpText := "Create image by adding image header to created " +
-		"binary file for <target-name>. Version number in the header is set " +
-		"to be <version>.\n\nTo sign the image give private key as <signing_key>."
-	createImageHelpEx := "  newt create-image <target-name> <version>\n"
-	createImageHelpEx += "  newt create-image my_target1 1.2.0\n"
+	createImageHelpText := "Create an image by adding an image header to the " +
+		"binary file created for <target-name>. Version number in the header is set " +
+		"to be <version>.\n\nTo sign the image give private key as <signing-key> and an optional key-id."
+	createImageHelpEx := "  newt create-image my_target1 1.2.0\n"
 	createImageHelpEx += "  newt create-image my_target1 1.2.0.3\n"
 	createImageHelpEx += "  newt create-image my_target1 1.2.0.3 private.pem\n"
+	createImageHelpEx += "  newt create-image my_target1 1.2.0.3 private.pem 5\n"
 
 	createImageCmd := &cobra.Command{
-		Use:     "create-image",
+		Use:     "create-image <target-name> <version> [signing-key [key-id]]",
 		Short:   "Add image header to target binary",
 		Long:    createImageHelpText,
 		Example: createImageHelpEx,

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/mfg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/mfg_cmds.go b/newt/cli/mfg_cmds.go
index 38816d7..1e35d4e 100644
--- a/newt/cli/mfg_cmds.go
+++ b/newt/cli/mfg_cmds.go
@@ -193,7 +193,7 @@ func AddMfgCommands(cmd *cobra.Command) {
 
 	mfgDeployCmd := &cobra.Command{
 		Use:   "deploy <mfg-package-name> [version #.#.#.#]",
-		Short: "Builds and uploads a manufacturing image (create + load)",
+		Short: "Build and upload a manufacturing image (create + load)",
 		Run:   mfgDeployRunCmd,
 	}
 	mfgCmd.AddCommand(mfgDeployCmd)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index d17e81f..315ae89 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -59,7 +59,7 @@ func pkgNewCmd(cmd *cobra.Command, args []string) {
 
 type dirOperation func(string, string) error
 
-func pkgCloneCmd(cmd *cobra.Command, args []string) {
+func pkgCopyCmd(cmd *cobra.Command, args []string) {
 	pkgCloneOrMoveCmd(cmd, args, util.CopyDir, "Cloning")
 }
 
@@ -243,25 +243,25 @@ func AddPackageCommands(cmd *cobra.Command) {
 	}
 
 	newCmd.PersistentFlags().StringVarP(&NewTypeStr, "type", "t",
-		"pkg", "Type of package to create: pkg, bsp, sdk.  Default pkg.")
+		"pkg", "Type of package to create: pkg, bsp, sdk.")
 
 	pkgCmd.AddCommand(newCmd)
 
-	cloneCmdHelpText := ""
-	cloneCmdHelpEx := ""
+	copyCmdHelpText := "Create a new package <dst-pkg> by cloning <src-pkg>"
+	copyCmdHelpEx := "  newt pkg copy apps/blinky apps/myapp"
 
-	cloneCmd := &cobra.Command{
-		Use:     "clone <srcpkg> <dstpkg>",
-		Short:   "Clone an existing package into another",
-		Long:    cloneCmdHelpText,
-		Example: cloneCmdHelpEx,
-		Run:     pkgCloneCmd,
+	copyCmd := &cobra.Command{
+		Use:     "copy <src-pkg> <dst-pkg>",
+		Short:   "Copy an existing package into another",
+		Long:    copyCmdHelpText,
+		Example: copyCmdHelpEx,
+		Run:     pkgCopyCmd,
 	}
 
-	pkgCmd.AddCommand(cloneCmd)
+	pkgCmd.AddCommand(copyCmd)
 
 	moveCmdHelpText := ""
-	moveCmdHelpEx := ""
+	moveCmdHelpEx := "  newt pkg move apps/blinky apps/myapp"
 
 	moveCmd := &cobra.Command{
 		Use:     "move <oldpkg> <newpkg>",

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/run_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/run_cmds.go b/newt/cli/run_cmds.go
index 55d7bbc..8f923bb 100644
--- a/newt/cli/run_cmds.go
+++ b/newt/cli/run_cmds.go
@@ -99,9 +99,9 @@ func AddRunCommands(cmd *cobra.Command) {
 	}
 
 	runCmd.PersistentFlags().StringVarP(&extraJtagCmd, "extrajtagcmd", "", "",
-		"extra commands to send to JTAG software")
+		"Extra commands to send to JTAG software")
 	runCmd.PersistentFlags().BoolVarP(&noGDB_flag, "noGDB", "n", false,
-		"don't start GDB from command line")
+		"Do not start GDB from command line")
 
 	cmd.AddCommand(runCmd)
 	AddTabCompleteFn(runCmd, func() []string {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/target_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/target_cmds.go b/newt/cli/target_cmds.go
index 54511fa..8888847 100644
--- a/newt/cli/target_cmds.go
+++ b/newt/cli/target_cmds.go
@@ -696,7 +696,7 @@ func AddTargetCommands(cmd *cobra.Command) {
 	targetHelpEx := ""
 	targetCmd := &cobra.Command{
 		Use:     "target",
-		Short:   "Command for manipulating targets",
+		Short:   "Commands to create, delete, configure, and query targets",
 		Long:    targetHelpText,
 		Example: targetHelpEx,
 		Run: func(cmd *cobra.Command, args []string) {
@@ -721,15 +721,19 @@ func AddTargetCommands(cmd *cobra.Command) {
 	targetCmd.AddCommand(showCmd)
 	AddTabCompleteFn(showCmd, targetList)
 
-	setHelpText := "Set a target variable (<var-name>) on target " +
-		"<target-name> to value <value>."
-	setHelpEx := "  newt target set <target-name> <var-name>=<value>\n"
-	setHelpEx += "  newt target set my_target1 var_name=value\n"
-	setHelpEx += "  newt target set my_target1 arch=cortex_m4\n"
-	setHelpEx += "  newt target set my_target1 var_name   (display valid values for <var_name>)"
+	setHelpText := "Set a target variable (<var-name>) on target "
+	setHelpText += "<target-name> to value <value>.\n\n"
+	setHelpText += "Warning: When setting the syscfg variable, a new syscfg.yml file\n"
+	setHelpText += "is created and the current settings are deleted. Only the settings\n"
+	setHelpText += "specified in the command are saved in the syscfg.yml file."
+	setHelpEx := "  newt target set my_target1 build_profile=optimized "
+	setHelpEx += "cflags=\"-DNDEBUG\"\n"
+	setHelpEx += "  newt target set my_target1 "
+	setHelpEx += "syscfg=LOG_NEWTMGR=1:CONFIG_NEWTMGR=0\n"
 
 	setCmd := &cobra.Command{
-		Use:     "set",
+		Use: "set <target-name> <var-name>=<value>" +
+			"[:<var-name>=<value>...]",
 		Short:   "Set target configuration variable",
 		Long:    setHelpText,
 		Example: setHelpEx,
@@ -768,12 +772,11 @@ func AddTargetCommands(cmd *cobra.Command) {
 
 	targetCmd.AddCommand(delCmd)
 
-	copyHelpText := "Create a new target by cloning <src-target>."
-	copyHelpEx := "  newt target copy <src-target> <dst-target>\n"
-	copyHelpEx += "  newt target copy blinky_sim my_target"
+	copyHelpText := "Create a new target <dst-target> by cloning <src-target>"
+	copyHelpEx := "  newt target copy blinky_sim my_target"
 
 	copyCmd := &cobra.Command{
-		Use:     "copy",
+		Use:     "copy <src-target> <dst-target>",
 		Short:   "Copy target",
 		Long:    copyHelpText,
 		Example: copyHelpEx,
@@ -783,7 +786,7 @@ func AddTargetCommands(cmd *cobra.Command) {
 	targetCmd.AddCommand(copyCmd)
 	AddTabCompleteFn(copyCmd, targetList)
 
-	configHelpText := "View and modify a target's system configuration."
+	configHelpText := "View or populate a target's system configuration"
 
 	configCmd := &cobra.Command{
 		Use:   "config",
@@ -799,7 +802,7 @@ func AddTargetCommands(cmd *cobra.Command) {
 	configShowCmd := &cobra.Command{
 		Use:   "show <target>",
 		Short: "View a target's system configuration",
-		Long:  "View a target's system configuration.",
+		Long:  "View a target's system configuration",
 		Run:   targetConfigShowCmd,
 	}
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/vals_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/vals_cmds.go b/newt/cli/vals_cmds.go
index e7b8ccb..267fc79 100644
--- a/newt/cli/vals_cmds.go
+++ b/newt/cli/vals_cmds.go
@@ -55,7 +55,7 @@ func valsRunCmd(cmd *cobra.Command, args []string) {
 }
 
 func AddValsCommands(cmd *cobra.Command) {
-	valsShortHelp := "Displays valid values for the specified element type(s)"
+	valsShortHelp := "Display valid values for the specified element type(s)"
 
 	valsLongHelp := valsShortHelp + ".\n\nElement types:\n    " +
 		strings.Join(VarTypes(), "\n    ")

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/cli/vars.go
----------------------------------------------------------------------
diff --git a/newt/cli/vars.go b/newt/cli/vars.go
index f741b59..7ed25de 100644
--- a/newt/cli/vars.go
+++ b/newt/cli/vars.go
@@ -130,9 +130,6 @@ var varsMap = map[string]func() ([]string, error){
 	"api": func() ([]string, error) {
 		return settingValues("pkg.apis")
 	},
-	"feature": func() ([]string, error) {
-		return settingValues("pkg.features")
-	},
 
 	// Target settings.
 	"build_profile": func() ([]string, error) {

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/91f6e0be/newt/newt.go
----------------------------------------------------------------------
diff --git a/newt/newt.go b/newt/newt.go
index 7ecc608..a09e57c 100644
--- a/newt/newt.go
+++ b/newt/newt.go
@@ -38,6 +38,7 @@ var newtQuiet bool
 var newtVerbose bool
 var newtLogFile string
 var newtNumJobs int
+var newtHelp bool
 
 func newtDfltNumJobs() int {
 	maxProcs := runtime.GOMAXPROCS(0)
@@ -115,12 +116,14 @@ func newtCmd() *cobra.Command {
 		"", "Filename to tee output to")
 	newtCmd.PersistentFlags().IntVarP(&newtNumJobs, "jobs", "j",
 		newtDfltNumJobs(), "Number of concurrent build jobs")
+	newtCmd.PersistentFlags().BoolVarP(&newtHelp, "help", "h",
+		false, "Help for newt commands")
 
-	versHelpText := cli.FormatHelp(`Display the Newt version number.`)
+	versHelpText := cli.FormatHelp(`Display the Newt version number`)
 	versHelpEx := "  newt version"
 	versCmd := &cobra.Command{
 		Use:     "version",
-		Short:   "Display the Newt version number.",
+		Short:   "Display the Newt version number",
 		Long:    versHelpText,
 		Example: versHelpEx,
 		Run: func(cmd *cobra.Command, args []string) {
@@ -137,7 +140,6 @@ func main() {
 	cmd := newtCmd()
 
 	cli.AddBuildCommands(cmd)
-	cli.AddCompleteCommands(cmd)
 	cli.AddImageCommands(cmd)
 	cli.AddPackageCommands(cmd)
 	cli.AddProjectCommands(cmd)


[14/41] incubator-mynewt-newt git commit: Add 'pkg clone' command

Posted by ma...@apache.org.
Add 'pkg clone' command


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/commit/c93b4e25
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/tree/c93b4e25
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/diff/c93b4e25

Branch: refs/heads/mynewt_1_0_0
Commit: c93b4e253bf06f99aacc8c00cd9ea8b1d207a744
Parents: 85bc49b
Author: Fabio Utzig <ut...@utzig.org>
Authored: Tue Feb 14 06:47:16 2017 -0800
Committer: Marko Kiiskila <ma...@runtime.io>
Committed: Mon Mar 6 13:33:55 2017 -0800

----------------------------------------------------------------------
 newt/cli/pkg_cmds.go | 46 +++++++++++++++++++++++++++++++++-------------
 1 file changed, 33 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-newt/blob/c93b4e25/newt/cli/pkg_cmds.go
----------------------------------------------------------------------
diff --git a/newt/cli/pkg_cmds.go b/newt/cli/pkg_cmds.go
index 4fdecca..0ddde3d 100644
--- a/newt/cli/pkg_cmds.go
+++ b/newt/cli/pkg_cmds.go
@@ -48,7 +48,17 @@ func pkgNewCmd(cmd *cobra.Command, args []string) {
 	}
 }
 
+type dirOperation func(string, string) error
+
+func pkgCloneCmd(cmd *cobra.Command, args []string) {
+	pkgCloneOrMoveCmd(cmd, args, util.CopyDir, "Cloning");
+}
+
 func pkgMoveCmd(cmd *cobra.Command, args []string) {
+	pkgCloneOrMoveCmd(cmd, args, util.MoveDir, "Moving");
+}
+
+func pkgCloneOrMoveCmd(cmd *cobra.Command, args []string, dirOpFn dirOperation, opStr string) {
 	if len(args) != 2 {
 		NewtUsage(cmd, util.NewNewtError("Exactly two arguments required to pkg move"))
 	}
@@ -63,12 +73,13 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	if err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
-	defer os.Chdir(wd)
 
 	if err := os.Chdir(proj.Path() + "/"); err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
 
+	defer os.Chdir(wd)
+
 	/* Find source package, defaulting search to the local project if no
 	 * repository descriptor is found.
 	 */
@@ -113,10 +124,10 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 			"use pkg delete first"))
 	}
 
-	util.StatusMessage(util.VERBOSITY_DEFAULT, "Moving package %s to %s\n",
-		srcLoc, dstLoc)
+	util.StatusMessage(util.VERBOSITY_DEFAULT, "%s package %s to %s\n",
+		opStr, srcLoc, dstLoc)
 
-	if err := util.MoveDir(srcPkg.BasePath(), dstPath); err != nil {
+	if err := dirOpFn(srcPkg.BasePath(), dstPath); err != nil {
 		NewtUsage(cmd, err)
 	}
 
@@ -137,7 +148,7 @@ func pkgMoveCmd(cmd *cobra.Command, args []string) {
 	 * directory.
 	 */
 	if path.Base(pkgName) != path.Base(srcPkg.Name()) {
-		util.MoveDir(dstPath+"/include/"+path.Base(srcPkg.Name()),
+		dirOpFn(dstPath+"/include/"+path.Base(srcPkg.Name()),
 			dstPath+"/include/"+path.Base(pkgName))
 	}
 }
@@ -154,17 +165,18 @@ func pkgRemoveCmd(cmd *cobra.Command, args []string) {
 	if err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
-	defer os.Chdir(wd)
 
 	if err := os.Chdir(proj.Path() + "/"); err != nil {
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
+
+	defer os.Chdir(wd)
+
 	/* Resolve package, and get path from package to ensure we're being asked
 	 * to remove a valid path.
 	 */
 	repoName, pkgName, err := newtutil.ParsePackageString(args[0])
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -172,7 +184,6 @@ func pkgRemoveCmd(cmd *cobra.Command, args []string) {
 	if repoName != "" {
 		repo = proj.FindRepo(repoName)
 		if repo == nil {
-			os.Chdir(wd)
 			NewtUsage(cmd, util.NewNewtError("Destination repo "+
 				repoName+" does not exist"))
 		}
@@ -180,7 +191,6 @@ func pkgRemoveCmd(cmd *cobra.Command, args []string) {
 
 	pkg, err := pkg.LoadLocalPackage(repo, pkgName)
 	if err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, err)
 	}
 
@@ -188,11 +198,8 @@ func pkgRemoveCmd(cmd *cobra.Command, args []string) {
 		args[0])
 
 	if err := os.RemoveAll(pkg.BasePath()); err != nil {
-		os.Chdir(wd)
 		NewtUsage(cmd, util.ChildNewtError(err))
 	}
-
-	os.Chdir(wd)
 }
 
 func AddPackageCommands(cmd *cobra.Command) {
@@ -231,11 +238,24 @@ func AddPackageCommands(cmd *cobra.Command) {
 
 	pkgCmd.AddCommand(newCmd)
 
+	cloneCmdHelpText := ""
+	cloneCmdHelpEx := ""
+
+	cloneCmd := &cobra.Command{
+		Use:     "clone <srcpkg> <dstpkg>",
+		Short:   "Clone an existing package into another",
+		Long:    cloneCmdHelpText,
+		Example: cloneCmdHelpEx,
+		Run:     pkgCloneCmd,
+	}
+
+	pkgCmd.AddCommand(cloneCmd)
+
 	moveCmdHelpText := ""
 	moveCmdHelpEx := ""
 
 	moveCmd := &cobra.Command{
-		Use:     "move",
+		Use:     "move <oldpkg> <newpkg>",
 		Short:   "Move a package from one location to another",
 		Long:    moveCmdHelpText,
 		Example: moveCmdHelpEx,