java发送短信之AT指令

时间:2015-11-29 15:50:20
【文件属性】:

文件名称:java发送短信之AT指令

文件大小:43KB

文件格式:RAR

更新时间:2015-11-29 15:50:20

AT 短信猫

短信内容的存储类 /*** * CommonSms 短信用于全局变量 */ public class CommonSms{ /** id */ private int id; /**短信内容*/ private String smstext; /**短信发送方*/ private String sender;//短信发送方 /**短信接收发*/ private String recver;//短信接收发 /**时间*/ private Date date; public String getSmstext() { return smstext; } public void setSmstext(String smstext) { this.smstext = smstext; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public String getRecver() { return recver; } public void setRecver(String recver) { this.recver = recver; } } 串口操纵实现类 /*** * 串口操纵实现类 */ public class Port { private CommPortIdentifier portId; private SerialPort serialPort; private OutputStreamWriter out; private InputStreamReader in; private String COMname; private static char symbol1 = 13; public String getCOMname() { return COMname; } public void setCOMname(String mname) { COMname = mname; } public CommPortIdentifier getPortId() { return portId; } public void setPortId(CommPortIdentifier portId) { this.portId = portId; } public SerialPort getSerialPort() { return serialPort; } public void setSerialPort(SerialPort serialPort) { this.serialPort = serialPort; } public OutputStreamWriter getOut() { return out; } public void setOut(OutputStreamWriter out) { this.out = out; } public InputStreamReader getIn() { return in; } public void setIn(InputStreamReader in) { this.in = in; } public boolean isused =true; public boolean isIsused() { return isused; } public void setIsused(boolean isused) { this.isused = isused; } /** * 打开com口 * @param portName * @return */ public Port(String portName) { try { portId = CommPortIdentifier.getPortIdentifier(portName); if (portId == null) { System.out.println("port is null"); } try { serialPort = (SerialPort) portId.open(portName,100000); } catch (PortInUseException e) { System.gc(); e.printStackTrace(); } // 下面是得到用于和COM口通讯的输进、输出流。 try { in = new InputStreamReader(serialPort.getInputStream()); out = new OutputStreamWriter(serialPort.getOutputStream()); } catch (IOException e) { System.gc(); System.out.println("IOException"); } // 下面是初始化COM口的传输参数,如传输速率:9600等。 try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); setCOMname(portId.getName()); setIsused(true); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); System.gc(); } } catch (NoSuchPortException e) { e.printStackTrace(); System.gc(); } } /** * 检查SIM是否存在 * @return */ public boolean chakanPort() { try { String atCommand = "AT+ccid"; String strReturn = sendAT(atCommand); if (strReturn.indexOf("OK", 0) != -1) { return true; } return false; } catch (Exception ex) { System.gc(); ex.printStackTrace(); return false; } } /** * 封闭COM口 * @return boolean */ public void close() { try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } serialPort.close(); System.gc(); setIsused(false); } /** * 向串口中写进字符串命令 * @param s 字符串命令 * @throws Exception 异常 */ public void writeln(String s) throws Exception { out.write(s); out.write('\r'); out.flush(); } /** * 读取COM命令的返回字符串 * @return 结果字符串 * @throws Exception */ public String read() throws Exception { int n, i; char c; String answer = ""; for (i = 0; i < 100; i++) { while (in.ready()) { n = in.read(); if (n != -1) { c = (char) n; answer = answer + c; Thread.sleep(1); } else break; } if (answer.indexOf("OK") != -1) { break; } Thread.sleep(100); } return answer; } /** * 向串口发送AT指令 * @param atcommand 指令内容 * @return 指令返回结果 * @throws java.rmi.RemoteException */ public String sendAT(String atcommand) throws java.rmi.RemoteException { String s = ""; try { Thread.sleep(100); writeln(atcommand); Thread.sleep(80); s = read(); Thread.sleep(100); } catch (Exception e) { System.gc(); System.out.println("ERROR: send AT command failed; " + "Command: " + atcommand + "; Answer: " + s + " " + e); } return s; } } 短信操纵类 /*** * 短信操纵类 */ public class Sms{ private CommonSms commonsms; private static char symbol1 = 13; private static String strReturn = "", atCommand = ""; public boolean SendSms(Port myport) { if(!myport.isIsused()) { System.out.println("COM通讯端口未正常打开!"); return false; } setMessageMode(myport,1); // 空格 char symbol2 = 34; // ctrl~z 发送指令 char symbol3 = 26; try { atCommand = "AT+CSMP=17,169,0,08" + String.valueOf(symbol1); strReturn = myport.sendAT(atCommand); System.out.println(strReturn); if (strReturn.indexOf("OK", 0) != -1) { atCommand = "AT+CMGS=" + commonsms.getRecver() + String.valueOf(symbol1); strReturn = myport.sendAT(atCommand); atCommand = StringUtil.encodeHex(commonsms.getSmstext().trim()) + String.valueOf(symbol3) + String.valueOf(symbol1); strReturn = myport.sendAT(atCommand); if (strReturn.indexOf("OK") != -1 && strReturn.indexOf("+CMGS") != -1) { System.out.println("短信发送成功..."); return true; } } } catch (Exception ex) { ex.printStackTrace(); System.out.println("短信发送失败..."); return false; } System.out.println("短信发送失败..."); return false; } /** * 设置消息模式 * @param op * 0-pdu 1-text(默认1 文本方式 ) * @return */ public boolean setMessageMode(Port myport,int op) { try { String atCommand = "AT+CMGF=" + String.valueOf(op) + String.valueOf(symbol1); String strReturn = myport.sendAT(atCommand); if (strReturn.indexOf("OK", 0) != -1) { System.out.println("*************文本方式设置成功************"); return true; } return false; } catch (Exception ex) { ex.printStackTrace(); return false; } } /** * 读取所有短信 * @return CommonSms集合 */ public List RecvSmsList(Port myport) { if(!myport.isIsused()) { System.out.println("System Message: COM通讯端口未正常打开!"); return null; } List listMes = new ArrayList(); try { atCommand = "AT+CMGL=\"ALL\""; strReturn = myport.sendAT(atCommand); listMes = StringUtil.analyseArraySMS(strReturn); } catch (Exception ex) { ex.printStackTrace(); } return listMes; } /** * 删除短信 * @param index 短信存储的位置 * @return boolean */ public boolean DeleteSMS(int index,Port myport) { if(!myport.isIsused()){ System.out.println("System Message: COM通讯端口未正常打开!"); return false; } try { atCommand = "AT+CMGD=" + index; strReturn = myport.sendAT(atCommand); if (strReturn.indexOf("OK") != -1) { System.out.println("System Message: 成功删除存储位置为" + index + "的短信......"); } } catch (Exception ex) { ex.printStackTrace(); } return true; } /** * 删除短信中所有短信 * @return boolean */ public boolean DeleteAllSMS(Port myport) { List list=RecvSmsList(myport); boolean ret=true; if(list!=null&&!list.equals("")&&list;.size()>0) { for(int i=0;i analyseArraySMS(String str) { List mesList = new ArrayList(); CommonSms cs; String[] messages; String temp; String[] t; if (str.indexOf("CMGL: ") == -1) return null; str = str.substring(0, str.indexOf("OK")).trim(); messages = str.split("\n"); if (messages.length < 2) return null; for (int i = 1; i < messages.length; i++) { cs = new CommonSms(); messages[i] = messages[i] .substring(messages[i].indexOf("CMGL: ") + 6); t = messages[i].split(","); if (t.length > 5) { cs.setId(Integer.parseInt(t[0].trim())); temp = t[1].substring(t[1].indexOf('"') + 1, t[1].lastIndexOf('"')).trim(); if (temp.equals("REC READ")) { cs.setState("已读"); } else { cs.setState("未读"); } cs.setSender((t[2].substring(t[2].indexOf('"') + 1, t[2] .lastIndexOf('"')).trim())); SimpleDateFormat df = new SimpleDateFormat("yy/MM/dd hh:mm:ss"); String datestring = t[4].substring(t[4].indexOf('"') + 1) + " " + t[5].substring(0, t[5].indexOf('"'));// 短信时间格式09/09/09 // 20:18:01+32 Date date = null; try { date = df.parse(datestring); } catch (Exception ex) { System.out.println(ex.getMessage()); } cs.setDate(date); i++; cs.setSmstext(analyseStr(messages[i].trim())); mesList.add(cs); } } return mesList; } /** * 将PDU编码的十六进制字符串 如“4F60597DFF01” 转换成unicode "\u4F60\u597D\uFF01" * @param str 要转化的字符串 * @return 转换后的十六进制字符串 */ public static String analyseStr(String str) { StringBuffer sb = new StringBuffer(); if (!(str.length() % 4 == 0)) return str; for (int i = 0; i < str.length(); i++) { if (i == 0 || i % 4 == 0) { sb.append("\\u"); } sb.append(str.charAt(i)); } return Unicode2GBK(sb.toString()); } /** * 将unicode编码 "\u4F60\u597D\uFF01" 转换成中文 "你好!" * @param dataStr 要转化的字符串 * @return 转换后的中文字符串 */ public static String Unicode2GBK(String dataStr) { int index = 0; StringBuffer buffer = new StringBuffer(); while (index < dataStr.length()) { if (!"\\u".equals(dataStr.substring(index, index + 2))) { buffer.append(dataStr.charAt(index)); index++; continue; } String charStr = ""; charStr = dataStr.substring(index + 2, index + 6); char letter = 0; try{letter = (char) Integer.parseInt(charStr, 16);}catch (Exception e) {} buffer.append(letter); index += 6; } return buffer.toString(); } /** * 将中文字符串转换成Unicode * @param str 要转换的中文字符串 * @return 转换后的Unicode */ public static String GBK2Unicode(String str) { StringBuffer result = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char chr1 = (char) str.charAt(i); if (!isNeedConvert(chr1)) { result.append(chr1); continue; } try{result.append("\\u" + Integer.toHexString((int) chr1));}catch (Exception e) {} } return result.toString(); } /** * 在中文字符串转换成Unicode方法中判定是否需要转换 * @param para 要转化的字符 * @return boolean */ public static boolean isNeedConvert(char para) { return ((para & (0x00FF)) != para); } /** * 使用Sms 的 SendSms()方法发送短信时,调用此方法将其短信内容转换成十六进制 * @param msg 短信内容 * @return 转换后的十六进制短信 */ public static final String encodeHex(String msg) { byte[] bytes = null; try { bytes = msg.getBytes("GBK"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } StringBuffer buff = new StringBuffer(bytes.length * 4); String b = ""; char a; int n = 0; int m = 0; for (int i = 0; i < bytes.length; i++) { try{b = Integer.toHexString(bytes[i]);}catch (Exception e) {} if (bytes[i] > 0) { buff.append("00"); buff.append(b); n = n + 1; } else { a = msg.charAt((i - n) / 2 + n); m = a; try{b = Integer.toHexString(m);}catch (Exception e) {} buff.append(b.substring(0, 4)); i = i + 1; } } return buff.toString(); } }


【文件预览】:
AT指令_sms
----.project(1KB)
----.mymetadata(282B)
----src()
--------com()
----WebRoot()
--------WEB-INF()
--------index.jsp(834B)
--------META-INF()
----.myeclipse()
----.settings()
--------org.eclipse.wst.jsdt.ui.superType.container(49B)
--------org.eclipse.wst.jsdt.ui.superType.name(6B)
--------org.eclipse.core.resources.prefs(176B)
--------.jsdtscope(500B)
----.classpath(429B)

网友评论

  • 下来运行报nosuchport错误,我把依赖包comm换成Rxtxcomm,串口配置加了数据流控serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT); (这个和硬件有关吧),就可以发送成功了
  • 看了下。。还不错。。比较全面
  • 好东西 有用
  • 我就看个发AT指令的例子,不错,学习了
  • 写得很好,程序可以运行,谢谢分享
  • 这个比较全面,是不错的例子
  • 虽然例子没有跑起来,但有一定指导意义~感谢~
  • 有帮助,谢谢额!!!
  • 命令很全,很好,谢谢
  • 我部署了一下,来参考参考你的。
  • 挺全面的。存下来慢慢看。
  • 挺全面的。存下来慢慢看。
  • 不错,可以运行。可惜没有服务器接口可以测试
  • 不错,可以运行。
  • 临阵抱抱佛脚,学习一下
  • 有点乱,而且中文还乱码