Data communication with PC

This is where you talk about the EV3 software itself, installation issues, and programming talk.

Moderators: roger, gloomyandy, skoehler

Data communication with PC

Postby ruperty » Thu Jul 17, 2014 3:35 pm

I would like to continuously transfer data from the EV3 to the PC, and send a response back. The data may be hundreds of floats.

I can set up a Socket server and client, but wondered if there was existing code that would allow me to do this?
Regards,
Rupert
www.perceptualrobots.com
ruperty
Active User
 
Posts: 132
Joined: Sun Oct 14, 2007 11:21 am

Re: Data communication with PC

Postby gloomyandy » Thu Jul 17, 2014 4:09 pm

Just use normal TCP network connections, standard Java classes allow you to do this.
User avatar
gloomyandy
leJOS Team Member
 
Posts: 4249
Joined: Fri Sep 28, 2007 2:06 pm
Location: UK

Re: Data communication with PC

Postby ruperty » Wed Jul 23, 2014 2:38 pm

In case this is useful to anyone else here are some classes I created for TCPIP communication (of strings) between the EV3 and the PC, which I use for plotting continuous values of certain variables. The first two are generic communication classes and the other two show how they are used, with my specific data structures.

If anyone has suggestions on how they could be improved they would be most welcome.

Here is the socket server, which runs on the EV3.

Code: Select all
package uk.co.moonsit.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Rupert Young
 */
public class SocketServer {

    private final ServerSocket serverSocket;
    private Socket server;
    private DataOutputStream out;
    private DataInputStream in;

