Pages: [1]   Go Down
Author Topic: problem reading a string from ethernet shield  (Read 750 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi I have a problem with a tcp socket.
I can send a string command to arduino ethernet shield. All is OK.
But I can't read Arduino reply (it should be "200 OK").
Always there is an exception

This is the java code used to talk to Arduino

Code:
try {
            outStream.writeBytes(message);
            outStream.flush();
            outStream.close();
      } catch (Exception ex) {
            System.err.println("Unable to write " + message + " " + socket.toString()
                    + ". Maybe the device is not connected.");
        }
      try {
            inStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.print("Received string: '");

            while (!inStream.ready()) {}
            System.out.println(inStream.readLine()); // Read one line and output it

            System.out.print("'\n");
            inStream.close();
          } catch(Exception e) {
                     System.out.print("It didn't work!\n");
               }
      socket.close();

     }

The problem is with inStream section

Thanks
Logged

Freedomotic Domotica Open Source
http://freedomotic.com
We need your help. Please contact us for contributing

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 217
Posts: 13707
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


Quote
But I can't read Arduino reply (it should be "200 OK").
Have you confirmed that the Arduino puts that string into the socket? e.g. by printing it to Serial.println(s) too?

When reading from a socket you never know if data comes in one pieces or in many pieces. Especially from a relative slow device as an Arduino it can be split in pieces.

Quote
Always there is an exception
Can you tell us what the exception tells you?

change   System.out.print("It didn't work!\n");  ==> System.out.print(e.getMessage());
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks,I'll try to print exception message.
But if I connect to Arduino by web browser I receive the correct string. All works!!
Logged

Freedomotic Domotica Open Source
http://freedomotic.com
We need your help. Please contact us for contributing

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 217
Posts: 13707
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
But if I connect to Arduino by web browser I receive the correct string. All works!!

That implies that your webbrowser waits until all data is received, while your program doesn't.
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I receive this exception

java.net.SocketException: socket is fclose

But I close the socket after reading Arduino reply.
Can you help me?
Logged

Freedomotic Domotica Open Source
http://freedomotic.com
We need your help. Please contact us for contributing

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 614
Posts: 49343
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The smippet of code you posted obviously doesn't tell the whole story. You need to post more of your code.
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

This is the complete code for my function sending a message to arduino ethernet shield. It is part of a domotic project more complex

Code:
public class ETHArduinoBoard extends Actuator {

    Properties protocol = new Properties(); //defines the protocol using a hashmap
    Socket socket = null;
    DataOutputStream outStream = null;
    BufferedReader inStream = null;
    String response = null;

    public ETHArduinoBoard() {
        super("ETH Arduino Board");
        //fillProtocolData();
        //connect(); //connects to eth device
        start(); //starts the plugin
    }


  private void connect(Command c) {
      try {
            socket = new Socket(c.getProperty("socket-host"), new Integer(c.getProperty("socket-port")));
            BufferedOutputStream buffOut = new BufferedOutputStream (socket.getOutputStream ());
            outStream = new DataOutputStream (buffOut);
          } catch (UnknownHostException e) {
            System.err.println("Unable to connect to host '" + configuration.getProperty("socket-host") + "' on port " + configuration.getProperty("socket-port"));
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                    + "the connection to " + c.getProperty("socket-host") + "' on port " + c.getProperty("socket-port"));

        }
//        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    }


    @Override
   public void onCommand(Command c) throws IOException, UnableToExecuteException {
      ElectricDevice dev = getDevice(c);
      connect(c); // called here to interact with arduino
      String message = createMessage(c);
      try {
            outStream.writeBytes(message);
            outStream.flush();
            outStream.close();
            //in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //String response = in.readLine();
            //System.out.println("Device answer:"+response+"\n");
            //in.close();
            //socket.close();
          } catch (Exception ex) {
            System.err.println("Unable to write " + message + " " + socket.toString()
                    + ". Maybe the device is not connected.");
        }
      try {
            inStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.print("Received string: '");

            while (!inStream.ready()) {}
            System.out.println(inStream.readLine()); // Read one line and output it

            System.out.print("'\n");
            inStream.close();
          } catch(Exception e) {
                     //System.out.print("It didn't work!\n");
                     System.out.print(e);
               }
      socket.close();

     }

   // create message to send to Arduino
   public String createMessage(Command c) {
     String message=null;
        message="GET /" + c.getProperty("code") + " HTTP 1.0\r\n\r\n";
        return(message);
       }

    private ElectricDevice getDevice(Command c) {
        //getting a safe reference to the targer object if exist
        ElectricDevice dev = null;
        try {
            dev = c.getTargetObject(ElectricDevice.class);
        } catch (NoObjectFoundException ex) {
            System.err.println("Undefined target object '" + c.getProperty("object") + "' in command '" + c.getName() + "'");
        } catch (ClassCastException classEx) {
            System.err.println("Attempt to handle an '" + c.getProperty("object") + "' as an 'ElectricDevice' -> " + classEx.getLocalizedMessage());
        }
        return dev;
    }


    /*
     * used only to update the state of the object in Freedom
     */
    protected void setTargetObjectBehavior(Command c) {
        ElectricDevice dev = getDevice(c);

        //getting the behavior to apply
        String state = c.getBehavior();

        try {
            if (state.equalsIgnoreCase("on")) {
                dev.switchOn(c.getProperties());
            }
            if (state.equalsIgnoreCase("off")) {
                dev.switchOff(c.getProperties());
            }
            if (state.equalsIgnoreCase("dim")) {
                Light light = (Light) dev;
                light.dim(c.getProperties());
            }
        } catch (Exception e) {
            System.err.println("Unable to change behavior");
        }
    }

    public void onDataAvailable(String data) {
        //do nothing
    }

    public boolean canExecute(Command c) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
Logged

Freedomotic Domotica Open Source
http://freedomotic.com
We need your help. Please contact us for contributing

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 614
Posts: 49343
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What triggers the onCommand() callback?

What happens if you don't close outStream until just before you close the socket?
Logged

Offline Offline
Jr. Member
**
Karma: 0
Posts: 89
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks PaulS!! You're a genius!!

I solved moving outStream.close() after reading from inStream:

 inStream.close();
 outStream.close();
 socket.close();
Logged

Freedomotic Domotica Open Source
http://freedomotic.com
We need your help. Please contact us for contributing

Pages: [1]   Go Up
Jump to: