Sie sind auf Seite 1von 50

SMS via PC

SYNOPSIS
SMS is technology that contributed varied beneficial services to the world and is used in different applications. These applications include business and trade, Ebanking, as well as social and spiritual applications. Indeed, mobile phones have made tremendous contributions to society and to mankind. From its inception as a tool of communication used only by deaf or hearing impaired individuals, SMS or Short Messaging Service had turned into a very powerful means of communication. Also, SMS had made the world smaller and much better as people rapidly gain access to mobile phones. Moreover, it created a new way of system of communication all together.

1. INTRODUCTION
1.1 OBJECTIVE & SCOPE Objective: Global: You can send International SMS to any country on the Planet. Two-way: Receive replies from your loved ones in your Inbox, or forward them to your cell Affordable: Save money. Text message for a fraction of the cost of long distance telephone calls Easy to use: Send from a web browser, Outlook, IM, Hotmail, GMail or any other email client Great Service: Messages are delivered in seconds. Customer questions are answered within an hour Convenient: Time zones don't matter. Set your messages to arrive with a delay to surprise your friends! Flexible: Configure your account to meet your text messaging needs. No mobile phone required. Scope: People all over the globe can send and receive SMS messages without even having a mobile phone capable of this function. Usable from any Internet-ready computer or cellular phone, the ipipi.com service is changing the way people text message. Text messages arrive in seconds, cost around 10c each and let your friends reply. There is simply no other service that lets you send messages from any PC and deliver them to any mobile phone on the Planet.

1.2 OVERVIEW OF THE PROJECT


Short Message Service (SMS) The Short Message Service (SMS) allows text messages to be sent and received to and from mobile telephones. The text can comprise words or numbers or an alphanumeric combination. SMS was created as part of the GSM Phase 1 standard. The first short message is believed to have been sent in December 1992 from a PC to a mobile phone on the Vodafone GSM network in the UK. Each short message is up to 160 characters in length when Latin alphabets are used and 70 characters in length when non-Latin alphabets such as Arabic and Chinese are used. Phones with SMS (Short Message Service) features are becoming quite popular. SMS allows users to send brief text messages (up to 160 characters) from their mobile phone directly to the screen of a friends mobile phone (providing it also has the ability to receive SMS). SMS, because of its very nature has unique advantages that other non voice services do not have. It provides a very convenient method of exchanging small bits of information. The reasons for the enormous popularity of SMS have been the fact that this mechanism of sending and receiving messages not only saves time but costs less as well. In many situations one is relatively much more comfortable sending a message via SMS than talking over phone. With new information services and unique value added services being used by the operators the popularity of SMS is increasing further. SMS is also uniquely positioned as a very attractive advertisement medium. SMS should no longer be treated as a value added service in mobile networks. SMS is not only providing a useful mechanism for a host of innovative services over mobile networks but it acting as a point of entry for new data services like WAP in mobile networks.

SMS Applications and Advantages: SMS has countless contributions to the worlds and let's discuss some of them. Banking: SMS had contributed so much in terms of transactions like depositing and withdrawing money. Instead of people going to the banks to transact, the latter had instituted various ways so that the customers can perform bank transactions through short messaging service. This makes them complete their financial transactions with out leaving their offices and or their homes. Social Aspect: SMS has made old acquaintances and family members become continually in touch. Business: SMS allows for the sales and purchase of goods easier. By just sending and receiving text messages, both buyers and vendors of products need not have to meet face-to-face when trading. Spiritual Aspect: In religion and beliefs, SMS too had played a significant role in propagating the faith and inspiring the weary soul.

2 SYSTEM REQUIREMENTS
2.1 HARDWARE REQUIREMENTS 1. Processor 2. Hard Disk 3. RAM 4. 5. 6. Key Board Mouse : Pentium-IV, 2.4 MHz. : 40 GB : 256MB : 101 Keys Standard Keyboard :Optical Mouse

Mobile with USB Cable

2.2

SOFTWARE REQUIREMENTS Technology Operating System Document Tool : Java : Platform Independent : MS-Word

2.3

SOFTWARE DESCRIPTION AND FEATURES

Java Overview Java is a simple, object-oriented, distributed, int6erpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded and dynamic language and software platform. Java is a network-oriented programming language invented by Sun Microsystems that is specifically designed for writing programs that can be safely downloaded to your computer through the Internet and immediately run without fear of viruses or other harm to your computer or files. Using small Java programs (called applets), Web pages can include functions such as animation, specialized calculators, and other programs. Like any human language, Java provides a way to express concepts. If

