Приложение доступа к последовательному порту, использующее библиотеку jSerialComm, не получает события LISTENING_EVENT_DATA_AVAILABLE - PullRequest
0 голосов
/ 19 июня 2020

Я пытаюсь установить связь с модулем BLE через соединение через последовательный порт. Аппаратное обеспечение реализовано в виде устройства USB-to-Serial, что затрудняет проверку контактов интерфейса.

Проблема в том, что, хотя я могу «видеть» записи на устройство BLE в программном пакете, который отображает трафик USB c, я не вижу никаких ответов от устройства BLE. Я могу отправлять и получать данные на устройство BLE с помощью teraTerm.

(Примечание: я подозреваю, что программа-сниффер USB будет "видеть" данные только с устройства BLE или l oop -back, если мой Java приложение вызывает функцию чтения.)

Я переключил последовательный порт с устройства BLE на обычное c устройство USB-to-Serial с передачей, подключенной к приему, и RTS, подключенной к CTS. Любые данные, отправленные в порт, должны быть возвращены эхом. Он работает с эмулятором последовательного порта (teraTerm), поэтому я знаю, что с оборудованием все в порядке, но мое приложение Java не отвечает.

Я установил точки останова в методах getListeningEvents () и serialEvent (), но они не позвоните. Похоже, я неправильно настроил код для получения событий. К сожалению, все примеры для библиотеки jSerialComm представляют собой фрагменты кода и не включают в себя полнофункциональную программу, поэтому я подозреваю, что некоторые детали об общей структуре приложения могут быть моей проблемой.

Код был первоначально разделен между GUI - связанный код и код, связанный с последовательным портом, но у меня были проблемы с объектами stati c и non-stati c. У меня более 30 лет опыта C и около 6 недель использования Java. Сложить все это в одном классе было подходом кувалды, но я не мог найти лучшего решения. Хотя то, что он компилируется, не означает, что он правильный ...

mainScreen. java это:

package foo;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.*;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SGrunza
 */
public class mainScreen extends javax.swing.JFrame
{

   static SerialPort portNINA;
   static String portNINAstr;

   public void msSleep(int msToSleep)
   {
      try
         {
         Thread.currentThread().sleep(msToSleep);
         }
      catch (InterruptedException ex)
         {
         System.out.println(ex);
         }
   }

   public String pickPort(JFrame topFrame)
   {

      String retVal;

      SerialPort[] ports = SerialPort.getCommPorts();

      // Create array of descriptive port names
      ArrayList<String> names = new ArrayList<>();

      for (int i = 0; i < ports.length; i++)
         {
         names.add(ports[i].getDescriptivePortName());
         }

      // Turn ArrayList into String array
      String nameString[] = new String[names.size()];
      for (int i = 0; i < names.size(); i++)
         {
         nameString[i] = names.get(i);
         }

      // Choose the port
      retVal = ListDialog.showDialog(
              topFrame,
              topFrame,
              "Choose the serial port used by the NINA module",
              "Configure Serial Port",
              nameString,
              null,
              null);

      //System.out.println( retVal );
      portNINAstr = retVal;
      portNINA = null;

      for (int i = 0; i < names.size(); i++)
         {
         if (nameString[i].equals(portNINAstr))
            {
            // Found it
            portNINA = ports[i];
            }
         }

      return retVal;
   }

   public void openNINAport() 
   {
      portNINA.openPort();

      portNINA.addDataListener(new SerialPortDataListener()
      {
         @Override
         public int getListeningEvents()
         {
            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
         }

         @Override
         public void serialEvent(SerialPortEvent event
         )
         {
            if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
               {
               while (portNINA.bytesAvailable() > 0)
                  {
                  byte[] newData = new byte[portNINA.bytesAvailable()];
                  int numRead = portNINA.readBytes(newData, newData.length);
                  setFromLog(newData, numRead);
                  }
               }
         }

      });

   }

   public void setFromLog(byte[] data, int len)
   {
      String text = new String(data);

      fromNINAlog.append(text + "\r\n");
      fromNINAlog.update(fromNINAlog.getGraphics());
   }

   public void setToLog(byte[] data, int len)
   {
      String text = new String(data);

      toNINAlog.append(text + "\r\n");
      toNINAlog.update(toNINAlog.getGraphics());
   }

   public void setFromLog(String text)
   {
      fromNINAlog.append(text + "\r\n");
      fromNINAlog.update(fromNINAlog.getGraphics());
   }

   public void setToLog(String text)
   {
      toNINAlog.append(text + "\r\n");
      toNINAlog.update(toNINAlog.getGraphics());
   }

