Java uses serial programming technology to operate Relays

Source: Internet
Author: User

First, you need to build the environment, that is, jdk and tomcat. You do not need to install it if you do not need to use it on the web! There is also the configuration, that is, the default comm. jar, javax. comm. properties, win32com. dll files need to be placed on the local comm. jar Files are stored in C: \ Program Files (x86) \ Java \ jdk1.7.0 _ 01 \ jre \ lib \ ext and in javax under the same jre directory. comm. properties is stored in C: \ Program Files (x86) \ Java \ jdk1.7.0 _ 01 \ jre \ lib and in win32com under jre. dll to C: \ Program Files (x86) \ Java \ jdk1.7.0 _ 01 \ jre \ bin is also placed under jre and win32com. dll is also placed in c: System32 in windows, and comm is also put. jar is configured in classpath. This completes the compilation of 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. commp ortidentifier; import javax. comm. portInUseException; import javax. comm. serialPort; import javax. comm. serialPortEvent; import javax. comm. serialPortEventListener ;/*** @ Project name: illegalsms * @ file name: SerialPort. java * @ package: org. serial * @ Function Description: serial class * @ creation date: 2012-9-13 * @ modification record: */public class DSerialPort implements Runnable, SerialPortEventListener {private String appName = "serial communication test "; private int timeout = 2000; // wait time for the open port private int threadTime = 0; private commp ortidentifier commp ORT; private SerialPort serialPort; private InputStream inputStream; private OutputStre Am outputStream;/*** @ Method Name: listPort * @ Function Description: lists all available serial ports * @ return value type: void */@ SuppressWarnings ("rawtypes ") public void listPort () {comatrix ortidentifier cpid; Enumeration en = comatrix ortidentifier. getPortIdentifiers (); System. out. println ("now to list all Port of this PC:" + en); while (en. hasMoreElements () {cpid = (comatrix ortidentifier) en. nextElement (); if (cpid. getPortType () = comatrix ortidentifier. PORT_SERI AL) {System. out. println (cpid. getName () + "," + cpid. getCurrentOwner () ;}}/ *** @ Method Name: selectPort * @ Function Description: select a port, for example, COM1 * @ return value type: void * @ param portName */@ SuppressWarnings ("rawtypes") public void selectPort (String portName) {this. comatrix ORT = null; comatrix ortidentifier cpid; Enumeration en = comatrix ortidentifier. getPortIdentifiers (); while (en. hasMoreElements () {cpid = (comatrix ortidentifier) en. nextElem Ent (); if (cpid. getPortType () = comatrix ortidentifier. PORT_SERIAL & cpid. getName (). equals (portName) {this. commp ORT = cpid; break;} openPort ();}/*** @ Method Name: openPort * @ Function Description: Enable SerialPort * @ return value type: void */private void openPort () {if (commp ORT = null) log (String. format ("unable to find the serial port named '% 1 $ s! ", Comatrix. getName (); else {log ("port selected successfully, current port:" + commp ort. getName () + ", now instantiate SerialPort:"); try {serialPort = (SerialPort) commp ort. open (appName, timeout); log ("instance SerialPort successful! ");} Catch (PortInUseException e) {throw new RuntimeException (String. format (" port '% 1 $ s' is in use! ", Comatrix. getName () ;}}/ *** @ Method Name: checkPort * @ Function Description: Check whether the port is correctly connected * @ return value type: void */private void checkPort () {if (commp ORT = null) throw new RuntimeException ("no port selected, please use" + "selectPort (String portName) method Selection port "); if (serialPort = null) {throw new RuntimeException (" the SerialPort object is invalid! ") ;}}/*** @ Method Name: write * @ Function Description: send data to the port. Please select the port before calling this method and make sure that the SerialPort is opened normally! * @ Return value type: void * @ param message */public void write (String message) {checkPort (); try {outputStream = new BufferedOutputStream (serialPort. getOutputStream ();} catch (IOException e) {throw new RuntimeException ("An error occurred while obtaining the port OutputStream:" + e. getMessage ();} try {outputStream. write (message. getBytes (); log ("message sent successfully! ");} Catch (IOException e) {throw new RuntimeException (" An error occurred while sending information to the port: "+ e. getMessage ();} finally {try {outputStream. close ();} catch (Exception e) {}}/*** @ Method Name: startRead * @ function description: start listening for data received from the port * @ return value type: void * @ param time * The survival time of the listener, in seconds, 0 is always listening */public void startRead (int time) {checkPort (); try {inputStream = new BufferedInputStream (serialPort. getInputStream ();} catch (IOException e) {thro W new RuntimeException ("error in InputStream obtaining port:" + e. getMessage ();} try {serialPort. addEventListener (this);} catch (TooManyListenersException e) {throw new RuntimeException (e. getMessage ();} serialPort. notifyOnDataAvailable (true); log (String. format ("Start listening for data from '% 1 $ s' ------------", comatrix. getName (); if (time> 0) {this. threadTime = time * 10; Thread t = new Thread (this); t. start (); log (String. format (" The listener will be closed after % 1 $ d seconds .... ", ThreadTime) ;}}/*** @ Method Name: close * @ Function Description: close SerialPort * @ return value type: void */public void close () {serialPort. close (); serialPort = null; commp ORT = null;} public void log (String msg) {System. out. println (appName + "-->" + msg);}/*** listener processing function for receiving data */@ Overridepublic void serialEvent (SerialPortEvent arg0) {switch (arg0.getEventType ()) {case SerialPortEvent. BI:/* Break interrupt, communication interruption */case SerialPortE Vent. OE:/* Overrun error, overflow error */case SerialPortEvent. FE:/* Framing error, frame transfer error */case SerialPortEvent. PE:/* Parity error, verification error */case SerialPortEvent. CD:/* Carrier detect, Carrier detection */case SerialPortEvent. CTS:/* Clear to send, Clear send */case SerialPortEvent. DSR:/* Data set ready, Data device ready */case SerialPortEvent. RI:/* Ring indicator, which indicates */case SerialPortEvent. OUTPUT_BUFFER_EMPTY:/** Output buffer is * empty, slow Output Clear */break; case SerialPortEvent. DATA_AVAILABLE:/** Data available at the serial * port. the port has available Data. Read the buffer array and output it to the terminal */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 ("received port returned data (Length:" + readStr. length () + "):" + readStr); log (s2);} catch (IOException e) {}}@ Overridepublic void run () {try {Thread. sleep (threadTime); serialPort. c Lose (); log (String. format ("port'' listener closed! ", Comatrix. getName ();} catch (Exception e) {e. printStackTrace () ;}} and 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) ;}} if it is used on the web, you need to build a web service project. We recommend that you use eclipse j2ee, and then create a web project and create the same class. Create a 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 stat Ic 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 requ Est, 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"); // address String state = request. getParameter ("state"); // status String bofile = request. getPar Ameter ("file"); // video address if (address! = Null & state! = Null) {runSerial (address, state, bofile);} else {address = "00"; state = "0"; runSerial (address, state, bofile);} System. out. println ("bofile:" + bofile);} // run the serial port 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) ;}}// play the 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 "; // file path // call the mplayer command line String cmd ="-vo directx identify wid String. value of (false)-colorkey 0x030303-slave-osdlevel String. valueOf (1) "+"-fullscreen "; try {Process rn = runtime.getruntime(cmd.exe c (mediaPath +" "+ path +" "+ cmd ); // execute the specified command and variable in a separate Process/** Process rn = runtime.getruntime(cmd.exe c (potplayer + "" + path ); * // execute the specified command and variable */System in a separate process. out. println ("video start playing");} catch (IOException e1) {e1.printStackTrace (); return ;}} I added a simple description of playing a video, if you don't understand it, I will. You can come and discuss it with me. QQ is in the upper left corner.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.