GPRS模块的使用&Java串口操作(2)

来源:互联网 发布:电子网络发票下载流程 编辑:程序博客网 时间:2024/06/05 21:58
续上,GPRS模块的使用&Java串口操作(2)
本章关注 Java串口配置和操作

配置:
 Win32串口编程前期准备 
1,去sun的官方网站下载开发包 javacomm20-win32.zip并解压
2,copy c:\commapi\win32com.dll →c:\jdk1.4.2\bin 
3,copy c:\commapi\javax.comm.properties → c:\jdk1.1.6\lib 
4,copy c:\commapi\comm.jar → c:\jdk1.1.6\lib
5, VIP:步骤,例化-导入驱动importDriver()!-初始化
6. 使用完关闭closePort();

这里重点提下,第五步,网上大多忽略此步骤编程时串口可能初始化不成功
public void importDriver() {
//加载驱动
String driverName = "com.sun.comm.Win32Driver";
CommDriver driver = null;
try {
  System.loadLibrary("win32com");
   driver = (CommDriver)Class.forName(driverName).newInstance();
  driver.initialize();
  } catch (InstantiationException e1) {
  e1.printStackTrace();
  } catch (IllegalAccessException e1) {
  e1.printStackTrace();
  } catch (ClassNotFoundException e1) {
  e1.printStackTrace();
  }   
//列出可用串口   
      CommPortIdentifier portId;
      Enumeration en =CommPortIdentifier.getPortIdentifiers();
      // iterate through the ports.
      while (en.hasMoreElements()) {       
          portId =(CommPortIdentifier) en.nextElement();
          if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            System.out.println(portId.getName());
          }
      }
    }


使用一般过程:
testPort = new SerialBean("COM1");
testPort.importDriver();
if (testPort.initialize()==1){//initialSuccess
  //写串口
testPort.writePort(mesg);
  //读串口
    String replys =testPort.getPack();

  //关串口
testPort.closePort(); 
}

UDP指令包接收与处理:
假设UDP连接成功,服务器发送控制指令到GPRS模块
指令1:setTextmode——设置GPRS模块为Text模式
指令2:发短信——指令格式: txt-phone-textcontent 

//处理指令1:
//setTextmode——设置GPRS模块为Text模式
if(replyMeg.contains("setTextmode")){
//打电话:ATDXXX;
System.out.println("设置短信为text mode");
System.out.println(replyMeg);
     setAction ="AT+CMGF=1";
testPort.writePort(setAction+"\r");//以“\r”结束输入并发送
waitforRec();//wait for a few seconds
replyMeg =testPort.getPack();
System.out.println(replyMeg);
}
//处理指令2:
//send SMS totarget phone
//指令格式;txt-phone-textcontent 
if(replyMeg.contains("txt")){
String[] msgs =replyMeg.split("-");
if(msgs.length==3){
System.out.println("准备发送短信给"+msgs[1]);
setAction ="AT+CMGS="+yh+msgs[1]+yh;
testPort.writePort(setAction+"\r");//此处仍以回车\r,not回车换行符\r\n
waitforRec();
replyMeg =testPort.getPack();
System.out.println(replyMeg);
//最好加一判断是否成功收到> 符号
//开始发送 SMSContent
setAction =msgs[2];
testPort.writePort(setAction+cz);//cz为ctrl-Z字符,详见上一篇
waitforRec();
replyMeg =testPort.getPack();
System.out.println(replyMeg);
}
}

意外发现:

当GPRS模块在进行拨号打电话操作时,UDP数据接收不到。只有当电话挂断后,才能正常接收Server数据!
不知道有木有人遇到过呢?求解决方法~

参考:
http://www.myexception.cn/program/465083.html
http://www.cnblogs.com/jiandanfy/archive/2009/03/23/1419373.html
0 0
原创粉丝点击