Skip to content

Commit e107efa

Browse files
aykevldeadprogram
authored andcommitted
main: detect specific serial port IDs based on USB vid/pid
This makes it possible to flash a board even when there are multiple different kinds of boards attached, e.g. an Arduino Uno and a Circuit Playground Express. You can find the VID/PID pair in several ways: 1. By running `lsusb` before and after attaching the board and looking at the new USB device. 2. By grepping for `usb_PID` and `usb_VID` in the TinyGo source code. 3. By checking the Arduino IDE boards.txt from the vendor. Note that one board may have multiple VID/PID pairs: * The bootloader and main program may have a different PID, so far I've seen that the main program generally has the bootloader PID with 0x8000 added. * The software running on the board may have an erroneous PID, for example from a different board. I've seen this happen a few times. * A single board may have had some revisions which changed the PID. This is particularly true for the Arduino Uno. As a fallback, if the given VID/PID pair isn't found, the whole set of serial ports will be used. There are many boards which I haven't included yet simply because I couldn't test them.
1 parent 8e33f1c commit e107efa

File tree

10 files changed

+74
-6
lines changed

10 files changed

+74
-6
lines changed

compileopts/target.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ type TargetSpec struct {
4545
FlashCommand string `json:"flash-command"`
4646
GDB []string `json:"gdb"`
4747
PortReset string `json:"flash-1200-bps-reset"`
48+
SerialPort []string `json:"serial-port"` // serial port IDs in the form "acm:vid:pid" or "usb:vid:pid"
4849
FlashMethod string `json:"flash-method"`
4950
FlashVolume string `json:"msd-volume-name"`
5051
FlashFilename string `json:"msd-firmware-name"`

main.go

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"path/filepath"
1616
"regexp"
1717
"runtime"
18+
"strconv"
1819
"strings"
1920
"sync/atomic"
2021
"time"
@@ -296,7 +297,7 @@ func Flash(pkgName, port string, options *compileopts.Options) error {
296297
return builder.Build(pkgName, fileExt, config, func(result builder.BuildResult) error {
297298
// do we need port reset to put MCU into bootloader mode?
298299
if config.Target.PortReset == "true" && flashMethod != "openocd" {
299-
port, err := getDefaultPort(strings.FieldsFunc(port, func(c rune) bool { return c == ',' }))
300+
port, err := getDefaultPort(port, config.Target.SerialPort)
300301
if err != nil {
301302
return err
302303
}
@@ -321,7 +322,7 @@ func Flash(pkgName, port string, options *compileopts.Options) error {
321322

322323
if strings.Contains(flashCmd, "{port}") {
323324
var err error
324-
port, err = getDefaultPort(strings.FieldsFunc(port, func(c rune) bool { return c == ',' }))
325+
port, err = getDefaultPort(port, config.Target.SerialPort)
325326
if err != nil {
326327
return err
327328
}
@@ -718,7 +719,8 @@ func windowsFindUSBDrive(volume string, options *compileopts.Options) (string, e
718719
}
719720

720721
// getDefaultPort returns the default serial port depending on the operating system.
721-
func getDefaultPort(portCandidates []string) (port string, err error) {
722+
func getDefaultPort(portFlag string, usbInterfaces []string) (port string, err error) {
723+
portCandidates := strings.FieldsFunc(portFlag, func(c rune) bool { return c == ',' })
722724
if len(portCandidates) == 1 {
723725
return portCandidates[0], nil
724726
}
@@ -734,13 +736,70 @@ func getDefaultPort(portCandidates []string) (port string, err error) {
734736
return "", err
735737
}
736738

739+
var preferredPortIDs [][2]uint16
740+
for _, s := range usbInterfaces {
741+
parts := strings.Split(s, ":")
742+
if len(parts) != 3 || (parts[0] != "acm" && parts[0] == "usb") {
743+
// acm and usb are the two types of serial ports recognized
744+
// under Linux (ttyACM*, ttyUSB*). Other operating systems don't
745+
// generally make this distinction. If this is not one of the
746+
// given USB devices, don't try to parse the USB IDs.
747+
continue
748+
}
749+
vid, err := strconv.ParseUint(parts[1], 16, 16)
750+
if err != nil {
751+
return "", fmt.Errorf("could not parse USB vendor ID %q: %w", parts[1], err)
752+
}
753+
pid, err := strconv.ParseUint(parts[2], 16, 16)
754+
if err != nil {
755+
return "", fmt.Errorf("could not parse USB product ID %q: %w", parts[1], err)
756+
}
757+
preferredPortIDs = append(preferredPortIDs, [2]uint16{uint16(vid), uint16(pid)})
758+
}
759+
760+
var primaryPorts []string // ports picked from preferred USB VID/PID
761+
var secondaryPorts []string // other ports (as a fallback)
737762
for _, p := range portsList {
738-
if p.IsUSB {
739-
ports = append(ports, p.Name)
763+
if !p.IsUSB {
764+
continue
740765
}
766+
if p.VID != "" && p.PID != "" {
767+
foundPort := false
768+
vid, vidErr := strconv.ParseUint(p.VID, 16, 16)
769+
pid, pidErr := strconv.ParseUint(p.PID, 16, 16)
770+
if vidErr == nil && pidErr == nil {
771+
for _, id := range preferredPortIDs {
772+
if uint16(vid) == id[0] && uint16(pid) == id[1] {
773+
primaryPorts = append(primaryPorts, p.Name)
774+
foundPort = true
775+
continue
776+
}
777+
}
778+
}
779+
if foundPort {
780+
continue
781+
}
782+
}
783+
784+
secondaryPorts = append(secondaryPorts, p.Name)
785+
}
786+
if len(primaryPorts) == 1 {
787+
// There is exactly one match in the set of preferred ports. Use
788+
// this port, even if there may be others available. This allows
789+
// flashing a specific board even if there are multiple available.
790+
return primaryPorts[0], nil
791+
} else if len(primaryPorts) > 1 {
792+
// There are multiple preferred ports, probably because more than
793+
// one device of the same type are connected (e.g. two Arduino
794+
// Unos).
795+
ports = primaryPorts
796+
} else {
797+
// No preferred ports found. Fall back to other serial ports
798+
// available in the system.
799+
ports = secondaryPorts
741800
}
742801

743-
if ports == nil || len(ports) == 0 {
802+
if len(ports) == 0 {
744803
// fallback
745804
switch runtime.GOOS {
746805
case "darwin":

targets/arduino-nano33.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@
22
"inherits": ["atsamd21g18a"],
33
"build-tags": ["arduino_nano33"],
44
"flash-command": "bossac -i -e -w -v -R -U --port={port} --offset=0x2000 {bin}",
5+
"serial-port": ["acm:2341:8057", "acm:2341:0057"],
56
"flash-1200-bps-reset": "true"
67
}

targets/arduino.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
"-Wl,--defsym=_stack_size=512"
77
],
88
"flash-command": "avrdude -c arduino -p atmega328p -P {port} -U flash:w:{hex}:i",
9+
"serial-port": ["acm:2341:0043", "acm:2341:0001", "acm:2a03:0043", "acm:2341:0243"],
910
"emulator": ["simavr", "-m", "atmega328p", "-f", "16000000"]
1011
}

targets/circuitplay-bluefruit.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"build-tags": ["circuitplay_bluefruit","nrf52840_reset_uf2", "softdevice", "s140v6"],
44
"flash-1200-bps-reset": "true",
55
"flash-method": "msd",
6+
"serial-port": ["acm:239a:8045", "acm:239a:45"],
67
"msd-volume-name": "CPLAYBTBOOT",
78
"msd-firmware-name": "firmware.uf2",
89
"uf2-family-id": "0xADA52840",

targets/circuitplay-express.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"build-tags": ["circuitplay_express"],
44
"flash-1200-bps-reset": "true",
55
"flash-method": "msd",
6+
"serial-port": ["acm:239a:8018", "acm:239a:18"],
67
"msd-volume-name": "CPLAYBOOT",
78
"msd-firmware-name": "firmware.uf2"
89
}

targets/itsybitsy-m4.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"build-tags": ["itsybitsy_m4"],
44
"flash-1200-bps-reset": "true",
55
"flash-method": "msd",
6+
"serial-port": ["acm:239a:802b", "acm:239a:002b"],
67
"msd-volume-name": "ITSYM4BOOT",
78
"msd-firmware-name": "firmware.uf2"
89
}

targets/nano-33-ble.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"inherits": ["nrf52840"],
33
"build-tags": ["nano_33_ble", "nrf52840_reset_bossa"],
44
"flash-command": "bossac_arduino2 -d -i -e -w -v -R --port={port} {bin}",
5+
"serial-port": ["acm:2341:805a", "acm:2341:005a"],
56
"flash-1200-bps-reset": "true",
67
"linkerscript": "targets/nano-33-ble.ld"
78
}

targets/pybadge.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"build-tags": ["pybadge"],
44
"flash-1200-bps-reset": "true",
55
"flash-method": "msd",
6+
"serial-port": ["acm:239a:8033", "acm:239a:33"],
67
"msd-volume-name": "PYBADGEBOOT",
78
"msd-firmware-name": "arcade.uf2"
89
}

targets/pyportal.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"build-tags": ["pyportal"],
44
"flash-1200-bps-reset": "true",
55
"flash-method": "msd",
6+
"serial-port": ["acm:239a:8035", "acm:239a:35", "acm:239a:8036"],
67
"msd-volume-name": "PORTALBOOT",
78
"msd-firmware-name": "firmware.uf2"
89
}

0 commit comments

Comments
 (0)