Java и библиотека JSerialComm 2.5.1, проблемы со связью через последовательный порт - PullRequest
0 голосов
/ 19 января 2020

Я запускаю программу в Java, которая должна отправлять и получать данные через один и тот же последовательный порт, между 2 windows 7, я использую библиотеку Jserialcomm 2.5.3, я использую Listeners для прослушивания на чтение и чтение. записывать события, но как только последовательный порт находится в режиме приема, я не могу открыть прослушиватель записи.

Это Modulo02

package control;

import com.fazecast.jSerialComm.SerialPort;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class Modulo02 {
    public static String byte1 = ""; 
    public static String byte2 = "";
    public static String byte3 = "";
    public static String byte4 = "";
    public static String byte5 = "";

    public static String byte1A = ""; 
    public static String byte2A = "";
    public static String byte3A = "";
    public static String byte4A = "";
    public static String byte5A = "";

    public static String byte1B = ""; 
    public static String byte2B = "";
    public static String byte3B = "";
    public static String byte4B = "";
    public static String byte5B = "";


    public static final String devicePortNameR = "COM2";
    public static final String devicePortNameC2 = "COM8";
    public static final String devicePortNameA = "COM11";
    public static final String devicePortNameB = "COM10";

    public static final String devicePortNameE = "COM1";
    public static final String devicePortNameC1 = "COM8";
    public static final String devicePortNameA1 = "COM9";

    public static SerialPort chosenPort = null;
    public static SerialPort chosenPort2 = null;
    public static SerialPort chosenPort3 = null;
    public static SerialPort chosenPort4 = null;
    public static SerialPort chosenPort5 = null;
    public static SerialPort com2Port = null;
    public static SerialPort chosenPort7 = null;
    public static SerialPort chosenPortX = null;

    public static int BAURD_RATE = 9600;
    public static int DATA_BITS = 8;
    public static int PCT = 0;
    public static final int PCEstado = 1;

    public static String codText = "";
    public static final int cant = 4;

    public static final String codEmergencia = "9876";
    public static final String codSimulacro = "5678";
    public static final String codPerifoneo = "1234";    
    public static final String codCancel = "9999";
    public static String zzz = "90000";
    public static final String codBtn97915 = "97915";        
    public static String mngLeds = "";
    public static String mngLeds_2 = "";
    public static final String mngCone = "CONECTADO";
    public static final String mngNoCo = "NO CONECTADO";
    public static final String mngEmer = "EMERGENCIA";
    public static final String mngSimu = "SIMULACRO";
    public static final String mngPeri = "PERIFONEO";
    public static final String mngEnvi = "ENVIADO";
    public static final String mngReci = "RECIBIDO";
    public static final String mngEmCm = "      ";
    public static final String mngSiCm = "       ";
    public static final String mngPeCm = "       ";

    public static final String codAmpEmer = "1";
    public static final String codAmpSimu = "2";
    public static final String codAmplifiOF = "0";
    public static final String codAmplifiON = "1";

    public static final String audEmer = "C:\\\\Music\\\\wen.wav";
    public static final String audSimu = "C:\\\\Music\\\\sim.wav";//

    public static final Color colorCone = Color.LIGHT_GRAY;
    public static final Color colorNoCo = Color.BLACK;
    public static final Color colorEmer = Color.RED;
    public static final Color colorSimu = Color.ORANGE;
    public static final Color colorPeri = Color.GREEN;

    public static final Color colorNorm = new Color(214,248,255);

    public static final int sleepM2Conectado = 120000;
    public static final int sleepM2Ejecuta = 2000;
    public static final int sleepM2Responde = 4000;
    public static final int sleepM1Conectado = 4000;
    public static final int sleepM1Ejecuta= 4000;
    public static final int sleepM1Responde = 4000;

    public static int contaBucle = 0;
    public static int origenEstado = -1;

    public void iniciaProcesoM2() {        
        com2Port = SerialPort.getCommPort(devicePortNameR);
        com2Port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        com2Port.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);
        com2Port.openPort();
        PacketListenerM2 listener = new PacketListenerM2();
        com2Port.addDataListener(listener);

    }
    public void enviarData(String cod) throws IOException{
        Control ct = new Control();
        String audioX = "";
        Color col;
        if(contaBucle == 0){
            if(cod==null || cod.isEmpty()){
                ct.codigo.requestFocus();
                return;
            }else if(cod.equals(codEmergencia)){
                mngLeds = mngEmer;
                mngLeds_2 = mngEmer+mngEmCm+mngEnvi;
                if(PCT == 0) audioX = audEmer;
                col = colorEmer;
            }else if(cod.equals(codSimulacro)){
                mngLeds = mngSimu;
                mngLeds_2 = mngSimu+mngSiCm+mngEnvi;
                if(PCT == 0) audioX = audSimu;
                col = colorSimu;
            }else if(PCT ==0 && cod.equals(codPerifoneo)){
                mngLeds = mngPeri;
                mngLeds_2 = mngPeri+mngPeCm+mngEnvi;
                col = colorPeri;
            }else{
                //col = new Color(214,248,255);
                //actf(mngLeds, col);
                System.out.println("wtf5");
                ct.codigo.requestFocus();
                return;
            }
            if(PCT == 0){
                mngConsola(mngLeds_2);          
                if(cod.equals(codPerifoneo)){                
                    actAmpl(codAmplifiOF);
                }else{
                    actAmpl(codAmplifiON);
                    playmusic(audioX);
                }                    
            }else if(PCT == 1){
                mngConsola1(mngLeds_2);
                mngTransmitir1(mngLeds);
            }
        //
            contaBucle++;
        }
    }

    public void volverAconectado() throws IOException {
        System.out.println("volverAconectado");
        mngLeds = mngCone;
        if(PCT == 0){
            //apagar musica
            actAmpl(codAmplifiOF);
            mngConsola(mngLeds);
        }
        if(PCT == 1){
            mngConsola1(mngLeds);
        }

        contaBucle = 0;
    }

    public void mngConsola(String mngleds) {    
        chosenPort2 = SerialPort.getCommPort(devicePortNameC2);
        chosenPort2.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        chosenPort2.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        chosenPort2.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        chosenPort2.openPort();

        PrintWriter output = new PrintWriter(chosenPort2.getOutputStream());

        int x = 0;
        while(x < 2) {
            System.out.println("mensaje consola2 : "+mngleds);
            output.print(mngleds);
            output.flush();
            x++;
            try {Thread.sleep(4000); } catch(Exception e) {}
        }
        chosenPort2.closePort();
    }

    public void actAmpl(String codAmp) throws IOException {
        chosenPort7 = SerialPort.getCommPort(devicePortNameA);
        chosenPort7.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        chosenPort7.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        chosenPort7.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);        
        chosenPort7.openPort();

        PrintWriter output = new PrintWriter(chosenPort7.getOutputStream());

        int x = 0;
        while(x < 2) {
            output.print(codAmp);
            output.flush();
            x++;
            try {Thread.sleep(2000); } catch(Exception e) {}
        }

        chosenPort7.closePort();
    }

    public void playmusic(String filepath) {
        InputStream music;
        try {
            music = new FileInputStream(new File(filepath));
            AudioStream audios = new AudioStream(music);
            AudioPlayer.player.start(audios);
        } catch (Exception e) { 
            System.out.println("error : "+e.getCause().toString());
        }
    }

    public void mngConsola1(String mngleds) {
        chosenPort4 = SerialPort.getCommPort(devicePortNameC1);
        chosenPort4.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        chosenPort4.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        chosenPort4.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        chosenPort4.openPort();

        PrintWriter output = new PrintWriter(chosenPort4.getOutputStream());

        int x = 0;
        while(x < 2) {
            output.print(mngleds);
            output.flush();
            x++;
            try {Thread.sleep(3000); } catch(Exception e) {}
        }
        chosenPort4.closePort();

    }

    public void mngTransmitir(String mngleds) {
        com2Port = SerialPort.getCommPort(devicePortNameR);
        com2Port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        com2Port.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        com2Port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        com2Port.openPort();

        if(mngleds.equalsIgnoreCase("CONECTADO")){
            zzz = "90005";
        }else if(mngleds.equalsIgnoreCase("SIMULACRO")){
            zzz = "97205";
        }else if(mngleds.equalsIgnoreCase("EMERGENCIA")){
            zzz = "97105";
        }else{//
            return;
        }

        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        byte[] sendData = zzz.getBytes();
        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        com2Port.writeBytes(sendData, DATA_BITS);
    }

    public void mngTransmitir1(String mngleds) {
        chosenPort4 = SerialPort.getCommPort(devicePortNameR);
        chosenPort4.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        chosenPort4.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        chosenPort4.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        chosenPort4.openPort();

        if(mngleds.equalsIgnoreCase("CONECTADO")){
            zzz = "90005";
        }else if(mngleds.equalsIgnoreCase("SIMULACRO")){
            zzz = "97205";
        }else if(mngleds.equalsIgnoreCase("EMERGENCIA")){
            zzz = "97105";
        }else{//
            return;
        }

        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        byte[] sendData = zzz.getBytes();
        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        chosenPort4.writeBytes(sendData, DATA_BITS);
    }
}

