Skip to content

Commit 9f967f9

Browse files
committed
Refactored code structure similarly to Arduino CLI
1 parent 5926613 commit 9f967f9

File tree

8 files changed

+128
-113
lines changed

8 files changed

+128
-113
lines changed

cli/cli.go

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// This file is part of FirmwareUploader
2+
// Copyright (C) 2021 ARDUINO SA (http://www.arduino.cc/)
3+
// This library is free software; you can redistribute it and/or
4+
// modify it under the terms of the GNU Lesser General Public
5+
// License as published by the Free Software Foundation; either
6+
// version 2.1 of the License, or (at your option) any later version.
7+
// This library is distributed in the hope that it will be useful,
8+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
9+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10+
// Lesser General Public License for more details.
11+
// You should have received a copy of the GNU Lesser General Public
12+
// License along with this library; if not, write to the Free Software
13+
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
14+
// USA
15+
16+
package cli
17+
18+
import (
19+
"encoding/json"
20+
"fmt"
21+
"log"
22+
"os"
23+
"strings"
24+
"time"
25+
26+
"github.com/arduino/FirmwareUploader/modules/nina"
27+
"github.com/arduino/FirmwareUploader/modules/sara"
28+
"github.com/arduino/FirmwareUploader/modules/winc"
29+
"github.com/arduino/FirmwareUploader/utils"
30+
"github.com/arduino/FirmwareUploader/utils/context"
31+
"github.com/arduino/go-paths-helper"
32+
"github.com/spf13/cobra"
33+
)
34+
35+
var ctx = &context.Context{}
36+
37+
func NewCommand() *cobra.Command {
38+
// FirmwareUploader is the root command
39+
firmwareUploaderCli := &cobra.Command{
40+
Use: "FirmwareUploader",
41+
Short: "FirmwareUploader.",
42+
Long: "FirmwareUploader (FirmwareUploader).",
43+
Example: " " + os.Args[0] + " <command> [flags...]",
44+
Args: cobra.NoArgs,
45+
Run: run,
46+
}
47+
48+
firmwareUploaderCli.Flags().StringVar(&ctx.PortName, "port", "", "serial port to use for flashing")
49+
firmwareUploaderCli.Flags().StringVar(&ctx.RootCertDir, "certs", "", "root certificate directory")
50+
firmwareUploaderCli.Flags().StringSliceVar(&ctx.Addresses, "address", []string{}, "address (host:port) to fetch and flash root certificate for, multiple values allowed")
51+
firmwareUploaderCli.Flags().StringVar(&ctx.FirmwareFile, "firmware", "", "firmware file to flash")
52+
firmwareUploaderCli.Flags().BoolVar(&ctx.ReadAll, "read", false, "read all firmware and output to stdout")
53+
firmwareUploaderCli.Flags().StringVar(&ctx.FWUploaderBinary, "flasher", "", "firmware upload binary (precompiled for the right target)")
54+
firmwareUploaderCli.Flags().StringVar(&ctx.BinaryToRestore, "restore_binary", "", "binary to restore after the firmware upload (precompiled for the right target)")
55+
firmwareUploaderCli.Flags().StringVar(&ctx.ProgrammerPath, "programmer", "", "path of programmer in use (avrdude/bossac)")
56+
firmwareUploaderCli.Flags().StringVar(&ctx.Model, "model", "", "module model (winc, nina or sara)")
57+
firmwareUploaderCli.Flags().StringVar(&ctx.BoardName, "get_available_for", "", "Ask for available firmwares matching a given board")
58+
firmwareUploaderCli.Flags().IntVar(&ctx.Retries, "retries", 9, "Number of retries in case of upload failure")
59+
60+
return firmwareUploaderCli
61+
}
62+
63+
func run(cmd *cobra.Command, args []string) {
64+
if ctx.BoardName != "" {
65+
el, _ := json.Marshal(utils.GetCompatibleWith(ctx.BoardName, ""))
66+
fmt.Println(string(el))
67+
os.Exit(0)
68+
}
69+
70+
if ctx.PortName == "" {
71+
log.Fatal("Please specify a serial port")
72+
}
73+
74+
if ctx.BinaryToRestore != "" {
75+
// sanity check for BinaryToRestore
76+
f := paths.New(ctx.BinaryToRestore)
77+
info, err := f.Stat()
78+
if err != nil {
79+
log.Fatalf("Error opening restore_binary: %s", err)
80+
}
81+
if info.IsDir() {
82+
log.Fatalf("Error opening restore_binary: is a directory...")
83+
}
84+
if info.Size() == 0 {
85+
log.Println("WARNING: restore_binary is empty! Will not restore binary after upload.")
86+
ctx.BinaryToRestore = ""
87+
}
88+
}
89+
90+
retry := 0
91+
for {
92+
var err error
93+
if ctx.Model == "nina" || strings.Contains(ctx.FirmwareFile, "NINA") || strings.Contains(ctx.FWUploaderBinary, "NINA") {
94+
err = nina.Run(ctx)
95+
} else if ctx.Model == "winc" || strings.Contains(ctx.FirmwareFile, "WINC") || strings.Contains(ctx.FWUploaderBinary, "WINC") {
96+
err = winc.Run(ctx)
97+
} else {
98+
err = sara.Run(ctx)
99+
}
100+
if err == nil {
101+
log.Println("Operation completed: success! :-)")
102+
break
103+
}
104+
log.Println("Error: " + err.Error())
105+
106+
if retry >= ctx.Retries {
107+
log.Fatal("Operation failed. :-(")
108+
}
109+
110+
retry++
111+
log.Println("Waiting 1 second before retrying...")
112+
time.Sleep(time.Second)
113+
log.Printf("Retrying upload (%d of %d)", retry, ctx.Retries)
114+
}
115+
}

