Created
April 17, 2020 03:10
-
-
Save BenJuan26/29fa0c5cd8197d713e0b83625e8e4e54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const baudRate = 9600 | |
type serialPort struct { | |
MaxBaudRate int | |
DeviceID string | |
} | |
func getSerialPort(pnp string) (*serial.Port, error) { | |
var dst []serialPort | |
// WMI needs the backslashes to be escaped. | |
escaped := strings.Replace(pnp, "\\", "\\\\", -1) | |
query := "SELECT DeviceID, MaxBaudRate FROM Win32_SerialPort WHERE PNPDeviceID='" + escaped + "'" | |
client := &wmi.Client{AllowMissingFields: true} | |
// Put the query results into a slice of serialPort objects. | |
err := client.Query(query, &dst) | |
if err != nil { | |
return nil, fmt.Errorf("Couldn't connect to serial port: %s", err.Error()) | |
} else if len(dst) < 1 { | |
return nil, fmt.Errorf("Couldn't find a PNP Device with ID '%s'", pnp) | |
} | |
// Open the serial connection. | |
conf := &serial.Config{Name: dst[0].DeviceID, Baud: baudRate} | |
s, err := serial.OpenPort(conf) | |
if err != nil { | |
return nil, fmt.Errorf("Couldn't open serial port: %s", err.Error()) | |
} | |
elog.Info(1, fmt.Sprintf("Connected to serial port %s at baud rate %d", dst[0].DeviceID, baudRate)) | |
// Everything seems to have worked; return the serial port. | |
return s, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment