BGS5T RS232 communication with 1-wire sensor - java

I have Gemalto BGS5T java module and 1-wire temperature sensor. I have java midlet which uses RS232 port to communicate with temperature sensor. But the problem is that, I get no response from the sensor no matter what I send. Sensor has the right voltage on it, so the connection should be fine.
I tried testing my program so that I connected rs232 port to computer and watched with terminal(Termite) if the sent data was correct and everything looks like it should.
Another test was that I connected temperature sensor directly to computer and sent data with terminal and it worked like it should. I even got responses on some random inputs like 9999. I checked the parameters for connection inside the terminal and copied them to java midlet, but with no success.
There was only one time that I got some responses, but when I tryed the next day to continue with the work I had no success.
Parameters inside terminal:
Baud rate:9600
Data bits : 8
Stop bits: 1
Parity: none
Flow control:RTS/CTS
Here is the Java code:
String strCOM = "comm:COM0;blocking=on;baudrate=9600";
commConn = (CommConnection)Connector.open(strCOM);
System.out.println("CommConnection(" + strCOM + ") opened");
System.out.println("Real baud rate: " + commConn.getBaudRate());
inStream = commConn.openInputStream();
outStream = commConn.openOutputStream();
System.out.println("InputStream and OutputStream opened");
while(1==1)
{
byte bC1 = (byte)Integer.parseInt("11000001",2);
byte C1 = hexToBin("C1");
byte bparameter2 = (byte)Integer.parseInt("00010111",2);
byte bparameter3 = (byte)Integer.parseInt("01000101",2);
byte bparameter4 = (byte)Integer.parseInt("01011011",2);
byte bparameter5 = (byte)Integer.parseInt("00001111",2);
byte bparameter6 = (byte)Integer.parseInt("10010101",2);
byte[] bArray = {bparameter2,bparameter3,bparameter4,bparameter5,bparameter6};
int ch;
try {
outStream.write(bC1);
Thread.sleep(50);
//outStream.write(bArray);
outStream.write(bparameter2);
outStream.write(bparameter3);
outStream.write(bparameter4);
outStream.write(bparameter5);
outStream.write(bparameter6);
System.err.println("inStream bytes:" + inStream.available());
if(inStream.available() > 0)
{
String msg = "";
while(inStream.available() > 0)
{
ch = inStream.read();
msg = msg + (char) ch;
}
System.out.println("Serial msg: " + msg);
}
outStream.write('9');
outStream.write('9');
outStream.write('9');
outStream.write('9');
Thread.sleep(100);
outStream.write('9');
outStream.write('9');
outStream.write('9');
outStream.write('9');
System.err.println("inStream bytes:" + inStream.available());
if(inStream.available() > 0)
{
String msg = "";
while(inStream.available() > 0)
{
ch = inStream.read();
msg = msg + (char) ch;
}
System.out.println("Serial msg: " + msg);
}

I had to use null modem cable to get it working.

Related

issue while receiving correct data from java client

I have a TCP client-server architecture. Server is written in C# and Client is written in Java.
I want to get MAC address of Client device. Connection between both is working. When I send packet with data "IPMAC" it is received and decoded correctly.
But when I send the MAC address to Server, it changes the data in it.
Java code for sending:
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
outStream.write(sb.toString().getBytes("UTF-8"));
System.out.println("Data sent " + sb.toString());
} catch (IOException e) {
System.out.println("Unable to get MAC address of device or send it to server");
}
C# code for receiving:
size = 6;
byte[] buffer = new byte[6];
int received = 0;
ticks = Environment.TickCount;
do
{
try
{
if (Environment.TickCount > ticks + timeout)
throw new TimeoutException("Timout while receiving!");
received = received + client.Client.Receive(buffer, received, size - received, SocketFlags.None);
}
catch (SocketException)
{
}
catch (TimeoutException)
{
break;
}
if (buffer.Length > 1)
{
MessageBox.Show("Packet received!", "Wow", MessageBoxButton.OK, MessageBoxImage.Information);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
sb.Append(String.Format("%02X%s", buffer[i], (i < buffer.Length - 1) ? "-" : ""));
}
Console.WriteLine(BitConverter.ToString(buffer));
break;
}
}
while (received < size);
I am using UTF-8 encoding on both side.
MAC address sent: 00-08-BA-11-00
MAC address received: A1-21-00-00-00
Thanks
You want to make sure you're decoding the bytes as UTF-8 as well
Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
In java you take bytes representing integers byte[] mac and perform a string format on them String.format("%02X%s".... You take this string, turn it into bytes and send it through the socket. The bytes you receive on the C# side represent UTF-8 characters, not integers, so don't try to string format them again. Remove the StringBuilder on the C# client and just decode the bytes into a utf8 string like above.
Also why did you pick the receive bytes size to be size = 6;? What if there are more than 6 bytes of data? The string "00-08-BA-11-00" in utf8 is 14 bytes long!
One solution might be to send the size of the data before sending the data. I asked for a code review on something similar the other week if you are interested!

how to print string from bytebuffer

i have just started playing around with java nio packages an am at a bit of a loss
i have a client
Socket s=new Socket(ip,port);
OutputStream out=new OutputStream();
PrintStream ps=new PrintStream(s.getOutputStream());
String t=""hiya";
ps.print(t);
ps.flush();
InputSTreamReader in=new InputSTreamReader(s.getInputSTream);
BufferReader b=nwe BufferedReader(in);
System.out.println(b.readLine());//prints echo response from server
and on the server side
this.selkey = selkey;
this.chan = (SocketChannel) chan.configureBlocking(false); // asynchronous/non-blocking
buf = ByteBuffer.allocateDirect(64); // 64 byte capacity
void read() {
try {
int amount_read = -1;
try {
amount_read = chan.read((ByteBuffer) buf.clear());
} catch (Throwable t) {
}
if (amount_read == -1)
disconnect();//deelts client on exit
if (amount_read < 1)
return; // if zero
System.out.println("sending back " + buf.position() + " bytes");
// turn this bus right around and send it back!
buf.flip();
chan.write(buf);//sending data 2 client
} catch (Throwable t) {
disconnect();
t.printStackTrace();
}
}
what this does i send string t to the server into bytebuffer and echos it back which all works fine but hoiw would i print the string on the server side for example in read method
buf.flip()
System.out.write(buff);//which just prints what looks to be chinese
k this is typical have been working on this problem for like an hour but when i post the question the answer acours to me
CAST IT TO A CHAR!
this works
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get();
}
System.out.println();
Since you are sending data as bytes, it wont work as Strings.
Even if you did, it would be referencing the byte array.
Try this:
String str = new String (buff);

