github.com/arduino/arduino-cloud-cli@v0.0.0-20240517070944-e7a449561083/command/device/list.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 device 19 20 import ( 21 "context" 22 "fmt" 23 "strings" 24 25 "github.com/arduino/arduino-cloud-cli/config" 26 "github.com/arduino/arduino-cloud-cli/internal/iot" 27 ) 28 29 // ListParams contains the optional parameters needed 30 // to filter the devices to be listed. 31 type ListParams struct { 32 Tags map[string]string // If tags are provided, only devices that have all these tags are listed. 33 DeviceIds string // If ids are provided, only devices with these ids are listed. 34 } 35 36 // List command is used to list 37 // the devices of Arduino IoT Cloud. 38 func List(ctx context.Context, params *ListParams, cred *config.Credentials) ([]DeviceInfo, error) { 39 iotClient, err := iot.NewClient(cred) 40 if err != nil { 41 return nil, err 42 } 43 44 foundDevices, err := iotClient.DeviceList(ctx, params.Tags) 45 if err != nil { 46 return nil, err 47 } 48 var deviceIdFilter []string 49 if params.DeviceIds != "" { 50 deviceIdFilter = strings.Split(params.DeviceIds, ",") 51 for i := range deviceIdFilter { 52 deviceIdFilter[i] = strings.TrimSpace(deviceIdFilter[i]) 53 } 54 } 55 56 var devices []DeviceInfo 57 for _, foundDev := range foundDevices { 58 if len(deviceIdFilter) > 0 && !sliceContains(deviceIdFilter, foundDev.Id) { 59 continue 60 } 61 dev, err := getDeviceInfo(&foundDev) 62 if err != nil { 63 return nil, fmt.Errorf("parsing device %s from cloud: %w", foundDev.Id, err) 64 } 65 devices = append(devices, *dev) 66 } 67 68 return devices, nil 69 } 70 71 func sliceContains(s []string, v string) bool { 72 for i := range s { 73 if v == s[i] { 74 return true 75 } 76 } 77 return false 78 }