//Mashed together code from Amit's LiveInput example for Sonia and Tom's Processing to PHP code.

import processing.net.*;

import pitaru.sonia_v2_9.*; // automcatically added when importing the library from the processing menu.

float meterDataLeft;

float meterDataRight;

float sensorValue;

boolean netSendInProgress = false;

Client client;

void setup(){

  size(512,200);
  Sonia.start(this); // Start Sonia engine.
  LiveInput.start(256); // Start LiveInput and return 256 FFT frequency bands.

}

void draw(){

  getMeterLevel(); // Show meter-level reading for Left/Right channels.   
  if (!netSendInProgress) {
    sendToNet(sensorValue);
  }
  if (netSendInProgress) {
    if (client.available() > 0) {
      int inByte = client.read();
      print((char)inByte);
      if (inByte == 0) {
        netSendInProgress = false;
        // don't overwhelm the server:
        delay(3000);

      }
    }
  }

}

void getMeterLevel(){

  // get Peak level for each channel (0 -> Left , 1 -> Right)
  // Value Range: float from 0.0 to 1.0
  // Note: use inputMeter.getLevel() to combine both channels (L+R) into one value.
  meterDataLeft = LiveInput.getLevel();
  meterDataRight = LiveInput.getLevel();
  sensorValue = ((meterDataLeft + meterDataRight)/2);

}

// Safely close the sound engine upon Browser shutdown. public void stop(){

  Sonia.stop();
  super.stop();

}

void sendToNet(float sensorValue) {

  // open a TCP socket to the host:
  client = new Client(this, "itp.nyu.edu", 80);

  //print the IP address of the host:
  println(client.ip());
  // send the HTTP GET request:
  String sensorString = Float.toString(sensorValue);
  client.write("GET /~gak217/fall05/sensor/sensorlog/sensor.php?micval=" + sensorValue + " HTTP/1.1\n");
  client.write("HOST: itp.nyu.edu\n\n");
  netSendInProgress = true;

}