|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + |
| 10 | + "github.com/arduino/arduino-cli/cli/instance" |
| 11 | + "github.com/arduino/arduino-cli/commands/board" |
| 12 | + "github.com/arduino/arduino-cli/commands/upload" |
| 13 | + "github.com/arduino/arduino-cli/configuration" |
| 14 | + rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1" |
| 15 | + "github.com/arduino/iot-cloud-cli/arduino" |
| 16 | + "github.com/sirupsen/logrus" |
| 17 | +) |
| 18 | + |
| 19 | +type commander struct { |
| 20 | + *rpc.Instance |
| 21 | +} |
| 22 | + |
| 23 | +// NewCommander instantiates and returns a new arduino-cli commander that allows to |
| 24 | +// programmatically call arduino-cli commands. |
| 25 | +// It directly imports the golang packages of the arduino-cli. |
| 26 | +func NewCommander() (arduino.Commander, error) { |
| 27 | + // Discard arduino-cli log messages |
| 28 | + logrus.SetOutput(ioutil.Discard) |
| 29 | + // Initialize arduino-cli configuration |
| 30 | + configuration.Settings = configuration.Init(configuration.FindConfigFileInArgsOrWorkingDirectory(os.Args)) |
| 31 | + // Create arduino-cli instance, needed to execute arduino-cli commands |
| 32 | + inst, err := instance.CreateInstance() |
| 33 | + if err != nil { |
| 34 | + err = fmt.Errorf("%s: %w", "creating arduino-cli instance", err) |
| 35 | + return nil, err |
| 36 | + } |
| 37 | + |
| 38 | + cmd := &commander{inst} |
| 39 | + return cmd, nil |
| 40 | +} |
| 41 | + |
| 42 | +// BoardList executes the 'arduino-cli board list' command |
| 43 | +// and returns its result. |
| 44 | +func (c *commander) BoardList() ([]*rpc.DetectedPort, error) { |
| 45 | + ports, err := board.List(c.GetId()) |
| 46 | + if err != nil { |
| 47 | + err = fmt.Errorf("%s: %w", "detecting boards", err) |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + return ports, nil |
| 51 | +} |
| 52 | + |
| 53 | +// UploadBin executes the 'arduino-cli upload -i' command |
| 54 | +// and returns its result. |
| 55 | +func (c *commander) UploadBin(fqbn, bin, port string) error { |
| 56 | + req := &rpc.UploadRequest{ |
| 57 | + Instance: c.Instance, |
| 58 | + Fqbn: fqbn, |
| 59 | + SketchPath: filepath.Dir(bin), |
| 60 | + ImportFile: bin, |
| 61 | + Port: port, |
| 62 | + Verbose: false, |
| 63 | + } |
| 64 | + |
| 65 | + if _, err := upload.Upload(context.Background(), req, os.Stdout, os.Stderr); err != nil { |
| 66 | + err = fmt.Errorf("%s: %w", "uploading binary", err) |
| 67 | + return err |
| 68 | + } |
| 69 | + |
| 70 | + return nil |
| 71 | +} |
0 commit comments