*
The moose likes Other JSE/JEE APIs and the fly likes sms gateway Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "sms gateway" Watch "sms gateway" New topic
Author

sms gateway

arun ram.ci
Greenhorn

Joined: Oct 15, 2009
Posts: 14
hai
i have down loaded sample code for sms gateway, i can able to send the sms to mobile , now my question is in this sms program while running the sms gui class ,applet was generated and while clicking the open port button "serial communication" is enabled later we will type the AT commands in message out text area of the message pannel (eg AT+CMGS="9965844325"), whether we can define the number and message in code itself ,if we can define means where i have to give that number and the message in the code, so that while running the gui "serial communication opens" and throw the message to the required number automatically , instead of typing the AT commands in the message out area code , i have attached the codes in this mail, please assist me where i have to define the number(9965844325) and the message ="hai how are u" if it is done later i can fetch many numbers from database to send sms



public class Sms_GUI extends Frame implements ActionListener
{


final int HEIGHT = 450;
final int WIDTH = 410;

private MenuBar mb;
private Menu fileMenu;
private Menu settingsMenu;
private Menu aboutMenu;
private MenuItem openItem;
private MenuItem saveItem;
private MenuItem exitItem;
private MenuItem serialItem;
private MenuItem aboutItem;

public Button openButton;
public Button closeButton;
private Panel buttonPanel;
public static List phoneno;
String msg="";
public Button send;
private Panel messagePanel;
private String at_command = "";
public TextArea OutTextArea;
public TextArea InTextArea;
private KeyHandler keyHandler;

private SerialPanel SerialSettings;
private InfoDialog info;
private SmsTerminal term;

private Properties props = null;

String address;
String name;
Statement st;
ResultSet rs=null;
Connection conn = null;
String mobileno;

/**
Main method. Checks to see if the command line agrument is requesting
usage informaition (-h, -help), if it is, display a usage message and
exit, otherwise create a new <code>SerialDemo</code> and set it visible.
*/
public static void main(String[] args)
{



if ((args.length > 0)
&& (args[0].equals("-h")
|| args[0].equals("-help")))
{
System.out.println("usage: java AccessSystemGUI [configuration File]");
System.exit(1);
}

Sms_GUI GUI = new Sms_GUI(args);
GUI.setVisible(true);
GUI.repaint();


}


public Sms_GUI(String[] args)
{
super("Serial SMS Client");
// Set up the GUI for the program
addWindowListener(new CloseHandler(this));

mb = new MenuBar();

fileMenu = new Menu("File");

openItem = new MenuItem("Load Settings");
openItem.addActionListener(this);
fileMenu.add(openItem);

saveItem = new MenuItem("Save Settings");
saveItem.addActionListener(this);
fileMenu.add(saveItem);

exitItem = new MenuItem("Exit");
exitItem.addActionListener(this);
fileMenu.add(exitItem);

mb.add(fileMenu);

settingsMenu = new Menu("Settings");

serialItem = new MenuItem("Serial Port Settings");
serialItem.addActionListener(this);
settingsMenu.add(serialItem);

mb.add(settingsMenu);

aboutMenu = new Menu("Info");
aboutItem = new MenuItem("About");
aboutItem.addActionListener(this);
aboutMenu.add(aboutItem);

mb.add(aboutMenu);


setMenuBar(mb);

messagePanel = new Panel();
messagePanel.setLayout(new GridLayout(2, 1));

OutTextArea = new TextArea();
OutTextArea.setEditable(false);
OutTextArea.setFont(new Font("Monospaced",0,12));

messagePanel.add(OutTextArea);

InTextArea = new TextArea();
InTextArea.setEditable(false);
InTextArea.setFont(new Font("Monospaced",0,12));

messagePanel.add(InTextArea);

add(messagePanel, "Center");

// Create a new KeyHandler to respond to key strokes in the
// messageAreaOut. Add the KeyHandler as a keyListener to the
// messageAreaOut.
keyHandler = new KeyHandler();
OutTextArea.addKeyListener(keyHandler);

buttonPanel = new Panel();

openButton = new Button("Open Port");
openButton.addActionListener(this);
buttonPanel.add(openButton);

closeButton = new Button("Stop");
closeButton.addActionListener(this);
closeButton.setEnabled(false);
buttonPanel.add(closeButton);

Panel southPanel = new Panel();

GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();

cons.gridwidth = GridBagConstraints.REMAINDER;
gridBag.setConstraints(buttonPanel, cons);
cons.weightx = 1.0;
gridBag.setConstraints(buttonPanel, cons);
southPanel.add(buttonPanel);

add(southPanel, "South");

parseArgs(args);

SerialSettings = new SerialPanel(this);

SerialSettings.setParameters();

info = new InfoDialog();

term = new SmsTerminal (this, SerialSettings.parameters,
OutTextArea, InTextArea);

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

setLocation(screenSize.width/2 - WIDTH/2,
screenSize.height/2 - HEIGHT/2);

setSize(WIDTH, HEIGHT);
setResizable(false);

phoneno= new List(5,true);

add(phoneno);

phoneno.addActionListener(this);


System.out.println("Peopletech");
try
{
System.out.println("Welcome To All");
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/smsgateway", "user", "user");
st = conn.createStatement();
rs=st.executeQuery("select * from sample");

while(rs.next())
{
name=rs.getString("name");
System.out.println("Name:"+name);
address=rs.getString("address");
System.out.println("Address:"+address);
mobileno=rs.getString("phoneno");
System.out.println("MobileNo:"+mobileno);
phoneno.add(mobileno);

}
}
catch(Exception e)
{
e.printStackTrace();
}

}

/**
Responds to the menu items and buttons.
*/
public void actionPerformed(ActionEvent e)
{





String cmd = e.getActionCommand();

// Loads a configuration file.
if (cmd.equals("Load Settings"))
{

FileDialog fd = new FileDialog(this,
"Load Serial Port Configuration",
FileDialog.LOAD);
fd.setVisible(true);
String file = fd.getFile();
if (file != null)
{
String dir = fd.getDirectory();
File f = new File(dir + file);
try
{
FileInputStream fis = new FileInputStream(f);
props = new Properties();
props.load(fis);
fis.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1);
}
catch (IOException e2)
{
System.err.println(e2);
}
loadParams();
}

}

// Saves a configuration file.
if (cmd.equals("Save Settings"))
{
SerialSettings.setParameters();
FileDialog fd = new FileDialog(this, "Save Serial Port Configuration",
FileDialog.SAVE);
fd.setFile("SerialPort.settings");
fd.setVisible(true);
String fileName = fd.getFile();
String directory = fd.getDirectory();
if ((fileName != null) && (directory != null))
{
writeFile(directory + fileName);
}
}

// Exits the program.
if (cmd.equals("Exit"))
{
this.setVisible(false);
try
{
term.close();
}
catch (NullPointerException ex)
{

}
}

// Calls serial settings window
if (cmd.equals("Serial Port Settings"))
{
SerialSettings.setVisible(true);
SerialSettings.repaint();
}

// Calls serial settings window
if (cmd.equals("About"))
{
info.setVisible(true);
info.repaint();

}


// Opens a port.
if (cmd.equals("Open Port"))
{
System.out.println("Open serial connection");
openButton.setEnabled(false);
SerialSettings.setParameters();
try
{
term.openConnection();
closeButton.setEnabled(true);
OutTextArea.setEditable(true);

}
catch (IOException e2)
{
AlertDialog ad = new AlertDialog(this,
"Error Opening Port!",
"Error opening port,",
e2.getMessage() + ".",
"Select new settings, try again.");
openButton.setEnabled(true);
return;
}
}

// Closes a port.
if (cmd.equals("Stop"))
{
try
{
term.close();
}
catch (NullPointerException ex)
{

}
openButton.setEnabled(true);
closeButton.setEnabled(false);
OutTextArea.setEditable(false);
}

}
/**
Writes the current parameters to a configuration file of the
java.properties style.
*/
private void writeFile(String path)
{

Properties newProps;
FileOutputStream fileOut = null;

newProps = new Properties();

newProps.put("portName", (SerialSettings.parameters).getPortName());
newProps.put("baudRate", (SerialSettings.parameters).getBaudRateString());
newProps.put("flowControlIn", (SerialSettings.parameters).getFlowControlInString());
newProps.put("flowControlOut", (SerialSettings.parameters).getFlowControlOutString());
newProps.put("parity", (SerialSettings.parameters).getParityString());
newProps.put("databits", (SerialSettings.parameters).getDatabitsString());
newProps.put("stopbits", (SerialSettings.parameters).getStopbitsString());

try
{
fileOut = new FileOutputStream(path);
}
catch (IOException e)
{
System.out.println("Could not open file for writiing");
}

try
{
newProps.store(fileOut, "Serial Port settings");
}
catch (IOException e)
{
System.out.println("Could not write file");
}

try
{
fileOut.close();
}
catch (IOException e)
{
System.out.println("Could not close file for writiing");
}
}


/**
Finds configuration file in arguments and creates a properties object from
that file.
*/
private void parseArgs(String[] args)
{
if (args.length < 1)
{
return;
}

File f = new File(args[0]);

if (!f.exists())
{
f = new File(System.getProperty("user.dir")
+ System.getProperty("path.separator")
+ args[0]);
}

if (f.exists())
{
try
{
FileInputStream fis = new FileInputStream(f);
props = new Properties();
props.load(fis);
fis.close();
loadParams();
}
catch (IOException e)
{
}
}
}
/**
Set the parameters object to the settings in the properties object.
*/
private void loadParams()
{
(SerialSettings.parameters).setPortName(props.getProperty("portName"));
(SerialSettings.parameters).setBaudRate(props.getProperty("baudRate"));
(SerialSettings.parameters).setFlowControlIn(props.getProperty("flowControlIn"));
(SerialSettings.parameters).setFlowControlOut(props.getProperty("flowControlOut"));
(SerialSettings.parameters).setParity(props.getProperty("parity"));
(SerialSettings.parameters).setDatabits(props.getProperty("databits"));
(SerialSettings.parameters).setStopbits(props.getProperty("stopbits"));
SerialSettings.setSerialPanel();
}


// Handles closing down system. Allows application to be closed with window close box.

class CloseHandler extends WindowAdapter
{

Frame sp;

public CloseHandler(Frame sp)
{
this.sp = sp;
}

public void windowClosing(WindowEvent e)
{
sp.setVisible(false);
try {
term.close();
}
catch (NullPointerException ex) { }
System.out.println("Program End");
System.exit(0);
}
}
private int detectComma(String text)
{
int i;
for (i=0; i < text.length()-1; i++ )
{
if (text.charAt(i)==',')
break;
}
return i;
}

