Exemple #1
0
import (
	"github.com/TheThingsNetwork/ttn/ttnctl/util"
	"github.com/apex/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var devicesCmd = &cobra.Command{
	Use:     "devices",
	Aliases: []string{"device"},
	Short:   "Manage devices",
	Long:    `ttnctl devices can be used to manage devices.`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		RootCmd.PersistentPreRun(cmd, args)
		util.GetAccount(ctx)
		ctx.WithFields(log.Fields{
			"AppID":  util.GetAppID(ctx),
			"AppEUI": util.GetAppEUI(ctx),
		}).Info("Using Application")
	},
}

func init() {
	RootCmd.AddCommand(devicesCmd)
	devicesCmd.PersistentFlags().String("app-id", "", "The app ID to use")
	viper.BindPFlag("app-id", devicesCmd.PersistentFlags().Lookup("app-id"))
	devicesCmd.PersistentFlags().String("app-eui", "", "The app EUI to use")
	viper.BindPFlag("app-eui", devicesCmd.PersistentFlags().Lookup("app-eui"))
}
`,
	Run: func(cmd *cobra.Command, args []string) {

		var err error

		if len(args) == 0 {
			ctx.Fatalf("Device ID is required")
		}

		devID := args[0]
		if !api.ValidID(devID) {
			ctx.Fatalf("Invalid Device ID") // TODO: Add link to wiki explaining device IDs
		}

		appID := util.GetAppID(ctx)
		appEUI := util.GetAppEUI(ctx)

		var devEUI types.DevEUI
		if len(args) > 1 {
			devEUI, err = types.ParseDevEUI(args[1])
			if err != nil {
				ctx.Fatalf("Invalid DevEUI: %s", err)
			}
		} else {
			ctx.Info("Generating random DevEUI...")
			copy(devEUI[1:], random.Bytes(7))
		}

		var appKey types.AppKey
		if len(args) > 2 {
			appKey, err = types.ParseAppKey(args[2])