    public SocketServer(int port, int timeout) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(timeout);
    }

    public void connect() throws IOException {
        System.out.println("Wait on " + serverSocket.getLocalPort() + "...");
        server = serverSocket.accept();

        System.out.println("Connected to " + server.getRemoteSocketAddress());
        out = new DataOutputStream(server.getOutputStream());
        in = new DataInputStream(server.getInputStream());
    }

    public int getPort() {
        int port = 0;
        if (serverSocket != null) {
            port = serverSocket.getLocalPort();
        }
        return port;
    }

    public boolean isConnected() {
        if (server == null) {
            return false;
        }
        return server.isConnected();
    }

    public String socketStatus() {
        return server == null ? "null" : "not null";
    }

    public void connectionLost() {
        server = null;
    }

    public String sendAndReceive(String message) throws IOException {
        out.writeUTF(message);
        String response = in.readUTF();
        return response;
    }

   @SuppressWarnings("null")
    public static void main(String[] args) {
        int port = Integer.parseInt(args[0]);
        int timeout = 30000;
        SocketServer ss = null;

        try {
            ss = new SocketServer(port, timeout);
        } catch (IOException ex) {
            Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            ss.connect();
        } catch (java.net.SocketTimeoutException ex) {
            Logger.getLogger(ex.toString());
        } catch (IOException ex) {
            Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (ss.isConnected()) {
            String response = null;
            try {
                response = ss.sendAndReceive("1");
                System.out.println("Response  " + response);
                response = ss.sendAndReceive("2");
                System.out.println("Response  " + response);
                response = ss.sendAndReceive("3");
                System.out.println("Response  " + response);
            } catch (IOException ex) {
                Logger.getLogger(SocketServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}



Here is the socket client, which runs on the PC.

Code: Select all
package uk.co.moonsit.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;

/**
 *
 * @author Rupert Young
 */
public class SocketClient {

    private final String server;
    private final int port;
    private Socket client;
    private DataInputStream in;
    private DataOutputStream out;

    public SocketClient(String server, int port) {
        this.server = server;
        this.port = port;
    }
 
    public void connect() throws IOException {
        System.out.println("Connecting to " + server + " on port " + port);
        client = new Socket(server, port);
        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        in = new DataInputStream(client.getInputStream());
        out = new DataOutputStream(client.getOutputStream());
    }

    public String receiveAndSend(String response) throws IOException, EOFException {
        String message =  in.readUTF();

        out.writeUTF(response);
        return message;
    }

    public boolean isConnected() {
        if(client==null)
            return false;
        return client.isConnected();
    }

    public void close() throws IOException {
        client.close();
    }

    public static void main(String[] args) {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);

        SocketClient sc = new SocketClient(serverName, port);
        String message = null;
        try {
            sc.connect();

            for (int i = 0; i < 10; i++) {
                message = sc.receiveAndSend("Ok");
                System.out.println(message);
            }
            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



Here is how the client, on the PC, is used.

Code: Select all
package uk.co.moonsit.sockets;

import java.io.EOFException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Rupert Young
 */
public class MessageClient extends Thread {

    private static final Logger logger = Logger.getLogger(MessageClient.class.getName());

    private final SocketClient client;
    private boolean firstMessage = true;
    private boolean running = true;
    private String config = null;
    private String message = null;

    public MessageClient(String serverName, int port) {
        client = new SocketClient(serverName, port);
    }

    @SuppressWarnings("SleepWhileInLoop")
    @Override
    public void run() {

        while (!client.isConnected()) {
            try {
                client.connect();
            } catch (IOException e) {
                logger.info("Not connected");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MessageClient.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        String msg;
        try {
            while (running) {
                msg = client.receiveAndSend("Ok");
                if (firstMessage) {
                    setConfig(msg);
                    firstMessage = false;
                } else {
                    setMessage(msg);
                }

                //System.out.println(msg);
            }
        } catch (EOFException ex) {
            Logger.getLogger(MessageClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MessageClient.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(MessageClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    synchronized public String getConfig() {
        return config;
    }

    synchronized public void setConfig(String config) {
        this.config = config;
    }

    synchronized public String getMessage() {
        return message;
    }

    synchronized public void setMessage(String message) {
        this.message = message;
    }

}


Here is how the server, on the EV3, is used.

Code: Select all
package uk.co.moonsit.utils.server;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import lejos.hardware.lcd.LCD;
import uk.co.moons.control.BaseControlHierarchy;
import uk.co.moonsit.sockets.SocketServer;
import uk.co.moonsit.utils.FileReader;

public class MessageServer extends Thread {

   static final Logger logger = Logger.getLogger(SocketServer.class.getName());

   private SocketServer ss = null;
   private boolean finished = false;
   private BaseControlHierarchy ch;
   private String config;
   private boolean sentConfig = false;
   private int port;

   public MessageServer(int port, int timeout, BaseControlHierarchy ch,
         String config) {
      try {
         this.config = config;
         this.ch = ch;
         this.port = port;
         ss = new SocketServer(port, timeout);
      } catch (IOException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public String getMessage() throws IOException {
      String rtn = null;
      if (!sentConfig) {
         Charset cs = Charset.defaultCharset();
         rtn = config + FileReader.readFile(config, cs);
         sentConfig = true;
      } else {
         rtn = ch.getDelimitedString();
      }

      return rtn;
   }

   public void run() {
      // int ctr=0;
      while (!finished) {
         try {
            if (!ss.isConnected()) {
               LCD.drawString(port + ".....", 0, 7);
               ss.connect();
               LCD.drawString("connected", 0, 7);            }
         } catch (java.net.SocketTimeoutException ex) {
            System.out.println("Timed out");
            continue;
         } catch (IOException ex) {
            Logger.getLogger(SocketServer.class.getName()).log(
                  Level.SEVERE, null, ex);
         } catch (Exception e) {
            e.printStackTrace();
         }

         if (ss.isConnected()) {
            String response = null;
            try {

               String msg = getMessage();
               // System.out.println("M:" + msg.substring(0, msg.length() >
               // 10 ? 10 : msg.length() ));

               response = ss.sendAndReceive(msg);
               // System.out.println("Response  " + response);

            } catch (IOException ex) {
               logger.warning(ex.toString());
               logger.info("socket " + ss.socketStatus());
               ss.connectionLost();
               sentConfig = false;
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
         // if(ctr++>5)
         // finished = true;
      }
      // System.out.println("Server finished");

   }

   public boolean isFinished() {
      return finished;
   }

   public void setFinished(boolean finished) {
      this.finished = finished;
   }

}


Here is how the PC client is run.

Code: Select all
mc = new MessageClient("192.168.1.5", 6666);
mc.start();


Here is how the EV3 server is run.

Code: Select all
int timeout = 10000;
ms = new MessageServer(6666, timeout, ch, config);
ms.start();
Regards,
Rupert
www.perceptualrobots.com
ruperty
Active User
 
Posts: 132
Joined: Sun Oct 14, 2007 11:21 am


Return to EV3 Software

Who is online

Users browsing this forum: No registered users and 1 guest

more stuff