// parsing SMS commands
public void parse_command(String at_command)
{
String temp;
int comma;

if ((at_command.toUpperCase()).startsWith("READSMS "))
{
int index= Integer.parseInt(at_command.substring(8, 9), 10);
term.ReadSMS(index);
}

if ((at_command.toUpperCase()).startsWith("DELETESMS "))
{
int index= Integer.parseInt(at_command.substring(10, 11), 10);
term.DeleteSMS(index);
}


else if ((at_command.toUpperCase()).startsWith("SENDSMS "))
{
temp = at_command.substring(8, at_command.length());
comma = detectComma(temp);
if (comma!=0)
{
if (temp.charAt(comma+1)==' ') temp=temp.substring(0,comma+1)+temp.substring(comma+2,temp.length());
term.SendMessage(temp.substring(0, comma), "", temp.substring(comma + 1, temp.length()));
}
}

else if ((at_command.toUpperCase()).startsWith("WRITERXSMS "))
{
temp = at_command.substring(11, at_command.length());
comma = detectComma(temp);
if (comma!=0)
{
if (temp.charAt(comma+1)==' ') temp=temp.substring(0,comma+1)+temp.substring(comma+2,temp.length());
term.WriteRxMessage(temp.substring(0, comma), "", temp.substring(comma + 1, temp.length()));
}
}

else if ((at_command.toUpperCase()).startsWith("WRITETXSMS "))
{
temp = at_command.substring(11, at_command.length());
comma = detectComma(temp);
if (comma!=0)
{
if (temp.charAt(comma+1)==' ' ) temp=temp.substring(0,comma+1)+temp.substring(comma+2,temp.length());
term.WriteTxMessage(temp.substring(0, comma), "", temp.substring(comma + 1, temp.length()));
}
}

else // Ordinary AT-Commands
{
term.atCmd(at_command, 0, 500);
}

}


