У меня есть этот код, используя библиотеку RxTx:RXTX отправляет строку как ASCII через последовательный порт?
public void sendSerial(String msg) throws IOException{
try{
out1.write(msg.getBytes());
}catch(Exception e){
e.printStackTrace();
}
try{
out1.flush();
}catch(Exception e){
e.printStackTrace();
}
}
Я основывая это прочь 2 пути примера связи. out1 (глобальная переменная) устанавливается, как это после выхода переменной было установлено:
out1 = out;
Но когда я пытаюсь писать или флеш, это дает мне NullPointerException на линии письма. Вот мой полный код:
package net.codepixl.serialPortBuk;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.ByteArrayInputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Scanner;
import org.bukkit.command.CommandSender;
public class Serial
{
public Serial()
{
super();
}
OutputStream out1;
CommPort commPort;
CommPortIdentifier portIdentifier = null;
SerialPort serialPort;
void connect (String portName, CommandSender s) throws Exception
{
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned())
{
System.out.println("Error: Port is currently in use");
s.sendMessage("Error: Port COM3 is currently in use");
}
else
{
commPort = portIdentifier.open(this.getClass().getName(),2000);
if (commPort instanceof SerialPort)
{
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
out1 = out;
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
}
}
}
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter (OutputStream out)
{
this.out = out;
}
public void run()
{
}
}
public void sendSerial(String msg,CommandSender s) throws IOException{
s.sendMessage("Sending "+msg+"...");
try{
out1.write(msg.getBytes());
}catch(Exception e){
e.printStackTrace();
}
s.sendMessage("Flushing output...");
try{
out1.flush();
}catch(Exception e){
e.printStackTrace();
}
s.sendMessage("Done!");
}
public void disconnect() {
if (commPort != null) {
try {
// close the i/o streams.
commPort.getInputStream().close();
commPort.getOutputStream().close();
} catch (IOException ex) {
// don't care
}
// Close the port.
commPort.close();
}
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader (InputStream in)
{
this.in = in;
}
public void run()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ((len = this.in.read(buffer)) > -1)
{
System.out.print(new String(buffer,0,len,"US-ASCII"));
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public void startSerial(CommandSender s)
{
try
{
(new Serial()).connect("COM3",s);
}
catch (Exception e)
{
s.sendMessage("COM port in use! (Maybe by this server...)");
}
}
}
(Не беспокойтесь о commandSender вещи, это CraftBukkit мод, и если вы не знаете, что это такое, не волнуйтесь, просто знаю, что когда программа. начинается, startSerial называется, и при написании строки, sendSerial называется.)
у вас есть NPE трассировки стека доступные? –
@ArnaudKleinveld единственная утка, которая у меня есть: Java.lang.NullPointerException, указывающая на строку, на которой я пишу свою строку. – user3042719
Предлагаю добавить код отладки. Например, начните с runnables, чтобы узнать, действительно ли они запущены: System.out.print («Запуск SerialReader»); –