2025-02-17 21:46:19 -05:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strings"
|
2025-05-27 16:40:15 -04:00
|
|
|
|
|
|
|
"github.com/samber/oops"
|
2025-02-17 21:46:19 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
func connectToSAM(address string) (net.Conn, error) {
|
|
|
|
conn, err := net.Dial("tcp", address)
|
|
|
|
if err != nil {
|
2025-05-27 16:40:15 -04:00
|
|
|
return nil, oops.Errorf("failed to connect to SAM bridge at %s: %w", address, err)
|
2025-02-17 21:46:19 -05:00
|
|
|
}
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func sendHelloAndValidate(conn net.Conn, s *SAM) error {
|
|
|
|
if _, err := conn.Write(s.SAMEmit.HelloBytes()); err != nil {
|
2025-05-27 16:40:15 -04:00
|
|
|
return oops.Errorf("failed to send hello message: %w", err)
|
2025-02-17 21:46:19 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := make([]byte, 256)
|
|
|
|
n, err := conn.Read(buf)
|
|
|
|
if err != nil {
|
2025-05-27 16:40:15 -04:00
|
|
|
return oops.Errorf("failed to read SAM response: %w", err)
|
2025-02-17 21:46:19 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
response := string(buf[:n])
|
|
|
|
switch {
|
|
|
|
case strings.Contains(response, HELLO_REPLY_OK):
|
|
|
|
log.Debug("SAM hello successful")
|
|
|
|
return nil
|
|
|
|
case response == HELLO_REPLY_NOVERSION:
|
2025-05-27 16:40:15 -04:00
|
|
|
return oops.Errorf("SAM bridge does not support SAMv3")
|
2025-02-17 21:46:19 -05:00
|
|
|
default:
|
2025-05-27 16:40:15 -04:00
|
|
|
return oops.Errorf("unexpected SAM response: %s", response)
|
2025-02-17 21:46:19 -05:00
|
|
|
}
|
|
|
|
}
|