📄 cservice.java
字号:
// SMSLib for Java
// An open-source API Library for sending and receiving SMS via a GSM modem.
// Copyright (C) 2002-2006, Thanasis Delenikas, Athens/GREECE
// Web Site: http://www.smslib.org
//
// SMSLib is distributed under the LGPL license.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
package org.smslib;
import java.io.*;
import java.util.*;
import org.apache.log4j.*;
/**
* This is the main SMSLib service class.
*/
public class CService
{
/**
* Dummy synchronization object.
*/
private static Object _SYNC_ = null;
/**
* Product name.
*/
public static final String _name = "SMSLib for Java";
/**
* Product version.
*/
public static final String _version = "v2.1.0";
/**
* Holds values representing the modem protocol used.
*/
public static class Protocol
{
/**
* PDU protocol.
*/
public static final int PDU = 0;
/**
* TEXT protocol.
*/
public static final int TEXT = 1;
}
/**
* Holds values representing receive mode.
*
* @see CService#setReceiveMode(int)
* @see CService#getReceiveMode()
*/
public static class ReceiveMode
{
/**
* Synchronous reading.
*/
public static final int Sync = 0;
/**
* Asynchronous reading - polling.
*/
public static final int AsyncCnmi = 1;
/**
* Asynchronous reading - CMTI indications.
*/
public static final int AsyncPoll = 2;
}
private static final String LOG_CONF = "smslib-log.conf";
private int keepAliveInterval = 30 * 1000;
private int asyncPollInterval = 10 * 1000;
private int asyncRecvClass = CIncomingMessage.MessageClass.All;
private int retriesNoResponse = 4;
private int delayNoResponse = 2000;
private int retriesCmsErrors = 4;
private int delayCmsErrors = 2000;
private Logger log;
private static final String VALUE_NOT_REPORTED = "* N/A *";
private String smscNumber;
private String simPin;
private int receiveMode;
private int protocol;
private AbstractATHandler atHandler;
private CNewMsgMonitor newMsgMonitor;
private CSerialDriver serialDriver;
private boolean connected;
private CDeviceInfo deviceInfo;
private CKeepAliveThread keepAliveThread;
private CReceiveThread receiveThread;
private ISmsMessageListener messageHandler;
private int outMpRefNo;
private LinkedList mpMsgList;
/**
* CService constructor.
*
* @param port
* The comm port to use (i.e. COM1, /dev/ttyS1 etc).
* @param baud
* The baud rate. 57600 is a good number to start with.
* @param gsmDeviceManufacturer
* The manufacturer of the modem (i.e. Wavecom, Nokia, Siemens, etc).
* @param gsmDeviceModel
* The model (i.e. M1306B, 6310i, etc).
*/
public CService(String port, int baud, String gsmDeviceManufacturer, String gsmDeviceModel)
{
if (_SYNC_ == null) _SYNC_ = new Object();
log = Logger.getLogger("org.smslib");
if (new File(LOG_CONF).exists()) PropertyConfigurator.configure(LOG_CONF);
else
{
BasicConfigurator.configure();
log.setLevel(Level.WARN);
//log.setLevel(Level.ALL);
}
smscNumber = "";
simPin = null;
connected = false;
serialDriver = new CSerialDriver(port, baud, log);
deviceInfo = new CDeviceInfo();
newMsgMonitor = new CNewMsgMonitor();
log.info(_name + " / " + _version);
log.info("Using port: " + port + " @ " + baud + " baud.");
log.info("JRE Version: " + System.getProperty("java.version"));
log.info("JRE Impl Version: " + System.getProperty("java.vm.version"));
log.info("O/S: " + System.getProperty("os.name") + " / " + System.getProperty("os.arch") + " / " + System.getProperty("os.version"));
try
{
atHandler = AbstractATHandler.load(serialDriver, log, this, gsmDeviceManufacturer, gsmDeviceModel);
log.info("Using " + atHandler.getDescription() + " AT handler.");
}
catch (Exception ex)
{
log.fatal("CANNOT INITIALIZE HANDLER (" + ex.getMessage() + ")");
}
protocol = Protocol.PDU;
receiveMode = ReceiveMode.Sync;
receiveThread = null;
outMpRefNo = new Random().nextInt();
if (outMpRefNo < 0) outMpRefNo *= -1;
outMpRefNo %= 65536;
mpMsgList = new LinkedList();
}
/**
* Return the status of the connection.
* <p>
* <strong>Warning</strong>: The method return the "theoretical" status of the connection, without testing the actual connection at the time of the call.
*
* @return True if the GSM device is connected.
* @see CService#connect()
* @see CService#disconnect()
*/
public boolean getConnected()
{
return connected;
}
/**
* Returns the DeviceInfo class.
*
* @see CDeviceInfo
*/
public CDeviceInfo getDeviceInfo()
{
return deviceInfo;
}
/**
* Sets the SMSC number. Needed in rare cases - normally, you should <strong>not</strong> set the SMSC number yourself and let the GSM device get it from its SIM.
*
* @param smscNumber
* The SMSC number (international format).
* @see CService#getSmscNumber()
*/
public void setSmscNumber(String smscNumber)
{
this.smscNumber = smscNumber;
}
/**
* Returns the SMSC number previously set with setSmscNumber() call.
*
* @return The SMSC number.
* @see CService#setSmscNumber(String)
*/
public String getSmscNumber()
{
return smscNumber;
}
/**
* Sets the SIM Pin.
*
* @param simPin
* The SIM pin code.
* @see CService#getSimPin()
*/
public void setSimPin(String simPin)
{
this.simPin = simPin;
}
/**
* Returns the SIM Pin previously set with setSimPin().
*
* @return The SIM Pin code.
* @see CService#setSimPin(String)
*/
public String getSimPin()
{
return simPin;
}
/**
* Sets the message handler for ASYNC mode. The handler is called automatically from SMSLib when a message is received. This handler is valid only for Asynchronous operation mode - in other modes, it is not used.
*
* @param messageHandler
* The message handler routine - must comply with ISmsMessageListener interface.
* @see CService#getMessageHandler()
*/
public void setMessageHandler(ISmsMessageListener messageHandler)
{
this.messageHandler = messageHandler;
}
/**
* Returns the message handler (if any).
*
* @return The message handler.
* @see CService#setMessageHandler(ISmsMessageListener)
*/
public ISmsMessageListener getMessageHandler()
{
return messageHandler;
}
/**
* Sets the Async Poll Interval (in seconds) - is every how many seconds will SMSLib poll the GSM modem for new messages.
*
* @param secs
* The interval in seconds.
* @see CService#getAsyncPollInterval()
* @see CService#setAsyncRecvClass(int)
* @see CService#getAsyncRecvClass()
*/
public void setAsyncPollInterval(int secs)
{
this.asyncPollInterval = secs * 1000;
}
/**
* Returns the Async Poll Interval, in seconds.
*
* @return The Poll Interval in seconds.
* @see CService#setAsyncPollInterval(int)
* @see CService#setAsyncRecvClass(int)
* @see CService#getAsyncRecvClass()
*/
public int getAsyncPollInterval()
{
return (asyncPollInterval / 1000);
}
public void setAsyncRecvClass(int msgClass)
{
asyncRecvClass = msgClass;
}
public int getAsyncRecvClass()
{
return asyncRecvClass;
}
/**
* Sets the Keep-Alive Interval - every how many seconds the Keep-Alive thread will run and send a dummy OK command to the GSM modem. This is used to keep the serial port alive and prevent it from timing out. The interval is, by default, set to 30 seconds which should be enough for all modems.
*
* @param secs
* The Keep-Alive Interval in seconds.
* @see CService#getKeepAliveInterval()
*/
public void setKeepAliveInterval(int secs)
{
this.keepAliveInterval = secs * 1000;
}
/**
* Returns the Keep-Alive Interval, in seconds.
*
* @return The Keep-Alive Interval in seconds.
* @see CService#setKeepAliveInterval(int)
*/
public int getKeepAliveInterval()
{
return keepAliveInterval / 1000;
}
/**
* Sets the number of retries that SMSLib performs during dispatch of a message, if it fails to get a response from the modem within the timeout period.
* <p>
* After the number of retries complete and the message is not sent, SMSLib treats it as undeliverable.
* <p>
* The default values should be ok in most cases.
*
* @param retries
* The number of retries.
* @see CService#getRetriesNoResponse()
* @see CService#setDelayNoResponse(int)
* @see CService#getDelayNoResponse()
*/
public void setRetriesNoResponse(int retries)
{
this.retriesNoResponse = retries;
}
/**
* Returns the current number of retries.
*
* @return The number of retries.
* @see CService#setRetriesNoResponse(int)
*/
public int getRetriesNoResponse()
{
return retriesNoResponse;
}
/**
* Sets the delay between consecutive attemps for dispatching a message.
*
* @param delay
* The delay in millisecs.
* @see CService#getDelayNoResponse()
* @see CService#setRetriesNoResponse(int)
* @see CService#getRetriesNoResponse()
*/
public void setDelayNoResponse(int delay)
{
this.delayNoResponse = delay * 1000;
}
/**
* Gets the delay between consecutive attemps for dispatching a message.
*
* @return delay The delay in millisecs.
* @see CService#getDelayNoResponse()
* @see CService#setRetriesNoResponse(int)
* @see CService#getRetriesNoResponse()
*/
public int getDelayNoResponse()
{
return delayNoResponse;
}
public void setRetriesCmsErrors(int retries)
{
this.retriesCmsErrors = retries;
}
public int getRetriesCmsErrors()
{
return retriesCmsErrors;
}
public void setDelayCmsErrors(int delay)
{
this.delayCmsErrors = delay * 1000;
}
public int getDelayCmsErrors()
{
return delayCmsErrors;
}
/**
* Returns the Log4J logger object used by SMSLib.
*
* @return The Log4J logger object.
*/
public Logger getLogger()
{
return log;
}
/**
* Sets the logger to a custom Log4J Logger object. You can also use this call to completely disable logging, by passing a null object.
*
* @param log
* A Log4J logger object.
*/
public void setLogger(Logger log)
{
this.log = log;
}
/**
* Sets the receive mode.
*
* @param receiveMode
* The receive mode.
* @see CService.ReceiveMode
*/
public void setReceiveMode(int receiveMode) throws Exception
{
this.receiveMode = receiveMode;
if (connected)
{
if (receiveMode == ReceiveMode.AsyncCnmi)
{
if (!atHandler.enableIndications())
{
if (log != null) log.warn("Could not enable CMTI indications, continuing without them...");
}
}
else
{
if (!atHandler.disableIndications())
{
if (log != null) log.warn("Could not disable CMTI indications, continuing without them...");
}
}
}
}
/**
* Returns the Receive Mode.
*
* @return The Receive Mode.
* @see CService.ReceiveMode
*/
public int getReceiveMode()
{
return receiveMode;
}
/**
* Sets the protocol to be used.
* <p>
* The default protocol is PDU. If you want to change it, you must call this method after constructing the CService object and before connecting. Otherwise, you will get an exception.
*
* @param protocol
* The protocol to be used.
* @see CService#getProtocol()
* @see CService.Protocol
*/
public void setProtocol(int protocol) throws Exception
{
if (getConnected()) throw new OopsException("Cannot change protocol while connected!");
else this.protocol = protocol;
}
/**
* Returns the protocol in use.
*
* @return The protocol use.
* @see CService.Protocol
*/
public int getProtocol()
{
return protocol;
}
/**
* Connects to the GSM modem.
* <p>
* The connect() function should be called before any operations. Its purpose is to open the serial link, check for modem existence, initialize modem, start background threads and prepare for subsequent operations.
*
* @see #disconnect()
* @throws NotConnectedException
* Nobody is answering.
* @throws AlreadyConnectedException
* Already connected.
* @throws NoPinException
* If PIN is requested from the modem but no PIN is defined.
* @throws InvalidPinException
* If the defined PIN is not accepted by the modem.
* @throws NoPduSupportException
* The modem does not support PDU mode - fatal error!
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -