资讯详情

Java使用串行编程操作继电器

首先,我们必须建立一个良好的环境,那就是,jdk并且tomcat。如果它不必须是web装了!

还有配置,即默认comm.jar ,javax.comm.properties , win32com.dll这些文件应该放在地方

comm.jar放到C:\Program Files (x86)\Java\jdk1.7.0_01\jre\lib\ext 同时也放jre同样的文件夹下

javax.comm.properties放到 C:\Program Files (x86)\Java\jdk1.7.0_01\jre\lib 也放到jre下

win32com.dll放到C:\Program Files (x86)\Java\jdk1.7.0_01\jre\bin也放到jre下

同一时候

win32com.dll也放到c:windows下的System32下 也把comm.jar配置到classpath下

这是编程程序。

package com.serial;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;

import javax.comm.PortInUseException;

import javax.comm.SerialPort;

import javax.comm.SerialPortEvent;

import javax.comm.SerialPortEventListener;

/**

* @项目名称 :illegalsms

* @文件名 :SerialPort.java

* @所在包 :org.serial

* @功能描述叙述 : 串口类

* @创建日期 :2012-9-13

* @改动记录 :

*/

public class DSerialPort implements Runnable, SerialPortEventListener {

private String appName = "串口通信测试";

private int timeout = 2000;// open 端口等待时间

private int threadTime = 0;

private CommPortIdentifier commPort;

private SerialPort serialPort;

private InputStream inputStream;

private OutputStream outputStream;

/**

* @方法名称 :listPort

* @功能描述叙述 :列出所有可用的串口

* @返回值类型 :void

*/

@SuppressWarnings("rawtypes")

public void listPort() {

CommPortIdentifier cpid;

Enumeration en = CommPortIdentifier.getPortIdentifiers();

System.out.println("now to list all Port of this PC:" en);

while (en.hasMoreElements()) {

cpid = (CommPortIdentifier) en.nextElement();

if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL) {

System.out.println(cpid.getName() ", "

cpid.getCurrentOwner());

}

}

}

/**

* @方法名称 :selectPort

* @功能描述叙述 :选择一个端口,例如:COM1

* @返回值类型 :void

* @param portName

*/

@SuppressWarnings("rawtypes")

public void selectPort(String portName) {

this.commPort = null;

CommPortIdentifier cpid;

Enumeration en = CommPortIdentifier.getPortIdentifiers();

while (en.hasMoreElements()) {

cpid = (CommPortIdentifier) en.nextElement();

if (cpid.getPortType() == CommPortIdentifier.PORT_SERIAL

&& cpid.getName().equals(portName)) {

this.commPort = cpid;

break;

}

}

openPort();

}

/**

* @方法名称 :openPort

* @功能描述叙述 :打开SerialPort

* @返回值类型 :void

*/

private void openPort() {

if (commPort == null)

log(String.format("找不到名字的‘%1%$s'的串口!", commPort.getName()));

else {

log("成功选择端口,当前端口:" commPort.getName() ",如今实例化 SerialPort:");

try {

serialPort = (SerialPort) commPort.open(appName, timeout);

log("实例 SerialPort 成功!");

} catch (PortInUseException e) {

throw new RuntimeException(String.format("端口'%1$s在使用中!",

commPort.getName()));

}

}

}

/**

* @方法名称 :checkPort

* @功能描述叙述 :检查端口是否正确连接

* @返回值类型 :void

*/

private void checkPort() {

if (commPort == null)

throw new RuntimeException("端口没有选择。请使用它。 "

"selectPort(String portName) 选择端口的方法");

if (serialPort == null) {

throw new RuntimeException("SerialPort 对象无效。");

}

}

/**

* @方法名称 :write

* @功能描述叙述 :在调用此方法之前,请将数据发送到端口 首先选择端口并确定SerialPort正常打开!

* @返回值类型 :void

* @param message

*/

public void write(String message) {

checkPort();

try {

outputStream = new BufferedOutputStream(

serialPort.getOutputStream());

} catch (IOException e) {

throw new RuntimeException("获取端口的OutputStream出错:" e.getMessage());

}

try {

outputStream.write(message.getBytes());

log("信息发送成功!

");

} catch (IOException e) {

throw new RuntimeException("向端口发送信息时出错:" + e.getMessage());

} finally {

try {

outputStream.close();

} catch (Exception e) {

}

}

}

/**

* @方法名称 :startRead

* @功能描写叙述 :開始监听从端口中接收的数据

* @返回值类型 :void

* @param time

* 监听程序的存活时间,单位为秒。0 则是一直监听

*/

public void startRead(int time) {

checkPort();

try {

inputStream = new BufferedInputStream(serialPort.getInputStream());

} catch (IOException e) {

throw new RuntimeException("获取端口的InputStream出错:" + e.getMessage());

}

try {

serialPort.addEventListener(this);

} catch (TooManyListenersException e) {

throw new RuntimeException(e.getMessage());

}

serialPort.notifyOnDataAvailable(true);

log(String.format("開始监听来自'%1$s'的数据--------------", commPort.getName()));

if (time > 0) {

this.threadTime = time * 10;

Thread t = new Thread(this);

t.start();

log(String.format("监听程序将在%1$d秒后关闭。

。。

", threadTime));

}

}

/**

* @方法名称 :close

* @功能描写叙述 :关闭 SerialPort

* @返回值类型 :void

*/

public void close() {

serialPort.close();

serialPort = null;

commPort = null;

}

public void log(String msg) {

System.out.println(appName + " --> " + msg);

}

/**

* 数据接收的监听处理函数

*/

@Override

public void serialEvent(SerialPortEvent arg0) {

switch (arg0.getEventType()) {

case SerialPortEvent.BI:/* Break interrupt,通讯中断 */

case SerialPortEvent.OE:/* Overrun error,溢位错误 */

case SerialPortEvent.FE:/* Framing error。传帧错误 */

case SerialPortEvent.PE:/* Parity error,校验错误 */

case SerialPortEvent.CD:/* Carrier detect,载波检測 */

case SerialPortEvent.CTS:/* Clear to send,清除发送 */

case SerialPortEvent.DSR:/* Data set ready,数据设备就绪 */

case SerialPortEvent.RI:/* Ring indicator,响铃指示 */

case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*

* Output buffer is

* empty,输出缓冲区清空

*/

break;

case SerialPortEvent.DATA_AVAILABLE:/*

* Data available at the serial

* port,端口有可用数据。读到缓冲数组。输出到终端

*/

byte[] readBuffer = new byte[1024];

String readStr = "";

String s2 = "";

try {

while (inputStream.available() > 0) {

inputStream.read(readBuffer);

readStr += new String(readBuffer).trim();

}

s2 = new String(readBuffer).trim();

log("接收到端口返回数据(长度为" + readStr.length() + "):" + readStr);

log(s2);

} catch (IOException e) {

}

}

}

@Override

public void run() {

try {

Thread.sleep(threadTime);

serialPort.close();

log(String.format("端口''监听关闭了。", commPort.getName()));

} catch (Exception e) {

e.printStackTrace();

}

}

}

还有就是

package com.serial;

public class TestSerial {

public static final String PORT_NAME = "COM1";

public static void main(String[] args) {

DSerialPort sp = new DSerialPort();

sp.listPort();

sp.selectPort(PORT_NAME);

sp.write("O(00,20,0)E");

sp.startRead(5);

}

}

要是在web上使用的话 就要建一web serviceproject

建议用eclipse j2ee版的,然后建一个web项目

然后创建同样的类放里面。然后再创建一个servlet

package com.serial.servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.serial.DSerialPort;

/**

* Servlet implementation class RunServlet

*/

public class RunServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public RunServlet() {

super();

}

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

this.doPost(request, response);

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)

*/

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

// String code = "O(00,20,1)E";

String address = request.getParameter("address"); // 地址

String state = request.getParameter("state"); // 状态

String bofile = request.getParameter("file"); // 视频地址

if (address != null && state != null) {

runSerial(address, state, bofile);

} else {

address = "00";

state = "0";

runSerial(address, state, bofile);

}

System.out.println("bofile:" + bofile);

}

// 运行串口

public void runSerial(String address, String state, String bofile) {

if (address != null && state != null) {

String PORT_NAME = "COM1";

String code = "O(00," + address + "," + state + ")E";

DSerialPort sp = new DSerialPort();

sp.listPort();

sp.selectPort(PORT_NAME);

sp.write(code);

/* if (bofile != null) { */

if (state.equals("1")) {

play(bofile);

}

/* } */

sp.startRead(1);

}

}

// 播放视频

public void play(String path) {

System.out.println("path:" + path);

// String

// potplayer="D:/The entertainment software/PotPlayer/PotPlayerMini64.exe";

String mediaPath = "C:/MPlayer_Windows/mplayer/MPlayer.exe"; // 文件路径

// 调用mplayer命令行

String cmd = " -vo directx identify wid String.valueOf(false) -colorkey 0x030303 -slave -osdlevel String.valueOf(1)"

+ " -fullscreen";

try {

Process rn = Runtime.getRuntime().exec(

mediaPath + " " + path + " " + cmd); // 在单独的进程中运行指定命令和变量

/*

* Process rn = Runtime.getRuntime().exec( potplayer + " " + path);

* // 在单独的进程中运行指定命令和变量

*/

System.out.println("视频開始播放");

} catch (IOException e1) {

e1.printStackTrace();

return;

}

}

}

我这个是再加了一个播放视频的

说的非常easy,要是有不知道,我可以。我可以来探索哦,QQ在左上角

标签: 继电器用什么串口3rn1继电器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台