sim-modem/api/modem/sms/sms.go

99 lines
2.3 KiB
Go
Raw Normal View History

2024-07-28 18:01:18 +00:00
package sms
import (
"fmt"
"io"
"log"
"strings"
"github.com/CGSG-2021-AE4/modem-test/api/modem/at"
)
type dialer struct {
logger *log.Logger
port at.Port
}
2024-08-06 17:37:20 +00:00
type Sms interface {
2024-07-28 18:01:18 +00:00
Init() error
2024-08-06 17:37:20 +00:00
Send(number, msg string) error // Send sms
ReadNew() ([]string, error) // Read new smses
2024-07-28 18:01:18 +00:00
io.Closer
}
2024-08-06 17:37:20 +00:00
func New(logger *log.Logger, port at.Port) Sms {
2024-07-29 13:51:54 +00:00
return &dialer{
logger: logger,
port: port,
}
}
2024-07-28 18:01:18 +00:00
func (d *dialer) Init() error {
// Ensure serial port
if !d.port.IsConnected() {
return fmt.Errorf("serial port is not connected")
}
2024-08-06 18:10:24 +00:00
// Check SIM an PIN
if resp, err := d.port.Send("AT+CPIN?"); err != nil || !resp.Check() {
if err != nil {
return fmt.Errorf("check pin: %w", err)
}
return fmt.Errorf("check pin: error response: %s", resp)
}
2024-07-28 18:01:18 +00:00
// Ensure text format
if resp, err := d.port.Send("AT+CMGF=1"); err != nil || !resp.Check() {
if err != nil {
return fmt.Errorf("set to text format request: %w", err)
2024-07-28 18:01:18 +00:00
}
return fmt.Errorf("set SIM format: error response: %s", resp)
2024-07-28 18:01:18 +00:00
}
return nil
}
func (d *dialer) Send(number, msg string) error {
2024-08-06 17:37:20 +00:00
d.port.Send(fmt.Sprintf(`AT+CMGS="%s"`, number)) // Because it will throw error
resp, err := d.port.RawSend(fmt.Sprintf("%s\n\r", msg)) // Add additional \r\n because there is not supposed to be
2024-07-29 15:53:55 +00:00
if err != nil {
return fmt.Errorf("message request: %w", err)
2024-07-28 18:01:18 +00:00
}
2024-08-06 17:37:20 +00:00
d.logger.Println("SEND RESPONSE:", resp)
resp, err = d.port.RawSend("\x1A")
if err != nil {
return fmt.Errorf("message request: %w", err)
2024-07-29 15:53:55 +00:00
}
d.logger.Println("SEND RESPONSE:", resp)
2024-07-29 15:53:55 +00:00
errCode, err := GetError([]byte(resp))
if err != nil {
return fmt.Errorf("send sms failed and failed to get error: %w", err)
}
return fmt.Errorf("failed to send with SMS error: %d - %s", errCode, DecodeError(errCode))
2024-07-28 18:01:18 +00:00
}
// Reads all new messages
func (d *dialer) ReadNew() ([]string, error) {
2024-08-01 16:34:58 +00:00
resp, err := d.port.Send("AT+CMGL=\"ALL\"")
2024-07-28 18:01:18 +00:00
if err != nil {
return nil, fmt.Errorf("AT+CMGL request: %w", err)
}
msgs := strings.Split(strings.Replace(string(resp), "\r", "", -1), "\n")
2024-07-29 17:03:22 +00:00
outMsgs := make([]string, 0)
for _, s := range msgs {
if len(s) >= len("+CMGL:") && s[:len("+CMGL:")] == "+CMGL:" {
params := strings.Split(s[len("+CMGL:"):], ",")
d.logger.Println("GET MSG:", params)
} else {
outMsgs = append(outMsgs, s)
}
}
return outMsgs, nil // TODO
2024-07-28 18:01:18 +00:00
}
2024-07-29 13:51:54 +00:00
func (d *dialer) Close() error {
return nil
}