⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smsterminal.java

📁 Java写的通过手机收发短信息的程序。
💻 JAVA
字号:
//// Copyright (c) 2001 Kvanttisofta oy.  All rights reserved.////// a class modeling the communication with a SMS terminal device.// (mikko.syrjalahti@iki.fi, aspa@users.sourceforge.net).//// $Id: SmsTerminal.java,v 1.1.1.1 2001/04/18 04:19:00 aspa Exp $.//// TODO:// - error handling. how should errors be communicated to the user?// - lineReceived: error handling//package fi.kvanttisofta.sms;import java.io.*;import java.util.*;import javax.comm.*;import fi.kvanttisofta.sms.*;public class SmsTerminal implements SerialPortEventListener {    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;    private SmsListenerInterface smsListener;    /* CMGF=0  --  SMS messages in PDU mode       AT+CNMI new mssage indications to DTE       - AT+CNMI=[<mode>[,<mt>[,<bm>[,<ds>[,<bfr>]]]]]         <mode> -- no indications when DTE-DCE link reserved	 <mt>   -- received messages (not class 2) routed to DTE with +CMT	 <bm>   -- no cell breadcast indications	 <ds>   -- no status reports	 <bfr>  -- flush indication buffer if <mode> = {1,2}       CSCS    --  select DTE character set     */    private static final String initcmd1 = "ATV1E0Q0X5+CMGF=0";    private static final String initcmd2 = "AT+CNMI=1,2,0,0,0";    private static final String initcmd3 = "AT+CSCS=\"8859-1\"";    private static final String initcmd4 = "AT+CMEE=2";    private static final String lfcr = "\015";    private int portStatus = OK;    private Boolean portStatusLock = new Boolean(true);    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 byte[] readBuffer = new byte[500]; // serialEvent    private int bufferOffset = 0;              // serialEvent    private boolean should_run = true; // not used    public SmsTerminal(String portName, SmsListenerInterface smsListener)	throws Exception {	CommPortIdentifier portId = null;	Enumeration portList = CommPortIdentifier.getPortIdentifiers();	/* initialize variables */	this.smsListener = smsListener;	/* find the requested port */	while (portList.hasMoreElements()) {	    portId = (CommPortIdentifier) portList.nextElement();	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {		if (portId.getName().equals(portName)) {		    try {			serialPort = (SerialPort)			    portId.open(SmsTerminal.class.getName(), 2000);		    } catch (PortInUseException e) {			//throw new PortInUseException("Already opened: " + e);			throw new IOException("port "+portName+" in use: "+e);		    }		}	    }	}	/* port not found */	if(serialPort == null) {	    //throw new NoSuchPortException();	    throw new IOException("NoSuchPortException: '"+portName+"'");	}	/* Open streams to the port */	try {	    outStream = serialPort.getOutputStream();	    inStream = serialPort.getInputStream();	} catch (IOException e) {	    serialPort.close();	    throw new IOException("Cannot get a stream to port: " + e);	}	/* Configure port */	try {	    serialPort.setSerialPortParams(9600,					   SerialPort.DATABITS_8,					   SerialPort.STOPBITS_1,					   SerialPort.PARITY_NONE);	} catch (UnsupportedCommOperationException e) {	    serialPort.close();	    throw new IOException ("Operation not supported: " + e);	}		/* Start a thread for handling comminication with the terminal */	serialPort.addEventListener(this);	/*Add handler for serial events*/	serialPort.notifyOnDataAvailable(true);	atCmd(initcmd1);	atCmd(initcmd2);	atCmd(initcmd3);    }    private int atCmd(String cmd) {	boolean gotTimeout = false;	synchronized(portStatusLock) {	    portStatus = WAIT;	    try {		outStream.write((cmd + lfcr).getBytes());	    } catch (IOException e) { ; }	    /* wait for response from device */	    try {		portStatusLock.wait(500); // millis	    } catch (InterruptedException e) { gotTimeout=true; }	    if(portStatus != OK) {		// port not ok	    }	} // end: synchronized(portStatusLock) {	    	// failed to get device	if(gotTimeout) {	    //System.err.println("SmsTerminal: timeout");	}	return OK;    }    private void close() {        serialPort.close();        should_run = false;    }    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 {		while ( (n = inStream.available()) > 0) {		    n = inStream.read(readBuffer, bufferOffset, n);		    bufferOffset += n;		    // lfcr detected, line ready		    if((readBuffer[bufferOffset-1] == 10) &&		       (readBuffer[bufferOffset-2] == 13)) {			String sbuf = new String(readBuffer,0,bufferOffset-2);			lineReceived(sbuf);			bufferOffset = 0;		    }		}	    } catch (IOException e) { ; }	    break; // end: case SerialPortEvent.DATA_AVAILABLE:	}    }        private void lineReceived(String buffer) {	String response;	StringTokenizer st = new StringTokenizer(buffer, "\r\n");	synchronized(portStatusLock) {	    while (st.hasMoreTokens()) {		response = st.nextToken();		if (response.equals("")) {		    portStatus = OK;		} else if (response.startsWith("OK")) {		    portStatus = OK;		} 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("04")) { // NB: BUG!		    SmsMsgIncoming msg = null;		    try {			msg = new SmsMsgIncoming(response);		    } catch (PduParseException e) {			smsListener.receiveSms(SC_PDU_PARSE_ERROR,					       "unable to parse PDU: '"+					       response+"'", null);		    }		    portStatus = OK;		    smsListener.receiveSms(SC_OK, null, msg);		} else {		    // unknown response from terminal		    //System.err.println("unknown response: '"+response+"'");		}	    } // end: while (st.hasMoreTokens()) {	    portStatusLock.notify();	} // end: synchronized(portStatusLock) {		return;    }    public synchronized boolean sendMessage(String number, String msg) {	if(number.startsWith("+"))	    number = number.substring(1);		SmsMsgOutgoing pdumsg = new SmsMsgOutgoing(number, msg);		String pdu = pdumsg.toString().toUpperCase();	String cmd = "AT+CMGS=" + (pdu.length()/2);		atCmd("");	atCmd(cmd);		atCmd(pdu);	atCmd("\032");		return true;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -