#include <SoftwareSerial.h>

SoftwareSerial gsmSerial(4, 5); // RX, TX
bool fullcmd = true; // true: use serialcommand; false: use upper code.

String gsmStatus = "AT";                                // OK for good connection; no response otherwise
String gsmCommands = "AT+CLAC";                         // get available commands
String gsmSetModeText = "AT+CMGF=1";                    // set mode to SMS
String gsmReadText = "AT+CNMI=2,2,0,0,0";               // read text
String gsmMakeCall = "ATD+1123456789";                  // replace with number and country code you like
String gsmDisconnectCall = "ATH";                       // disconnect call
String gsmReceiveCall = "ATA";                          // receive call
// String gsmSendText = "AT+CMGS=\"+6281542787536\"\r";    // replace with number and country code
String gsmSendText = "AT+CMGS=\"+639433119821\"\r";     // replace with number and country code
char gsmEndText = (char)26;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  gsmSerial.begin(9600);
  Serial.println("\nready");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (gsmSerial.available() > 0) {
    char c = gsmSerial.read();
    Serial.write(c);
  }

  if (fullcmd) {
    serialCommand();
  }
  else {
    if (Serial.available() > 0) {
      char c = Serial.read();
      gsmSerial.write(c);
    }
  }
}

void serialCommand() {
  if (Serial.available() > 0) {
    String cmd = Serial.readStringUntil('\r');

    if (cmd.startsWith("gsm|")) {
      gsmSerial.println(cmd.substring(4));
    }
    else if (cmd == "test") {
      testSMS();
    }
  }
}

void testSMS() {
  // set to message mode
  gsmSerial.println(gsmSetModeText);
  delay(1000);
  while (gsmSerial.available() > 0) {
    Serial.write(gsmSerial.read());
  }
  // set number
  gsmSerial.println(gsmSendText);
  delay(1000);
  while (gsmSerial.available() > 0) {
    Serial.write(gsmSerial.read());
  }
  // set message
  gsmSerial.println("FROM MERTECH'S TROPIKGEAR\nName: Juan Dela Cruz\n");
  delay(100);
  while (gsmSerial.available() > 0) {
    Serial.write(gsmSerial.read());
  }
  gsmSerial.println("SOS: Need immediate rescue.\nUrgent assistance required!");
  delay(100);
  while (gsmSerial.available() > 0) {
    Serial.write(gsmSerial.read());
  }
  gsmSerial.println((char)26);
  delay(1000);
  while (gsmSerial.available() > 0) {
    Serial.write(gsmSerial.read());
  }
  // Serial.println("Done?");
}
