SerialServer
Search:
ClassWork / SerialServer

Processing Simplest Server, takes in data and relays back out to all clients

(also echos it to client it came from)

import processing.core.PApplet; import processing.core.PFont; import processing.net.Client; import processing.net.Server; import processing.serial.Serial;

public class SensorServer extends PApplet {

	Server myServer;

	int endOfMessageChar = 10;

	int socketPort = 9002;

	static public void main(String _args[]) {

		PApplet.main(new String[] { "SensorServer" });
	}

	public void setup() {
		size(256, 256); // Stage size
		noStroke(); // No border on the next thing drawn

		myServer = new Server(this, socketPort);

		println("Starting a server at port " + socketPort);

		PFont myFont = createFont("Arial", 18);
		textFont(myFont);
	}
	public void draw(){
		Client myClient = myServer.available();
		if (myClient != null){
			String _whatClientSaid = myClient.readStringUntil(endOfMessageChar);
			if (_whatClientSaid != null){
			println("Client said: " + _whatClientSaid);
			myServer.write("They said " + _whatClientSaid);
			}
		}
	}
	public void serverEvent(Server someServer, Client _newClient) {
			println("We have a new client: " + _newClient.ip());
	}

}


Mobile Processing Code for Relaying Data from Bluetooth to a Socket connection (can be used with above)

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;

import javax.microedition.io.Connector; import javax.microedition.io.SocketConnection; import javax.microedition.io.StreamConnection;

import processing.core.PFont; import processing.core.PMIDlet;

public class BT2Socket extends PMIDlet {

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  //String BT_ADDRESS = "000666015f5e";  //blue smirf hardware address
  //stuff you should change
  String BT_ADDRESS = "00a0961799ea";

  String ip = "128.122.151.239"; // my IP
  int port = 9002;

  SocketThread internet;
  BTThread blueTooth;

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  int xpos;
  PFont font;
  String accumulatedFromBT = "";
  String accumulatedFromInternet = "";



  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  public void setup( ){
    font = loadFont("ACaslonPro-Bold-12.mvlw");

    // start the internet
    internet = new SocketThread();
    // start the BlueTooth
    blueTooth = new BTThread();
    blueTooth.start();


    textFont(font);
    text("url:" + ip, 10,90);



  }

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -
  public void keyPressed(){

    internet.send( key);
    internet.send( 10);
  }


  public void draw() {
    // The draw happens at the events
  }

