62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
|
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
|
||
|
}
|
||
|
|
||
|
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 {
|
||
|
cmd := fmt.Sprintf("AT+CMGS=\"%s\"\r%s%c", number, msg, 26)
|
||
|
if resp, err := d.port.Send(cmd); err != nil || !resp.Check() {
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("AT+CGMS= request: %w", err)
|
||
|
}
|
||
|
if errCode, err := GetError(resp.Bytes()); err != nil {
|
||
|
return fmt.Errorf("failed to send with SMS error: %s", DecodeError(errCode))
|
||
|
}
|
||
|
return fmt.Errorf("failed to send SMS")
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// Reads all new messages
|
||
|
func (d *dialer) ReadNew() ([]string, error) {
|
||
|
resp, err := d.port.Send("AT+CMGL")
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("AT+CMGL request: %w", err)
|
||
|
}
|
||
|
msgs := strings.Split(strings.Replace(string(resp), "\r", "", -1), "\n")
|
||
|
return msgs, nil // TODO
|
||
|
}
|