package sms import ( "fmt" "strconv" "strings" ) func (d *dialer) setupMsgSt() error { // Check for free space for messages // !!! I use one! memory for all three bindings // 1: read and delete // 2: sending // 3: write received // First try SM if _, err := d.port.Send(`AT+CPMS="SM","SM","SM"`); err != nil { return fmt.Errorf(`AT+CPMS="SM","SM","SM" request: %w`, err) } st, err := d.getCurMsgStSize() if err != nil { return fmt.Errorf("SM: %w", err) } if st[0].Used < st[0].Total { d.logger.Printf("Use SM message storage: %d/%d\n", st[0].Used, st[0].Total) return nil // There is space } d.logger.Printf("SM message storage is full: %d/%d\n", st[0].Used, st[0].Total) // Second try ME if _, err := d.port.Send(`AT+CPMS="ME","ME","ME"`); err != nil { return fmt.Errorf(`AT+CPMS="ME","ME","ME" request: %w`, err) } st, err = d.getCurMsgStSize() if err != nil { return fmt.Errorf("ME: %w", err) } if st[0].Used < st[0].Total { d.logger.Printf("Use ME message storage: %d/%d\n", st[0].Used, st[0].Total) return nil // There is space } d.logger.Printf("ME message storage is full: %d/%d\n", st[0].Used, st[0].Total) // Otherwise error return fmt.Errorf("all storages are full") } // Message storage type msgSt struct { Name string Used int Total int } // Get size of used and total mem of current memory storage func (d *dialer) getCurMsgStSize() ([]msgSt, error) { // Request resp, err := d.port.Send("AT+CPMS?") if err != nil { return nil, fmt.Errorf("AT+CPMS? request: %w", err) } // Check start and end if !resp.Check() && !resp.CheckFront("+CPMS:") { return nil, fmt.Errorf("AT+CPMS") } // Remove front and cut to values resp = resp.RmFront("+CPMS:") values := strings.Split(strings.ReplaceAll(strings.Split(resp.String(), "\n")[0], "\r", ""), ",") if len(values) != 9 { return nil, fmt.Errorf("CPMS response: invalid values count: [%s]", values) } // Parse values outMsgs := [3]msgSt{} for i := 0; i < 3; i++ { name := values[i] used, err := strconv.Atoi(values[i*3+1]) if err != nil { return nil, fmt.Errorf("parse value #%d: %w", i+1, err) } total, err := strconv.Atoi(values[i*3+2]) if err != nil { return nil, fmt.Errorf("parse value #%d, %w", i+2, err) } outMsgs[i] = msgSt{name, used, total} } return outMsgs[:], nil }