|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "path" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/arduino/go-paths-helper" |
| 10 | + |
| 11 | + "github.com/arduino/remoteocd/board" |
| 12 | + "github.com/arduino/remoteocd/feedback" |
| 13 | +) |
| 14 | + |
| 15 | +const binaryDir = "/tmp/remoteocd/" |
| 16 | +const binaryName = "sketch.elf-zsk.bin" |
| 17 | + |
| 18 | +func flash(ctx context.Context, cmder board.Boarder, binary *paths.Path, files []*paths.Path) error { |
| 19 | + err := cmder.MkDirAll(ctx, binaryDir) |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
| 23 | + |
| 24 | + feedback.Logf("Pushing binary %q", binary) |
| 25 | + remoteBinary, err := pushBinary(ctx, cmder, binary) |
| 26 | + if err != nil { |
| 27 | + return err |
| 28 | + } |
| 29 | + |
| 30 | + feedback.Logf("Pushing config files: %v", files) |
| 31 | + remoteFiles, err := pushFiles(ctx, cmder, files) |
| 32 | + if err != nil { |
| 33 | + return err |
| 34 | + } |
| 35 | + |
| 36 | + args := makeOpenOCDCmd(remoteBinary, remoteFiles...) |
| 37 | + feedback.Logf("Running command: %s", strings.Join(args, " ")) |
| 38 | + err = cmder.Run(ctx, args...) |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("error running OpenOCD: %w", err) |
| 41 | + } |
| 42 | + |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +func pushBinary(ctx context.Context, cmder board.Boarder, binary *paths.Path) (string, error) { |
| 47 | + destination := path.Join(binaryDir, binaryName) |
| 48 | + |
| 49 | + if err := cmder.CopyTo(ctx, binary.String(), destination); err != nil { |
| 50 | + return "", err |
| 51 | + } |
| 52 | + |
| 53 | + return destination, nil |
| 54 | +} |
| 55 | + |
| 56 | +func pushFiles(ctx context.Context, cmder board.Boarder, files []*paths.Path) ([]string, error) { |
| 57 | + remoteFiles := make([]string, 0, len(files)) |
| 58 | + for _, file := range files { |
| 59 | + destination := path.Join(binaryDir, file.Base()) |
| 60 | + |
| 61 | + if err := cmder.CopyTo(ctx, file.String(), destination); err != nil { |
| 62 | + return nil, err |
| 63 | + } |
| 64 | + |
| 65 | + remoteFiles = append(remoteFiles, destination) |
| 66 | + } |
| 67 | + |
| 68 | + return remoteFiles, nil |
| 69 | +} |
| 70 | + |
| 71 | +const openOCDPath = "/opt/openocd" |
| 72 | +const openOCDBin = openOCDPath + "/bin/openocd" |
| 73 | + |
| 74 | +func makeOpenOCDCmd(binary string, files ...string) []string { |
| 75 | + args := []string{ |
| 76 | + openOCDBin, "-d2", |
| 77 | + "-s", openOCDPath, |
| 78 | + "-s", openOCDPath + "/share/openocd/scripts", |
| 79 | + "-f", "openocd_gpiod.cfg", |
| 80 | + "-c", "set filename " + binary, |
| 81 | + } |
| 82 | + for _, file := range files { |
| 83 | + args = append(args, "-f", file) |
| 84 | + } |
| 85 | + return args |
| 86 | +} |
0 commit comments