Пример #1
0
// 发送短信.
// num 接收者的号码.
// msg 需要发送的短信内容.
// return 错误; ==nil 发送正常.
func (g *Gsm) SendSMS(num, msg string) error {
	g.mMutex.Lock()
	defer g.mMutex.Unlock()
	if _, err := g.atcmd("AT", "OK", time.Millisecond*250); nil != err {
		return err
	}

	s := sms.Message{
		Encoding: sms.Encodings.Gsm7Bit,
		Text:     msg,
		Address:  sms.PhoneNumber(num),
		VP:       sms.ValidityPeriod(time.Hour * 24 * 4),
		VPFormat: sms.ValidityPeriodFormats.Relative,
		Type:     sms.MessageTypes.Submit,
	}

	if len(msg) != len([]rune(msg)) {
		s.Encoding = sms.Encodings.UCS2
	}

	n, octets, err := s.PDU()

	if err != nil {
		return err
	}

	cmd := fmt.Sprintf("AT+CMGS=%d", n)
	if _, err := g.atcmd(cmd, "", time.Millisecond*300); nil != err {
		return err
	}

	buf := make([]byte, hex.EncodedLen(len(octets))+1)
	n = hex.Encode(buf, octets)
	buf[n] = 0x1A

	if _, err := g.mPort.Write(buf); nil != err {
		return err
	}
	_, err = g.atcmd("", "OK", time.Second*10)
	return err
}
Пример #2
0
// SendSMS sends an SMS message with given text to the given address,
// the encoding and other parameters are default.
func (d *Device) SendSMS(text string, address sms.PhoneNumber) (err error) {
	msg := sms.Message{
		Text:     text,
		Type:     sms.MessageTypes.Submit,
		Encoding: sms.Encodings.Gsm7Bit,
		Address:  address,
		VPFormat: sms.ValidityPeriodFormats.Relative,
		VP:       sms.ValidityPeriod(24 * time.Hour * 4),
	}
	for _, w := range text {
		// detected a double-width char
		if w > 1 {
			msg.Encoding = sms.Encodings.UCS2
			break
		}
	}
	n, octets, err := msg.PDU()
	if err != nil {
		return err
	}
	err = d.Commands.CMGS(n, octets)
	return
}