
import com.phidgets.*;
import com.phidgets.event.*;

public class TextLCDExample
{
	TextLCDPhidget lcd;

	public TextLCDExample() throws Exception {

		System.out.println(Phidget.getLibraryVersion());

		//create and set handlers
		lcd = new TextLCDPhidget();				

		lcd.addAttachListener(new AttachListener() {
			public void attached(AttachEvent ae) {
				System.out.println("attachment of " + ae);
			}
		});
		lcd.addDetachListener(new DetachListener() {
			public void detached(DetachEvent ae) {
				System.out.println("detachment of " + ae);
			}
		});
		lcd.addErrorListener(new ErrorListener() {

			public void error(ErrorEvent ee) {
				System.out.println("error event for " + ee);
			}
		});
		
		//open, attach, and print info
		lcd.openAny();				
		System.out.println("waiting for TextLCD attachment...");
		lcd.waitForAttachment();

		//Print device info
		System.out.println("Serial: " + lcd.getSerialNumber());
		System.out.println("rows: " + lcd.getRowCount());
		System.out.println("columns: " + lcd.getColumnCount());
		
		//Use customcharacter feature
		lcd.setCustomCharacter(8, 0x0, 0xF8000);
		lcd.setCustomCharacter(9, 0x0, 0xFFC00);
		lcd.setCustomCharacter(10, 0x0, 0xFFFE0);
		lcd.setCustomCharacter(11, 0x0, 0xFFFFF);
		lcd.setCustomCharacter(12, 0xF8000, 0xFFFFF);
		lcd.setCustomCharacter(13, 0xFFC00, 0xFFFFF);
		lcd.setCustomCharacter(14, 0xFFFE0, 0xFFFFF);
		lcd.setCustomCharacter(15, 0xFFFFF, 0xFFFFF);

		lcd.setDisplayString(1, "\010\011\012\013\014\015\016\017"); //Note: representation is octal
	}


	public void stop() throws Exception{
		System.out.print("closing...");
		
		clear();
		off();
		
		lcd.close();
		lcd = null;
		
		System.out.println(" ok");
	}
	
	public void display(String s) throws Exception {
		StringBuffer buf = new StringBuffer();
		
		int min = lcd.getColumnCount();
		if(s.length() < min)
			min = s.length();
		
		for(int i = 0; i < min; i++){
			buf.append(s.charAt(i));
			lcd.setDisplayString(0, buf.toString());
			Thread.sleep(100);
		}
	}
	
	public void clear() throws Exception {
		lcd.setDisplayString(0, "");
		lcd.setDisplayString(1, "");
	}
	
	public void on() throws Exception {
		lcd.setBacklight(true);
	}
	
	public void off() throws Exception {
		lcd.setBacklight(false);
	}
	
	public static final void main(String args[]) throws Exception {

		TextLCDExample lcd = new TextLCDExample();

		//Turn light on
		lcd.on();
		Thread.sleep(5000);
		
		//Display some text
		lcd.display("Hello, CS401!");
		Thread.sleep(1000);
		
		//Flash the display
		lcd.off();
		Thread.sleep(1000);
		lcd.on();
		Thread.sleep(1000);		

		//close and clear
		lcd.stop();
	}
}