// For typing AT Command in Input window
class KeyHandler extends KeyAdapter
{

public KeyHandler()
{

}
public void keyTyped(KeyEvent evt)
{

if ((int) evt.getKeyChar() == 10)
{
parse_command(at_command);
at_command = "";
}
else
{
at_command=at_command + evt.getKeyChar();
}
}
}

}




/////////////////// sms terminal////////////////////////////////////////////////////////////////





// SMS Tool for handling SMS communication with a mobile terminal
// (C) 2001 by Stefan Moscibroda

// Class for handling the serial connection and protocol support



import java.io.*;
import java.util.*;
import javax.comm.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
import java.util.TooManyListenersException;


public class SmsTerminal implements SerialPortEventListener, CommPortOwnershipListener {
public static final int SC_OK = 0;
public static final int SC_ERROR = 1;
public static final int SC_PDU_PARSE_ERROR = 2;

private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public IncomingSms rx_sms = null;
private Sms_GUI parent;
private SerialParameters parameters;
private TextArea OutTextArea;
private TextArea InTextArea;

private static final String lfcr = "\r\n";

public int portStatus = OK;
private Boolean portStatusLock = new Boolean(true);
private boolean POLLING_FLAG;
private String portStatusMsg = "";
private static final int OK = 1;
private static final int WAIT = 2;
private static final int ERROR = 3;
private static final int WMSG = 4;
private static final int RMSG = 5;
private static final int ECHO = 6;
private static final int TIMEOUT = 7;

private CommPortIdentifier portId;
private SerialPort sPort;

private byte[] readBuffer = new byte[20000]; // serialEvent
private int bufferOffset = 0; // serialEvent

public SmsTerminal(Sms_GUI parent,
SerialParameters parameters,
TextArea OutTextArea,
TextArea InTextArea) {
this.parent = parent;
this.parameters = parameters;
this.OutTextArea = OutTextArea;
this.InTextArea = InTextArea;
}


public void openConnection() throws IOException {

// Obtain a CommPortIdentifier object for the port you want to open.
try {
portId =
CommPortIdentifier.getPortIdentifier(parameters.getPortName());
} catch (NoSuchPortException e) {
throw new IOException(e.getMessage());
}

// Open the port represented by the CommPortIdentifier object. Give
// the open call a relatively long timeout of 30 seconds to allow
// a different application to reliquish the port if the user
// wants to.
try {
sPort = (SerialPort)portId.open("MobileAccess", 500);
} catch (PortInUseException e) {
throw new IOException(e.getMessage());
}


// Set the parameters of the connection. If they won't set, close the
// port before throwing an exception.
try {
setConnectionParameters();
} catch (IOException e) {
sPort.close();
throw e;
}

// Open the input and output streams for the connection. If they won't
// open, close the port before throwing an exception.
try {
outStream = sPort.getOutputStream();
inStream = sPort.getInputStream();
} catch (IOException e) {
sPort.close();
throw new IOException("Error opening i/o streams");
}

// Add this object as an event listener for the serial port.
try {
sPort.addEventListener(this);
} catch (TooManyListenersException e) {
sPort.close();
throw new IOException("too many listeners added");
}

// Set notifyOnDataAvailable to true to allow event driven input.
sPort.notifyOnDataAvailable(true);

// Add ownership listener to allow ownership event handling.
portId.addPortOwnershipListener(this);

// Turn off command echo
atCmd("ATE0", 0, 1000);

}


/**
Handles ownership events. If a PORT_OWNERSHIP_REQUESTED event is
received a dialog box is created asking the user if they are
willing to give up the port. No action is taken on other types
of ownership events.
*/
public void ownershipChange(int type) {
if (type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED) {
PortRequestedDialog prd = new PortRequestedDialog(parent, this);
}
}


/**
Sets the connection parameters to the setting in the parameters object.
If set fails return the parameters object to origional settings and
throw exception.
*/
private void setConnectionParameters() throws IOException {

// Save state of parameters before trying a set.
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();

// Set connection parameters, if set fails return parameters object
// to original state.
try {
sPort.setSerialPortParams(parameters.getBaudRate(),
parameters.getDatabits(),
parameters.getStopbits(),
parameters.getParity());
} catch (UnsupportedCommOperationException e) {
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
throw new IOException("Unsupported parameter");
}

// Set flow control.
try {
sPort.setFlowControlMode(parameters.getFlowControlIn()
| parameters.getFlowControlOut());
} catch (UnsupportedCommOperationException e) {
throw new IOException("Unsupported flow control");
}
}



// To be used to send AT command via the IR/serial link to the mobile
// device (for standard AT commands use mode=0)
public synchronized int atCmd(String cmd, int mode, int timeout) {

synchronized(portStatusLock) {
portStatus = WAIT;

try {
if (mode == 0)
// normal end of at command
outStream.write((cmd + lfcr).getBytes());
if (mode == 1)
// end of pdu <CTRL+Z>
outStream.write((cmd + "\032").getBytes());
if (mode == 2)
// no lfcr: used for polling (just echoed back)
outStream.write((cmd).getBytes());

} catch (IOException e) { ; }

// wait for response from device
try {
// Respond time can vary for different types of AT commands and mobiles!
portStatusLock.wait(timeout);
} catch (InterruptedException e) { }

}

return OK;
}

// Terminates IR/Serial connection to Mobile device
public void close() {

// Turn on again command echo
atCmd("ATE1", 0, 1000);
if (sPort != null) {
try {
// close the i/o streams.
outStream.close();
inStream.close();
} catch (IOException e) {
System.err.println(e);
}

// Close the port.
sPort.close();

// Remove the ownership listener.
portId.removePortOwnershipListener(this);
}

}

// Listener Function: Data received from serial link and interpreted
public void serialEvent(SerialPortEvent event) {

switch (event.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: break;
case SerialPortEvent.DATA_AVAILABLE:
int n;

try {
if (POLLING_FLAG == false) {
while ( (n = inStream.available()) > 0) {
n = inStream.read(readBuffer, bufferOffset, n);
bufferOffset += n;

String sbuf = new String(readBuffer,0,bufferOffset-2);

// lfcr detected, line ready
if(((readBuffer[bufferOffset-1] == 10) &&
(readBuffer[bufferOffset-2] == 13))) {

lineReceived(sbuf);
bufferOffset = 0;
}
}
}
else portStatus = ECHO;

} catch (IOException e) { ; }

break; // end: case SerialPortEvent.DATA_AVAILABLE:
}
}

// used for analyzing mobile response
private void lineReceived(String buffer) {

String response;
StringTokenizer st = new StringTokenizer(buffer, "\r\n");
rx_sms = null;
synchronized(portStatusLock) {
while (st.hasMoreTokens()) {
response = st.nextToken();
InTextArea.append(response + lfcr);
if (response.startsWith("OK")) {
portStatus = OK;
portStatusLock.notify();
InTextArea.append(lfcr);
} else if (response.startsWith(">")) {
portStatus = WMSG;
} else if (response.startsWith("ERROR")) {
portStatus = ERROR;
} else if (response.startsWith("+CME ERROR") ||
response.startsWith("+CMS ERROR")) {
portStatus = ERROR;
portStatusMsg = response;
}

else if (response.startsWith("07") || response.startsWith("00")) {

try {
rx_sms = new IncomingSms(response);
portStatusLock.notify();

InTextArea.append("\r\nSMS received: " + rx_sms.toString()+"\r\n");

} catch (PduParseException e) {
System.err.println("Error receiving SMS message: unable to parse PDU:\r\n"+
response);
portStatus = ERROR;
}
}
else { }
}

}
return;
}



// Send an SMS to number (using SMS central having number "smsc_number")
public synchronized void SendMessage(String number, String smsc_number, String msg) {

// to specify specific SMS settings (character coding, sms type, ...)
int tpPid = 0x00;
int tpDcs = 0x00;

if(number.startsWith("+"))
number = number.substring(1);
if(smsc_number.startsWith("+"))
smsc_number = smsc_number.substring(1);

try {

OutgoingSms pdumsg = new OutgoingSms(number, smsc_number, msg, tpPid, tpDcs);

String cmd = "AT+CMGS=" + pdumsg.length();
String pdu = pdumsg.toString();

atCmd(cmd,0,500); // Delay needed -> Waiting for ">" Prompt, otherwise Error MSG!
// For some mobiles > 1000 ms!
atCmd(pdu,1,1500);

} catch (Exception e) {
System.err.println("Irregular SMS format"); }

}


// Write SMS to phone/SIM memory (tranmit format)
/* public synchronized void WriteTxMessage(String number, String smsc_number, String msg) {

// to specify specific SMS settings (character coding, sms type, ...)
int tpPid = 0x00;
int tpDcs = 0x00;

if(number.startsWith("+"))
number = number.substring(1);
if(smsc_number.startsWith("+"))
smsc_number = smsc_number.substring(1);

try {

OutgoingSms pdumsg = new OutgoingSms(number, smsc_number, msg, tpPid, tpDcs);

String cmd = "AT+CMGW=" + pdumsg.length();
String pdu = pdumsg.toString();

atCmd(cmd,0,500);

atCmd(pdu,1,1500);

} catch (Exception e) {
System.err.println("Irregular SMS format"); }

}


// Write SMS to phone/SIM memory (received format)
public synchronized void WriteRxMessage(String number, String smsc_number, String msg) {

// to specify specific SMS settings (character coding, sms type, ...)
int tpPid = 0x00;
int tpDcs = 0x00;

if(number.startsWith("+"))
number = number.substring(1);
if(smsc_number.startsWith("+"))
smsc_number = smsc_number.substring(1);

try {

OutgoingSms pdumsg = new OutgoingSms(number, smsc_number, msg, tpPid, tpDcs);
GregorianCalendar time = new GregorianCalendar();
pdumsg.transform_to_received_SMS(time);
String pdu_r = pdumsg.toString();

// Important: PDU of SMS to be stored in RECEIVED (,0) folder
// must follow received SMS PDU format!
String cmd_r = "AT+CMGW=" + pdumsg.length() + ",0";

atCmd(cmd_r,0,500);

atCmd(pdu_r,1,1500);

} catch (Exception e) {
System.err.println("Irregular SMS format"); }

}

// Read SMS from Mobile/SIM storage having index i
public synchronized void ReadSMS(int i) {

atCmd("AT+CMGR=" + i, 0, 1000); // Receive SMS

}


// Delete SMS from Mobile/SIM storage having index i
public synchronized void DeleteSMS(int i) {

atCmd("AT+CMGD=" + i, 0, 1000); // Delete SMS

}*/

}