и M2Listener

package control;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import static control.Modulo02.com2Port;
import java.awt.Color;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class M2Listener implements SerialPortDataListener{
    Modulo02 mod2 = new Modulo02();

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
    }

    @Override
    public void serialEvent(SerialPortEvent event) {        
        if(event.getEventType()!=SerialPort.LISTENING_EVENT_DATA_AVAILABLE){
            return;
        }
        byte[] newData = new byte[com2Port.bytesAvailable()];
        if(newData == null){
            return;
        }

        String str = new String(newData);
        int byteSize = 0;
        try {
            byteSize = str.getBytes("UTF-8").length;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(PacketListenerM1.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (byteSize == Control.PACKET_SIZE_IN_BYTES) {
            //if(Modulo2.mngLeds.equals(Modulo2.mngCone) || Modulo2.mngLeds.equals(Modulo2.mngPeri)){
                if(Modulo2.contaBucle == 0 ){
                    char car1[];
                    car1 = str.toCharArray();
                    Modulo2.byte1B = car1[0]+"";
                    Modulo2.byte2B = car1[1]+"";
                    Modulo2.byte3B = car1[2]+"";
                    Modulo2.byte4B = car1[3]+"";
                    Modulo2.byte5B = car1[4]+"";

                    String audioX = "";
                    Color col;
                    int w = 0;

                    if(Modulo2.byte3B.equals("1")){
                        Modulo2.mngLeds = Modulo2.mngEmer;
                        Modulo2.mngLeds_2 = Modulo2.mngEmer+Modulo2.mngEmCm+Modulo2.mngReci;
                        col = Modulo2.colorEmer;
                        audioX = Modulo2.audEmer;
                    }else if(Modulo2.byte3B.equals("2")){
                        Modulo2.mngLeds = Modulo2.mngSimu;
                        Modulo2.mngLeds_2 = Modulo2.mngSimu+Modulo2.mngSiCm+Modulo2.mngReci;
                        col = Modulo2.colorSimu;
                        audioX = Modulo2.audSimu;
                    }else if(Modulo2.byte3B.equals("3")){
                        Modulo2.mngLeds = Modulo2.mngPeri;
                        Modulo2.mngLeds_2 = Modulo2.mngPeri+Modulo2.mngPeCm+Modulo2.mngReci;
                        col = Modulo2.colorPeri;
                    }else{
                        Modulo2.mngLeds = Modulo2.mngCone;
                        Modulo2.mngLeds_2 = Modulo2.mngCone;
                        col = Modulo2.colorNorm;
                        w = 1;
                    }                        
                    try {
                        mod2.mngConsola1(Modulo2.mngLeds_2);
                        if(w==1){
                            mod2.actAmpl(Modulo2.codAmplifiOF);
                        }else{
                            mod2.actAmpl(Modulo2.codAmplifiON);
                        }

                        if(Modulo2.byte3B.equals("0")){                
                            //OFF MUSIC
                        }else if(Modulo2.byte3B.equals("1") || Modulo2.byte3B.equals("2")){
                            mod2.playmusic(audioX);
                        }else{
                            //OFF MUSIC
                        }
                        Control eee = new Control();
                        eee.botonColorEstado.setBackground(col);
                        eee.botonColorEstado.setText(Modulo2.mngLeds);
                        eee.botonColorEstado1.setBackground(col);
                        eee.botonColorEstado1.setText(Modulo2.mngLeds);
                        eee.estadoX.setText(Modulo2.mngLeds);
                        eee.estadoX.setForeground(col);
                        eee.Titulo.setForeground(col);
                        eee.codigo.requestFocus();
                        Modulo2.contaBucle++;
                        Modulo2.origenEstado = 1;
                    } catch (IOException ex) {
                        Logger.getLogger(PacketListener.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }else{
                    Modulo2.contaBucle = 0;
                    Modulo2.origenEstado = 0;
                }

        }else{
            System.out.println("No Received data: ");
        }
    }
}

И посмотреть в методе mngTransmitir класса Modulo02

public void mngTransmitir(String mngleds) {
        com2Port = SerialPort.getCommPort(devicePortNameR);
        com2Port.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        com2Port.setComPortParameters(BAURD_RATE, DATA_BITS, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        com2Port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
        com2Port.openPort();

        if(mngleds.equalsIgnoreCase("CONECTADO")){
            zzz = "90005";
        }else if(mngleds.equalsIgnoreCase("SIMULACRO")){
            zzz = "97205";
        }else if(mngleds.equalsIgnoreCase("EMERGENCIA")){
            zzz = "97105";
        }else{//
            return;
        }

        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        byte[] sendData = zzz.getBytes();
        try {Thread.sleep(sleepM2Ejecuta); } catch(Exception e) {}
        com2Port.writeBytes(sendData, DATA_BITS);
    }

я могу отправить данные, но не могу их получить.

Пожалуйста, я был бы признателен за некоторую помощь.

...