maggick_wiimote_glove/mouse/mouse.pde
import processing.serial.*;
import java.awt.AWTException;
import java.awt.Robot;
/*arduino information*/

Serial port;
String portname = "/dev/tty.usbserial-AD01U4VO";
//String portname = "/dev/ttyBluetooth-PDA-Sync";

final color ORANGE = color(204,102,0);
final color RED = color(205,0,0);
final color GREEN = color(0,205,0);
final color WHITE = color(255,255,255);
final color BLACK = color(0,0,0);
final color BLUE = color(0,0,255);
final color YELLOW = color(255,255,0);
final color GREY = color(165,165,165);
boolean started = false;

final int W_HEIGHT = 130;
final int W_WIDTH = 150;

int n_data  = 3;

Robot bot;
int bot_x = 0;
int bot_y = 0;
int ax_bot = 0;
int ay_bot = 0;

void setup() {
  background(WHITE);
  try { 
    bot = new Robot();
    bot_x = displayWidth/2;
    bot_y = displayHeight/2;
  } 
  catch (AWTException e) {
    e.printStackTrace();
  }
  bot.mouseMove(bot_x,bot_y);
  
  
  size(W_WIDTH,W_HEIGHT); // définition de la surface de travail
  port = new Serial(this, portname, 9600);
  port.clear();
  background(BLACK);
  fill(WHITE);
}

void draw(){
  if(started){
    /*message à arduino pour l'acquisition des données*/
    port.write(ENTER);

    /*attendre que le buffer contienne toutes les données*/
    while(!(port.available() >= n_data ));

    background(BLACK);

    /*les données reçues vont de 0 à 180, on veut du +/-90*/
    ax_bot = 90 - port.read();
    ay_bot = 90 - port.read() + 40;
    port.read();//composante z dont on se fiche

    /*on set le maximum pour éviter de faire des mouvements trops grands*/
    float xbot_lim = 35.0;
    float ybot_lim = 30.0;
    if(ax_bot > xbot_lim) ax_bot = (int)xbot_lim;
    else if(ax_bot < -xbot_lim) ax_bot = -(int)xbot_lim;
    else if(abs(ax_bot) < 5.0) ax_bot = 0;
    if(ay_bot > ybot_lim) ay_bot = (int)ybot_lim;
    else if(ay_bot < -ybot_lim) ay_bot = -(int)ybot_lim;
    else if(abs(ay_bot) < 3.0) ay_bot = 0;
    
    /*on opère les changements*/
    bot_x = (int) ((displayHeight / 2) * (1 + (ax_bot/xbot_lim)));
    if(bot_x < 0) bot_x = 0;
    if(bot_x > displayHeight) bot_x = displayHeight;
    
    bot_y -= (int) ((displayWidth / 50.0) * (ay_bot/ybot_lim));
    if(bot_y < 0) bot_y = 0;
    if(bot_y > displayWidth) bot_y = displayWidth;
    bot.mouseMove(bot_y,bot_x);
    
    fill(GREEN);
    text("x: " + bot_y, 30, 30);
    fill(RED);
    text("y: " + bot_x, 30, 40);
    
  }
}

void keyPressed(){
  if(key == ESC){
    while(port.available()>0){
      port.read();
    }
    exit();
  }
  if(!started){
    started = true;
  }
}