successful, this medium of expression will be significantly easier and more flexible than the alternatives as problems grow larger and more complex. You cant look at Java as just a collection of features; some of the features make no sense in isolation.

You can use the sum of the parts only if you are thinking about design, not simply coding. History of Java On May 23, 1995, John Gage, director of the Science Office for Sun Microsystems, and Marc Andersen, co-founder and executive vice-president at Netscape, stepped onto a stage and announced to the Sun World audience that Java technology was real, it was official, and it was going to be incorporated into Netscape Navigator, the worlds portal to the Internet. At that time, the entire Java technology team, not yet a division, numbered less than 30 people. It was the original members of this small group who created and nurtured a technology that would change the computing world. Features of Java Java provides various advanced features when compared to many other languages. They are: Handles are always checked and exceptions are thrown for failures All array accesses are checked for bounds violations Automatic garbage collection prevents memory leaks Clean, relatively fool-proof exception handling Simple language support for multithreading Creating, compiling and executing Java programs Turning a Java source program into an object program takes a couple of steps. Assuming that you are using the popular, but awkward, JDK by Sun Microsystems, do the following: 1. Create the source program with a text editor (e.g. jEdit, Notepad,..). Save it in a file with the same name as the public class adding the extension .java (e.g. Demo.java). A common error is to use a different name for the file and the class. The name before the . Must be the same as the class name, including upper- or lower- case. Many programmers save their source file every 10

minutes or so Its quick and saves the aggravation of having to type it again if there is a system crash. 2. Open a DOS command window and cd to the directory containing the source file. This is easy if youve used short directory names without spaces. 3. Compile the source program (Demo.java in this example) with the following DOS command: javac Demo.java This produces one or more .class files, which are the object (Java byte code) form of Java programs. You can produce a .exe file from this, but that isnt normally done. 4. Run it with: java Demo This loads all the necessary classes. Execution starts with the main method in the class. . Java Virtual Machine Most compilers translate from the source language (e.g. C or Pascal) into machine language for one specific type of machine (e.g. Pentium or Sun). The machine language for a Sun computer is not the same as for a Macintosh, or a Windows machine. You cannot use the same machine code program on different kinds for machines.

Fig: Most compilers produce code for the real machine

Fig: Java compiler produces code for a virtual machine Fig: Comparison of compilers Java compilers translate applets in two steps. The first part of the translation is from Java source to JVM machine code. This may seem strange because there isnt any real machine that can use JVM instructions yet. JVM code is designed so that it is easy to translate it into machine instructions for real machines, so the second part of the translation to real machine instructions is done in the browser on the users

machine. The browser takes the applet JVM code that it gets from the server and translates from JVM code to the machine code the browser is using, e.g., a Pentium. This compiler in the browser often called a JIT compiler. JIT stands for Just-InTime, and it means that the last part of the compilation is done just before running the program. The diagram below shows how browsers on different machines use the same applet JVM code.

Fig: Java Virtual Machine Two-step compilation allows Java applets to run on many kinds of machines. Class libraries Sometimes someone may say that Java is a small language, smaller than C++, and perhaps smaller than C. This may be true if you ignore one of the most important things: the class libraries. There are a huge number of methods (the special OOP word for function) in the thousands of classes that are grouped in packages. Packages and OOP are the reasons that it is possible to have such large libraries.

Java components Components are the basic user interface elements the user interacts with: labels, buttons, text field components are placed in a container (e.g. Jpanel). The visual arrangement of the components depends on the containers layout. When the user does something to a component, the components listener is sent an event. Input components Buttons (JButton, Radio Button, JCheckBox) Text (JTextField, JTextArea) Menus (JMenuBar, JMenu, JMenuItem) Sliders (JSlider) Combo Boxes (JComboBox)

Information display components JLabel Progress bars (JProgressBar) Tool tips (using JComponent's setToolTipText(s) method)

Choosers File Chooser (JFileChooser) Color Chooser (JColorChooser)

More complex displays Tables (JTable) Trees (JTree) Formatted Text

Methods Introduction The word method is commonly used in Object-Oriented Programming and is used in Java. It means the same as function, procedure, or subroutine in other Many programmers use these other terms, especially programming languages.

function, but these notes will use method.

Why use methods? For reusable code: If you need to do the same thing, or almost the same thing many times, write a method to do it, then call the method each time you have to do that task. To parameterize code: In addition to making reusable code that is the same in all cases, you will often want to use parameters that change the way the method works. For top-down programming: A very useful style of programming is called topdown programming. You solve a big problem (the top) by breaking it down into little problems. To do this in a program, you write a method for solving your big problem by calling on other methods to solve the smaller parts of the problem. And these methods for solving the simpler problems similarly call on other methods until you can get down to simple methods that help solve simple problems. To create conceptual units: Create methods to do something that is one action in your mental view of the problem. This will make it much easier for you to work with your programs. To simplify: As local variables and statements of a method cannot be seen from outside the method, they (and their complexity) are hidden from other parts of the program, which prevents accidental errors or confusion.

Main If you have a main method, it must be declared as public static void main (String args[]) { } Return If a method does not return a value, there is no need for a return statement. If a method returns a non-void value, it must use a return statement.

Classes and Interfaces Class definition A class definition prototype: Visibility class class-name [extends parent-class] [implements interface-name..] {class-body}

Name

Meaning Public - Visible to everyone. Private - Visible only in this class. Protected Visible in this class and all subclasses The default visibility is package visibility where everyone in the package can see it. This is the name of the parent class of this class. The default parent class is Object. For each interface that is implemented, this class must define all methods in that interface.

Visibility

Parent-class Interface-name Arrays Introduction

An array can store many similar values in memory. The word array in Java means approximately the same thing as array, matrix or vector does in math. Unlike math, you must declare the array and allocate a fixed amount of memory for it. Declaring an array An array variable is like other variables you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then [], then the name of the array variable. The declaration only allocates space associated with a variable name for a reference to an array, but doesnt create the actual array object. String[] args; // args is an array of Strings int[] scores; // scores is an array of integers Jbutton[] bs; // bs is an array of Jbuttons Unlike some languages, never put the size of the array in the declaration because an array declaration only tells Java that the variable is an array and the element type. Allocating an array object

Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99]. int[] a ; // Declares a to be an array of integers a = new int[100] ; // Allocates an array of 100 integers Import Following the optional package declaration, you can have import statements, which allow you to specify classes that can be reference without qualifying them with their package. Packages are directories or folders that contain the Java classes, and are a way of grouping related classes together. For small programs, it is common to omit a package specification. (Java creates a default package in this case). Swing and AWT The original GUI for Java was called the Abstract Windowing Toolkit. Performance and extendibility problems with the AWT were resolved by introducing a new GUI interface, known as Swing. Swing provides replacements for most of the AWT components, although many AWT non-component classes remain in use. Upward compatibility is assured in almost all cases; an AWT continues to work in Java.

Choosing between Swing and AWT Mixing both Swing and AWT components in the same interface can produce errors, so one has to make a decision about which to use. Despite the advantages of Swing, there actually are arguments for using AWT. Swing Swing is a new GUI component kit that simplifies and streamlines the development of windowing components. Windowing components are the visual components (such as menus, tool bars, dialogs and the like) that are used in graphicsbased applets and applications. The Swing component set is part of the new class library called the Java Foundation Classes, or JFC. Swing makes up the bulk of JFC. JFC is also comprised of Java 2D, Drag and Drop, and Accessibility APIs. Until Swing1.0 was released, Java-language programmers created GUIs for their applets and applications using the AWT, which is a standard package provided with the Java programming language. Swing components are so much more powerful and elegant than their AWT counterparts that just about all Java-language developers are now migrating to Swing. Swing components allow for efficient graphical user interface (GUI) development. Swing components are a collection of lightweight visual components. They contain replacements for the basic heavyweight AWT components as well as complex userinterface components such as trees and tables. Swing components contain a This allows the same pluggable look-and-feel abbreviated as PL&F or plaf.

application to run with a native look-and-feel on different platforms. For example, when running on a Windows platform, the application will look like an application written specifically for the Windows-based computer. The same application, when run on an Apple Macintosh computer, looks like it was written specifically for the Macintosh. When the application is run on a UNIX workstation, it looks like a UNIX application, and so on for any platform to which the JVM has been ported. Swing components are also Java Bean compliant. With a lot of great new features provided by the JFC, it may be asked if the AWT is required at all. The answer is yes, it is. This is because Swing is an extension for the AWT, and not a replacement.

Fig: The Swing architecture Accessibility and Swing Another important feature of the Swing set is its accessibility, that is, its compatibility with hardware and software designed for people with special needs, such as limited sight or the inability to operate a mouse. Accessibility is an important feature of Swing, because the Swing set is the only Java-language component set that can be used to write Web content that is accessible to disabled people. Furthermore, accessible applications can be beneficial to people who are not disabled. For instance, the Java Accessibility API makes it easy to create touchscreen programs such as those using in kiosks.