   public void healthCheck()
   {
      Calendar now = Calendar.getInstance();
      int hour = now.get(Calendar.HOUR_OF_DAY);
      int minute = now.get(Calendar.MINUTE);
      int second = now.get(Calendar.SECOND);

      String timeString = new String();

      timeString = timeString.format("%02d:%02d:%02d", hour, minute, second);
      clockField.setText(timeString);
      //System.out.println( timeString );

      if (portNINA != null)
         {
         if (portNINA.isOpen())
            {
            commStatusTextField.setText(portNINA.getSystemPortName() + " open");

            if (portNINA.bytesAvailable() > 0)
               {
               System.out.println("Data available on com port");
               }

            }
         else
            {
            commStatusTextField.setText(portNINA.getSystemPortName() + " not open");
            }
         }
      else
         {
         commStatusTextField.setText("Not open");
         }

   } // end of healthCheck()

   /**
    * Creates new form mainScreen
    */
   public mainScreen()
   {
      Timer healthTimer = new Timer();

      initComponents();

      fromNINAlog.setLineWrap(true);
      fromNINAlog.setWrapStyleWord(true);
      toNINAlog.setLineWrap(true);
      toNINAlog.setWrapStyleWord(true);

      healthTimer.scheduleAtFixedRate(new TimerTask()
      {
         @Override
         public void run()
         {
            //System.out.println( "healthTask " + new Date() +
            //        "Thread name: " + Thread.currentThread().getName() );
            healthCheck();
         }
      },
              0, // delay until first run
              1000); // delay for each subsequent run

      clockField.setToolTipText("If the clock is updating, the code is running");
      clockField.setHorizontalAlignment(JTextField.CENTER);

      // Picking COM port each time is annoying
      String retVal;

      SerialPort[] ports = SerialPort.getCommPorts();

      // Create array of descriptive port names
      ArrayList<String> names = new ArrayList<>();

      for (int i = 0; i < ports.length; i++)
         {
         names.add(ports[i].getDescriptivePortName());
         }

      // Turn ArrayList into String array
      String nameString[] = new String[names.size()];
      for (int i = 0; i < names.size(); i++)
         {
         nameString[i] = names.get(i);
         }

      // Should be from a config file
      portNINAstr = "USB Serial Port (COM19)";
      portNINA = null;

      for (int i = 0; i < names.size(); i++)
         {
         if (nameString[i].equals(portNINAstr))
            {
            // Found it
            portNINA = ports[i];
            }
         }

      // Handle case where default didn't work
      if (portNINA == null)
         {
         portNINAstr = null;
         }
   }

