Reading data from embedded controller using COM port - java

we are receiving data from controller using terminal software and as well as also java program ..
but think is that we get proper data on terminal software but java program can not show like terminal .. actually data come in ASCII and we convert to HEX terminal application show proper data but java program can not show terminal data.....
java program data
import java.io.*; // IOException
import java.util.*; // Scanner
import jssc.*;
/**
*
* #author Emiliarge
*/
public class ComPortSendReceive1 {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
for (char ch : receivedData.toCharArray()) {
System.out.format("%H ", ch);
} // prints "31 32 2E 30 31 33 "
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}

Related

Java and XON XOFF serial print

I m build a java code to use xon xoff protocol to print a fiscal document with cash register Custom K3. This is the setting of this cash register.
This is the code about DriverPrinterSeriale.java
package prove;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.mcsolution.common.LoggerFactory.MyLog4J;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
public class DriverPrinterSeriale {
private SerialPort serialPort;
private OutputStream outStream;
private InputStream inStream;
public static MyLog4J log;
public DriverPrinterSeriale(String portaCOM){
log = new MyLog4J();
try {
this.connect(portaCOM);
} catch (IOException e) {
log.logStackTrace(e);
}
}
public void apriCassetto(){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
//log.information("output acquisito ");
String messageString = "a";
outStream.write(messageString.getBytes());
log.information("cassetto aperto");
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void provaScontrino(String codiceDaInviare){
try {
outStream = serialPort.getOutputStream();
//inStream = serialPort.getInputStream();
log.information("output acquisito ora provo a stampare uno scontrino");
//String messageString = "j";
//outStream.write(messageString.getBytes());
//messageString = "'PANTALONE'10H1R";
//outStream.write(messageString.getBytes());
//String messageString = "\"MAGLIA. 1\"100H1R";
outStream.write(codiceDaInviare.getBytes());
//messageString = "1T";
//outStream.write(messageString.getBytes());
//messageString = "J";
//outStream.write(messageString.getBytes());
log.information("scontrino stampato ora apro il cassetto");
//apriCassetto();
} catch (Exception e) {
log.logStackTrace(e);
}
}
public void connect(String portName) throws IOException {
try {
// Obtain a CommPortIdentifier object for the port you want to open
CommPortIdentifier portId =
CommPortIdentifier.getPortIdentifier(portName);
log.information("apro porta seriale");
//System.out.println("apro porta seriale");
// Get
serialPort =
(SerialPort) portId.open("Demo application", 5000);
// Set the parameters of the connection.
setSerialPortParameters();
log.information("settaggio porta terminato");
} catch (NoSuchPortException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (PortInUseException e) {
log.logStackTrace(e);
throw new IOException(e.getMessage());
} catch (IOException e) {
log.logStackTrace(e);
serialPort.close();
throw e;
}
}
/**
* Get the serial port input stream
* #return The serial port input stream
*/
public InputStream getSerialInputStream() {
return inStream;
}
/**
* Get the serial port output stream
* #return The serial port output stream
*/
public OutputStream getSerialOutputStream() {
return outStream;
}
/**
* Sets the serial port parameters
*/
private void setSerialPortParameters() throws IOException {
int baudRate = 19200; // 57600bps
//int baudRate = 38400; // 57600bps
try {
// Set serial port to 57600bps-8N1..my favourite
serialPort.setSerialPortParams(
baudRate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE
);
log.information("settaggio porta iniziato");
serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_NONE);
log.information("settaggio porta eseguito");
} catch (UnsupportedCommOperationException ex) {
log.logStackTrace(ex);
throw new IOException("Unsupported serial port parameter");
}
}
}
This is the code to print a fiscal document:
driverSeriale = new DriverPrinterSeriale("COM3");
String rigaDaStampare = "\"Pippo"+
"\"10"+"*1"+"H1R";
driverSeriale.provaScontrino(rigaDaStampare);
I have no error but I m not able to print fiscal document. nothing comes out of the cash register
I found a copy of your printer manual located here. Page 40 lists the printer parameters supported. From your description, it seems like there is a mismatch of parameters. First, I would try setting it to something other than CUSTOM XON-XOFF and see if the printer will work with hardware flow control. That shouldn't be a problem with today's equipment and may make this work out of the box.
If you can't change to hardware flow control, then I think you need to set flowcontrol in your serial port. Here is a link to Java documentation on setFlowControlMode. From the current configuration, it appears you might want to logical or include both FLOWCONTROL_XONXOFF_IN and FLOWCONTROL_XONXOFF_OUT.

ClientSocket NOT listening

Im flabbergasted.
I took code from https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java
for the server. And
https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java
for the Client. I made minor changes. Mostly so that there is no back and forth echoing. Rather the Server should constantly with 2 second delays send same string. But I just cant understand why the client isnt working.
It sends the Exception message:
Couldn't get I/O for the connection to 127.0.0.1
I run the server with: java 6788
and the client with: 127.0.0.1 6788
I tried other ports.
I do this in eclipse so I set the arguments in Runconfiguration before running the classes. I start the server first. I tried in terminal outside of eclipse. Nothing makes it work.
Basically, the client should connect to server and output with System.out.println() what the server in turn outputs to the client. But nothing happens.
what is wrong?
Client:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
) {
String userInput;
while (true) {
System.out.println("recieved: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Server:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
System.out.println(args[0]);
InetAddress add = InetAddress.getLocalHost();
System.out.println(add.getHostAddress());
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream());
) {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("HELLO!");
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
You have to send the answer to the client.
Add a out.flush();
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println("HELLO!");
out.flush();
}
As in the comment I eventually found a solution. BufferedReader.readLine() "blocked". When reading from a file it returns a line after reading up to a newline character, if I understand it correctly.
But since it was "A steady flow" from server with no newlines, it just kept "reading" and never returned a String.
I then tried using BufferedReader.read() method, that reads character by character, and returns after each char (thus never blocking). It then prints each character as it arrives, also it listens for a newline being sent from server, and once a read character equals a newline, it then prints a newline instead. Sort of emulating the "read line" behaviour I was expecting from original question.
Reading part of client:
while(true) {
character = (char) reader.read();
if(Character.isISOControl(character)) {
System.out.println();
}
else {
System.out.printf("%c", character);
}
}
Sending Part of Server:
private String message = "HELLO\n";
...
while(true) {
try {
Thread.sleep(2000);
writer.write(message);
writer.flush();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Wait all byte (JSSC)

I'm trying to read a String from my Sara g350 module. I'm using a serial port comunication. The code that I use is this one:
private static SerialPort serialPort;
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// OPEN PORT
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("AT+CMEE=2");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
}
The Problem is that i read only the eco response and not all String.
I send "AT+CMEE=2" and the response could be:
AT+CMEE=2
OK
Can anyone help me? Thank you!

Arduino Uno in Proteus send � character

I'm writing a java program to read data from COM3 port. Data sent by Arduino [1]: https://imgur.com/a/MiNfTZN
But in Java Program (I'm using JSSC) it return � character. If I use RXTX, it return java.io.IOException: Underlying input stream returned zero bytes. I wonder how I can fix it?
This is my code
Using JSSC:
public class SerialTestJSSC {
private static SerialPort serialPort;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length == 0) {
System.out.println("There are no serial-ports :( You can use an emulator, such ad VSPE, to create a virtual serial port.");
System.out.println("Press Enter to exit...");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
// выбор порта
System.out.println("Available com-ports:");
for (int i = 0; i < portNames.length; i++){
System.out.println(portNames[i]);
}
System.out.println("Type port name, which you want to use, and press Enter...");
Scanner in = new Scanner(System.in);
String portName = in.next();
// writing to port
serialPort = new SerialPort(portName);
try {
// opening port
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
// writing string to port
serialPort.writeString("Hurrah!!!");
System.out.println("String wrote to port, waiting for response..");
}
catch (SerialPortException ex) {
System.out.println("Error in writing data to port: " + ex);
}
}
// receiving response from port
private static class PortReader implements SerialPortEventListener {
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
// получение ответа от порта
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response from port: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
}
}
}
Using RXTX
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"COM3", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader
* converting the bytes into characters
* making the displayed results codepage independent
*/
private static BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
public void initialize() {
// the next line is for Raspberry Pi and
// gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
//System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
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();
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
/**
* Handle an event on the serial port. Read the data and print it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println("System "+inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
try {
Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}}

Telnet Apache Commons NET Printing Junk Characters

We wanted to execute some commands on Windows Server 2008/Windows 7 using telnet. As everytime logining in and running commands on around 50 of the same is tedious so I searched in google and zeored to apache commons and I found an example.
It works but it is printing some junk characters (I'm thinking it is some issue with character encoding of Windows, I'm new to this).
package com.kiran.telnet;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.InputStream;
import java.io.PrintStream;
public class AutomatedTelnetClient {
private TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private String prompt = ">";
public AutomatedTelnetClient(String server, String user, String password) {
try {
// Connect to the specified server
telnet.connect(server, 23);
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream(telnet.getOutputStream(), true);
// Log the user on
readUntil("login: ");
write(user);
readUntil("password: ");
write(password);
// Advance to a prompt
readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
public void su(String password) {
try {
write("su");
readUntil("Password: ");
write(password);
prompt = ">";
readUntil(prompt + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
public String readUntil(String pattern) {
try {
char lastChar = pattern.charAt(pattern.length() - 1);
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = (char) in.read();
while (true) {
System.out.print(ch);
sb.append(ch);
if (ch == lastChar) {
if (sb.toString().endsWith(pattern)) {
return sb.toString();
}
}
ch = (char) in.read();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String value) {
try {
out.println(value);
out.flush();
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
public String sendCommand(String command) {
try {
write(command);
return readUntil(prompt);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void disconnect() {
try {
telnet.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
AutomatedTelnetClient telnet = new AutomatedTelnetClient(
"127.0.0.1", "Kiran", "artha");
System.out.println("Got Connection...");
telnet.sendCommand("hostname");
//telnet.sendCommand("ipconfig");
//telnet.sendCommand("ps -ef ");
//System.out.println("run command");
//telnet.sendCommand("ls ");
//System.out.println("run command 2");
telnet.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The Output while I run this is:
Welcome to Microsoft Telnet Service
login: Kiran
Kiran
password: artha
[1;1H*=============================================================== [2;1HMicrosoft Telnet Server. [3;1H*=============================================================== [4;1HC:\Users\Kiran> Got Connection...
hostname
[5;1H[K[6;1H[K[7;1H[K[8;1H[K[9;1H[K[10;1H[K[11;1H[K[12;1H[K[13;1H[K[14;1H[K[15;1H[K[16;1H[K[17;1H[K[18;1H[K[19;1H[K[20;1H[K[21;1H[K[22;1H[K[23;1H[K[24;1H[K[25;1H[K[4;16Hhostname[5;1HKiran-PC[7;1HC:\Users\Kiran>DONE
And some ESC char before "["
Any help regarding this one.
Thank You.
Take a look at this wiki article. This symbols are just control characters, used to format the output in your terminal.
You can try to configure your terminal type like:
TelnetClient telnet = new TelnetClient("dumb");
Or you can try to configure it with TerminalTypeOptionHandler.
By default your telnet client is created with terminal type vt100' which supports control sequences. The dumb one does not support them. But you have to understand, that it is not guaranteed, that remote server support this terminal type.

Categories