The diagram shows how Swing sits on top of a number of the APIs that implement the various parts of the JFC - including the Java 2D and Drag and Drop

APIs. Although both those APIs are part of JFC, they are not part of Swing. That is because certain tasks that they perform require use of native code. Swing components, as we have seen, never rely on peer code. So Java 2D and Drag and Drop appear beneath, not inside, the rectangle labeled Swing in the diagram. So does the old-style AWT component set which is extended (but not replaced) by Swing. Advantages of Swing Fast More complete than AWT Swing is being actively improved

Weaknesses of Java Although Java is arguably the best overall programming language, there are problems with it too. Installing Java programs: Elliott Rusty Harold, author of several good books on Java, described one of Javas main problems are Javas insanely complex, difficult and unintuitive installation process. You wont find any disagreement with this, although it has improved in recent versions. Changes: Java has several versions 1.0, 1.1, the Java2 series (1.2, 1.3, 1.4), and a mysterious leap in numbering to Java 5 (also known as Java 1.5). Each version contains major improvements, but this has also created compatibility problems. Speed: Java programs run faster than Visual Basic programs, but are sometimes slower than C programs. Javas speed has been improving with every new version, and it is now close to C/C++. To put this in perspective, the difference in speed is probably less than the hardware speed improvement in one year. Lack of a few features: Java lacks a few features that some C++ programmers find useful, for example, macros and operator overloading. Many of the features of C++ that are not in Java have been removed to make the language better (e.g. pointers and multiple inheritance).

Enemies: As the portability of Java programs allows users to move programs from one operating system to another, users are no longer locked into one system. Java has been a great threat to Microsofts monopoly, and therefore, Microsoft has opposed it for many years, making integrating with Windows awkward. More recently, Microsoft has responded by creating C#, a language which is pretty much a clone of Java. Apple Computer likewise shows little enthusiasm as suggested by their poor support for Java. It is, of course, good business strategy to create large switching costs for your customers. But it is not in the customers interests.

3. SYSTEM STUDY
3.1 EXISTING SYSTEM 1. Sending SMS One By One 2. Must need Broadband connection and SMS gateway 3. We cant generate Reports for Past Data 4. No Auto Responder

3.2 PROPOSED SYSTEM 1. Easy to carry any where 2. Easy to transfer any data as SMS text 3. Data queuing is enabled 4. Easy to generate the past reports 5. Auto Response for incoming Messages- by Read & Answer Method.

3.3 COMPONENT DETAILS Modules: This project developed under the following modules. Mobile Connector Load Contacts Create Content to Send Sending SMS Reports

Module Description: Mobile Connector: In this module the user connect the mobile with the system via USB port and the mobile connector find the mobile compatibility for send message. Load Contacts This module is mainly used for store the mobile numbers as text file. Create Content to Send This module is mainly used for which content to send as a message and its saved in a text file. Sending SMS: This module sent the saved content to all contacts one by one. Reports: In this module, user can view the successfully sent message contacts.

4.

System Analysis

4.1 FEASIBILITY STUDY 4.1.1 Technical Feasibility Technical feasibility deals hardware as well as software requirements. The hardware requires, deals with Pentium based server and software in Java. If necessary requirements are made available with the system then the proposed system is said to be technically feasible. Here the proposed system is Technically Feasible. 4.1.2 Economical Feasibility Even though an initial investment has to be made on the software and the Hardware aspects, the proposed system aims on at processing of transaction efficiently, thus saving the time and money. Since the existing system is manual on the possibility for the wrong data entry in higher and consumes a lot of time. Thus benefits acquired out of the system are sufficient for the project to undertaken. It also fast access for viewing reports. So the proposed system is economically feasible. 4.1.3 Operational Feasibility The proposed system offers greater user friendliness combined with greater processing speed. 4.2 DATA FLOW DIAGRAM The data flow diagram (DFD) is one of the most important tools used by system analysis. Data flow diagrams are made up of a symbol, which represent system components. Most data flow modeling methods use four kinds of symbols. These symbols are used to represent four kinds of system components processor, data stores, data flows and external entities. Circles represent processors. Data flow is represented by a thin line, data store has a unique name and represented by open rectangle represents external entities.

Modules

Process

Link

DataBase

Connect the Mobile

Load Contacts

Create Content to Send

Sending sms

Report

4.3 SYSTEM FLOW DIAGRAM

System Read Numbers Load contacts

Connection Mobile Phone Sending SMS Report Create Content to send Sending SMS Read Content to Send

4.4 I/O FORM DESIGN 4.4.1 Input design The input design is the process of converting an external user oriented description of the input to system in to machine oriented format the source document was prepared for the input of data in order at make. Here the Text file which contains the list of Cell Nos and Text messages that is to be sent are given as input. 4.4.2 Output Design: The output design of this Project should be like the Report that display the information of

5. TESTING & IMPLEMENTATION

Introduction: Testing is an activity that ensures whether a correct system is built it or not. It is carried out not only after the development phase is completed, but also is parallel with all stages of development. Objectives of Testing: 1. 2. 3. First it executes the program to find errors. The good test case is the higher probability of finding The successful test is to cover the undiscovered errors. Testing is the process, which includes verification and validation of software. Verification is the process of checking whether developed software is right and validation is the process of checking whether the right software is being developed in a right manner or not. Testing is performed with the intention of finding errors, so it has to be performed by a third party other than that developed the software. Testing For Real Time System: The testing of this project is undertaken carefully. Various functional units of the software are tested according to the testing strategies. Testing of this system provided master challenges when conducted. Testing should not be done as a single phase; it should be integrated with all phases of the software development life cycle. Testing seems to be negative but it is the process, which brings out the creativity of the software professional. Test data or test case is to be designed before testing begins. Testing can be performed at different stages.

undiscovered errors.

Based on this, testing is classified into various types: Unit Testing Black Box Testing White Box Testing Integration Testing Validation Testing 5.1 Unit Testing: Testing should be started as early as possible in the software development process. Unit testing involves testing individual modules or units of errors. As each unit developed it is tested for errors by test team, which consists of members not in the development team. The project leader just explains the requirements and functionality of the module and hands over the module to the testers. They validate the module against the requirements gathered. Any errors found are reported to the project team for correction. 5.2 Black Box Testing: Black Box testing attempts to find error in the following categories. Incorrect or missing functions Interface errors Errors in data structures or external data base access Performance errors Initialization and termination errors Using this method the functional validity is tested, good test cases are found, and they are verified. The system sensitivity is checked for certain input values. The tolerance of data rates and data volume of the system is verified.

5.3 White Box Testing: This is a test case design method that uses the control structure of the procedural design to derive test cases, Using it, the software engineer, can derive test cases that, All independent paths within a module have been checked Exercise all logical decision on their true and false sides Exercise all loops at their boundaries and within operational bounds Exercise internal data structure to assure their validity 5.4 Integration Testing The need for the integrated test is to find the overall system performance. Once each module has been tested individually it has to be integrated into a single system. While testing the whole application were can expect many errors because there should be proper interaction between modules. So integrated testing has been performed successfully after uniting all modules. 5.5 Validation Testing At the culmination of integration testing, software is completely assembled as a package, interfacing errors have been uncovered and corrected and a final series of software upon which validation tests begin. Validation testing can be defined in many was but a simple definition id that validation succeeds when the software function is a manner that can be relationally expected by the client. After validation test has been conducted one of the two possible condition exits the function or performance characteristics conform to specification and are expected. A deviation from specification is uncovered and a deficiency list is created.

5.6 Implementation The implementation of a computer based system requires to be tested first so that one can firm whether it work effectively. It is also tested on the basis of its performable and effectiveness. The tested should be carried out is a well planned and it is structured manner to see whether there are only loop holes and there loop holes must be effectively removed. There is no need for qualified or trained persons for operating the developed system because it has been developed in a user-friendly manner with all the necessary help menus.

6. FUTURE ENHANCEMENT
This project has been design; develop, flexible according to the current requirement of the user needs. It can be expanded in future with the following aspect. o o Provide the facility to send MMS Provide the facility to send horoscope, news details through SMS.

7. CONCLUSION
People all over the globe can send and receive SMS messages without even having a mobile phone capable of this function. Usable from any Internet-ready computer or cellular phone, the ipipi.com service is changing the way people text message. Text messages arrive in seconds, cost around 10p each and let your friends reply. There is simply no other service that lets you send messages from any PC and deliver them to any mobile phone on the Planet.

8. APPENDIX
8.1 Sample Coding Sms Client: public class SMSClient implements Runnable { public final static int SYNCHRONOUS=0; public final static int ASYNCHRONOUS=1; private Thread myThread=null; private int mode=-1; private String recipient=null; private String message=null; public int status=-1; public long messageNo=-1; public SMSClient(int mode) { this.mode=mode; } public int sendMessage (String recipient, String message) { this.recipient=recipient; this.message=message; //System.out.println("recipient: " + recipient + " message: " + message); myThread = new Thread(this); myThread.start(); // run(); return status; } public void run() { Sender aSender = new Sender(recipient,message); try{ //send message aSender.send (); // System.out.println("sending ... "); //in SYNCHRONOUS mode wait for return : 0 for OK, -2 for timeout, -1 for other errors

if (mode==SYNCHRONOUS) { while (aSender.status == -1){ myThread.sleep (1000); } } if (aSender.status == 0) messageNo=aSender.messageNo ; }catch (Exception e){ e.printStackTrace(); } this.status=aSender.status ; aSender=null; } } Serial Connection: import javax.comm.*; import java.io.*; import java.awt.TextArea; import java.awt.event.*; import java.util.TooManyListenersException; /** A class that handles the details of a serial connection. Reads from one TextArea and writes to a second TextArea. Holds the state of the connection. */ public class SerialConnection implements SerialPortEventListener, CommPortOwnershipListener { // private SerialDemo parent; /* private TextArea messageAreaOut; private TextArea messageAreaIn; */ private SerialParameters parameters; private OutputStream os; private InputStream is; private KeyHandler keyHandler; private CommPortIdentifier portId; private SerialPort sPort;

private boolean open; private String receptionString=""; public String getIncommingString(){ byte[] bVal= receptionString.getBytes(); receptionString=""; return new String (bVal); } /** Creates a SerialConnection object and initilizes variables passed in as params. @param parent A SerialDemo object. @param parameters A SerialParameters object. @param messageAreaOut The TextArea that messages that are to be sent out of the serial port are entered into. @param messageAreaIn The TextArea that messages comming into the serial port are displayed on. */ public SerialConnection(SerialParameters parameters) { this.parameters = parameters; open = false; } /** Attempts to open a serial connection and streams using the parameters in the SerialParameters object. If it is unsuccesfull at any step it returns the port to a closed state, throws a <code>SerialConnectionException</code>, and returns. Gives a timeout of 30 seconds on the portOpen to allow other applications to reliquish the port if have it open and no longer need it. */ public void openConnection() throws SerialConnectionException { // System.out.println("OK 0 "); // Obtain a CommPortIdentifier object for the port you want to open. try { // System.out.println(parameters.getPortName()); portId = CommPortIdentifier.getPortIdentifier(parameters.getPortName()); } catch (NoSuchPortException e) { // System.out.println("Yes the problem is here 1 "); e.printStackTrace(); // throw new SerialConnectionException(e.getMessage()); }catch(Exception e) {

// System.out.println("ErrorErrorErrorError"); e.printStackTrace(); } //System.out.println(portId); //System.out.println("OK 1 "); // 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("SMSConnector", 30000); } catch (PortInUseException e) { throw new SerialConnectionException(e.getMessage()); } //System.out.println("OK 2 "); sPort.sendBreak(1000); // Set the parameters of the connection. If they won't set, close the // port before throwing an exception. try { setConnectionParameters(); } catch (SerialConnectionException e) { sPort.close(); throw e; } // System.out.println("OK 3 "); // Open the input and output streams for the connection. If they won't // open, close the port before throwing an exception. try { os = sPort.getOutputStream(); is = sPort.getInputStream(); } catch (IOException e) { sPort.close(); throw new SerialConnectionException("Error opening i/o streams"); } //System.out.println("OK 4 "); /* // Create a new KeyHandler to respond to key strokes in the // messageAreaOut. Add the KeyHandler as a keyListener to the // messageAreaOut. keyHandler = new KeyHandler(os); messageAreaOut.addKeyListener(keyHandler); */ // Add this object as an event listener for the serial port. try { sPort.addEventListener(this); } catch (TooManyListenersException e) { sPort.close(); throw new SerialConnectionException("too many listeners added");

} //System.out.println("OK 5 "); // Set notifyOnDataAvailable to true to allow event driven input. sPort.notifyOnDataAvailable(true); // Set notifyOnBreakInterrup to allow event driven break handling. sPort.notifyOnBreakInterrupt(true); // Set receive timeout to allow breaking out of polling loop during // input handling. try { sPort.enableReceiveTimeout(30); } catch (UnsupportedCommOperationException e) { } //System.out.println("OK 6 "); // Add ownership listener to allow ownership event handling. portId.addPortOwnershipListener(this); open = true; } /** Sets the connection parameters to the setting in the parameters object. If set fails return the parameters object to origional settings and throw exception. */ public void setConnectionParameters() throws SerialConnectionException { // 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 SerialConnectionException("Unsupported parameter"); }

// Set flow control. try { sPort.setFlowControlMode(parameters.getFlowControlIn() | parameters.getFlowControlOut()); } catch (UnsupportedCommOperationException e) { throw new SerialConnectionException("Unsupported flow control"); } } /** Close the port and clean up associated elements. */ public void closeConnection() { // If port is alread closed just return. if (!open) { return; } // // Remove the key listener. messageAreaOut.removeKeyListener(keyHandler); // Check to make sure sPort has reference to avoid a NPE. if (sPort != null) { try { // close the i/o streams. os.close(); is.close(); } catch (IOException e) { System.err.println(e); } // Close the port. sPort.close(); // Remove the ownership listener. portId.removePortOwnershipListener(this); } open = false; } /** Send a one second break signal. */ public void sendBreak() { sPort.sendBreak(1000); } /** Reports the open status of the port.

@return true if port is open, false if port is closed. */ public boolean isOpen() { return open; } /** Handles SerialPortEvents. The two types of SerialPortEvents that this program is registered to listen for are DATA_AVAILABLE and BI. During DATA_AVAILABLE the port buffer is read until it is drained, when no more data is availble and 30ms has passed the method returns. When a BI event occurs the words BREAK RECEIVED are written to the messageAreaIn. */ public void serialEvent(SerialPortEvent e) { // Create a StringBuffer and int to receive input data. StringBuffer inputBuffer = new StringBuffer(); int newData = 0; // Determine type of event. switch (e.getEventType()) { // Read data until -1 is returned. If \r is received substitute // \n for correct newline handling. case SerialPortEvent.DATA_AVAILABLE: while (newData != -1) { try { newData = is.read(); if (newData == -1) { break; } if ('\r' == (char)newData) { inputBuffer.append('\n'); } else { inputBuffer.append((char)newData); } } catch (IOException ex) { System.err.println(ex); return; } } // Append received data to messageAreaIn. receptionString=receptionString+ (new String(inputBuffer)); //System.out.print("<-"+receptionString); break; // If break event append BREAK RECEIVED message. case SerialPortEvent.BI:

receptionString=receptionString+("\n--- BREAK RECEIVED ---\n"); } } /** 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); } */ } /** A class to handle <code>KeyEvent</code>s generated by the messageAreaOut. When a <code>KeyEvent</code> occurs the <code>char</code> that is generated by the event is read, converted to an <code>int</code> and writen to the <code>OutputStream</code> for the port. */ class KeyHandler extends KeyAdapter { OutputStream os; /** Creates the KeyHandler. @param os The OutputStream for the port. */ public KeyHandler(OutputStream os) { super(); this.os = os; } /** Handles the KeyEvent. Gets the <code>char</char> generated by the <code>KeyEvent</code>, converts it to an <code>int</code>, writes it to the <code> OutputStream</code> for the port. */ public void keyTyped(KeyEvent evt) { char newCharacter = evt.getKeyChar(); if ((int)newCharacter==10) newCharacter = '\r'; System.out.println ((int)newCharacter); try { os.write((int)newCharacter);

} catch (IOException e) { System.err.println("OutputStream write error: " + e); } } } public void send(String message) { byte[] theBytes= (message+"\n").getBytes(); for (int i=0; i<theBytes.length;i++){ char newCharacter = (char)theBytes[i]; if ((int)newCharacter==10) newCharacter = '\r'; try { os.write((int)newCharacter); } catch (IOException e) { System.err.println("OutputStream write error: " + e); } } //System.out.println (">'" +message +"' sent");

} } Sender: import java.util.Date; public class Sender implements Runnable { private static final long STANDARD=500; private static final long LONG=2000; private static final long VERYLONG=20000; SerialConnection mySerial =null; static final private char cntrlZ=(char)26; String in, out; Thread aThread=null; private long delay=STANDARD; String recipient=null; String message=null; private String csca="+6596845999"; // the message center private SerialParameters defaultParameters= new SerialParameters ("COM2",9600,0,0,8,1,0);

public int step; public int status=-1; public long messageNo=-1; public Sender(String recipient, String message){ this.recipient=recipient; this.message=message; } /** * connect to the port and start the dialogue thread */ public int send () throws Exception{ SerialParameters params = defaultParameters; mySerial =new SerialConnection (params); mySerial.openConnection(); aThread=new Thread(this); aThread.start() ; //log("start"); return 0; } /** * implement the dialogue thread, * message / response via steps, * handle time out */ public void run(){ boolean timeOut=false; long startTime=(new Date()).getTime();

while ((step <7) && (!timeOut)){ // log(""+((new Date()).getTime() - startTime); //check where we are in specified delay timeOut=((new Date()).getTime() - startTime)>delay; //if atz does not work, type to send cntrlZ and retry, in case a message was stuck if (timeOut && (step==1)) { step=-1;

mySerial.send( }

""+cntrlZ);

//read incoming string String result= mySerial.getIncommingString() ; // log ("<- "+result+"\n--------"); int expectedResult=-1; try{ //log ("Step:"+step); switch (step){ case 0: mySerial.send("atz"); delay=LONG; startTime=(new Date()).getTime(); break; case 1: delay=STANDARD; mySerial.send("ath0"); startTime=(new Date()).getTime(); break; case 2: expectedResult=result.indexOf("OK"); //log ("received ok ="+expectedResult); if (expectedResult>-1){ mySerial.send("at+cmgf=1"); startTime=(new Date()).getTime(); }else{ step=step-1; } break; case 3: expectedResult=result.indexOf("OK"); // log ("received ok ="+expectedResult); if (expectedResult>-1){ mySerial.send("at+csca=\""+csca+"\""); startTime=(new Date()).getTime(); }else{ step=step-1; } break; case 4: expectedResult=result.indexOf("OK");

// log ("received ok ="+expectedResult); if (expectedResult>-1){ mySerial.send("at+cmgs=\""+recipient+"\""); startTime=(new Date()).getTime(); }else{ step=step-1; } break; case 5: expectedResult=result.indexOf(">"); // log ("received ok ="+expectedResult); if (expectedResult>-1){ mySerial.send(message+cntrlZ); startTime=(new Date()).getTime(); }else{ step=step-1; } delay=VERYLONG;//waitning for message ack break; case 6: expectedResult=result.indexOf("OK"); //read message number if (expectedResult>-1){ int n=result.indexOf("CMGS:"); result=result.substring(n+5); n=result.indexOf("\n"); status=0; messageNo=Long.parseLong(result.substring(0,n).trim() ); log ("sent message no:"+messageNo); }else{ step=step-1; } break; } step=step+1; aThread.sleep(100); }catch (Exception e){ e.printStackTrace(); }

} mySerial.closeConnection() ; //if timed out set status if (timeOut ) { status=-2; log("*** time out at step "+step+"***"); } } /** * logging function, includes date and class name */ private void log(String s){ System.out.println (new java.util.Date()+":"+this.getClass().getName()+":"+s); } }

8.2 Screen Shots

Reference:
1. Crocker, D. and P. Overell, Augmented BNF for Syntax Specifications: ABNF, RFC 2234, November 1997. 2. Josefsson, S., The Base16, Base32, and Base64 Data Encodings, RFC 3548, July 2003. 3. Alvestrand, H., IETF Policy on Character Sets and Languages, BCP 18, RFC 2277, January 1998 (TXT, HTML, XML). 4. Leach, P. and C. Newman, Using Digest Authentication as a SASL Mechanism, RFC 2831, May 2000. 5. Mockapetris, P., Domain names - implementation and specification, STD 13, RFC 1035, November 1987. 6. Linn, J., Generic Security Service Application Program Interface Version 2, Update 1, RFC 2743, January 2000. 7. Rescorla, E., HTTP Over TLS, RFC 2818, May 2000. 8. Faltstrom, P., Hoffman, P., and A. Costello, Internationalizing Domain Names in Applications (IDNA), RFC 3490, March 2003. 9. Hinden, R. and S. Deering, Internet Protocol Version 6 (IPv6) Addressing Architecture, RFC 3513, April 2003. 10. Alvestrand, H., Tags for the Identification of Languages, BCP 47, RFC 3066, January 2001. 11. Hoffman, P. and M. Blanchet, Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN), RFC 3491, March 2003. 12. Eastlake, D., Crocker, S., and J. Schiller, Randomness Recommendations for Security, RFC 1750, December 1994. 13. Myers, J., Simple Authentication and Security Layer (SASL), RFC 2222, October 1997 (TXT, HTML, XML). 14. Gulbrandsen, A., Vixie, P., and L. Esibov, A DNS RR for specifying the location of services (DNS SRV), RFC 2782, February 2000. 15. Hoffman, P. and M. Blanchet, Preparation of Internationalized Strings ("stringprep"), RFC 3454, December 2002.

Das könnte Ihnen auch gefallen