0

I am trying to write this string out of a serial port and I get an error java.io.UnsupportedEncodingException: *995R15,67,3#. As far as i can see this is just ASCII characters? Can anyone tell me why i get this error?

I have edited my Question to include everything in case there is something else wrong The first one is EBIAlarm.java

import java.io.*;

import javax.swing.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


public class EBIAlarm extends javax.swing.JFrame {

public TwoWaySerialComm twoWaySerCom;
public TwoWaySerialComm.SerialWriter serialWriter;


public EBIAlarm() {
    initComponents();
    twoWaySerCom = new TwoWaySerialComm();



    try {

        twoWaySerCom.connect("COM7");
    } 
    catch (Exception e) {

        e.printStackTrace();
        }
}



private void initComponents() {

    jTextArea1 = new javax.swing.JTextArea();
    jTextArea2 = new javax.swing.JTextArea();
    jScrollPane1 = new javax.swing.JScrollPane();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jTextArea1.setColumns(60);
    jScrollPane1.setViewportView(jTextArea2);




    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Alarm Generator");

    jTextArea1.setText("Enter custom string here");
    jTextArea2.setText("Result");
    jButton1.setText("Alarm 1");
    jButton2.setText("Alarm 2");
    jButton3.setText("Alarm 3");
    jButton4.setText("Custom Alarm");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()               

                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)    
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextArea1)
                    .addComponent(jTextArea2)
                    .addComponent(jScrollPane1)


    )));
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()

            .addComponent(jButton1)
            .addGap(20)
            .addComponent(jButton2)
             .addGap(20)
            .addComponent(jButton3)
             .addGap(20)
            .addComponent(jButton4)
            .addGap(20)
            .addComponent(jTextArea1)
            .addGap(20)
            .addComponent(jTextArea2)
            .addContainerGap(0,0))
            .addComponent(jScrollPane1)
    );

    pack();

    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt){
            jButton1ActionPerformed(evt);
        }

        private synchronized void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea1.setText("Alarm 1 Activated, String: "+alarm1);
            try {
                alarm1.getBytes(alarm1);
                serialWriter.out.write(alarm1.getBytes("US-ASCII"));
            } catch (IOException e) {
                // Do something to handle the exception
                e.printStackTrace();
            }
        }

    });

    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Alarm 2 Activated, String: "+alarm2);
        }
    });

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Alarm 3 Activated, String: "+alarm3);
        }
    });

    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextArea2.setText("Custom alarm, string sent: "+jTextArea1.getText ());
        }
    });
}


public static void main(String args[]) {        

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new EBIAlarm().setVisible(true);


        }
    });


}



    private void updateTextArea(final String text) {
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              jTextArea2.append(text);
            }
          });
        }
    private void redirectSystemStreams() {
          OutputStream out = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
              updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
              write(b, 0, b.length);
            }
          };

          System.setOut(new PrintStream(out, true));
          System.setErr(new PrintStream(out, true));
        }

// Variables declaration                    
private static javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JTextArea jTextArea1;
public javax.swing.JTextArea jTextArea2;
private javax.swing.JScrollPane jScrollPane1;
String alarm1 = "*995R15,67,3#";
String alarm2 = "*993R03,67,6#";
String alarm3 = "*994R14,67,1#";

// End of variables declaration                   
}

This is TwoWaySerialComm.java

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;





public class TwoWaySerialComm {
public TwoWaySerialComm()

{
    super();
}

void connect ( String portName ) throws Exception
{

    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if ( portIdentifier.isCurrentlyOwned() )
    {

        System.out.println("Error: Port is currently in use");
    }
    else
    {
        CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

        if ( commPort instanceof SerialPort )
        {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

            InputStream in = serialPort.getInputStream();
            OutputStream out = serialPort.getOutputStream();

            (new Thread(new SerialReader(in))).start();
            (new Thread(new SerialWriter(out))).start();

        }
        else
        {
            System.out.println("Error: Only serial ports are handled by this.");
        }
    }     
}

/** */
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));

            }
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }            
    }
}

/** */
public static class SerialWriter implements Runnable 
{
    OutputStream out;

    public SerialWriter ( OutputStream out )
    {
        this.out = out;
    }

    public void run ()
    {
        try
        {                
            int c = 0;
            while ( ( c = System.in.read()) > -1 )
            {
                this.out.write(c);
            }                
        }
        catch ( IOException e )
        {
            e.printStackTrace();
        }            
    }
}



}
dusan
  • 9,104
  • 3
  • 35
  • 55
Display Name
  • 405
  • 6
  • 26
  • Why are you using the string itself as the encoding name? It fails because you told it to use the encoding called "*995R15,67,3#" and there is no such encoding. – user253751 Feb 13 '15 at 06:57
  • @immibis is talking about this line - `alarm1.getBytes(alarm1);` The argument to `getBytes()` should either be a string representation of a valid charset name or a Charset itself. – TheLostMind Feb 13 '15 at 07:02
  • @immibis Like below? I had that before and just got a null pointer: alarm1.getBytes("ASCII"); Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at EBIAlarm$1.jButton1ActionPerformed(EBIAlarm.java:109) at EBIAlarm$1.actionPerformed(EBIAlarm.java:102) – Display Name Feb 13 '15 at 07:05
  • @TheLostMind I have edited my question to include more code incase i have dome something else wrong. – Display Name Feb 13 '15 at 07:27
  • @codeMan I have edited my question to include more code in case i have dome something else wrong. – Display Name Feb 13 '15 at 07:28
  • http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – JB Nizet Feb 13 '15 at 07:29
  • @JB Nizet Thanks for the link. I think i understand but i need to do more reading tonight. In this case I am still stuck can you offer any other pointers? – Display Name Feb 13 '15 at 08:19

2 Answers2

2

You are getting UnsupportedEncodingException because of this line, you should exclude it from your code:

alarm1.getBytes(alarm1);

getBytes(String charsetName) method defined in java.lang.String as below:

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException {
    if (charsetName == null) throw new NullPointerException();
    return StringCoding.encode(charsetName, value, 0, value.length);
}

You are passing alarm1 to getBytes method as a parameter however its value is not valid charset.

Suat Keskin
  • 116
  • 5
0

I got this working using the below in the end. It seems to work fine for me.

Thanks for your assistance.

try {
                byte[] b = alarm2.getBytes("ASCII");

                TwoWaySerialComm.SerialWriter sw = new       TwoWaySerialComm.SerialWriter(
                        twoWaySerCom.serialPort.getOutputStream());

                sw.out.write(b);
            } catch (IOException e) {
                // Do something to handle the exception
                e.printStackTrace();
            }
Display Name
  • 405
  • 6
  • 26