package ubaa.net.usbwebsocket;


// https://github.com/mik3y/usb-serial-for-android

import android.util.Log;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbDeviceConnection;

import java.util.List;
import java.io.IOException;

public class Arduino
{

    MainActivity app;
    UsbSerialPort port;

    public Arduino( MainActivity app )
    {
        this.app = app;
        app.ArduinoLog( "waiting for Arduino" );
        waitingForConnection();
    }


    public void waitingForConnection()
    {
        UsbManager manager = (UsbManager)app.getSystemService(Context.USB_SERVICE);
        List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
        if (availableDrivers.isEmpty()) {
            app.ArduinoLog( "no USB manager found" );
            return;
        }

        // Open a connection to the first available driver.
        UsbSerialDriver driver = availableDrivers.get(0);
        UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
        if (connection == null) {
            app.ArduinoLog( "no USB driver found" );
            return;
        }

        List<UsbSerialPort> ports = driver.getPorts();
        port = ports.get(0);
        try {
            port.open(connection);
            port.setParameters( 9600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            app.ArduinoLog( "connected to Arduino" );
            // byte buffer[] = new byte[16];
            // int numBytesRead = port.read(buffer, 1000);
            // Log.d( "[Arduino]", "Read " + numBytesRead + " bytes.");
        } catch (IOException e) {}
    }


    public void close()
    {
        try {
            if (port != null) port.close();
            port = null;
        } catch (IOException e) {
            // Deal with error.
        }
        app.ArduinoLog( "disconnected from Arduino" );
    }
}