main.go

Lines changed: 4 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,14 @@
11
package main
22

33
import (
4-
"encoding/json"
5-
"flag"
6-
"fmt"
7-
"log"
84
"os"
9-
"strings"
10-
"time"
115

12-
"github.com/arduino/FirmwareUploader/modules/nina"
13-
"github.com/arduino/FirmwareUploader/modules/sara"
14-
"github.com/arduino/FirmwareUploader/modules/winc"
15-
"github.com/arduino/FirmwareUploader/utils"
16-
"github.com/arduino/FirmwareUploader/utils/context"
17-
"github.com/arduino/go-paths-helper"
6+
"github.com/arduino/FirmwareUploader/cli"
187
)
198

20-
var ctx = &context.Context{}
21-
22-
func init() {
23-
flag.StringVar(&ctx.PortName, "port", "", "serial port to use for flashing")
24-
flag.StringVar(&ctx.RootCertDir, "certs", "", "root certificate directory")
25-
flag.Var(&ctx.Addresses, "address", "address (host:port) to fetch and flash root certificate for, multiple values allowed")
26-
flag.StringVar(&ctx.FirmwareFile, "firmware", "", "firmware file to flash")
27-
flag.BoolVar(&ctx.ReadAll, "read", false, "read all firmware and output to stdout")
28-
flag.StringVar(&ctx.FWUploaderBinary, "flasher", "", "firmware upload binary (precompiled for the right target)")
29-
flag.StringVar(&ctx.BinaryToRestore, "restore_binary", "", "binary to restore after the firmware upload (precompiled for the right target)")
30-
flag.StringVar(&ctx.ProgrammerPath, "programmer", "", "path of programmer in use (avrdude/bossac)")
31-
flag.StringVar(&ctx.Model, "model", "", "module model (winc, nina or sara)")
32-
flag.StringVar(&ctx.Compatible, "get_available_for", "", "Ask for available firmwares matching a given board")
33-
flag.IntVar(&ctx.Retries, "retries", 9, "Number of retries in case of upload failure")
34-
}
35-
369
func main() {
37-
flag.Parse()
38-
if ctx.Compatible != "" {
39-
el, _ := json.Marshal(utils.GetCompatibleWith(ctx.Compatible, ""))
40-
fmt.Println(string(el))
41-
os.Exit(0)
42-
}
43-
44-
if ctx.PortName == "" {
45-
log.Fatal("Please specify a serial port")
46-
}
47-
48-
if ctx.BinaryToRestore != "" {
49-
// sanity check for BinaryToRestore
50-
f := paths.New(ctx.BinaryToRestore)
51-
info, err := f.Stat()
52-
if err != nil {
53-
log.Fatalf("Error opening restore_binary: %s", err)
54-
}
55-
if info.IsDir() {
56-
log.Fatalf("Error opening restore_binary: is a directory...")
57-
}
58-
if info.Size() == 0 {
59-
log.Println("WARNING: restore_binary is empty! Will not restore binary after upload.")
60-
ctx.BinaryToRestore = ""
61-
}
62-
}
63-
64-
retry := 0
65-
for {
66-
var ctxCopy context.Context
67-
ctxCopy = *ctx
68-
var err error
69-
if ctx.Model == "nina" || strings.Contains(ctx.FirmwareFile, "NINA") || strings.Contains(ctx.FWUploaderBinary, "NINA") {
70-
err = nina.Run(&ctxCopy)
71-
} else if ctx.Model == "winc" || strings.Contains(ctx.FirmwareFile, "WINC") || strings.Contains(ctx.FWUploaderBinary, "WINC") {
72-
err = winc.Run(&ctxCopy)
73-
} else {
74-
err = sara.Run(&ctxCopy)
75-
}
76-
if err == nil {
77-
log.Println("Operation completed: success! :-)")
78-
break
79-
}
80-
log.Println("Error: " + err.Error())
81-
82-
if retry >= ctx.Retries {
83-
log.Fatal("Operation failed. :-(")
84-
}
85-
86-
retry++
87-
log.Println("Waiting 1 second before retrying...")
88-
time.Sleep(time.Second)
89-
log.Printf("Retrying upload (%d of %d)", retry, ctx.Retries)
10+
uploaderCmd := cli.NewCommand()
11+
if err := uploaderCmd.Execute(); err != nil {
12+
os.Exit(1)
9013
}
9114
}

modules/nina/main.go renamed to modules/nina/nina.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,16 @@ import (
3131
"github.com/arduino/FirmwareUploader/programmers/avrdude"
3232
"github.com/arduino/FirmwareUploader/programmers/bossac"
3333
"github.com/arduino/FirmwareUploader/programmers/rp2040load"
34+
"github.com/arduino/FirmwareUploader/utils"
3435
"github.com/arduino/FirmwareUploader/utils/context"
3536
"github.com/pkg/errors"
3637
)
3738

3839
var flasher *Flasher
3940
var payloadSize uint16
40-
var programmer context.Programmer
4141

4242
func Run(ctx *context.Context) error {
43+
var programmer utils.Programmer
4344

4445
if ctx.ProgrammerPath != "" {
4546
if strings.Contains(filepath.Base(ctx.ProgrammerPath), "bossac") {

modules/sara/main.go renamed to modules/sara/sara.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import (
3232

3333
var flasher *Flasher
3434
var payloadSize uint16
35-
var programmer context.Programmer
3635

3736
func Run(ctx *context.Context) error {
3837
programmer := bossac.NewBossac(ctx)
File renamed without changes.

utils/context/context.go

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,15 @@
11
package context
22

3-
import (
4-
"fmt"
5-
6-
"github.com/arduino/arduino-cli/arduino/serialutils"
7-
)
8-
9-
type addressFlags []string
10-
11-
func (af *addressFlags) String() string {
12-
return fmt.Sprint(*af)
13-
}
14-
15-
func (af *addressFlags) Set(value string) error {
16-
*af = append(*af, value)
17-
return nil
18-
}
19-
203
type Context struct {
214
PortName string
225
RootCertDir string
23-
Addresses addressFlags
6+
Addresses []string
247
FirmwareFile string
258
FWUploaderBinary string
269
ReadAll bool
2710
BinaryToRestore string
2811
ProgrammerPath string
2912
Model string
30-
Compatible string
13+
BoardName string
3114
Retries int
3215
}
33-
34-
type Programmer interface {
35-
Flash(filename string, cb *serialutils.ResetProgressCallbacks) error
36-
}

utils/flasher.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"log"
55
"time"
66

7+
"github.com/arduino/arduino-cli/arduino/serialutils"
78
"go.bug.st/serial"
89
)
910

@@ -16,6 +17,10 @@ var baudRates = []int{
1617
38400,
1718
}
1819

20+
type Programmer interface {
21+
Flash(filename string, cb *serialutils.ResetProgressCallbacks) error
22+
}
23+
1924
func OpenSerial(portName string) (serial.Port, error) {
2025
var lastError error
2126

utils/utils.go

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,6 @@ type combo struct {
1919
loader string
2020
}
2121

22-
func isPreferred(path string) bool {
23-
if path == "" {
24-
return false
25-
}
26-
return true
27-
}
28-
2922
func GetCompatibleWith(name string, rootPath string) map[string][]firmware {
3023

3124
files := make(map[string][]firmware)

0 commit comments

Comments
 (0)