///////////////////////////////////////////////////////////////////////////////////////////////////////// outgoing sms class////////////////////////////////////////////////////////////////////////////////
// Serial SMS Client for handling SMS communication with a mobile terminal
// (C) 2001 by Stefan Moscibroda


// class representing outgoing SMS


import java.util.*;

public class OutgoingSms {
public final int SMS_MSG_ENCODING_7BIT = 0;

private int smscAddressLength= 0x00;
private int smscAddressType = 0x91;
public String smscAddress;
private String smscAddressEnc;
private int smsSubmitCode = 0x11;
private int tpMsgRef = 0;
private int recipientAddressLength;
private int recipientAddressType = 0x91;
public String recipientAddress;
private String recipientAddressEnc;
public int tpPid;
public int tpDcs;
private int tpValidity = 0xaa;
private int tpUdl; // message length.
private String tpUd; // user message (as sent).
public String msg; // user message (unencoded).

private String pdu;

public OutgoingSms(String recipientAddress, String smscAddress,
String msg, int tpPid, int tpDcs) {
this.recipientAddress = recipientAddress;
this.smscAddress= smscAddress;
this.msg = msg;
this.tpPid = tpPid;
this.tpDcs = tpDcs;
StringBuffer sb = new StringBuffer(320);
smscAddressLength = smscAddress.length();

// Internal smsc Adress settings taken from mobile
// if other add smscAddressType and smscAddressType to sb.

if(smscAddressLength == 0) {

sb.append("00"); // Optional, some mobile don't work if added

}

else {

// add smscAddressType and smscAddressType to sb.
sb.append(SmsPduCodec.toHexString(0x07));

if( (smscAddressLength%2) == 1 )
smscAddressEnc = SmsPduCodec.swapDigits(smscAddress+"F");
else
smscAddressEnc = SmsPduCodec.swapDigits(smscAddress);

sb.append(SmsPduCodec.toHexString(smscAddressType));
sb.append(smscAddressEnc);
}

sb.append(SmsPduCodec.toHexString(smsSubmitCode));
sb.append(SmsPduCodec.toHexString(tpMsgRef));

// recipientAddress
recipientAddressLength = recipientAddress.length();
if ((recipientAddress.length() % 2) == 1 )
recipientAddressEnc = SmsPduCodec.swapDigits(recipientAddress+"F");
else
recipientAddressEnc = SmsPduCodec.swapDigits(recipientAddress);

sb.append(SmsPduCodec.toHexString(recipientAddressLength));
sb.append(SmsPduCodec.toHexString(recipientAddressType));
sb.append(recipientAddressEnc);
sb.append(SmsPduCodec.toHexString(tpPid));
sb.append(SmsPduCodec.toHexString(tpDcs));
sb.append(SmsPduCodec.toHexString(tpValidity));

// encode message and calculate message length.
if ((tpDcs & 4) == 0) {
tpUd = SmsPduCodec.sevenBitEncode(msg);
tpUdl = msg.length();
}
else {
tpUd = msg;
tpUdl = msg.length()/2;
}
sb.append(SmsPduCodec.toHexString(tpUdl));
sb.append(tpUd);
pdu = sb.toString();
}


public String toString() {

return pdu.toUpperCase();

}

public int length() {

if ((pdu.substring(0,2)).equals("00")) return (pdu.length()-2)/2;
else return (pdu.length()-16)/2;
}


// Transforms an outgoing to an incoming pdu
// contains no SMCS

public void transform_to_received_SMS(Calendar time) {

int length;
length=pdu.length();
// if no SMCS specified, otherwise adaption needed
int offset1;
String beginning;

if ((pdu.substring(0,2)).equals("00")) {
// if transmit without smsc adress enter dummy some smsc address
beginning="07911497949900F0";
offset1=6;
}
else {
beginning=pdu.substring(0,16);
offset1=20;
}

String addressLenStr = pdu.substring(offset1, offset1+2);
int senderAddressLength = Integer.parseInt(addressLenStr, 16);


int offset2= offset1 + 4 + senderAddressLength+senderAddressLength%2;

String pdu_r=beginning+"04"+pdu.substring(offset1, offset2+4);

// If errors with timestamp just enter dummy time stamp
// pdu_r=pdu_r+"00000000000000"+pdu.substring(offset2+6,length);

pdu_r=pdu_r+ SmsPduCodec.TimeStampEncode(time) +pdu.substring(offset2+6,length);

pdu=pdu_r;
}


}






Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

Please use code tags. Right now, your code is simply not readable.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
arun ram.ci
Greenhorn

Joined: Oct 15, 2009
Posts: 14
arun ram.ci
Greenhorn

Joined: Oct 15, 2009
Posts: 14
hai
really sorry i have posted the code with database connection terribly sorry here is the original source code which i have downloaded there are some more class files related to this code like alertdialog , portrequest , serial parameters,serial panel but this files deal with getting parameter for serial communication if you need i will send it .


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You can't expect people to read 1,000 lines of code. It would be much better if you displayed 50 lines of code which exhibit the problem you are asking about.
arun ram.ci
Greenhorn

Joined: Oct 15, 2009
Posts: 14
hai
i have given the code as small as possible for me, in this code while running applet will be generated which contains two message panel(in(response area) and out(AT command) message area),in the out message area i will type the AT commands (AT+CMGS="9965844325"<enter>,"hai buddy"<enter>) ,out message area extends to key handler class, in key handler class a method parse_command(at_command) is invoked , in the parse_command method will extend to sms terminal class , this sms terminal will extend for outgoing sms class for encoding and return to sms terminal class for sending sms....my question instead of typing the AT commands in the mesage area(applet gui) we can define the AT+CMGS="9965844325" and the message string "hai buddy" in code itself so that while running the code, message will be thrown to the number instead of entering AT commands in the applet gui, where i have to define this values in the code


 
Don't get me started about those stupid light bulbs.
 
subject: sms gateway