two way com port communication using java swing











up vote
0
down vote

favorite












i want to do com port two way communication with embedded controller using java .when i send some string to controller my controller send me return response

example string 01 04 01 00 00 0C F1 F3



public class SerialClass implements SerialPortEventListener
{



public SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES =
{
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM9", // Windows
};

public static BufferedReader input;
public static OutputStream output;
/** Milliseconds to block while waiting for port open */
public static final int TIME_OUT = 200;
/** Default bits per second for COM port. */
public static final int DATA_RATE = 9600;

public void initialize()
{
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements())
{
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES)
{
if (currPortId.getName().equals(portName))
{
portId = currPortId;
break;
}
}
}
if (portId == null)
{
System.out.println("Could not find COM port.");
return;
}

try
{
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);

// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
char ch = 1;
output.write(ch);

// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (Exception e)
{
System.err.println(e.toString());
}
}

public synchronized void close()
{
if (serialPort != null)
{
serialPort.removeEventListener();
serialPort.close();
}
}

@Override
public synchronized void serialEvent(SerialPortEvent oEvent)
{
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
String inputLine=input.readLine();
System.out.println("aa"+inputLine);
}
catch (Exception e)
{
System.err.println(e.toString());
}
}

}

public static synchronized void writeData(String data)
{
System.out.println("Sent: " + data);
try
{
output.write(data.getBytes());
}
catch (Exception e)
{
System.out.println("could not write to port");
}
}

public static void main(String args) throws Exception {
SerialClass main = new SerialClass();
main.initialize();
Thread t=new Thread()
{
public void run()
{
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try
{
Thread.sleep(1500);
writeData("01 04 01 00 00 0C F1 F3");

//serialEvent
}
catch (InterruptedException ie)
{

}
}
};
t.start();
System.out.println("Started");
}


}










share|improve this question







New contributor




amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    0
    down vote

    favorite












    i want to do com port two way communication with embedded controller using java .when i send some string to controller my controller send me return response

    example string 01 04 01 00 00 0C F1 F3



    public class SerialClass implements SerialPortEventListener
    {



    public SerialPort serialPort;
    /** The port we're normally going to use. */
    private static final String PORT_NAMES =
    {
    "/dev/tty.usbserial-A9007UX1", // Mac OS X
    "/dev/ttyUSB0", // Linux
    "COM9", // Windows
    };

    public static BufferedReader input;
    public static OutputStream output;
    /** Milliseconds to block while waiting for port open */
    public static final int TIME_OUT = 200;
    /** Default bits per second for COM port. */
    public static final int DATA_RATE = 9600;

    public void initialize()
    {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    //First, Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements())
    {
    CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
    for (String portName : PORT_NAMES)
    {
    if (currPortId.getName().equals(portName))
    {
    portId = currPortId;
    break;
    }
    }
    }
    if (portId == null)
    {
    System.out.println("Could not find COM port.");
    return;
    }

    try
    {
    // open serial port, and use class name for the appName.
    serialPort = (SerialPort) portId.open(this.getClass().getName(),
    TIME_OUT);

    // set port parameters
    serialPort.setSerialPortParams(DATA_RATE,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);

    // open the streams
    input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
    output = serialPort.getOutputStream();
    char ch = 1;
    output.write(ch);

    // add event listeners
    serialPort.addEventListener(this);
    serialPort.notifyOnDataAvailable(true);
    }
    catch (Exception e)
    {
    System.err.println(e.toString());
    }
    }

    public synchronized void close()
    {
    if (serialPort != null)
    {
    serialPort.removeEventListener();
    serialPort.close();
    }
    }

    @Override
    public synchronized void serialEvent(SerialPortEvent oEvent)
    {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE)
    {
    try
    {
    String inputLine=input.readLine();
    System.out.println("aa"+inputLine);
    }
    catch (Exception e)
    {
    System.err.println(e.toString());
    }
    }

    }

    public static synchronized void writeData(String data)
    {
    System.out.println("Sent: " + data);
    try
    {
    output.write(data.getBytes());
    }
    catch (Exception e)
    {
    System.out.println("could not write to port");
    }
    }

    public static void main(String args) throws Exception {
    SerialClass main = new SerialClass();
    main.initialize();
    Thread t=new Thread()
    {
    public void run()
    {
    //the following line will keep this app alive for 1000 seconds,
    //waiting for events to occur and responding to them (printing incoming messages to console).
    try
    {
    Thread.sleep(1500);
    writeData("01 04 01 00 00 0C F1 F3");

    //serialEvent
    }
    catch (InterruptedException ie)
    {

    }
    }
    };
    t.start();
    System.out.println("Started");
    }


    }










    share|improve this question







    New contributor




    amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      i want to do com port two way communication with embedded controller using java .when i send some string to controller my controller send me return response

      example string 01 04 01 00 00 0C F1 F3



      public class SerialClass implements SerialPortEventListener
      {



      public SerialPort serialPort;
      /** The port we're normally going to use. */
      private static final String PORT_NAMES =
      {
      "/dev/tty.usbserial-A9007UX1", // Mac OS X
      "/dev/ttyUSB0", // Linux
      "COM9", // Windows
      };

      public static BufferedReader input;
      public static OutputStream output;
      /** Milliseconds to block while waiting for port open */
      public static final int TIME_OUT = 200;
      /** Default bits per second for COM port. */
      public static final int DATA_RATE = 9600;

      public void initialize()
      {
      CommPortIdentifier portId = null;
      Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

      //First, Find an instance of serial port as set in PORT_NAMES.
      while (portEnum.hasMoreElements())
      {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES)
      {
      if (currPortId.getName().equals(portName))
      {
      portId = currPortId;
      break;
      }
      }
      }
      if (portId == null)
      {
      System.out.println("Could not find COM port.");
      return;
      }

      try
      {
      // open serial port, and use class name for the appName.
      serialPort = (SerialPort) portId.open(this.getClass().getName(),
      TIME_OUT);

      // set port parameters
      serialPort.setSerialPortParams(DATA_RATE,
      SerialPort.DATABITS_8,
      SerialPort.STOPBITS_1,
      SerialPort.PARITY_NONE);

      // open the streams
      input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
      output = serialPort.getOutputStream();
      char ch = 1;
      output.write(ch);

      // add event listeners
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
      }
      catch (Exception e)
      {
      System.err.println(e.toString());
      }
      }

      public synchronized void close()
      {
      if (serialPort != null)
      {
      serialPort.removeEventListener();
      serialPort.close();
      }
      }

      @Override
      public synchronized void serialEvent(SerialPortEvent oEvent)
      {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE)
      {
      try
      {
      String inputLine=input.readLine();
      System.out.println("aa"+inputLine);
      }
      catch (Exception e)
      {
      System.err.println(e.toString());
      }
      }

      }

      public static synchronized void writeData(String data)
      {
      System.out.println("Sent: " + data);
      try
      {
      output.write(data.getBytes());
      }
      catch (Exception e)
      {
      System.out.println("could not write to port");
      }
      }

      public static void main(String args) throws Exception {
      SerialClass main = new SerialClass();
      main.initialize();
      Thread t=new Thread()
      {
      public void run()
      {
      //the following line will keep this app alive for 1000 seconds,
      //waiting for events to occur and responding to them (printing incoming messages to console).
      try
      {
      Thread.sleep(1500);
      writeData("01 04 01 00 00 0C F1 F3");

      //serialEvent
      }
      catch (InterruptedException ie)
      {

      }
      }
      };
      t.start();
      System.out.println("Started");
      }


      }










      share|improve this question







      New contributor




      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      i want to do com port two way communication with embedded controller using java .when i send some string to controller my controller send me return response

      example string 01 04 01 00 00 0C F1 F3



      public class SerialClass implements SerialPortEventListener
      {



      public SerialPort serialPort;
      /** The port we're normally going to use. */
      private static final String PORT_NAMES =
      {
      "/dev/tty.usbserial-A9007UX1", // Mac OS X
      "/dev/ttyUSB0", // Linux
      "COM9", // Windows
      };

      public static BufferedReader input;
      public static OutputStream output;
      /** Milliseconds to block while waiting for port open */
      public static final int TIME_OUT = 200;
      /** Default bits per second for COM port. */
      public static final int DATA_RATE = 9600;

      public void initialize()
      {
      CommPortIdentifier portId = null;
      Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

      //First, Find an instance of serial port as set in PORT_NAMES.
      while (portEnum.hasMoreElements())
      {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES)
      {
      if (currPortId.getName().equals(portName))
      {
      portId = currPortId;
      break;
      }
      }
      }
      if (portId == null)
      {
      System.out.println("Could not find COM port.");
      return;
      }

      try
      {
      // open serial port, and use class name for the appName.
      serialPort = (SerialPort) portId.open(this.getClass().getName(),
      TIME_OUT);

      // set port parameters
      serialPort.setSerialPortParams(DATA_RATE,
      SerialPort.DATABITS_8,
      SerialPort.STOPBITS_1,
      SerialPort.PARITY_NONE);

      // open the streams
      input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
      output = serialPort.getOutputStream();
      char ch = 1;
      output.write(ch);

      // add event listeners
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
      }
      catch (Exception e)
      {
      System.err.println(e.toString());
      }
      }

      public synchronized void close()
      {
      if (serialPort != null)
      {
      serialPort.removeEventListener();
      serialPort.close();
      }
      }

      @Override
      public synchronized void serialEvent(SerialPortEvent oEvent)
      {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE)
      {
      try
      {
      String inputLine=input.readLine();
      System.out.println("aa"+inputLine);
      }
      catch (Exception e)
      {
      System.err.println(e.toString());
      }
      }

      }

      public static synchronized void writeData(String data)
      {
      System.out.println("Sent: " + data);
      try
      {
      output.write(data.getBytes());
      }
      catch (Exception e)
      {
      System.out.println("could not write to port");
      }
      }

      public static void main(String args) throws Exception {
      SerialClass main = new SerialClass();
      main.initialize();
      Thread t=new Thread()
      {
      public void run()
      {
      //the following line will keep this app alive for 1000 seconds,
      //waiting for events to occur and responding to them (printing incoming messages to console).
      try
      {
      Thread.sleep(1500);
      writeData("01 04 01 00 00 0C F1 F3");

      //serialEvent
      }
      catch (InterruptedException ie)
      {

      }
      }
      };
      t.start();
      System.out.println("Started");
      }


      }







      java






      share|improve this question







      New contributor




      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 19 mins ago









      amit gavli

      1




      1




      New contributor




      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      amit gavli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          amit gavli is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208325%2ftwo-way-com-port-communication-using-java-swing%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          amit gavli is a new contributor. Be nice, and check out our Code of Conduct.










           

          draft saved


          draft discarded


















          amit gavli is a new contributor. Be nice, and check out our Code of Conduct.













          amit gavli is a new contributor. Be nice, and check out our Code of Conduct.












          amit gavli is a new contributor. Be nice, and check out our Code of Conduct.















           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208325%2ftwo-way-com-port-communication-using-java-swing%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'