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
|
|
|
|
}
|
|
|
|
|
|
|
|
type Dialer interface {
|
|
|
|
Init() error
|
|
|
|
Send(number, msg string) error
|
|
|
|
ReadNew() ([]string, error)
|
|
|
|
io.Closer
|
|
|
|
}
|
|
|
|
|
2024-07-29 13:51:54 +00:00
|
|
|
func New(logger *log.Logger, port at.Port) Dialer {
|
|
|
|
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")
|
|
|
|
}
|
|
|
|
// Ensure text format
|
|
|
|
if resp, err := d.port.Send("AT+CMGF=1"); err != nil || !resp.Check() {
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("AT+CMGF=1 request: %w", err)
|
|
|
|
}
|
|
|
|
return fmt.Errorf("failed to set SMS format")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *dialer) Send(number, msg string) error {
|
2024-07-29 17:03:22 +00:00
|
|
|
d.port.Send(fmt.Sprintf("AT+CMGS=\"%s\"", number)) // Because it will throw error
|
|
|
|
resp, err := d.port.RawSend(fmt.Sprintf("%s\x1A", 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-07-29 15:53:55 +00:00
|
|
|
if at.Resp(resp).Check() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|