// Plik CH4ExamplesActivity.java, część 1. z 7
package ch4.example2.proArduino;
  import java.io.FileDescriptor;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.IOException;
  // komponenty urządzenia Android
  import android.app.Activity;
  import android.app.PendingIntent;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.os.Bundle;
  import android.os.ParcelFileDescriptor;
  import android.util.Log;
  import com.android.future.usb.*;
  import android.os.Handler;  // nowy
  import android.os.Message; // nowy
  // komponenty interfejsu użytkownika 
  import android.view.View;
  import android.widget.Button; // nowy
import android.widget.EditText; // nowy
    
// Plik CH4ExamplesActivity.java, część 2. z 7

/////////////////////////////////////////
// początek sekcji Frame work
/////////////////////////////////////////

public class CH4Examples2Activity extends Activity implements Runnable {  // nowy
   // deklaracje wejścia i wyjścia ADK	
   UsbAccessory ARDUINO_ADK; // obiekt akcesorium
   ParcelFileDescriptor ADKstreamObj;
   FileInputStream ReciveFromADK;
   FileOutputStream SendtoADK;
   // konfiguracja i logowanie 
   private static final String ACTION_USB_PERMISSION = "MEGA_ADK.USB_PERMISSION";
   private static final String TAG = "MEGA ADK"; // tag debugujący do logu
   private UsbManager UsbManagerOBJ;
   private PendingIntent Needed_Permission;
   private boolean IsPermissionNeeded;
   // komponenty interfejsu uzytkownika 
   private Button buttonSend;   // nowy
   private Button ScreenClear;  // nowy
   private EditText DataFromArduino;  // nowy
   private EditText outgoingData ;  // nowy
       
// Plik CH4ExamplesActivity.java, część 3. z 7

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setupAccessory();
   setContentView(R.layout.main);
   registerUIobjects();
}// koniec onCreate	
@Override
public void onDestroy() {
   unregisterReceiver(ADKReceiver);
   super.onDestroy();
}// koniec onDestroy

@Override
public void onPause() {
   super.onPause();
   closeAccessory();
} // koniec onPause()  
@Override
public void onResume() {
   super.onResume();
    if (ReciveFromADK != null && SendtoADK != null) {
      return;
     } // koniec if (ReciveFromADK != ...
   UsbAccessory[] accessories = UsbManagerOBJ.getAccessoryList();
   UsbAccessory accessory = (accessories == null ? null : accessories[0]);
    if (accessory != null) {
     if (UsbManagerOBJ.hasPermission(accessory)) {
       openAccessory(accessory);
     } // koniec if (UsbManagerOBJ.hasPermission(accessory))
     else {
      synchronized (ADKReceiver) {
       if (IsPermissionNeeded == true) {
         UsbManagerOBJ.requestPermission(accessory, Needed_Permission);
         IsPermissionNeeded = false;
       } // koniec if (IsPermissionNeeded == true) 
      } // koniec synchronized ADKReceiverr)
     } // koniec else for  if (UsbManagerOBJ...
    }// koniec if (accessory != null)
    else {
      Log.d(TAG, "zmienna accessory ma wartosc null");		
    } // koniec else if (accessory != null)
} // koniec onResume()

// Plik CH4ExamplesActivity.java, część 4. z 7

private BroadcastReceiver ADKReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
     if (ACTION_USB_PERMISSION.equals(action) == true) {
       synchronized (this) {
        UsbAccessory accessory = UsbManager.getAccessory(intent);
         if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
           openAccessory(accessory);
         }
         else {
           Log.d(TAG, "brak uprawnien dla akcesorium "+ accessory);
         }
        IsPermissionNeeded = true;
       } // koniec  synchronized (this)
     }  // koniec if (ACTION_USB_PERMISSION.equals...
     else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
       UsbAccessory accessory = UsbManager.getAccessory(intent);
        if (accessory != null && accessory.equals(ARDUINO_ADK)) {
          closeAccessory();
        }
     } // koniec else if (UsbManager...
 } // koniec void onReceive(Context contex ...
}; // koniec private BroadcastReceiver..
@Override
public Object onRetainNonConfigurationInstance() {
   if (ARDUINO_ADK != null) {
     return ARDUINO_ADK;
   }
   else {
      return super.onRetainNonConfigurationInstance();
   }
} // koniec public Object  onRetainNon*...

