java 用Java从串口读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:51:35  来源:igfitidea点击:

Reading file from serial port in Java

javaserial-port

提问by

i'm beginner in java technology, I have to read file from port. Frst I'll write "FLASH" to outputstream then I'll get response as a "FLASH_OK" from target device, after getting FLASH_OK as response then again i have to write name of the file which i want,but problem is its not writing file name to outputstream, below is my code. Please help me.

我是 Java 技术的初学者,我必须从端口读取文件。首先,我将“FLASH”写入输出流,然后我会从目标设备获得“FLASH_OK”响应,在获得 FLASH_OK 作为响应之后,我再次必须写出我想要的文件名,但问题是它没有写输出流的文件名,下面是我的代码。请帮我。

package writeToPort;

import java.awt.Toolkit;
import java.io.*;
import java.util.*;

import javax.comm.*;
import javax.swing.JOptionPane;

import constants.Constants;

public class Flashwriter implements SerialPortEventListener {
Enumeration portList;
CommPortIdentifier portId;
String messageString = "\r\nFLASH\r\n";
SerialPort serialPort;
OutputStream outputStream;
InputStream inputStream;
Thread readThread;
String one, two;
String test = "ONLINE";
String[] dispArray = new String[1];
int i = 0;

byte[] readBufferArray;
int numBytes;
String response;
FileOutputStream out;
final int FLASH = 1, FILENAME = 2;
int number;

File winFile;

public static void main(String[] args) throws IOException {
    Flashwriter sm = new Flashwriter();
    sm.FlashWriteMethod();
}

public void FlashWriteMethod() throws IOException {

    portList = CommPortIdentifier.getPortIdentifiers();
    winFile = new File("D:\testing\out.FLS");

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals("COM2")) {
                try {
                    serialPort = (SerialPort) portId.open("SimpleWriteApp",
                            1000);
                } catch (PortInUseException e) {
                }

                try {
                    inputStream = serialPort.getInputStream();

                    System.out.println(" Input Stream... " + inputStream);
                } catch (IOException e) {
                    System.out.println("IO Exception");
                }
                try {
                    serialPort.addEventListener(this);

                } catch (TooManyListenersException e) {
                    System.out.println("Tooo many Listener exception");
                }
                serialPort.notifyOnDataAvailable(true);

                try {
                    outputStream = serialPort.getOutputStream();
                    inputStream = serialPort.getInputStream();
                } catch (IOException e) {
                }
                try {
                    serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                    serialPort
                            .setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
                                            number = FLASH;
                    sendRequest(number);

                } catch (UnsupportedCommOperationException e) {
                }

            }
        }
    }
}

public void serialEvent(SerialPortEvent event) {
    SerialPort port = (SerialPort) event.getSource();

    switch (event.getEventType()) {
    case SerialPortEvent.DATA_AVAILABLE:
        try {
            if (inputStream.available() > 0) {
                numBytes = inputStream.available();
                readBufferArray = new byte[numBytes];
                int readBytes = inputStream.read(readBufferArray);

                one = new String(readBufferArray);
                System.out.println("readBytes " + one);
            }
            if (one.indexOf("FLASH_") > -1 & !(one.indexOf("FLASH_F") > -1)) {
                System.out.println("got message");
                response = "FLASH_OK";
                number = FILENAME;
                sendRequest(number);
            }

            out = new FileOutputStream(winFile, true);
            out.write(readBufferArray);
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        readBufferArray = null;
        // break;
    }


}


public void sendRequest(int num) {
    switch (num) {
    case FLASH:
        try {
            outputStream.write(messageString.getBytes());
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    case FILENAME:
        try {
            outputStream.write("\r\n26-02-08.FLS\r\n".getBytes());
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;

    }
}

}

回答by Edison Gustavo Muenz

Have you tested with a Serial Port Emulator software?

您是否使用串行端口仿真器软件进行过测试?

When I did this kind of app for college, our professor told us to build the app and test it using an emulator, since it's much cheaper and less error prone.

当我为大学做这种应用程序时,我们的教授告诉我们构建应用程序并使用模拟器进行测试,因为它更便宜且不易出错。

While searching for google you can find some softwares that do that. I don't remember exactly the one we used at that time, but it worked quite well.

在搜索谷歌时,您可以找到一些可以做到这一点的软件。我不记得我们当时用的那个,但它运行得很好。

I mean products like this: Eterlogic - Virtual Serial Ports Emulator, but that's just an example (and I haven't tested this software, I just googled it)

我的意思是这样的产品:Eterlogic - Virtual Serial Ports Emulator,但这只是一个例子(我还没有测试过这个软件,我只是用谷歌搜索了它)

回答by kgiannakakis

You are erroneously assuming that full messages are always going to be received. Instead, when a serial event is triggered, only part of the message may be available. For example, you may get an event and read "FLAS" and a subsequent event will give "H_OK". You need to adapt your code to something like this:

您错误地认为总是会收到完整的消息。相反,当触发串行事件时,可能只有部分消息可用。例如,您可能会收到一个事件并读取“FLAS”,随后的事件将给出“H_OK”。您需要将代码调整为如下所示:

// member variables
byte [] receiveBuffer = new byte[BUFFER_LENGTH];
int receiveIndex = 0;

// Receive code

receiveIndex +=
   inputStream.read(receiveBuffer, receiveIndex, BUFFER_LENGTH - receiveIndex);

回答by IanW

Sorry I can't help you with the Java code but are you sure the data "FLASH" is actually being sent on your serial port ? When I'm having this kind of problem I usually use an oscilloscope to look on the TX pin on the serial port and check if I can "see" the data being sent (the data burst will be brief but you will be able to see it). If you can see it use the scope to look on the RX pin of the serial port and see if you can see the "FLASH_OK" response actually being sent.

抱歉,我无法帮助您处理 Java 代码,但您确定数据“FLASH”实际上是通过您的串行端口发送的吗?当我遇到此类问题时,我通常使用示波器查看串行端口上的 TX 引脚,并检查是否可以“看到”正在发送的数据(数据突发很短,但您将能够看到它)。如果可以看到它,请使用示波器查看串行端口的 RX 引脚,看看是否可以看到实际发送的“FLASH_OK”响应。

Nine out of ten times the problem isn't the software but a hardware issue often due to handshaking pins being incorrectly connected.

十分之九的问题不是软件问题,而是硬件问题,通常是由于握手引脚连接不正确。

Good luck with this.

祝你好运。