  void  internetEvent(int input){
    accumulatedFromInternet = accumulatedFromInternet + (char) input; // Empty String
    if (input == 10) { // why 10?
      background(127);
      println("New From Internet " +  accumulatedFromInternet);
      text("Internet: " +  accumulatedFromInternet ,10,30);


      accumulatedFromInternet = "";  //reset accumulation
      // send a byte out in case other side is waiting to be prompted
    }



  }
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  void blueToothEvent(int input) { // bilt in java bluetoothEvent
    accumulatedFromBT = accumulatedFromBT + (char) input; // Empty String


    if (input == 10) { // why 10?
      println("In From BlueTooth: " + accumulatedFromBT);
      if (internet != null){
        internet.send(accumulatedFromBT);
        // internet.send( 10);
      }
      String[] parts = split(accumulatedFromBT,",");
      accumulatedFromBT = "";  //reset accumulation
      // send a byte out in case other side is waiting to be prompted



      blueTooth.send(65);


    }
  } // End of blueToothEvent

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  int getLength(Object[] o) { //don't pay attention, servicing a bug in m.p.
    return o.length; //ideally you could just say yourObject.length
  }

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  class BTThread extends Thread {
    StreamConnection btConnection = null;
    OutputStream btOutputStream = null;
    // thread to accumulate bytes



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

    public void run() {
      textFont(font);

      try {
        //surrounds hardware address in bluetooth stuff. ":01? is for the serial service
        String BTurl = "btspp://" + BT_ADDRESS + ":01;authenticate=false;encrypt=false;master=false";
        btConnection = (StreamConnection) Connector.open(BTurl);
        try {
          InputStream btInputStream = btConnection.openInputStream();
          btOutputStream = btConnection.openOutputStream();
          ///send a byte out in case other side is waiting to be prompted
          send(65);
          while(true) {
            //read in a byte at a time, this stops for the byte, that is why we are in a thread
            int input = btInputStream.read();
            blueToothEvent(input);
          }
        } 
        catch(IOException e) {
          println("Stopped Listening To BlueTooth");
        }
      } 
      catch(IOException e) {
        println("Sorry but could not connect to " + BT_ADDRESS);
      }
      disconnect();
    } // End of run

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

    void send(int _output) {
      try {
        btOutputStream.write( _output);
        btOutputStream.flush();
      } 
      catch(IOException e) {
        println("Stopped Listening To BlueTooth");
      }
    } // End of Send


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

    void disconnect() {
      try {

        btConnection.close();
      } 
      catch(Exception e) {
        println("Trouble Closing Connection");
      }
    } // End of disconnect

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  } // End of BTThread Class

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  class SocketThread extends Thread {
    SocketConnection socket ;
    DataInputStream dis = null;
    DataOutputStream dout = null;

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

    SocketThread(){
      textFont(font);

      // Socket at this IP address and this port:
      String address = "socket://" + ip + ":" + port;
      try {
        socket = (SocketConnection) Connector.open(address);
        text("Connected",10,50);
        dis = new DataInputStream(socket.openInputStream());
        dout = new DataOutputStream(socket.openOutputStream());
        text("Have Streams ",10,70);
      } 
      catch (Exception e) {
        text("Could not make connections" + address, 10,10);
      }
      start();
    }

    public void run() {

      while(true) {
        //read in a byte at a time, this stops for the byte, that is why we are in a thread
        if (dis == null) continue;
        try{
          int input = dis.read();
          internetEvent(input);
        }
        catch(Exception e){
          text("Problem Reading " + e, 10,20);
          disconnect();
          break;
        }

      }



    } // End of run

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

    void send(int _output) {
      try{ 
        if (dout != null){
          dout.write( _output);
          dout.flush();
        }
      }

      catch(Exception e) {
        text("Sending prob To Internet",10,10);
      }
    } // End of send

    void send(String _output) {
      try{ 
        if (dout != null){
          dout.write( _output.getBytes());
          dout.flush();
        }
      }

      catch(Exception e) {
        text("Sending prob To Internet",10,10);
      }
    } // End of Send

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - -

    void disconnect() {
      try {
        socket.close();
      } 
      catch (Exception e) {
        println("Trouble Closing Connection");
      }
    } // End of disconnect

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -

  } // End of SocketThread Class

  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

}


Processing Code for Text Chat using Socket Connections

import processing.core.PApplet;
import processing.core.PFont;
import processing.net.Client;
import processing.net.Server;
import processing.serial.Serial;

public class Chat extends PApplet {



	Server myServer;

	int endOfMessageChar = 10;

	Client myClient;

	int socketPort = 10002;

	String ip = "128.122.151.100";

	boolean serverRole = true;

	String displayText = "Nothing Yet";

	static String[] args;

	String testString = "";

	static public void main(String _args[]) {
		args = _args;
		PApplet.main(new String[] { "Chat" });
	}

	public void setup() {
		size(256, 256); // Stage size
		noStroke(); // No border on the next thing drawn
		// Print a list of the serial ports, for debugging purposes to find out what your ports are called:
		// println(Serial.list());
		getParams();
		if (serverRole) {
			myServer = new Server(this, socketPort);
			println("Starting a server at port " + socketPort);
		} else {
			myClient = new Client(this, ip, socketPort);
			println("Connecting as client at " + socketPort + " on " + ip);
		}
		PFont myFont = createFont("Arial", 18);
		textFont(myFont);
	}

	public void draw() {
		// listen to client, should be able to do this with ClientEvent but this seems not to work with Clients created by the server
		if (myClient != null) {
			String whatClientSaid = myClient.readStringUntil(endOfMessageChar);
			if (whatClientSaid != null) {
				displayText = "Got: " + whatClientSaid;
			}
		}

		background(0);
		if (testString.equals("")) {
			text(displayText, 20, 20);
		} else {
			text(testString + " Press Enter To Send", 20, 20);
		}
	}