Reading a String array [NETWORKING]

I have this block of code to read an array sent from the server to the client of recent updates, the issue is that sometimes it works and sometimes it doesn't. It will print out the version properly, but everything else will either not print out, all print out on the same line, or have 2 on the same line.
The purpose of this is to receive a String[] of recent updates from the server, which is looped through and sent as an individual String. Those updates are then displayed on a GUI.
private Response update() {
try {
Socket socket = new Socket(RS2Client.IP, 55555);
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
String version = new String(bytes);
System.err.println("VERSION READ " + version);
for (int i = 0; i < 6; i++) {
byte[] b = new byte[1024];
socket.getInputStream().read(b);
String text = new String(b);
getRecentUpdates().add(text.trim());
System.out.println("New update: " + text);
}
for (String update : getRecentUpdates()) {
System.err.println(update);
}
System.out.println("Client connected! Version: " + version);
socket.close();
if (Double.parseDouble(version) != RS2Client.CLIENT_VERSION) {
return Response.BAD;
}
} catch (Exception e) {
e.printStackTrace();
return Response.ERROR;
}
return Response.GOOD;
}
A socket sends a stream of bytes. It does not keep track of the end of each byte array you send.
If you want to send a byte array, you should send the length first, so you know how many bytes to expect.

Why can't I read the body from POST request in java?

Code
public HttpRequest(BufferedReader from) {
String firstLine = "";
try {
firstLine = from.readLine();
} catch (IOException e) {
System.out.println("Error reading request line: " + e);
}
String[] tmp = firstLine.split(" ");
method = tmp[0];
URI = tmp[1];
version = tmp[2];
System.out.println("URI is: " + URI);
if(method.equals("POST")){
try {
String line = from.readLine();
while (line.length() != 0) {
headers += line + CRLF;
if (line.startsWith("Host:")) {
tmp = line.split(" ");
if (tmp[1].indexOf(':') > 0) {
String[] tmp2 = tmp[1].split(":");
host = tmp2[0];
port = Integer.parseInt(tmp2[1]);
} else {
host = tmp[1];
port = HTTP_PORT;
}
}
line = from.readLine();
}
headers += "Connection: close" + CRLF;
headers += CRLF;
}
catch (IOException e) {
System.out.println("Error reading from socket: " + e);
return;
}
}
else {
System.out.println("Error: Method not supported");
return;
}
System.out.println("Host to contact is: " + host + " at port " + port);
}
Problem
I am making a proxy server using Java.
The code above handles an HTTP POST Request. It successfully reads the POST header and prints it in the command prompt but the body is missing.
Can you take look at my code and see the problem? Thanks.
(NOTE: I excluded the GET part because there were no problems with that.)
Result
The problem is that you still have things to read on the InputStream. That's why when you shut down the browser, there's nothing else to read so is printed. You have to read exactly the number of bytes that is declared in "Content-Length"
Try something like this:
int cL = Integer.valueOf(contentLength);
byte[] buffer = new byte[cL];
String postData = "";
System.out.println("Reading "+ cL + "bytes");
in.read(buffer, 0, cL);
postData = new String(buffer, 0, buffer.length);
System.out.println(postData);
The body request will be in the postData string.
This is not how to write a proxy server. A proxy server only has to do the following:
Accept incoming connections. For each connection:
Read an HTTP CONNECT request.
Connect to the target host specified in the CONNECT request and send an appropriate response to the client.
If the connect succeeded, copy bytes between the upstream server and the downstream client, in both directions simultaneously.
When you read EOS in one direction, shutdown the opposite socket for output.
When you have shutdown in both directions, close both sockets.
That's it. There is no parsing of POST requests or anything else required. Not even a Reader.

receiving a C struct from serial port using Java

I've got two programs. one is written in C, sending out structs of unsinged chars via serial port.
The other one is written in Java and supposed to receive this data.
I'm using the jSSC library which returns a byte array after reading from the serial port.
How can I now extract the original values?
what is send: 1,99,23,15,16,17,18
bytes I received: [B#c1c428
bytes converted to chars: [C#13526b0
Sending the data works correctly. I also wrote a C program to read the data which receives it correctly so the problem seems to be in the Java program.
System.out.println("Port " + PortName + " opened: " + serialPort.openPort());
//serialPort.setParams(9600, 8, 1, 0);
byte[] input;
if((input = serialPort.readBytes()) == null){
System.out.println("No data to be read");
System.exit(0);
}
char[] chars = new String(input).toCharArray();
System.out.println("Bytes read: " + input.length);
System.out.println("Byteoutput: " + input);
System.out.println("Charoutput: " + chars);
In order to actually output a byte array you need to do something like:
System.out.print("Byte output: ");
for(int i=0; i < input.length; ++i)
System.out.print(((int)input[i]) + ", ");
System.out.println();

Categories

Resources