Android Open Source - MultiWork B T Single Synch Transfer






From Project

Back to project page MultiWork.

License

The source code is released under:

Copyright (c) 2013, Torti Andr?s Fernando All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions a...

If you think the Android project MultiWork listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.bluetoothutils.andres;
//  www  .  java  2 s .co  m
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

public class BTSingleSynchTransfer {
  
  private final static boolean DEBUG = true;
  /** Datos de transmicion */
  private static final byte startByte = 'S';
  private static final byte ACK = 0x06;
  
  private OutputStream mOutputStream;
  private InputStream mInputStream;
  
  /** TimeOut de la espera del byte de ACK en nS (1 segundo por defecto) */
  private long timeOut = 1000000000;
  
  private boolean isBTSending = false;
  private boolean isNewDataToSend = false;
  
  private byte[] dataToSend;
  private byte dataTypeToSend;
  
  //private Buffer mFifo = BufferUtils.synchronizedBuffer(new CircularFifoBuffer(8));

  /**
   * Constructor
   * @param outS OutputStream usado para enviar los datos
   * @param inS InputStream usado para recibir los datos
   */
  public BTSingleSynchTransfer(final OutputStream outS, final InputStream inS) {
    mOutputStream = outS;
    mInputStream = inS;
  }
  
  /**
   * Inicia el Thread que enviar los datos por Bluetooth, debe llamarse luego de haberse creado el objeto
   */
  public void start (){
    mBTThread.start();
  }
  
  /**
   * Configura el timeout de la espera de un ACK en mS (por defecto 1 segundo)
   * @param time tiempo en mS
   */
  public void setTimeout (final int time){
    timeOut = time*1000000;
  }
  
  /**
   * Obtiene el timeout de la espera de un ACK en mS
   * @return tiempo en mS
   */
  public int getTimeOut (){
    return (int)(timeOut/1000000);
  }
  
  /**
   * 
   * @param data bytes a enviar
   * @param dataType tipo de dato a enviar
   */
  public void btSendDataWithSync (final byte[] data, final byte dataType){
    dataToSend = data;        // Datos
    dataTypeToSend = dataType;    // Tipo de dato
    isNewDataToSend = true;      // Nuevos datos para enviar
  }
  
    // Thread que ejecuta al Runnable
  private final Thread mBTThread = new Thread(){
      @Override
        public void run() {
        if(DEBUG) Log.i("BTThread", "Thread Running");
        while(true){
          if(mInputStream != null && mOutputStream != null && !isBTSending && isNewDataToSend){
            isNewDataToSend = false;
            mBTSendRunnable.run();
          }
          try { Thread.sleep(10); }
          catch (InterruptedException e) { e.printStackTrace(); }
        }
        }
    };
    
  // Runnable que enva los datos por Bluetooth
  private final Runnable mBTSendRunnable = new Runnable() {
        public void run() {
          isBTSending = true;
          
          if(DEBUG) Log.i("BTSendBrazo", "Sending Start...");
      // Envo el Byte de Start
      try { mOutputStream.write(startByte); }
      catch (IOException e2) { e2.printStackTrace(); }
      
      if(DEBUG) Log.i("BTSendBrazo", "Waiting ACK...");
      // Espero por un ACK
      try {
        int data = -1;
        long startTime = System.nanoTime();
        do{
          if(mInputStream.available() > 0) data = mInputStream.read();
          // TimeOut
          if((System.nanoTime() - startTime) >= timeOut){
            if(DEBUG) Log.i("BTSendBrazo", "TimeOut");
            isBTSending = false;
            return;
          }
        }while(data != ACK); 
      }
      catch (IOException e2) { e2.printStackTrace(); }
      
      if(DEBUG) Log.i("BTSendBrazo", "Sending data type...");
      // Envo el tipo de dato que voy a enviar
      try { mOutputStream.write(dataTypeToSend); }
      catch (IOException e2) { e2.printStackTrace(); }
      
      // Envo los datos
      btSendByteWithSync(dataToSend);
      isBTSending = false;
        }
  };

  /**
   * Enva una cadena de bytes y espera en caso de que ser pida una espera antes de seguir enviando
   * @param dataToSend
   */
  private synchronized void btSendByteWithSync (final byte[] dataToSend){
    
    long st = System.nanoTime();
    for(int n = 0; n < dataToSend.length; ++n){
      
      if(DEBUG) Log.i("BTSendBrazo", "Waiting ACK 2...");
      
      // Espero por un ACK
      try {
        int data = -1;
        long startTime = System.nanoTime();
        do{
          if(mInputStream.available() > 0) data = mInputStream.read();
          // 1 segundo de time out
          if((System.nanoTime() - startTime) >= timeOut){
            if(DEBUG) Log.i("BTSendBrazo", "TimeOut 2");
            return;
          }
        }while(data != ACK); 
      }
      catch (IOException e2) { e2.printStackTrace(); }
      
      try { mOutputStream.write(dataToSend[n]); }
      catch (IOException e) { e.printStackTrace(); }
    }
    long sp = System.nanoTime();
    if(DEBUG) Log.i("BTSendBrazo", "Time to transfer " + ((sp-st)/1000000) + "mS");
  }
}




Java Source Code List

com.bluetoothutils.andres.BTSingleSynchTransfer.java
com.bluetoothutils.andres.BluetoothHelper.java
com.bluetoothutils.andres.DeviceScanner.java
com.bluetoothutils.andres.OnBluetoothConnected.java
com.bluetoothutils.andres.OnDeviceSelected.java
com.bluetoothutils.andres.OnNewBluetoothDataReceived.java
com.frecuencimeter.andres.FrecView.java
com.frecuencimeter.andres.Frecuencia.java
com.multiwork.andres.ApplicationContext.java
com.multiwork.andres.LCView.java
com.multiwork.andres.MainMenu.java
com.multiwork.andres.MainPrefs.java
com.multiwork.andres.MenuListAdapter.java
com.protocolanalyzer.andres.AnalyzerExpandableAdapter.java
com.protocolanalyzer.andres.CRC16.java
com.protocolanalyzer.andres.LogicAnalizerPrefsFragment.java
com.protocolanalyzer.andres.LogicAnalizerPrefs.java
com.protocolanalyzer.andres.LogicAnalyzerActivity.java
com.protocolanalyzer.andres.LogicAnalyzerChartFragment.java
com.protocolanalyzer.andres.LogicAnalyzerListFragment.java
com.protocolanalyzer.andres.OnActionBarClickListener.java
com.protocolanalyzer.andres.OnDataClearedListener.java
com.protocolanalyzer.andres.OnDataDecodedListener.java
com.roboticarm.andres.BrazoRobot.java
com.roboticarm.andres.JoystickView.java
com.roboticarm.andres.Joystick.java
com.tjerkw.slideexpandable.library.AbstractSlideExpandableListAdapter.java
com.tjerkw.slideexpandable.library.ActionSlideExpandableListView.java
com.tjerkw.slideexpandable.library.ExpandCollapseAnimation.java
com.tjerkw.slideexpandable.library.SlideExpandableListAdapter.java
com.tjerkw.slideexpandable.library.SlideExpandableListView.java
com.tjerkw.slideexpandable.library.WrapperListAdapterImpl.java
com.utils.andres.ConflictChecker.java
com.utils.andres.Dependency.java
com.utils.andres.Pair.java