Thursday, May 24, 2012

Send SMS using AT command with the help of Java

import java.io.*;
import java.util.*;
import javax.comm.*;
 
public class GSMConnect implements SerialPortEventListener,
  CommPortOwnershipListener {
 
  private String comPort = "COM3"; // This COM Port must be connect with GSM Modem or your mobile phone
  private String messageString = "";
  private CommPortIdentifier portId = null;
  private Enumeration portList;
  private InputStream inputStream = null;
  private OutputStream outputStream = null;
  private SerialPort serialPort;
 
  /** Creates a new instance of GSMConnect */
  public GSMConnect(String comm) {
 
    this.comPort = comm;
 
  }
 
  public boolean init() {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equals(comPort)) {
          return true;
        }
      }
    }
    return false;
  }
 
  public void checkStatus() {
    send("AT+CREG?\r\n");
  }
 
  public void dial(String phoneNumber) {
    try {
//dial to this phone number
      messageString = "ATD" + phoneNumber + ";\n\r";
      outputStream.write(messageString.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 
  public void send(String cmd) {
    try {
      outputStream.write(cmd.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 
  public void sendMessage(String phoneNumber, String message) {
    send("AT+CMGS=\"" + phoneNumber + "\"\r\n");
    send(message + '\032');
  }
 
  public void hangup() {
    send("ATH\r\n");
  }
 
  public void connect() throws NullPointerException {
    if (portId != null) {
      try {
        portId.addPortOwnershipListener(this);
        serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
      } catch (PortInUseException e) {
        e.printStackTrace();
      }
 
      try {
        inputStream = serialPort.getInputStream();
        outputStream = serialPort.getOutputStream();
      } catch (IOException e) {
        e.printStackTrace();
      }
 
      try {
        /** These are the events we want to know about*/
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
      } catch (TooManyListenersException e) {
        e.printStackTrace();
      }
 
//Register to home network of sim card
 
      send("ATZ\r\n");
 
    } else {
      throw new NullPointerException("COM Port not found!!");
    }
  }
 
  public void serialEvent(javax.comm.SerialPortEvent serialPortEvent) {
    switch (serialPortEvent.getEventType()) {
      case SerialPortEvent.BI:
      case SerialPortEvent.OE:
      case SerialPortEvent.FE:
      case SerialPortEvent.PE:
      case SerialPortEvent.CD:
      case SerialPortEvent.CTS:
      case SerialPortEvent.DSR:
      case SerialPortEvent.RI:
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
      case SerialPortEvent.DATA_AVAILABLE:
 
        byte[] readBuffer = new byte[2048];
        try {
          while (inputStream.available() & gt;
          0)
          {
            int numBytes = inputStream.read(readBuffer);
          }
//print response message
          System.out.print(new String(readBuffer));
        } catch (IOException e) {
        }
        break;
    }
  }
 
  public void ownershipChange(int type) {
    switch (type) {
      case CommPortOwnershipListener.PORT_UNOWNED:
        System.out.println(portId.getName() + ": PORT_UNOWNED");
        break;
      case CommPortOwnershipListener.PORT_OWNED:
        System.out.println(portId.getName() + ": PORT_OWNED");
        break;
      case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
        System.out.println(portId.getName() + ": PORT_INUSED");
        break;
    }
 
  }
 
  public static void main(String args[]) {
    GSMConnect gsm = new GSMConnect(comPort);
    if (gsm.init()) {
      try {
        gsm.connect();
        gsm.checkStatus();
        Thread.sleep(5000);
        gsm.sendMessage("Mobile Phone Number", "Your Message");
        Thread.sleep(20000);
        gsm.hangup();
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("Can't init this card");
    }
  }
}
 

Using AT commands to send and read SMS

 
Introduction
 
 
This article discusses how to use AT commands to send and receive SMS. It can be used to create a PC application that send SMS from the phone. This kind of application is useful, for example, in automating test cases related to SMS.
 
Note that not all phones support all SMS AT commands. For example, some phones may support send command only and not support read command. See also links at the end of this article to find more about AT commands, including complete list of SMS AT commands on Nokia's GSM and WCDMA products.
 
 
 
Message Format
 
 
There are basically two modes to work with SMS, i.e.:
 
  • PDU (Protocol Data Unit)
  • Text mode.
 
A mobile phone internally uses PDU format. Developers normally uses text mode because it is easier to use. AT+CMGF is the command to set the mode.
 
AT+CMGF=0
 
sets the format to PDU mode.
 
AT+CMGF=1
 
sets the format to text mode.
 
AT+CMGF?
 
queries the current format.
 
 
Sending SMS
 
 
Although you can send SMS in PDU or text mode, it is easier to use text mode to type the message.
 
The following commands change the message format to text mode and send a text message.
 
AT+CMGF=1
OK
AT+CMGS="7789952010"
> Hello World<Ctrl>+<Z>
+CMGS: 44
 
OK
 
Note that <Ctrl>+<Z> has to be entered at the end of message to send the message.
 
 
Reading SMS
 
 
Use the following command to read the list of all messages on the phone:
 
AT+CMGL="ALL"
+CMGL: 123,"REC READ","+123456789"
Hello World
 
 
OK
 
Use the following command to read a message with has index of 123:
 
AT+CMGR=123
+CMGR: "REC READ","+17789975545","08/09/05,17:46:49-12"
Hello World
 
OK
----------------------------------------------------------------------------------------------------------------------------------------------------------
 
 
AT Commands
 
What you should know
 
 
Different phones support different sets of AT commands. This means that a specific phone might not support all AT commands listed below. Currently there is no authoritative list available of supported AT commands by all phones.
 
Overview
 
 
AT commands are also known as Hayes AT commands. There are different views to understand the meanings of "AT". Some call it "Attention Telephone", whereas others interpret it as "Attention Terminal" commands.
 
AT commands allow giving instructions to both mobile devices and ordinary landline telephones. The commands are sent to the phone's modem, which can be a GSM modem or PC modem. This article focuses on AT commands on Nokia's GSM and WCDMA products only. Different manufacturers may have different sets of AT commands. Fortunately, many AT commands are the same. Mobile device manufacturers may also give attention to operators to allow or not to allow some commands on phones.
 
AT commands can be used for operations that are usually done from the keypad, for instance calling a number, sending, reading, or deleting an SMS, setting the SMSC number, looking for a GPRS access point, reading and deleting phonebook data, reading the battery status, reading the signal strength, and so on. When you want to make a PC-based application to interface a mobile phone using USB, IR, or Bluetooth, these commands are needed to communicate with mobile phones. Basically such commands are the application layer of MBUS or FBUS commands. Nokia provides an AT command set guide, where you can see the basic command syntax and the response of the command in various situations. See the Related Links section at the end of this article).
 
 
Using AT Commands with HyperTerminal
 
 
AT commands work on devices that have a built-in GSM modem. If there is one, you do not need to install virtual modem software on your PC. If you are using very old Nokia devices, you have to find out the DATA suite, not the PC Suite, for these devices (such as the Nokia 5110) to be able to use AT commands. This article focuses on mobile devices that have a built-in GSM modem.
 
To use AT commands:
 
  • Connect the mobile phone to your PC in PC Suite mode using any available connection (Bluetooth, USB, or IR).
 
  • Make sure that you have installed the correct GSM modem driver on your PC. You can check it from Control Panel | System | Hardware | Device Manager. Check the Modems section. If you see something like "Nokia XY USB Modem" or "Nokia XY Bluetooth Modem", the device has a built-in GSM modem. If you don't have it, go to the Nokia Web site and download the driver from the product page of your device.
 
 
  • Right Click on Nokia N95 8GB USB Modem and find the port used by selecting the modem tab, in our case it is COM 4. Also it is good to test the modem by selecting Diagnostics | Query Modem, this will tell us if the modem is working properly.
  • Open the HyperTerminal, which is a communication utility on Microsoft Windows OS. HyperTerminal is located in Start | Programs | Accessories | Communication.
 
  • Create a new connection set on HyperTerminal and give a name to the connection.
  • Select the port number by seleting drop down box "Connect using". In our case the port number is COM 4
 
 
  • You need to select some settings related to ASCII setup, To do select File | Properties | Settings (tab) | ASCII Setup
 
 
  • You may need to set some parameters, such as baud rate (for example, 9600), handshaking mode (Xon-Xoff), parity bit (default), and so on.
 
 
  • Note that you also need to select the communication port on which your mobile has been connected. The port number can be found by right-clicking the modem item in Control Panel.
 
 
  • After this, you can give the basic AT command. Simply type AT in the window and you will get the "OK" response.
 
 
The above picture also shows how to dial a number using the ATD command. Note that there is a semi-colon (;) at the end of the phone number indicating that this is a voice call. If there is no semi-colon, a data call (CSD call) is will be performed.
 
 
AT commands set for Nokia GSM and WCDMA products
 
 
Call control
 
Command  Description     
ATA      Answer command  
ATD      Dial command    
ATH      Hang up call    
ATL      Monitor speaker loudness        
ATM      Monitor speaker mode    
ATO      Go on-line      
ATP      Set pulse dial as default       
ATT      Set tone dial as default        
AT+CSTA  Select type of address  
AT+CRC   Cellular result codes   
 

Data card control commands
 
Command  Description     
ATI      Identification  
ATS      Select an S-register    
ATZ      Recall stored profile   
AT&F     Restore factory settings        
AT&V     View active configuration       
AT&W     Store parameters in given profile       
AT&Y     Select Set as powerup option    
AT+CLCK  Facility lock command   
AT+COLP  Connected line identification presentation      
AT+GCAP  Request complete capabilities list      
AT+GMI   Request manufacturer identification     
AT+GMM   Request model identification    
AT+GMR   Request revision identification 
AT+GSN   Request product serial number identification (IMEI)     
 
Phone control commands
 
Command  Description     
AT+CBC   Battery charge  
AT+CGMI  Request manufacturer identification     
AT+CGMM  Request model identification    
AT+CGMR  Request revision identification 
AT+CGSN  Request product serial number identification    
AT+CMEE  Report mobile equipment error   
AT+CPAS  Phone activity status   
AT+CPBF  Find phone book entries 
AT+CPBR  Read phone book entry   
AT+CPBS  Select phone book memory storage        
AT+CPBW  Write phone book entry  
AT+CSCS  Select TE character set 
AT+CSQ   Signal quality  
 

Computer data card interface commands
 
Command  Description     
ATE      Command Echo    
ATQ      Result code suppression 
ATV      Define response format  
ATX      Response range selection        
AT&C     Define DCD usage        
AT&D     Define DTR usage        
AT&K     Select flow control     
AT&Q     Define communications mode option       
AT&S     Define DSR option       
AT+ICF   DTE-DCE character framing       
AT+IFC   DTE-DCE Local flow control      
AT+IPR   Fixed DTE rate  
 

Service
 
Command  Description     
AT+CLIP  Calling line identification presentation        
AT+CR    Service reporting control       
AT+DR    Data compression reporting      
AT+ILRR  DTE-DCE local rate reporting    
 
 
Network communication parameter commands
 
Command  Description     
ATB      Communications standard option  
AT+CBST  Select bearer service type      
AT+CEER  Extended error report   
AT+CRLP  Radio link protocol     
AT+DS    Data compression        
 
 
Miscellaneous commands
 
Command  Description     
A/       Re-execute command line 
AT?      Command help    
AT*C     Start SMS interpreter   
AT*T     Enter SMS block mode protocol   
AT*V     Activate V.25bis mode   
AT*NOKIATEST     Test command    
AT+CESP  Enter SMS block mode protocol   
 
 
SMS commands
 
 
SMS text mode
 
Command  Description     
AT+CSMS  Select message service  
AT+CPMS  Preferred message storage       
AT+CMGF  Message format  
AT+CSCA  Service centre address  
AT+CSMP  Set text mode parameters        
AT+CSDH  Show text mode parameters       
AT+CSCB  Select cell broadcast message types     
AT+CSAS  Save settings   
AT+CRES  Restore settings        
AT+CNMI  New message indications to TE   
AT+CMGL  List messages   
AT+CMGR  Read message    
AT+CMGS  Send message    
AT+CMSS  Send message from storage       
AT+CMGW  Write message to memory 
AT+CMGD  Delete message  
 
 
SMS PDU ode
 
Command  Description     
AT+CMGL  List Messages   
AT+CMGR  Read message    
AT+CMGS  Send message    
AT+CMGW  Write message to memory