import jp.co.denso.fa.jcaosql.*;

public class Main {

	CaoSQLEngine eng = null;
	CaoSQLController ctrl = null;
	CaoSQLItem item = null;

	public void init() throws Exception {
		eng = CaoSQLEngine.createInstance();
		sleep(1000);
		if (eng.count() < 1) {
			throw new Exception("there is no controller settings.");
		}
		String[] ctrl_names = eng.getControllerNames();
		ctrl = eng.Controller(ctrl_names[0]);

		ctrl.attachListener(
			new CaoSQLControllerListener() {
				public void onChangeItem(CaoSQLItem pIitem) {
					System.out.println("OnChangeItem: raised event");
					pIitem.release();
				}
				public void onChangeState(long state) {
					System.out.println("OnChangeState: raised event");
					System.out.println(state);
				}
			}
		);
		if (ctrl.getCount() < 1) {
			throw new Exception("there is no item settings.");
		}
		String[] item_names = ctrl.getItemNames();
		item = ctrl.Item(item_names[0]);

	}

	public void dispose() {
		if (item != null) item.release();
		if (ctrl != null) {
			ctrl.detachListener();
			ctrl.release();
		}
		if (eng != null) eng.release();
	}

	public void sendEvent() throws Exception {
		System.out.println("call event...");
		ctrl.start();
		Integer value = new Integer(555);
		item.putValue(value);
		sleep(1000);
		ctrl.stop();
	}

	public static void main(String[] args) {

		Main sample = new Main();

		try {
			sample.init();

			sample.sendEvent();
			// wait for event.
			sample.sleep(3000);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			sample.dispose();
		}
	}

	private synchronized void sleep(int time) {
		try {
			wait(time);
		} catch(InterruptedException e) {
		}
	}
}