76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package stty
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"golang.org/x/sys/unix"
|
|
"golang.org/x/term"
|
|
"os/exec"
|
|
)
|
|
|
|
type stty struct {
|
|
}
|
|
|
|
func ValidateTtyFile(filepath string) error {
|
|
file, err := os.Open(filepath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
err = unix.Access(filepath, unix.W_OK)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if term.IsTerminal(int(file.Fd())) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("File is not a tty.")
|
|
}
|
|
|
|
func Get() (*stty, error) {
|
|
checkSttyCMD := exec.Command("stty", "--version")
|
|
sttyOutput, err := checkSttyCMD.Output()
|
|
if err != nil || len(sttyOutput) == 0 {
|
|
return nil, fmt.Errorf("Stty is missing. Because: " + err.Error())
|
|
}
|
|
return &stty{}, nil
|
|
}
|
|
|
|
func (s *stty) SetBaudRate(portPath string, baudrate int) error {
|
|
setBaudRateCMD := exec.Command("stty", "-F", portPath, fmt.Sprint(baudrate))
|
|
_, err := setBaudRateCMD.Output()
|
|
return err
|
|
}
|
|
|
|
func (s *stty) CheckBaudRate(portPath string) (baudrate int, err error) {
|
|
checkBaudRateCMD := exec.Command("stty", "-F", portPath, "speed")
|
|
sttyOutput, err := checkBaudRateCMD.Output()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("Failed to invoke stty. Because: " + err.Error())
|
|
}
|
|
|
|
_, err = fmt.Sscan(string(sttyOutput), &baudrate)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("Failed to read baudrate from stty output. Because:" + err.Error())
|
|
}
|
|
return baudrate, nil
|
|
}
|
|
|
|
func (s *stty) TestBaudRate(portPath string, baudrate int) (error) {
|
|
err := s.SetBaudRate(portPath, baudrate)
|
|
if err != nil {
|
|
return fmt.Errorf("Failed to set baudrate using stty. Because: " + err.Error())
|
|
}
|
|
|
|
newBaudRate, err := s.CheckBaudRate(portPath)
|
|
if err != nil {
|
|
return fmt.Errorf("Failed to check baudrate using stty. Because: " + err.Error())
|
|
}
|
|
|
|
if newBaudRate == baudrate {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("Selected baudrate is not supported.")
|
|
}
|