package jGPIO.I2C;

import jGPIO.jGPIO;
import anywheresoftware.b4a.*;

@BA.Events(values = {
		"log(msg as string)"
})
@BA.ShortName("i2cbus")

/**
 * Source : https://groups.google.com/forum/#!topic/jna-users/9X0bu4tv7Fk
 * @author rdkartono
 *
 */
public class I2C_BUS {
	private final int O_RDWR = 0x00000002;
	
	private boolean opened = false;
	private String i2c_name = "";
	private int i2c_handle = -1;
	private I2C_BUS_Event javaevent;
	
	
	private BA ba;
	private String event;
	private boolean need_log_event = false;
	// disediain buat B4X
	public I2C_BUS() {	
	}
	
	/**
	 * Initialize I2C Bus
	 * @param event Eventname
	 * @param busname bus name, for example /dev/i2c-1
	 */
	public void Initialize(BA ba, String event, String busname) {
		this.ba = ba;
		this.event = event;
		this.i2c_name = busname;
		check_b4x_event();
	}
	
	private void check_b4x_event() {
		if (ba!=null) {
			if (event!=null) {
				if (!event.isEmpty()) {
					need_log_event = ba.subExists(event+"_log");
				}
			}
		}
	}
	
	/**
	 * Open I2C Bus using I2C Name
	 * @param i2c_name : i2c name, example : /dev/i2c-1
	 */
	@BA.Hide
	public I2C_BUS(String i2c_name) {
		if (i2c_name.isEmpty()) 
			return;
		else
			this.i2c_name = i2c_name;
	}
	
	@BA.Hide
	public void SetJavaEvent(I2C_BUS_Event ev) {
		javaevent = ev;
	}
	
	/**
	 * Open Bus
	 * @return true if opened
	 */
	public boolean Open_Bus() {
		opened = false;
		if (i2c_name.isEmpty()) return false;
		
		i2c_handle = jGPIO.libC.open(i2c_name, O_RDWR);
		if (i2c_handle<0) {
			raise_log("Open_Bus failed");
			opened = false;			
		}
		else {
			raise_log("Open_Bus success");
			opened = true;
		}
			
		return opened;
		
	}
	
	/**
	 * Close Bus
	 */
	public void Close_Bus() {
		if (i2c_handle >= 0) {
			jGPIO.libC.close(i2c_handle);
			i2c_handle = -1;
		}
		opened = false;
		raise_log("Bus Closed");
	}
	
	/**
	 * check if I2C bus is opened
	 * @return true if opened
	 */
	public boolean IsOpened() {
		return opened;
	}
	
	/**
	 * Get I2C Open handle
	 * @return -1 if closed
	 */
	public int I2C_Handle() {
		return i2c_handle;
	}
	
	private void raise_log(String msg) {
		if (javaevent!=null) {
			javaevent.Log(msg);
		}
		if (need_log_event) ba.raiseEventFromDifferentThread(I2C_BUS.this, null, 0, event+"_log", false, new Object[] {msg});
	}
}