	public void serverEvent(Server someServer, Client _newClient) {
		myClient = _newClient;
		println("We have a new client: " + _newClient.ip());
	}


	void tellSocket(String _whatSerialSaid) {
		displayText = "Told Socket " + _whatSerialSaid;
		if (myClient != null) myClient.write(_whatSerialSaid + "\n");
	}



	public void keyPressed() {
		if (key == ENTER || key == RETURN) {
			tellSocket(testString);
			testString = "";
		} else {
			testString = testString + key;
		}
	}

	void getParams() {
		if (args != null) { // running as an application

			if (args.length > 0) socketPort = Integer.parseInt(args[0]);
			if (args.length > 1) {
				ip = args[1];
				serverRole = false;
			}
		} else { // running as an applet


			String isItThere = getParameter("socketPort");
			if (isItThere != null) socketPort = Integer.parseInt(isItThere);
			isItThere = getParameter("ip");
			if (isItThere != null) ip = isItThere;

		}
	}

}

Processing Code for Tele White Board


import processing.core.PApplet;
import processing.core.PFont;
import processing.net.Client;
import processing.net.Server;
import processing.serial.Serial;

public class TeleDraw extends PApplet {

	Server myServer;

	int endOfMessageChar = 10;

	Client myClient;

	int socketPort = 10002;

	String ip = "128.122.151.100";

	boolean serverRole = true;

	static String[] args;

	static public void main(String _args[]) {
		args = _args;
		PApplet.main(new String[] { "TeleDraw" });
	}

	public void setup() {
		size(256, 256); // Stage size
		noStroke(); // No border on the next thing drawn
		// Print a list of the serial ports, for debugging purposes to find out what your ports are called:
		// println(Serial.list());
		getParams();
		if (serverRole) {
			myServer = new Server(this, socketPort);
			println("Starting a server at port " + socketPort);
		} else {
			myClient = new Client(this, ip, socketPort);
			println("Connecting as client at " + socketPort + " on " + ip);
		}

	}

	public void draw() {
		// listen to client, should be able to do this with ClientEvent but this seems not to work with Clients created by the server
		if (myClient != null) {
			String whatClientSaid = myClient.readStringUntil(endOfMessageChar);
			if (whatClientSaid != null) {
				println("What " +  serverRole + " " + whatClientSaid);
				String[] parts = whatClientSaid.split(",");
				if (parts.length > 1) {
					fill(0);
					ellipse(Integer.parseInt(parts[0].trim()), Integer.parseInt(parts[1].trim()), 2, 2);
				}
			}
		}

	}

	public void serverEvent(Server someServer, Client _newClient) {
		myClient = _newClient;
		println("We have a new client: " + _newClient.ip());
	}

	void tellSocket(String _whatSerialSaid) {
		if (myClient != null) myClient.write(_whatSerialSaid + "\n");
	}

	public void mouseDragged() {
		println(String.valueOf(mouseX) + "," + String.valueOf(mouseY));
		tellSocket(String.valueOf(mouseX) + "," + String.valueOf(mouseY));
	}

	void getParams() {
		if (args != null) { // running as an application
			if (args.length > 0) socketPort = Integer.parseInt(args[0]);
			if (args.length > 1) {
				ip = args[1];
				serverRole = false;
			}
		} else { // running as an applet

			String isItThere = getParameter("socketPort");
			if (isItThere != null) socketPort = Integer.parseInt(isItThere);
			isItThere = getParameter("ip");
			if (isItThere != null) ip = isItThere;

		}
	}

}

Arduino and Processing Code for Relaying Sensor Data Across the Internet


int ledPin = 3;                 // LED connected to digital pin 13
int photocell = 0;
boolean  lastPhotocellCondition;
boolean pinCondition = false;
int photoThreshold = 450;


void setup()
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
  beginSerial(9600);
}

