stty/stty.go

56 lines
1.4 KiB
Go
Raw Normal View History

2025-04-28 22:57:43 +03:00
package stty
import (
"fmt"
"os/exec"
)
type stty struct {
}
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) (bool, error) {
err := s.SetBaudRate(portPath, baudrate)
if err != nil {
return false, fmt.Errorf("Failed to set baudrate using stty. Because: " + err.Error())
}
newBaudRate, err := s.CheckBaudRate(portPath)
if err != nil {
return false, fmt.Errorf("Failed to check baudrate using stty. Because: " + err.Error())
}
if newBaudRate == baudrate {
return true, nil
}
return false, nil
}