// Plik CH4ExamplesActivity.java, część 5. z 7

private void openAccessory(UsbAccessory accessory) {
   ADKstreamObj = UsbManagerOBJ.openAccessory(accessory);
    if (ADKstreamObj != null) {
      ARDUINO_ADK = accessory;
      FileDescriptor fd = ADKstreamObj.getFileDescriptor();
      ReciveFromADK = new FileInputStream(fd);
      SendtoADK = new FileOutputStream(fd);
      Thread ADKreadthread = new Thread(null, this, "ADK_Read_Thread"); // nowy
      ADKreadthread.start();                   // nowy
      Log.d(TAG, "accessory opened");
    } // koniec if (ADKstreamObj
    else {
      Log.d(TAG, "błąd otwarcia akcesorium");
    }
} // koniec void openAccessory...

private void setupAccessory() {
   UsbManagerOBJ = UsbManager.getInstance(this);
   Needed_Permission = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
   IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
   filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
   registerReceiver(ADKReceiver, filter);
    if (getLastNonConfigurationInstance() != null) {
    	ARDUINO_ADK = (UsbAccessory) getLastNonConfigurationInstance();
      openAccessory(ARDUINO_ADK);
   }
} // koniec private void setupAccessory() 

private void closeAccessory() {
   try {
    if (ADKstreamObj != null) {
      ADKstreamObj.close();
    }
   }// koniec try 
   catch (IOException e) {
	   Log.e(TAG, "IO Exception", e);
   } 
   finally {
     ADKstreamObj = null;
     ARDUINO_ADK = null;
   } // koniec wszystkich try catch finally
}// koniec private void closeAccessory()

// Plik CH4ExamplesActivity.java, część 6. z 7

private void write(byte[] send){
   if (SendtoADK != null) {
      try {
        SendtoADK.write(send);
      }
      catch (IOException e){ 
        Log.e(TAG, "błąd zapisu", e);
      }
   }// koniec if (SendtoADK != null)	
}// koniec private void write..

// nowy kod
public void run() {
int RevivedBytes  = 0;
 while (true) { // pętla działa cały czas    
  byte[] buffer = new byte[80]; // maksymalna wielkość to 16384, ale spowalnia program                                      
  try {
     RevivedBytes = ReciveFromADK.read(buffer);
  } 
  catch (IOException e) {
     Log.e(TAG, "Błąd odczytu", e);
     break; 
  }
  if  (RevivedBytes >= 1 ) {
     Message MakeBufferTransferable = Message.obtain(IncomingDataHandler);
     MakeBufferTransferable.obj = new BufferData( buffer ,RevivedBytes);
     IncomingDataHandler.sendMessage(MakeBufferTransferable);
  }	
 }// koniec while 
}// koniec public void run()

/////////////////////////////////////////
// koniec sekcji Frame work
/////////////////////////////////////////

////////////////////////////////////////////////
//
// poniższy kod jest zmieniony w porównaniu z plikiem CH4ExamplesActivity.java
//
////////////////////////////////////////////////

private void registerUIobjects(){
    buttonSend = (Button) findViewById(R.id.sendbutton); // funkcja wywoływana w innym przypadku
                                                         // niezaimplementowanym
    ScreenClear = (Button) findViewById(R.id.clear);     // w tym programie
    DataFromArduino = (EditText)findViewById(R.id.incomingData);
    outgoingData =  (EditText)findViewById(R.id.outgoingData);
 } // koniec registerUIobjects

Handler IncomingDataHandler = new Handler() {
 @Override
 public void handleMessage(Message msg) {
 BufferData IncomingBuffer = (BufferData) msg.obj;
 // od tego miejsca dane są dostępne do przetwarzania
   String str = new String(IncomingBuffer.getBuffer());
   DataFromArduino.append(str);
 } // koniec handleMessage(Message msg)
}; // koniec Handler IncomingDataHandler = new Handler()

 public void clearScreen (View v) {
     DataFromArduino.setText(null);
 } // koniec clearScreen (View v)
 public void SendData(View v) {
    String convert = outgoingData.getText().toString(); 
    byte[] BytestoSend = convert .getBytes(); 
    write(BytestoSend); // wysłanie bufora do ADK
    outgoingData.setText(null);
 } // koniec void SendData(View v)
} // koniec class CH4ExamplesActivity