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

📄 cservice.java

📁 Sending and receiving of SMS using Java
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
	public void deleteMessage(CIncomingMessage message) throws Exception
	{
		synchronized (_SYNC_)
		{
			if (message.getMemIndex() >= 0) deleteMessage(message.getMemIndex(), message.getMemLocation());
			else if ((message.getMemIndex() == -1) && (message.getMpMemIndex().length() != 0))
			{
				StringTokenizer tokens = new StringTokenizer(message.getMpMemIndex(), ",");
				while (tokens.hasMoreTokens())
					deleteMessage(Integer.parseInt(tokens.nextToken()), message.getMemLocation());
			}
		}
	}

	/**
	 * Deletes ALL messages of the specified message class.
	 * <p>
	 * Delete operations are irreversible.
	 * 
	 * @param messageClass
	 *            The message class.
	 * @throws NotConnectedException
	 *             Either connect() is not called or modem has been disconnected.
	 * @see CIncomingMessage.MessageClass
	 */
	public void deleteMessages(int messageClass) throws Exception
	{
		LinkedList msgList;

		synchronized (_SYNC_)
		{
			msgList = new LinkedList();
			readMessages(msgList, messageClass);
			for (int i = 0; i < msgList.size(); i++)
				deleteMessage((CIncomingMessage) msgList.get(i));
		}
	}

	/**
	 * Reads (or refreshes) all GSM modem information (like manufacturer, signal level, etc).
	 * <p>
	 * This method is called automatically upon connection. Should you require fresh info, you should call it yourself when you need it.
	 * 
	 * @throws NotConnectedException
	 *             Either connect() is not called or modem has been disconnected.
	 * @see CDeviceInfo
	 */
	public void refreshDeviceInfo() throws Exception
	{
		synchronized (_SYNC_)
		{
			if (getConnected())
			{
				if (deviceInfo.manufacturer.length() == 0) deviceInfo.manufacturer = getManufacturer();
				if (deviceInfo.model.length() == 0) deviceInfo.model = getModel();
				if (deviceInfo.serialNo.length() == 0) deviceInfo.serialNo = getSerialNo();
				if (deviceInfo.imsi.length() == 0) deviceInfo.imsi = getImsi();
				if (deviceInfo.swVersion.length() == 0) deviceInfo.swVersion = getSwVersion();
				deviceInfo.gprsStatus = getGprsStatus();
				deviceInfo.batteryLevel = getBatteryLevel();
				deviceInfo.signalLevel = getSignalLevel();
			}
			else throw new NotConnectedException();
		}
	}

	public void catchAsyncException(Exception e)
	{
		if (log != null) log.debug("Unexpected exception", e);
		else e.printStackTrace();
	}

	protected boolean isAlive()
	{
		boolean alive;

		if (!connected) alive = false;
		else try
		{
			alive = atHandler.isAlive();
		}
		catch (Exception e)
		{
			alive = false;
		}
		return alive;
	}

	private boolean waitForNetworkRegistration() throws Exception
	{
		StringTokenizer tokens;
		String response;
		int answer;

		while (true)
		{
			response = atHandler.getNetworkRegistration();
			if (response.indexOf("ERROR") > 0) return false;
			response = response.replaceAll("\\s+OK\\s+", "");
			response = response.replaceAll("\\s+", "");
			response = response.replaceAll("\\+CREG:", "");
			tokens = new StringTokenizer(response, ",");
			tokens.nextToken();
			try
			{
				answer = Integer.parseInt(tokens.nextToken());
			}
			catch (Exception e)
			{
				answer = -1;
			}
			switch (answer)
			{
				case 0:
					if (log != null) log.error("GSM: Auto-registration disabled!");
					throw new OopsException("GSM Network Auto-Registration disabled!");
				case 1:
					if (log != null) log.info("GSM: Registered to home network.");
					return true;
				case 2:
					if (log != null) log.warn("GSM: Not registered, searching for network...");
					break;
				case 3:
					if (log != null) log.error("GSM: Network registration denied!");
					throw new OopsException("GSM Network Registration denied!");
				case 4:
					if (log != null) log.error("GSM: Unknown registration error!");
					throw new OopsException("GSM Network Registration error!");
				case 5:
					if (log != null) log.info("GSM: Registered to foreign network (roaming).");
					return true;
				case -1:
					if (log != null) log.info("GSM: Invalid CREG response.");
					throw new OopsException("GSM: Invalid CREG response.");
			}
			Thread.sleep(1000);
		}
	}

	/**
	 * Send a custom AT command to the modem and returns its response.
	 * 
	 * @param cmd
	 *            The custom AT command
	 * @return The modem response
	 */
	public String sendCustomCmd(String cmd) throws Exception
	{
		synchronized (_SYNC_)
		{
			return atHandler.send(cmd);
		}
	}

	private String getManufacturer() throws Exception
	{
		String response;

		response = atHandler.getManufacturer();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return VALUE_NOT_REPORTED;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		return response;
	}

	private String getModel() throws Exception
	{
		String response;

		response = atHandler.getModel();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return VALUE_NOT_REPORTED;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		return response;
	}

	private String getSerialNo() throws Exception
	{
		String response;

		response = atHandler.getSerialNo();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return VALUE_NOT_REPORTED;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		return response;
	}

	private String getImsi() throws Exception
	{
		return "** MASKED **";
		// IMSI is masked on purpose.
		// Uncomment following code for IMSI to be reported.
		//
		// String response; response = atHandler.getImsi(); if
		// (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+"))
		// return VALUE_NOT_REPORTED; response =
		// response.replaceAll("\\s+OK\\s+", ""); response =
		// response.replaceAll("\\s+", ""); return response;
		//
	}

	private String getSwVersion() throws Exception
	{
		String response;

		response = atHandler.getSwVersion();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return VALUE_NOT_REPORTED;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		return response;
	}

	private boolean getGprsStatus() throws Exception
	{
		return (atHandler.getGprsStatus().matches("\\s*[\\p{ASCII}]CGATT[\\p{ASCII}]*1\\s*OK\\s*"));
	}

	private int getBatteryLevel() throws Exception
	{
		String response;
		StringTokenizer tokens;

		response = atHandler.getBatteryLevel();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return 0;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		tokens = new StringTokenizer(response, ":,");
		tokens.nextToken();
		tokens.nextToken();
		return Integer.parseInt(tokens.nextToken());
	}

	private int getSignalLevel() throws Exception
	{
		String response;
		StringTokenizer tokens;

		response = atHandler.getSignalLevel();
		if (response.matches("\\s*[\\p{ASCII}]*\\s+ERROR(?:: \\d+)?\\s+")) return 0;
		response = response.replaceAll("\\s+OK\\s+", "");
		response = response.replaceAll("\\s+", "");
		tokens = new StringTokenizer(response, ":,");
		tokens.nextToken();
		return (Integer.parseInt(tokens.nextToken().trim()) * 100 / 31);
	}

	private boolean isIncomingMessage(String pdu)
	{
		int index, i;

		i = Integer.parseInt(pdu.substring(0, 2), 16);
		index = (i + 1) * 2;

		i = Integer.parseInt(pdu.substring(index, index + 2), 16);
		if ((i & 0x03) == 0) return true;
		else return false;
	}

	private boolean isStatusReportMessage(String pdu)
	{
		int index, i;

		i = Integer.parseInt(pdu.substring(0, 2), 16);
		index = (i + 1) * 2;

		i = Integer.parseInt(pdu.substring(index, index + 2), 16);
		if ((i & 0x02) == 2) return true;
		else return false;
	}

	public boolean received(CIncomingMessage message)
	{
		return false;
	}

	private class CKeepAliveThread extends Thread
	{
		private volatile boolean stopFlag;

		private volatile boolean stopped;

		public CKeepAliveThread()
		{
			stopFlag = false;
			stopped = false;
		}

		public void killMe()
		{
			stopFlag = true;
			synchronized (_SYNC_)
			{
				this.interrupt();
			}
		}

		public boolean killed()
		{
			return stopped;
		}

		public void run()
		{
			try
			{
				while (!stopFlag)
				{
					try
					{
						sleep(keepAliveInterval);
					}
					catch (Exception e)
					{
					}
					if (stopFlag) break;
					synchronized (_SYNC_)
					{
						if (getConnected()) try
						{
							if (log != null) log.info("** Keep-Live **");
							atHandler.isAlive();
						}
						catch (Exception e)
						{
							if (!stopFlag && log != null) log.debug("Unexpected exception", e);
						}
					}
				}

			}
			finally
			{
				if (log != null) log.debug("KeepAlive Thread is teminated!");
				stopped = true;
			}
		}
	}

	private class CReceiveThread extends Thread
	{
		private volatile boolean stopFlag;

		private volatile boolean stopped;

		public CReceiveThread()
		{
			stopFlag = false;
			stopped = false;
		}

		public void killMe()
		{
			stopFlag = true;
			synchronized (newMsgMonitor)
			{
				newMsgMonitor.notify();
			}
		}

		public boolean killed()
		{
			return stopped;
		}

		public void run()
		{
			LinkedList messageList = new LinkedList();
			try
			{
				while (!stopFlag)
				{
					int state = newMsgMonitor.waitEvent(asyncPollInterval);
					if (stopFlag) break;
					if (getConnected() && (receiveMode == ReceiveMode.AsyncCnmi || receiveMode == ReceiveMode.AsyncPoll))
					{
						try
						{
							if (state == CNewMsgMonitor.DATA && !atHandler.dataAvailable() && newMsgMonitor.getState() != CNewMsgMonitor.CMTI) continue;

							newMsgMonitor.reset();
							messageList.clear();
							readMessages(messageList, asyncRecvClass);
							for (int i = 0; i < messageList.size(); i++)
							{
								CIncomingMessage message = (CIncomingMessage) messageList.get(i);
								if (getMessageHandler() == null)
								{
									if (received(message)) deleteMessage(message);
								}
								else
								{
									if (getMessageHandler() != null && getMessageHandler().received(CService.this, message)) deleteMessage(message);
								}

							}
						}
						catch (Exception e)
						{
							catchAsyncException(e);
						}
					}
				}

			}
			finally
			{
				if (log != null) log.debug("Receive Thread is terminated!");
				stopped = true;
			}
		}
	}

	public static void main(String[] args)
	{
		System.out.println(_name + " " + _version);
		System.out.println("	Java API for sending / receiving SMS messages via GSM modem.");
		System.out.println("	This software is distributed under the LGPL license.");
		System.out.println("");
		System.out.println("Copyright (C) 2002-2007, Thanasis Delenikas, Athens / GREECE.");
		System.out.println("Visit http://smslib.org for latest information.\n");
	}
}

⌨️ 快捷键说明

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