RebeccaHid1 HidDiscoverer code

From CSWiki
Jump to: navigation, search

Add this class first.

//Basic code for game controller / joystick
//Rebecca Fiebrink, 10/9/08
public class HidDiscoverer
{
	Hid js;
	HidMsg msg;
	int deviceID;

	public int init(int i) {
		i => deviceID;
		return js.openJoystick(i);
	}
	new float[0] @=> float axes[];
	new int[0] @=> int buttons[];
	new int[0] @=> int hats[];
	int numAxes, numButtons, numHats;
	1 => int isSetup;   
	1 => int isGo;

fun string name() {
	return js.name();
}


fun void setup() {
while (isSetup) {
	js => now;
	while (js.recv(msg)) {
		//<<< "I see you">>>;
		msg.which => int id;
		if (msg.isAxisMotion()) {
			if (id >= axes.size()) {
				id + 1 => axes.size;
				numAxes++;
			}
			if (axes[id] == 0.0) {
				msg.fdata+1 => axes[id];
			}
		} else if (msg.isButtonDown() || msg.isButtonUp()) {
			if (id >= buttons.size()) {
				id + 1 => buttons.size;
				numButtons++;
			}
			if (buttons[id] == 0) {
				msg.idata+1 => buttons[id];
			}
		} else if (msg.isHatMotion()) {
			//<<< "HAT">>>;
			if (id >= hats.size()) {
				id + 1 => hats.size;
				numHats++;
			}
			if (hats[id] == 0) {
			//	<<<"new">>>;
				msg.idata+1 => hats[id];
				<<< hats[id]>>>;
			}
		}
	}
}
}

fun void stopSetupAndStartRun() {
	0 => isSetup;
	<<< "Setup results: ">>>;
	for (0 => int i; i < axes.size(); i++) {
		if (axes[i] != 0.0) {
			<<< "Axis for which=" + i>>>;
		}
	}

	for (0 => int i; i < buttons.size(); i++) {
		if (buttons[i] != 0) {
			<<< "Button for which=" + i>>>;
		}
	}
	for (0 => int i; i < hats.size(); i++) {
		if (hats[i] != 0) {
			<<< "Hat for which=" + i>>>;
		}
	}
	run();
}

fun int numFeatures() {
	return axes.size() + buttons.size() + hats.size();
}

//must run in order to have features!
fun void run() {
	1 => isGo;
  while (isGo) {
	js => now;
	while (js.recv(msg)) {
	//	<<< "Got one">>>;
		msg.which => int id;
		if (msg.isAxisMotion()) {
			if (id < axes.size()) {
				msg.fdata+1 => axes[id];
			//	<<<"Axis " + id + " " + axes[id]>>>;
			}
		} else if (msg.isButtonDown() || msg.isButtonUp()) {
			if (id < buttons.size()) {
				 msg.idata + 1  => buttons[id];
			//	<<< "Button " + id + " " + buttons[id] >>>;
			}
		} else if (msg.isHatMotion()) {
			if (id <  hats.size()) {
				msg.idata + 1 => hats[id] ;
			//	<<< "Hat " + id + " " + hats[id] >>>;
			}
		}
	}
  }
}

fun void extractFeatureLoop() {
	while (true) {
		extractFeatures();
		.25::second => now;
	}	
}

fun float[] extractFeatures() {
		new  float[0] @=> float feats[];
	//	<<< "FEATURES">>>;
	 	for (0 => int i; i < axes.size(); i++) {
	//		<<< i >>>;
	//		<<< axes[i] >>>;
			feats << axes[i];
		}
		for (0 => int i; i < buttons.size(); i++) {
	//		<<< "Button ", i>>>;
	//		<<< buttons[i] >>>;
			feats << buttons[i]$float;
		}
		for (0 => int i; i < hats.size(); i++) {
		//	<<< "hat ", i>>>;
		//	<<< hats[i] >>>;
			feats << hats[i]$float;
	}
//	<<< "Done extracting">>>;
	return feats;
}

fun void stop() {
	1 => isGo;
}

//end of class
}