github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/cli/thing/bind.go (about)

     1  // This file is part of arduino-cloud-cli.
     2  //
     3  // Copyright (C) 2021 ARDUINO SA (http://www.arduino.cc/)
     4  //
     5  // This program is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Affero General Public License as published
     7  // by the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // This program is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU Affero General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Affero General Public License
    16  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    17  
    18  package thing
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"os"
    24  
    25  	"github.com/arduino/arduino-cli/cli/errorcodes"
    26  	"github.com/arduino/arduino-cli/cli/feedback"
    27  	"github.com/arduino/arduino-cloud-cli/command/thing"
    28  	"github.com/arduino/arduino-cloud-cli/config"
    29  	"github.com/sirupsen/logrus"
    30  	"github.com/spf13/cobra"
    31  )
    32  
    33  type bindFlags struct {
    34  	id       string
    35  	deviceID string
    36  }
    37  
    38  func initBindCommand() *cobra.Command {
    39  	flags := &bindFlags{}
    40  	bindCommand := &cobra.Command{
    41  		Use:   "bind",
    42  		Short: "Bind a thing to a device",
    43  		Long:  "Bind a thing to a device on Arduino IoT Cloud",
    44  		Run: func(cmd *cobra.Command, args []string) {
    45  			if err := runBindCommand(flags); err != nil {
    46  				feedback.Errorf("Error during thing bind: %v", err)
    47  				os.Exit(errorcodes.ErrGeneric)
    48  			}
    49  		},
    50  	}
    51  	bindCommand.Flags().StringVarP(&flags.id, "id", "i", "", "Thing ID")
    52  	bindCommand.Flags().StringVarP(&flags.deviceID, "device-id", "d", "", "Device ID")
    53  	bindCommand.MarkFlagRequired("id")
    54  	bindCommand.MarkFlagRequired("device-id")
    55  	return bindCommand
    56  }
    57  
    58  func runBindCommand(flags *bindFlags) error {
    59  	logrus.Infof("Binding thing %s to device %s", flags.id, flags.deviceID)
    60  
    61  	cred, err := config.RetrieveCredentials()
    62  	if err != nil {
    63  		return fmt.Errorf("retrieving credentials: %w", err)
    64  	}
    65  
    66  	params := &thing.BindParams{
    67  		ID:       flags.id,
    68  		DeviceID: flags.deviceID,
    69  	}
    70  	if err = thing.Bind(context.TODO(), params, cred); err != nil {
    71  		return err
    72  	}
    73  
    74  	logrus.Info("Thing-Device bound successfully updated")
    75  	return nil
    76  }