cservice.java
来自「SMSLib一个很有用的程序,有服务平台和收发平台」· Java 代码 · 共 647 行 · 第 1/2 页
JAVA
647 行
// 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 java.text.*;
import java.lang.reflect.*;
public class CService
{
public static final String _name = "SMSLib API for Java";
public static final String _version = "1.1";
public static final String _reldate = "April 21, 2006";
private int keepAliveInterval = 15 * 1000;
private int asyncPollInterval = 10 * 1000;
private int asyncRecvClass = CIncomingMessage.CLASS_ALL;
private static CLogger log;
public static final int RECEIVE_MODE_SYNC = 1;
public static final int RECEIVE_MODE_ASYNC_CNMI = 2;
public static final int RECEIVE_MODE_ASYNC_POLL = 3;
public static final String VALUE_NOT_REPORTED = "* N/A *";
private String smscNumber;
private String simPin;
private int receiveMode;
private CATHandler atHandler;
private CNewMsgMonitor newMsgMonitor;
private CSerialDriver serialDriver;
private boolean connected;
private CPhoneBook phoneBook;
private CDeviceInfo deviceInfo;
private CKeepAliveThread keepAliveThread;
private CReceiveThread receiveThread;
private CSmsMessageListener messageHandler;
private int outMpRefNo;
public CService(String port, int baud, String gsmDeviceManufacturer, String gsmDeviceModel)
{
log = new CLogger();
smscNumber = null;
simPin = null;
connected = false;
serialDriver = new CSerialDriver(port, baud, log);
phoneBook = new CPhoneBook();
deviceInfo = new CDeviceInfo();
newMsgMonitor = new CNewMsgMonitor();
if ((System.getProperty("smslib.debug") != null) && (System.getProperty("smslib.debug").equalsIgnoreCase("true"))) log.setLevel(CLogger.LOG_ALL);
else log.setLevel(CLogger.LOG_WARNING);
if ((System.getProperty("smslib.debug.output") != null) && (System.getProperty("smslib.debug.output").length() > 0)) log.setStream(System.getProperty("smslib.debug.output"));
log.log(CLogger.LOG_INFO, _name + " / " + _version + " / " + _reldate);
log.log(CLogger.LOG_INFO, "Using port: " + port + " @ " + baud + " baud.");
log.log(CLogger.LOG_INFO, "JRE Version: " + System.getProperty("java.version"));
log.log(CLogger.LOG_INFO, "JRE Impl Version: " + System.getProperty("java.vm.version"));
log.log(CLogger.LOG_INFO, "O/S: " + System.getProperty("os.name") + " / " + System.getProperty("os.arch") + " / " + System.getProperty("os.version"));
String BASE_HANDLER = "org.smslib.CATHandler";
String[] handlerClassNames = { null, null, BASE_HANDLER };
String[] handlerDescriptions = { null, null, "Generic" };
StringBuffer handlerClassName = new StringBuffer(BASE_HANDLER);
if (gsmDeviceManufacturer != null && !gsmDeviceManufacturer.equals(""))
{
handlerClassName.append("_").append(gsmDeviceManufacturer);
handlerClassNames[1] = handlerClassName.toString();
handlerDescriptions[1] = gsmDeviceManufacturer + " (Generic)";
if (gsmDeviceModel != null && !gsmDeviceModel.equals(""))
{
handlerClassName.append("_").append(gsmDeviceModel);
handlerClassNames[0] = handlerClassName.toString();
handlerDescriptions[0] = gsmDeviceManufacturer + " " + gsmDeviceModel;
}
}
Class handlerClass = null;
for (int i=0; i<3; i++)
{
try
{
if (handlerClassNames[i] != null)
{
handlerClass = Class.forName(handlerClassNames[i].toString());
log.log(CLogger.LOG_INFO, "Using " + handlerDescriptions[i] + " AT handler.");
break;
}
}
catch (ClassNotFoundException cnfE) { if (i == 2) log.log(CLogger.LOG_ERROR, "CANNOT INITIALIZE HANDLER (" + cnfE.getMessage() + ")"); }
}
try
{
Class[] constructorParameters = { CSerialDriver.class, CLogger.class };
Constructor handlerConstructor = handlerClass.getConstructor(constructorParameters);
Object[] handlerParameters = {serialDriver, log};
atHandler = (CATHandler)handlerConstructor.newInstance(handlerParameters);
}
catch (Exception e) { log.log(CLogger.LOG_ERROR, "CANNOT INITIALIZE HANDLER (" + e.getMessage() + ")"); }
receiveMode = RECEIVE_MODE_SYNC;
receiveThread = null;
outMpRefNo = new Random().nextInt();
if (outMpRefNo < 0) outMpRefNo *= -1;
outMpRefNo %= 65536;
}
public boolean getConnected() { return connected; }
public CDeviceInfo getDeviceInfo() { return deviceInfo; }
public void setSmscNumber(String smscNumber) { this.smscNumber = smscNumber; }
public String getSmscNumber() { return smscNumber; }
public void setSimPin(String simPin) { this.simPin = simPin; }
public String getSimPin() { return simPin; }
public void setMessageHandler(CSmsMessageListener messageHandler) { this.messageHandler = messageHandler; }
protected CSmsMessageListener getMessageHandler() { return messageHandler; }
public void setAsyncPollInterval(int secs) { this.asyncPollInterval = secs * 1000; }
public int getAsyncPollInterval() { return (asyncPollInterval / 1000); }
public void setAsyncRecvClass(int msgClass) { asyncRecvClass = msgClass; }
public int getAsyncRecvClass() { return asyncRecvClass; }
public void setKeepAliveInterval(int secs) { this.keepAliveInterval = secs * 1000; }
public int getKeepAliveInterval() { return keepAliveInterval; }
public boolean isAlive()
{
boolean alive;
if (!connected) alive = false;
else try { alive = atHandler.isAlive(); } catch (Exception e) { alive = false; }
return alive;
}
public void setReceiveMode(int receiveMode) throws Exception
{
this.receiveMode = receiveMode;
if (connected)
{
if (receiveMode == RECEIVE_MODE_ASYNC_CNMI)
{
if (!atHandler.enableIndications()) log.log(CLogger.LOG_WARNING, "Could not enable CMTI indications, continuing without them...");
}
else
{
if (!atHandler.disableIndications()) log.log(CLogger.LOG_WARNING, "Could not disable CMTI indications, continuing without them...");
}
}
}
public int getReceiveMode() { return receiveMode; }
public void setPhoneBook(String phoneBookFile) throws Exception
{
phoneBook.load(phoneBookFile);
}
public void connect() throws Exception
{
if (getConnected()) throw new AlreadyConnectedException();
else
try
{
serialDriver.open();
serialDriver.setNewMsgMonitor(newMsgMonitor);
atHandler.reset();
atHandler.sync();
atHandler.echoOff();
if (atHandler.isAlive())
{
if (atHandler.waitingForPin())
{
if (getSimPin() == null) throw new NoPinException();
else if (!atHandler.enterPin(getSimPin())) throw new InvalidPinException();
}
atHandler.init();
atHandler.echoOff();
atHandler.setVerboseErrors();
if (!atHandler.setPduMode()) throw new NoPduSupportException();
connected = true;
setReceiveMode(receiveMode);
refreshDeviceInfo();
receiveThread = new CReceiveThread();
receiveThread.start();
keepAliveThread = new CKeepAliveThread();
keepAliveThread.start();
}
else throw new NotConnectedException("GSM device is not responding.");
}
catch (Exception e)
{
disconnect();
throw e;
}
}
public void disconnect()
{
serialDriver.killMe();
if (receiveThread != null)
{
receiveThread.killMe();
receiveThread.interrupt();
while (!receiveThread.killed()) try { receiveThread.join(); } catch (Exception e) {}
receiveThread = null;
}
if (keepAliveThread != null)
{
keepAliveThread.killMe();
keepAliveThread.interrupt();
while (!keepAliveThread.killed()) try { keepAliveThread.join(); } catch (Exception e) {}
keepAliveThread = null;
}
try { serialDriver.close(); } catch (Exception e) {}
connected = false;
}
public void readMessages(LinkedList messageList, int messageClass) throws Exception
{
int i, j, memIndex;
String response, line, sms, temp, originator, text, pdu;
BufferedReader reader;
CIncomingMessage mpMsg = null;
if (getConnected())
{
atHandler.switchToCmdMode();
response = atHandler.listMessages(messageClass);
response = response.replaceAll("\\s+OK\\s+", "\nOK");
reader = new BufferedReader(new StringReader(response));
for (;;)
{
line = reader.readLine();
if (line == null) break;
line = line.trim();
if (line.length() > 0) break;
}
for (;;)
{
if (line == null) break;
line = line.trim();
if (line.length() <= 0 || line.equalsIgnoreCase("OK")) break;
i = line.indexOf(':');
j = line.indexOf(',');
memIndex = Integer.parseInt(line.substring(i + 1, j).trim());
pdu = reader.readLine();
if (isIncomingMessage(pdu))
{
CIncomingMessage msg;
msg = new CIncomingMessage(pdu, memIndex);
if (msg.getMpRefNo() == 0)
{
messageList.add(msg);
deviceInfo.getStatistics().incTotalIn();
}
else
{
if (msg.getMpSeqNo() == 1)
{
if (mpMsg == null)
{
mpMsg = new CIncomingMessage(pdu, memIndex);
mpMsg.setMpMemIndex(memIndex);
}
}
else
if ((msg.getMpRefNo() == mpMsg.getMpRefNo()) && (msg.getMpSeqNo() == mpMsg.getMpSeqNo() + 1))
{
mpMsg.addText(msg.getText());
mpMsg.setMpSeqNo(msg.getMpSeqNo());
mpMsg.setMpMemIndex(memIndex);
if (mpMsg.getMpSeqNo() == mpMsg.getMpMaxNo())
{
mpMsg.setMemIndex(-1);
messageList.add(mpMsg);
}
}
}
}
else if (isStatusReportMessage(pdu))
{
messageList.add(new CStatusReportMessage(pdu, memIndex));
deviceInfo.getStatistics().incTotalIn();
}
line = reader.readLine().trim();
}
reader.close();
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?