sim-modem/api/modem/internet/ic.go

135 lines
2.7 KiB
Go
Raw Normal View History

package internet
import (
"fmt"
"io"
"log"
"os/exec"
"strings"
2024-08-08 10:32:55 +00:00
"gitea.unprism.ru/KRBL/sim-modem/api/modem/at"
"gitea.unprism.ru/KRBL/sim-modem/api/modem/utils"
)
var apns = map[string]string{
"Tinkoff": "m.tinkoff",
}
const pppConfigName = "annalistnet"
const pppConfig = `
# Annalist project custom internet connection
# APN:
connect "/usr/sbin/chat -v -f /etc/chatscripts/gprs -T %s"
# Port:
%s
# Baudrate:
%d
noipdefault
usepeerdns
defaultroute
persist
noauth
nocrtscts
local
`
type conn struct {
logger *log.Logger
port at.Port
}
type Conn interface {
Init() error
Connect() error
Disconnect() error
Ping() bool // Is connected
io.Closer
}
func New(logger *log.Logger, port at.Port) Conn {
return &conn{
logger: logger,
port: port,
}
}
func (c *conn) Connect() error {
if ok, err := utils.CheckService(c.port, c.logger); err != nil || !ok {
if err != nil {
return fmt.Errorf("check service: %w", err)
}
return fmt.Errorf("no service")
}
2024-07-29 11:02:06 +00:00
resp, err := exec.Command("pon", pppConfigName).Output()
if err != nil {
return fmt.Errorf("execute connect cmd: %w", err)
}
c.logger.Println("DEBUG pon response:", string(resp))
return nil
}
func (c *conn) Disconnect() error {
2024-07-29 11:02:06 +00:00
resp, err := exec.Command("poff", pppConfigName).Output()
if err != nil {
return fmt.Errorf("execute disconnect cmd: %w", err)
}
c.logger.Println("DEBUG poff response:", string(resp))
return nil
}
func (c *conn) Init() error {
// Setup
if err := c.setup(); err != nil {
return fmt.Errorf("setup: %w", err)
}
// // Connect
// c.logger.Println("Connect...")
// if err := c.Connect(); err != nil {
// return fmt.Errorf("connect: %w", err)
// }
// //DEBUG
// resp, err := exec.Command("ifconfig").Output()
// if err != nil {
// return fmt.Errorf("execute ifconfig cmd: %w", err)
// }
// c.logger.Println("DEBUG ifconfig resp:", string(resp))
// // Test connectin using Ping
// c.logger.Println("Test...")
// if !c.Ping() {
// return fmt.Errorf("ping failed")
// }
return nil
}
func (c *conn) Ping() bool {
// Test - try to connect to Google DNS
// ping -I ppp0 8.8.8.8
resp, err := exec.Command("ping", "8.8.8.8").Output()
if err != nil {
c.logger.Println("Ping 1 cmd error:", err)
}
c.logger.Println("Ping 1 resp:", string(resp))
resp, err = exec.Command("ping", "-I", "ppp0", "8.8.8.8").Output()
if err != nil {
c.logger.Println("Ping 2 cmd error:", err)
}
c.logger.Println("Ping 2 resp:", string(resp))
2024-08-02 16:16:39 +00:00
return !(strings.Contains(string(resp), "Destination Host Unreachable") || strings.Contains(string(resp), "Destination Net Unreachable")) // tmp solution
}
func (c *conn) Close() error {
if err := c.Disconnect(); err != nil {
return fmt.Errorf("diconnect: %w", err)
}
return nil
}