   /**
    * This method is called from within the constructor to initialize
    * the form. WARNING: Do NOT modify this code. The content of this
    * method is always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
   private void initComponents()
   {

      helpAboutDialog = new javax.swing.JOptionPane();
      jPanel1 = new javax.swing.JPanel();
      resetButton = new javax.swing.JButton();
      factoryResetButton = new javax.swing.JButton();
      connectButton = new javax.swing.JButton();
      clockField = new javax.swing.JTextField();
      disconnectButton = new javax.swing.JButton();
      jLabel1 = new javax.swing.JLabel();
      commStatusTextField = new javax.swing.JTextField();
      configureNINAbutton = new javax.swing.JButton();
      jPanel2 = new javax.swing.JPanel();
      jScrollPane1 = new javax.swing.JScrollPane();
      toNINAlog = new javax.swing.JTextArea();
      jPanel3 = new javax.swing.JPanel();
      jScrollPane2 = new javax.swing.JScrollPane();
      fromNINAlog = new javax.swing.JTextArea();
      jMenuBar1 = new javax.swing.JMenuBar();
      FileMenu = new javax.swing.JMenu();
      QuitMenuItem = new javax.swing.JMenuItem();
      EditMenu = new javax.swing.JMenu();
      ConfigMenu = new javax.swing.JMenu();
      configSerialPort = new javax.swing.JMenuItem();
      HelpMenu = new javax.swing.JMenu();
      AboutMenuItem = new javax.swing.JMenuItem();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setTitle("Bogie IQ Emulator");

      jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

      resetButton.setText("Reset");

      factoryResetButton.setText("Factory Reset");
      factoryResetButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            factoryResetButtonActionPerformed(evt);
         }
      });

      connectButton.setText("Connect");
      connectButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            connectButtonActionPerformed(evt);
         }
      });

      disconnectButton.setText("Disconnect");
      disconnectButton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            disconnectButtonActionPerformed(evt);
         }
      });

      jLabel1.setText("Comm Status:");

      commStatusTextField.setToolTipText("Select Comm port in Config menu");

      configureNINAbutton.setText("Configure NINA");
      configureNINAbutton.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            configureNINAbuttonActionPerformed(evt);
         }
      });

      javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
      jPanel1.setLayout(jPanel1Layout);
      jPanel1Layout.setHorizontalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addGroup(jPanel1Layout.createSequentialGroup()
                  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(resetButton)
                        .addGap(51, 51, 51)
                        .addComponent(configureNINAbutton))
                     .addComponent(disconnectButton))
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                     .addComponent(factoryResetButton)
                     .addComponent(clockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
               .addGroup(jPanel1Layout.createSequentialGroup()
                  .addComponent(connectButton)
                  .addGap(87, 87, 87)
                  .addComponent(jLabel1)
                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                  .addComponent(commStatusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addGap(0, 189, Short.MAX_VALUE)))
            .addContainerGap())
      );

      jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {clockField, connectButton, disconnectButton, factoryResetButton, resetButton});

      jPanel1Layout.setVerticalGroup(
         jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(resetButton)
               .addComponent(clockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addComponent(configureNINAbutton))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
               .addComponent(connectButton)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(jLabel1)
                  .addComponent(commStatusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(18, 18, 18)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
               .addComponent(disconnectButton)
               .addComponent(factoryResetButton))
            .addContainerGap(26, Short.MAX_VALUE))
      );

      jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("To NINA"));

      toNINAlog.setColumns(20);
      toNINAlog.setRows(5);
      jScrollPane1.setViewportView(toNINAlog);

      javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
      jPanel2.setLayout(jPanel2Layout);
      jPanel2Layout.setHorizontalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane1)
      );
      jPanel2Layout.setVerticalGroup(
         jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
      );

      jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("From NINA"));

      fromNINAlog.setColumns(20);
      fromNINAlog.setRows(5);
      jScrollPane2.setViewportView(fromNINAlog);

      javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
      jPanel3.setLayout(jPanel3Layout);
      jPanel3Layout.setHorizontalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane2)
      );
      jPanel3Layout.setVerticalGroup(
         jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE)
      );

      FileMenu.setText("File");

      QuitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
      QuitMenuItem.setText("Quit");
      QuitMenuItem.setToolTipText("No checks so be careful");
      QuitMenuItem.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            QuitMenuItemActionPerformed(evt);
         }
      });
      FileMenu.add(QuitMenuItem);

      jMenuBar1.add(FileMenu);

      EditMenu.setText("Edit");
      jMenuBar1.add(EditMenu);

      ConfigMenu.setText("Config");

      configSerialPort.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.ALT_MASK));
      configSerialPort.setText("Serial Port");
      configSerialPort.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            configSerialPortActionPerformed(evt);
         }
      });
      ConfigMenu.add(configSerialPort);

      jMenuBar1.add(ConfigMenu);

      HelpMenu.setText("Help");
      HelpMenu.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            HelpMenuActionPerformed(evt);
         }
      });

      AboutMenuItem.setText("About");
      AboutMenuItem.addActionListener(new java.awt.event.ActionListener()
      {
         public void actionPerformed(java.awt.event.ActionEvent evt)
         {
            AboutMenuItemActionPerformed(evt);
         }
      });
      HelpMenu.add(AboutMenuItem);

      jMenuBar1.add(HelpMenu);

      setJMenuBar(jMenuBar1);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
               .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(37, 37, 37)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
      );

      pack();
   }// </editor-fold>                        

   private void QuitMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                             
   {                                                 
      // TODO add your handling code here:
      System.exit(0);
   }                                            

   private void HelpMenuActionPerformed(java.awt.event.ActionEvent evt)                                         
   {                                             
      // TODO add your handling code here:
   }                                        

   private void AboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)                                              
   {                                                  
      // TODO add your handling code here:
      // Trying to launch an About dialog
      String versionString;
      try
         {
         versionString = "Compiled on " + programBuildTime.getLastModifiedDate();
         }
      catch (IOException | URISyntaxException ex)
         {
         versionString = "Unknown";
         }

      System.out.println("Version Info is: " + versionString);

      helpAboutDialog.showMessageDialog(jPanel1,
              versionString, // Message info
              "Version Info",
              JOptionPane.INFORMATION_MESSAGE);
   }                                             

   private void configSerialPortActionPerformed(java.awt.event.ActionEvent evt)                                                 
   {                                                     
      // TODO add your handling code here:
      JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);

      pickPort(topFrame);
   }                                                

   private void factoryResetButtonActionPerformed(java.awt.event.ActionEvent evt)                                                   
   {                                                       
      // TODO add your handling code here:
   }                                                  

   private void connectButtonActionPerformed(java.awt.event.ActionEvent evt)                                              
   {                                                  
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         // Try to open the serial port
         fromNINAlog.append("Connecting to " + portNINAstr + "\r\n");
         toNINAlog.append("Connecting to " + portNINAstr + "\r\n");

         portNINA.openPort();

         portNINA.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 2000, 2000);
         portNINA.setComPortParameters(115200, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
         portNINA.setFlowControl(SerialPort.FLOW_CONTROL_RTS_ENABLED | SerialPort.FLOW_CONTROL_CTS_ENABLED);
         //portNINA.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
         portNINA.setDTR();
         portNINA.setRTS();

         }
      else
         {
         javax.swing.JOptionPane errDialog = new javax.swing.JOptionPane();
         errDialog.showMessageDialog(errDialog,
                 "No serial port selected", // Message info
                 "Serial Port Error",
                 helpAboutDialog.ERROR_MESSAGE);
         }
   }                                             

   private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt)                                                 
   {                                                     
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         if (portNINA.isOpen())
            {
            // Turn off the module
            portNINA.clearDTR();
            portNINA.closePort();
            }
         }
   }                                                

   private void configureNINAbuttonActionPerformed(java.awt.event.ActionEvent evt)                                                    
   {                                                        
      // TODO add your handling code here:
      if (portNINAstr != null)
         {
         if (portNINA.isOpen())
            {
            String cfgString;
            byte[] cfg;

            // Make sure NINA is in control/AT mode
            portNINA.clearDTR();
            msSleep(500);
            portNINA.setDTR();

            // Configure device name.  Should be looked up from BIQ
            // serial number
            //cfgString = "AT+UBTLN=\"BIQ_emu-001930" + clockField.getText() + "\"";
            cfgString = "AT+UBTLN=\"BIQ_" + clockField.getText() + "\"";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP connectable mode
            cfgString = "AT+UBTCM=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP general discoverable mode
            cfgString = "AT+UBTDM=3";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set GAP pairing mode
            cfgString = "AT+UBTPM=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Set Bluetooth low energy Peripheral
            cfgString = "AT+UBTLE=2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            // Switch to extended data mode
            cfgString = "ATO2";
            cfg = cfgString.getBytes();
            portNINA.writeBytes(cfg, cfg.length);
            setToLog(cfgString);
            msSleep(2000);

            }
         }
   }                                                   

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args)
   {
      /* Set the Nimbus look and feel */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
      try
         {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
            if ("Nimbus".equals(info.getName()))
               {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
               }
            }
         }
      catch (ClassNotFoundException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (InstantiationException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (IllegalAccessException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      catch (javax.swing.UnsupportedLookAndFeelException ex)
         {
         java.util.logging.Logger.getLogger(mainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
         }
      //</editor-fold>

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable()
      {
         public void run()
         {
            new mainScreen().setVisible(true);

         }
      });
   }

   // Variables declaration - do not modify                     
   public javax.swing.JMenuItem AboutMenuItem;
   public javax.swing.JMenu ConfigMenu;
   public javax.swing.JMenu EditMenu;
   public javax.swing.JMenu FileMenu;
   public javax.swing.JMenu HelpMenu;
   public javax.swing.JMenuItem QuitMenuItem;
   public javax.swing.JTextField clockField;
   public javax.swing.JTextField commStatusTextField;
   public javax.swing.JMenuItem configSerialPort;
   public javax.swing.JButton configureNINAbutton;
   public javax.swing.JButton connectButton;
   public javax.swing.JButton disconnectButton;
   public javax.swing.JButton factoryResetButton;
   public javax.swing.JTextArea fromNINAlog;
   public javax.swing.JOptionPane helpAboutDialog;
   public javax.swing.JLabel jLabel1;
   public javax.swing.JMenuBar jMenuBar1;
   public javax.swing.JPanel jPanel1;
   public javax.swing.JPanel jPanel2;
   public javax.swing.JPanel jPanel3;
   public javax.swing.JScrollPane jScrollPane1;
   public javax.swing.JScrollPane jScrollPane2;
   public javax.swing.JButton resetButton;
   public javax.swing.JTextArea toNINAlog;
   // End of variables declaration                   
}

Если вы действительно собираете и запускаете этот код, вам необходимо выберите последовательный порт с помощью al oop -back (RX to TX, CTS to RTS), чтобы заставить его работать. Если вы отключите управление потоком, вам понадобится только соединение TX-RX.

Выберите меню «Конфигурация», чтобы выбрать последовательный порт, затем выберите «Подключиться», чтобы открыть последовательный порт. Затем выберите «Настроить NINA», чтобы отправить текст на соединение l oop -back. Вы должны увидеть текст, идущий к модулю NINA в окне «To NINA», и такой же текст в модуле «From NINA».

Существует метод healthCheck, который обновляет часы в верхнем правом углу экрана. Если метод jSerialComm bytesAvailble () возвращает ненулевое значение, значит, библиотека обнаружила, что есть данные для чтения, но событие для чтения не было инициировано.

Может быть, с этот код. Я хочу узнать, как это исправить, но ключевой проблемой является отсутствие события LISTENING_EVENT_DATA_AVAILABLE.

Моя среда - NetBeans 8.2 с Java 8 на 64-битной Win10.

...