void loop()
{
  photocell = analogRead(4);
   //Serial.println(photocell,DEC);
  boolean now = (photocell > photoThreshold);

  if (now != lastPhotocellCondition) {
    if (now == true){
      Serial.print(65,BYTE);
      Serial.print(10,BYTE);
    }
    else{
      Serial.print(66,BYTE);
      Serial.print(10,BYTE);
    }
    lastPhotocellCondition  = now;
  }
  if (Serial.available() > 1){
    int condition = Serial.read();
    Serial.read();  //burn the delimiter
    if (condition == 65){
      digitalWrite(ledPin, HIGH);   // sets the LED on
    }
    else{
      digitalWrite(ledPin, LOW);   // sets the LED on
    }       
  } 
}






import processing.core.PApplet;
import processing.core.PFont;
import processing.net.Client;
import processing.net.Server;
import processing.serial.Serial;

public class SerialServerApp extends PApplet {

	Serial serialPort;

	Server myServer;

	int endOfMessageChar = 10;

	Client myClient;

	String serialPortName;

	int socketPort = 10002;

	String ip = "128.122.151.100";

	boolean serverRole = true;

	String displayText = "Nothing Yet";

	static String[] args;

	String testString = "";

	static public void main(String _args[]) {
		args = _args;
		PApplet.main(new String[] { "SerialServerApp" });
	}

	public void setup() {
		size(256, 256); // Stage size
		noStroke(); // No border on the next thing drawn
		// Print a list of the serial ports, for debugging purposes to find out what your ports are called:
		// println(Serial.list());
		getParams();
		if (Serial.list()[0] == null) serialPortName = Serial.list()[0];
		serialPort = new Serial(this, serialPortName, 9600); // or you can just specify it
		println("Connecting to serial port " + serialPortName);
		if (serverRole) {
			myServer = new Server(this, socketPort);
			println("Starting a server at port " + socketPort);
		} else {
			myClient = new Client(this, ip, socketPort);
			println("Connecting as client at " + socketPort + " on " + ip);
		}
		PFont myFont = createFont("Arial", 18);
		textFont(myFont);
	}

	public void draw() {
		// listen to client, should be able to do this with ClientEvent but this seems not to work with Clients created by the server
		if (myClient != null) {
			String whatClientSaid = myClient.readStringUntil(endOfMessageChar);
			if (whatClientSaid != null) {
				whatClientSaid = whatClientSaid.trim();
				tellSerial(whatClientSaid);
			}
		}

		background(0);
		if (testString.equals("")) {
			text(displayText, 20, 20);
		} else {
			text(testString + " Press Enter To Send", 20, 20);
		}
	}

	public void serverEvent(Server someServer, Client _newClient) {
		myClient = _newClient;
		println("We have a new client: " + _newClient.ip());
	}

	public void serialEvent(Serial port) {

		String whatSerialSaid = serialPort.readStringUntil(endOfMessageChar); // make sure you return (Ascii 13) at the end of your transmission

		//println("Serial " + whatSerialSaid);
		if (whatSerialSaid != null) {

			whatSerialSaid = whatSerialSaid.trim();
			tellSocket(whatSerialSaid);
		}
	}

	void tellSocket(String _whatSerialSaid) {
		displayText = "Told Socket " + _whatSerialSaid;
		if (myClient != null) myClient.write(_whatSerialSaid + "\n");
	}

	void tellSerial(String _whatSocketSaid) {
		displayText = "Told Serial " + _whatSocketSaid;
		serialPort.write(_whatSocketSaid + "\n");
	}

	public void keyPressed() {
		if (key == ENTER || key == RETURN) {
			tellSocket(testString);
			testString = "";
		} else {
			testString = testString + key;
		}
	}

	void getParams() {
		if (args != null) { // running as an application
			if (args.length > 0) serialPortName = args[0];
			if (args.length > 1) socketPort = Integer.parseInt(args[1]);
			if (args.length > 2) {
				ip = args[2];
				serverRole = false;
			}
		} else { // running as an applet

			String isItThere = getParameter("serialPort");
			if (isItThere != null) serialPortName = isItThere;
			isItThere = getParameter("socketPort");
			if (isItThere != null) socketPort = Integer.parseInt(isItThere);
			isItThere = getParameter("ip");
			if (isItThere != null) ip = isItThere;

		}
	}

}


Search
  Page last modified on November 09, 2009, at 03:12 PM