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

📄 cservice.java

📁 开源的手机短信开发包!包括例子程序和比较详细的文档
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
//
//	jSMSEngine API.
//	An open-source API package for sending and receiving SMS via a GSM device.
//	Copyright (C) 2002-2005, Thanasis Delenikas, Athens/GREECE
//		Web Site: http://www.jsmsengine.org
//
//	jSMSEngine is a package which can be used in order to add SMS processing
//		capabilities in an application. jSMSEngine is written in Java. It allows you
//		to communicate with a compatible mobile phone or GSM Modem, and
//		send / receive SMS messages.
//
//	jSMSEngine 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

package org.jsmsengine;

import java.io.*;
import java.util.*;
import java.util.logging.*;
import java.text.*;

/**
	This class provides all the functionality of jSMSEngine API to the developer.
	<br><br>
	The class CService provides all the interface routines to jSMSEngine. It
	is responsible for initialization of the communication with the GSM device,
	reading and sending messages, setting the phonebook.
	<br><br>
	The sequence of actions that need to be done are:
	<ul>
		<li>Call initialize() to setup the service.</li>
		<li>Call connect() to connect with the GSM device.</li>
		<li>Call sendMessage(), or readMessages() to send or receive messages
				from the device. Call deleteMessage() to delete a message from
				the device's memory.</li>
		<li>Call refreshDeviceInfo() to get updated GSM device specific information.</li>
		<li>Call disconnect() to disconnect from the GSM device.</li>
	</ul>
	<br>
*/
public class CService
{
	/**
		Internal Software Name.
	*/
	public static final String _name = "jSMSEngine API";
	/**
		Version.
	*/
	public static final String _version = "1.2.7";
	/**
		Release Date.
	*/
	public static final String _reldate = "June 20, 2005";

	/**
		Logging facilities.
	*/
    private static Logger log = Logger.getLogger("org.jsmsengine");

	/**
		This error value is returned when the operation was succesfull.
	*/
	public static final int ERR_OK = 0;

	/**
		This is a generic error, which is not classified yet. More error classifications may
		be introduced at a later stage.
	*/
	public static final int ERR_GENERIC_ERROR = -1;

	/**
		This error value is returned when the service is not initialized yet. You should call method
		initialize().
	*/
	public static final int ERR_NOT_INITIALIZED = -10;

	/**
		This error value is returned when the service is not connected to the GSM device.
		You should call method connect().
	*/
	public static final int ERR_NOT_CONNECTED = -11;

	/**
		This error value is returned when the GSM device does not support ASCII or
		PDU mode. This is a fatal error, in the sense that jSMSEngine can work only
		with GSM devices supporting ASCII or PDU Mode.
	*/
	public static final int ERR_COMM_NOT_SUPPORTED = -20;

	/**
		This error value is returned when the GSM device does not support HEX mode.
		This is a fatal error, in the sense that jSMSEngine can work only with GSM
		devices supporting HEX Mode when in ASCII mode. In order to get around this
		error, switch to PDU mode.
	*/
	public static final int ERR_CHARSET_HEX_NOT_SUPPORTED = -21;

	/**
		This error value is returned when the GSM device does not support the 
		AT+CNMI command for disabling indications to TE.
	*/
	public static final int ERR_CANNOT_DISABLE_INDICATIONS = -22;

	/**
		This error value is returned when the specific message was not found.
		Double-check your message and/or memory index used.
	*/
	public static final int ERR_MESSAGE_NOT_FOUND = -30;

	/**
		This error value is returned when a send-message operation failed.
		This could be attributed to a number of reasons: Coverage problems,
		invalid recipient phone number, GSM device malfunction.
	*/
	public static final int ERR_SEND_FAILED = -40;

	/**
		This error value is returned when the specified phonebook file did not load.
		Recheck your XML file for errors in its structure.
	*/
	public static final int ERR_PHONEBOOK_NOT_LOADED = -50;

	/**
		This error value is returned when the given directory is invalid.
	*/
	public static final int ERR_INVALID_DIR = -100;

	/**
		This error value on attempting to connect to the GSM device without first
		having defined the cache directories.
	*/
	public static final int ERR_NO_CACHE = -101;

	/**
		This error value is returned when the GSM device asks for a PIN number,
		however the PIN given is invalid. Please check your PIN.
	*/
	public static final int ERR_SIM_PIN_ERROR =-102;

	/**
		This error value is returned when the specified operation is not supported by
		jSMSEngine API.
	*/
	public static final int ERR_NOT_SUPPORTED = -9999;

	/**
		Constant value for ASCII operation mode. 
	*/
	public static final int MODE_ASCII = 1;

	/**
		Constant value for PDU operation mode. 
	*/
	public static final int MODE_PDU = 2;


	/**
		Receive modes: Synchronous and Ascynchronous.
	*/
	public static final int RECEIVE_MODE_SYNC = 1;
	public static final int RECEIVE_MODE_ASYNC = 2;

	/**
		Default value for information that is not reported by the GSM device. 
	*/
	public static final String DEFAULT_VALUE_NOT_REPORTED = "* N/A *";

	public static final int MAX_SMS_LEN_7BIT = 160;
	public static final int MAX_SMS_LEN_8BIT = 140;
	public static final int MAX_SMS_LEN_UNICODE = 70;
	private static final String SMS_SPLIT_SIGNATURE = "?$;";
	private static final int SMS_PARTS = 8;
	private static int smsSplitId = 0;

	private String cacheDir;
	private String smscNumber;
	private String simPin;
	private int operationMode;
	private int supportedModes;
	private int receiveMode;

	private CSerialDriver serialDriver;
	private boolean initialized;
	private boolean connected;
	private CPhoneBook phoneBook;
	private CDeviceInfo deviceInfo;

	private CReceiveThread receiveThread;

	/**
		Synchronization object for critical sections of the API.
	*/
	private Object _SYNC_ = new Object();

	/**
		Default constructor of the class.

		@param	port	the serial port where the GSM device is connected (e.g. "com1"). 
		@param	baud	the connection speed (i.e. 9600, 19200 etc).

		<br><br>
		Notes:
		<ul>
			<li>Use one of the standard values for baud. Most GSM devices work well
					at 9600 or 19200. Some may handle speeds up to 115200 (like Nokia
					mobile phone model 6210 does). The connection speed is not that
					important to the speed at which jSMSEngine processes messages.
					Personally, I work at 9200 to avoid pushing the mobile. Dedicated GSM
					modems may handle higher speeds better than mobile phones do.</li>
		</ul>
	*/
	public CService(String port, int baud)
	{
		setInitialized(false);
		setConnected(false);
		serialDriver = new CSerialDriver(port, baud, log);
		phoneBook = new CPhoneBook();
		deviceInfo = new CDeviceInfo();
		receiveMode = RECEIVE_MODE_SYNC;
		receiveThread = new CReceiveThread();
		receiveThread.start();
		log.setLevel(Level.WARNING);
	}

	/**
		Returns TRUE if the service has already been initialized.

		@return  TRUE if the service has already been initialized.
	*/
	public boolean getInitialized() { return initialized; }

	/**
		Returns TRUE if the service is connected with the GSM device.

		@return  TRUE if the service is connected with the GSM device.
	*/
	public boolean getConnected() { return connected; }

	/**
		Returns a CDeviceInfo object that holds information about the GSM
		device in use.

		@return  a CDeviceInfo object.
		@see	CDeviceInfo
	*/
	public CDeviceInfo getDeviceInfo() { return deviceInfo; }

	/**
		Sets the cache directory for messages.

		@param	dir	The directory which will act like a cache.
		@return  One of ERR_* values.
	*/
	public int setCacheDir(String dir)
	{
		if (dir == null) return ERR_INVALID_DIR;
		else
		{
			File f = new File(dir);
			if (f.exists())
			{
				cacheDir = dir;
				return ERR_OK;
			}
			else return ERR_INVALID_DIR;
		}
	}

	/**
		Sets the Short Message Service Center (SMSC) number. Please use international format.
		If you don't want to set the SMSC and use the one defined in your GSM device, use an
		empty string parameter. Another way to do the same, is to pass a null parameter. Some
		phones may prefer one way or the other - please test your phone.

		@param	smscNumber	the SMSC number.
	*/
	public void setSmscNumber(String smscNumber) { this.smscNumber = smscNumber; }

	/**
		Returns the Short Message Service Center (SMSC) number you have previously
		defined with setSmscNumber().

		@return  the SMSC number.
	*/
	public String getSmscNumber() { return smscNumber; }

	/**
		Sets the SIM pin number. This is used if and when the GSM device asks for it. If you set it to
		null, then the API does not give any PIN to the device (in order to avoid locking it up), and
		returns ERR_SIM_PIN_ERROR.

		@param	simPin	the SIM pin number.
	*/
	public void setSimPin(String simPin) { this.simPin = simPin; }

	/**
		Returns the SIM pin number.

		@return  the SIM pin number.
	*/
	public String getSimPin() { return simPin; }

	/**
		Sets the operation mode of the GSM device

		@param	mode	the mode of operation (one of values MODE_ASCII, MODE_PDU).
		@return	TRUE if the change of mode succeded.
		@see	CService#getOperationMode()
	*/
	public boolean setOperationMode(int mode)
	{
		boolean result;

		try
		{
			switch (mode)
			{
				case MODE_ASCII:
					serialDriver.send(CATCommands.AT_ASCII_MODE);
					if (serialDriver.getResponse().equalsIgnoreCase(CATCommands.AT_OK))
					{
						result = true;
						operationMode = MODE_ASCII;
					}
					else result = false;
					break;
				case MODE_PDU:
					serialDriver.send(CATCommands.AT_PDU_MODE);
					if (serialDriver.getResponse().equalsIgnoreCase(CATCommands.AT_OK))
					{
						result = true;
						operationMode = MODE_PDU;
					}
					else result = false;
					break;
				case 0:
					operationMode = 0;
					result = true;
					break;
				default:
					result = false;
			}
		}
		catch (Exception e) { result = false; }
		return result;
	}

	/**
		Returns the operation mode of the GSM device, i.e. one of the values
		MODE_ASCII, MODE_PDU.

		@return  the operation mode.
		@see	CService#setOperationMode(int)
	*/
	public int getOperationMode() { return operationMode; }

	/**
		Sets the reception mode.
		There are two reception modes, the synchronous and the asynchronous.
		In synchronous mode, you should call readMessages() function on demand,
		where you want to check for new messages. In asynchronous mode, the engine
		automatically calls the received() method (which you <strong>should</strong>
		override) for every received message.
		<br>By default, the reception mode is the synchronous one.

		@param	receiveMode	the reception mode (one of values RECEIVE_MODE_ASYNC, RECEIVE_MODE_SYNC).
		@see	CService#getReceiveMode()
	*/
	public void setReceiveMode(int receiveMode) { this.receiveMode = receiveMode; }

	/**
		Returns the reception mode.

		@return	the reception mode (one of values RECEIVE_MODE_ASYNC, RECEIVE_MODE_SYNC).
		@see	CService#setReceiveMode(int)
	*/
	public int getReceiveMode() { return receiveMode; }

	/**
		Returns the cache directory for messages.

		@return  the caching directory.
		@see	CService#setCacheDir(String)
	*/
	public String getCacheDir() { return cacheDir; }

	/**
		Initializes the service. This should be the first method call.

		@return  ERR_OK (for this version).
		@see	CService#connect()
	*/
	public int initialize()
	{
		cacheDir = null;
		smscNumber = null;
		simPin = null;
		operationMode = 0;
		supportedModes = 0;
		setInitialized(true);
		return ERR_OK;
	}

	/**
		Connects to the GSM device. Opens the serial port, and sends the appropriate
		AT commands to initialize the operation mode of the GSM device. Retrieves
		information about the GSM device. This method should be called after
		initialize() has been called.
		<br>
		By default, jSMSEngine API sets your GSM device to PDU mode. If you want to
		switch to ASCII mode (I don't see any reason why, but anyway...), use the
		setOperationMode() method.
		<br><br>
		Notes:
		<br>
		<ul>
			<li>The GSM device specific information (read by the call to refreshDeviceInfo()
					function is called once from this method. Since some information changes
					with time (such as battery or signal level), its your responsibility to
					call refreshDeviceInfo() periodically in order to have the latest information.
					Otherwise, you will get the information snapshot taken at the time
					of the initial connection.
			</li>
		</ul>

		@return  One of ERR_* values.
		@see	CDeviceInfo
		@see	CService#refreshDeviceInfo()
		@see	CService#disconnect()
		@see	CService#initialize()
		@see	CService#setOperationMode(int)
	*/
	public int connect()
	{
		synchronized (_SYNC_)
		{
			if (getInitialized())
			{
				if (getCacheDir() == null) return ERR_NO_CACHE;
				else
				{
					try
					{
						if (serialDriver.open())
						{
							try { Thread.sleep(2000); } catch (Exception e) {}
							serialDriver.clearBuffer();
							serialDriver.send(CATCommands.AT_ECHO_OFF);
							serialDriver.getResponse();
							serialDriver.send(CATCommands.AT_AT);
							if (serialDriver.getResponse().equalsIgnoreCase(CATCommands.AT_OK))
							{

⌨️ 快捷键说明

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