📄 modemdriver.java
字号:
// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Copyright (C) 2002-2007, Thanasis Delenikas, Athens/GREECE
// Portions Copyright:
// Davide Bettoni, Clusone/ITALY, dbettoni@users.sourceforge.net
// Tomek Cejner, Polland, heretique@users.sourceforge.net
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.smslib.gateway;
import java.util.*;
import java.util.regex.*;
import org.smslib.*;
public abstract class ModemDriver
{
public enum AsyncEvents
{
Delete, Nothing, InboundMessage, InboundStatusReportMessage, InboundCall
};
protected static final int RECEIVE_TIMEOUT = 30 * 1000;
protected static final int BUFFER_SIZE = 16384;
protected static final int CLEAR_WAIT = 1000;
protected static final boolean ENABLE_QUEUE_DEBUG = true;
// Match error messages from modem
private static final String rxErrorWithCode = "\\s*[\\p{ASCII}]*\\s*\\+(CM[ES]) ERROR: (\\d+)\\s";
private static final String rxPlainError = "\\s*[\\p{ASCII}]*\\s+ERROR\\s";
protected Object SYNC_Reader, SYNC_Commander;
protected ModemGateway gateway;
protected boolean dataReceived;
private boolean connected;
private CharQueue queue;
private ModemReader modemReader;
private KeepAlive keepAlive;
private AsyncNotifier asyncNotifier;
/**
* Code of last error
*
* -1 = empty or invalid response 0 = OK 5xxx = CME error xxx 6xxx = CMS
* error xxx 9000 = ERROR
*/
private int lastError;
protected ModemDriver(ModemGateway gateway, String deviceParms)
{
SYNC_Reader = new Object();
SYNC_Commander = new Object();
this.gateway = gateway;
connected = false;
dataReceived = false;
queue = new CharQueue();
}
abstract protected void connectPort() throws Exception;
abstract protected void disconnectPort() throws Exception;
abstract protected void clear() throws Exception;
protected void connect() throws Exception
{
String response;
try
{
synchronized (SYNC_Commander)
{
connectPort();
clearBuffer();
gateway.getATHandler().sync();
gateway.getATHandler().echoOff();
while (true)
{
response = gateway.getATHandler().getSimStatus();
while (response.indexOf("BUSY") >= 0)
{
gateway.getLogger().debug("SIM found busy, waiting...");
Thread.sleep(5000);
response = gateway.getATHandler().getSimStatus();
}
if (response.indexOf("SIM PIN") >= 0)
{
gateway.getLogger().debug("SIM requesting PIN.");
if ((gateway.getSimPin() == null) || (gateway.getSimPin().length() == 0)) throw new NoPinException();
if (!gateway.getATHandler().enterPin(gateway.getSimPin())) throw new IncorrectCredentialsException();
Thread.sleep(10000);
}
if (response.indexOf("READY") >= 0) break;
}
gateway.getATHandler().init();
gateway.getATHandler().echoOff();
waitForNetworkRegistration();
gateway.getATHandler().setVerboseErrors();
if (gateway.getATHandler().getStorageLocations().length() == 0) gateway.getATHandler().readStorageLocations();
gateway.getLogger().info("MEM: Storage Locations Found: " + gateway.getATHandler().getStorageLocations());
if (!gateway.getATHandler().setIndications()) gateway.getLogger().warn("Callback indications were *not* set succesfully!");
switch (gateway.getProtocol())
{
case PDU:
if (!gateway.getATHandler().setPduProtocol()) throw new ProtocolNotSupportedException();
break;
case TEXT:
if (!gateway.getATHandler().setTextProtocol()) throw new ProtocolNotSupportedException();
break;
}
}
}
catch (Exception e)
{
disconnect();
throw e;
}
}
protected void disconnect() throws Exception
{
disconnectPort();
}
protected void setConnected(boolean value) throws Exception
{
connected = value;
if (connected)
{
modemReader = new ModemReader();
keepAlive = new KeepAlive();
asyncNotifier = new AsyncNotifier();
}
else
{
if (asyncNotifier != null)
{
asyncNotifier.interrupt();
asyncNotifier.join();
asyncNotifier = null;
}
if (keepAlive != null)
{
keepAlive.interrupt();
keepAlive.join();
keepAlive = null;
}
if (modemReader != null)
{
modemReader.interrupt();
modemReader.join();
modemReader = null;
}
}
}
abstract public void write(char c) throws Exception;
abstract protected int read() throws Exception;
abstract protected boolean portHasData() throws Exception;
public boolean dataAvailable() throws Exception
{
return (queue.peek() == -1 ? false : true);
}
public void write(String s) throws Exception
{
gateway.getLogger().debug("SEND :" + formatLog(new StringBuffer(s)));
for (int i = 0; i < s.length(); i++)
write(s.charAt(i));
}
public String getResponse() throws Exception
{
StringBuffer buffer;
String response;
byte c;
boolean terminate;
int i;
String terminators[];
lastError = -1;
terminators = gateway.getATHandler().getTerminators();
buffer = new StringBuffer(BUFFER_SIZE);
while (true)
{
while ((queue.peek() == 0x0a) || (queue.peek() == 0x0d))
queue.get();
while (true)
{
c = queue.get();
if(ENABLE_QUEUE_DEBUG) gateway.getLogger().debug("OUT READER QUEUE : " + (int) c + " / " + (char) c);
if (c != 0x0a) buffer.append((char) c);
else break;
}
if (buffer.charAt(buffer.length() - 1) != 0x0d) buffer.append((char) 0x0d);
response = buffer.toString();
terminate = false;
for (i = 0; i < terminators.length; i++)
if (response.matches(terminators[i]))
{
terminate = true;
break;
}
if (terminate) break;
}
if (i >= terminators.length - 4)
{
switch (gateway.getATHandler().processUnsolicitedEvents(buffer.toString()))
{
case Nothing:
break;
case InboundMessage:
asyncNotifier.setEvent(AsyncEvents.InboundMessage);
break;
case InboundStatusReportMessage:
asyncNotifier.setEvent(AsyncEvents.InboundStatusReportMessage);
break;
case InboundCall:
asyncNotifier.setEvent(AsyncEvents.InboundCall);
break;
}
return getResponse();
}
// Try to interpret error code
if (response.matches(rxErrorWithCode))
{
Pattern p = Pattern.compile(rxErrorWithCode);
Matcher m = p.matcher(response);
if (m.find())
{
if (m.group(1).equals("CME"))
{
int code = Integer.parseInt(m.group(2));
lastError = 5000 + code;
}
else if (m.group(1).equals("CMS"))
{
int code = Integer.parseInt(m.group(2));
lastError = 6000 + code;
}
else throw new InvalidResponseException("Invalid error response: " + m.group(1));
}
else throw new InvalidResponseException("Cannot match error code. Should never happen!");
}
else if (response.matches(rxPlainError))
{
lastError = 9000;
}
else if (response.indexOf("OK") >= 0)
{
lastError = 0;
}
gateway.getLogger().debug("RECV :" + formatLog(buffer));
return buffer.toString();
}
public void clearBuffer() throws Exception
{
gateway.getLogger().debug("clearBuffer() called.");
Thread.sleep(CLEAR_WAIT);
clear();
queue.clear();
}
private boolean waitForNetworkRegistration() throws Exception
{
StringTokenizer tokens;
String response;
int answer;
while (true)
{
response = gateway.getATHandler().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:
gateway.getLogger().error("GSM: Auto-registration disabled!");
throw new OopsException("GSM Network Auto-Registration disabled!");
case 1:
gateway.getLogger().info("GSM: Registered to home network.");
return true;
case 2:
gateway.getLogger().warn("GSM: Not registered, searching for network...");
break;
case 3:
gateway.getLogger().error("GSM: Network registration denied!");
throw new OopsException("GSM Network Registration denied!");
case 4:
gateway.getLogger().error("GSM: Unknown registration error!");
throw new OopsException("GSM Network Registration error!");
case 5:
gateway.getLogger().info("GSM: Registered to foreign network (roaming).");
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -