├── GetSensorData20.zip └── GetSensorData20 ├── GetSensorData.iml ├── GetSensorData21.apk ├── GetSensorData21b.apk ├── GetSensorData21c.apk ├── app ├── build.gradle ├── hs_err_pid4332.log ├── hs_err_pid4776.log ├── hs_err_pid5580.log ├── hs_err_pid6684.log ├── hs_err_pid8528.log ├── lint.xml ├── replay_pid4332.log ├── replay_pid4776.log ├── replay_pid5580.log ├── replay_pid6684.log ├── replay_pid8528.log └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── es │ │ └── csic │ │ └── getsensordata │ │ ├── LPMSB_IMU.java │ │ ├── MIMU22BT.java │ │ ├── MTi_XSens_IMU.java │ │ ├── MainActivity.java │ │ ├── Microphone.java │ │ ├── MyApplication.java │ │ ├── PantallaPreferencias.java │ │ └── RFIDM220Reader.java │ └── res │ ├── drawable-hdpi │ ├── ic_action_search.png │ └── ic_launcher.png │ ├── drawable-ldpi │ └── ic_launcher.png │ ├── drawable-mdpi │ ├── action_settings_black.png │ ├── ic_action_search.png │ └── ic_launcher.png │ ├── drawable-xhdpi │ ├── ic_action_search.png │ └── ic_launcher.png │ ├── layout │ └── activity_main.xml │ ├── menu │ └── activity_main.xml │ ├── values-v11 │ └── styles.xml │ ├── values-v14 │ └── styles.xml │ ├── values │ ├── integers.xml │ ├── opciones_delay.xml │ ├── strings.xml │ └── styles.xml │ └── xml │ └── pantalla_preferencias.xml ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── import-summary.txt └── settings.gradle /GetSensorData20.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20.zip -------------------------------------------------------------------------------- /GetSensorData20/GetSensorData.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /GetSensorData20/GetSensorData21.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/GetSensorData21.apk -------------------------------------------------------------------------------- /GetSensorData20/GetSensorData21b.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/GetSensorData21b.apk -------------------------------------------------------------------------------- /GetSensorData20/GetSensorData21c.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/GetSensorData21c.apk -------------------------------------------------------------------------------- /GetSensorData20/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 24 5 | buildToolsVersion '28.0.3' //26.0.2 25.0.0 6 | 7 | defaultConfig { 8 | applicationId "es.csic.getsensordata" 9 | minSdkVersion 18 10 | targetSdkVersion 24 11 | } 12 | 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | compile fileTree(dir: 'libs', include: ['*.jar']) 23 | 24 | //compile 'com.android.support:appcompat-v7:25.4.0' 25 | //compile 'com.android.support:appcompat-v7:23.0.1' 26 | compile 'com.android.support:appcompat-v7:24.2.1' 27 | 28 | compile 'com.estimote:sdk:0.13.0@aar' 29 | // compile 'com.estimote:sdk:1.0.3@aar' 30 | } 31 | -------------------------------------------------------------------------------- /GetSensorData20/app/hs_err_pid4332.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/hs_err_pid4332.log -------------------------------------------------------------------------------- /GetSensorData20/app/hs_err_pid4776.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/hs_err_pid4776.log -------------------------------------------------------------------------------- /GetSensorData20/app/hs_err_pid5580.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/hs_err_pid5580.log -------------------------------------------------------------------------------- /GetSensorData20/app/hs_err_pid6684.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/hs_err_pid6684.log -------------------------------------------------------------------------------- /GetSensorData20/app/hs_err_pid8528.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/hs_err_pid8528.log -------------------------------------------------------------------------------- /GetSensorData20/app/lint.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 23 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/java/es/csic/getsensordata/LPMSB_IMU.java: -------------------------------------------------------------------------------- 1 | /*********************************************************************** 2 | ** Copyright (C) 2012 LP-Research 3 | ** All rights reserved. 4 | ** Contact: LP-Research (klaus@lp-research.com) 5 | ** 6 | ** Redistribution and use in source and binary forms, with 7 | ** or without modification, are permitted provided that the 8 | ** following conditions are met: 9 | ** 10 | ** Redistributions of source code must retain the above copyright 11 | ** notice, this list of conditions and the following disclaimer. 12 | ** Redistributions in binary form must reproduce the above copyright 13 | ** notice, this list of conditions and the following disclaimer in 14 | ** the documentation and/or other materials provided with the 15 | ** distribution. 16 | ** 17 | ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 20 | ** FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | ***********************************************************************/ 29 | 30 | package es.csic.getsensordata; 31 | 32 | import java.io.BufferedOutputStream; 33 | import java.io.IOException; 34 | import java.io.InputStream; 35 | import java.io.OutputStream; 36 | import java.lang.reflect.Method; 37 | import java.nio.ByteBuffer; 38 | import java.util.UUID; 39 | 40 | import android.bluetooth.BluetoothAdapter; 41 | import android.bluetooth.BluetoothDevice; 42 | import android.bluetooth.BluetoothSocket; 43 | import android.os.Bundle; 44 | import android.os.Handler; 45 | import android.os.Message; 46 | import android.os.ParcelUuid; 47 | import android.util.Log; 48 | 49 | /** 50 | * Thread class to retrieve data from LPMS-B (and eventually control configuration of LPMS-B) 51 | * based on the code available in: http://www.lp-research.com/support/ 52 | * 53 | * To get access to the LPMS IMU, it is necessary to: 54 | * 1) Get the Bluetooth adapter: 55 | * mAdapter = BluetoothAdapter.getDefaultAdapter(); 56 | * 2) Create the object (according to the desired communication) 57 | * mLpmsB = new LPMSB_IMU(mAdapter,MacAddress,handlerMTi); //Bluetooth ID MacAddress (in our case "00:06:66:45:D2:83") 58 | * 3) Connect a socket to the Bluetooth RFID reader device 59 | mLpmsB.connect(true, true, true, false, false,true); 60 | * 4) Start reading the LPMS IMU (put the reader in Measurement mode): 61 | mLpmsB.startreading(); 62 | Now the UI principal thread receives messages in the handlerLPMS. The messages are: 63 | Connected: 64 | "MensajeType"->"Connect" 65 | "ReaderName"->"LPMS_IMU" 66 | "Connected"->true 67 | or 68 | Data received: 69 | "MensajeType"->"IMU_Data" 70 | "ReaderName"->"LPMS_IMU" 71 | "Accelerations_x"-> float (m/s^2) 72 | "Accelerations_y"-> float (m/s^2) 73 | "Accelerations_z"-> float (m/s^2) 74 | "TurnRates_x" -> float (rad/s) 75 | "TurnRates_y" -> float (rad/s) 76 | "TurnRates_z" -> float (rad/s) 77 | "MagneticFields_x" -> float (mT) 78 | "MagneticFields_y" -> float (mT) 79 | "MagneticFields_z" -> float (mT) 80 | "Euler_Roll" -> float (�) 81 | "Euler_Pitch" -> float (�) 82 | "Euler_Yaw" -> float (�) 83 | "Temperature" -> float (0.0f) not used for the momment 84 | "Pressure" -> Atmospheric Pressure (mbar) 85 | "Counter" -> short (package number) 86 | "Time" -> long (System time in ns) 87 | "timeStamp" -> IMU time (s) 88 | 89 | * 5) When you do not need the LPMS IMU anymore stop and disconnect it: 90 | mLpmsB.stopreading(); // llamada en onPause(); 91 | mLpmsB.disconnect(); // llamada en onDestroy(); 92 | 93 | */ 94 | public class LPMSB_IMU extends Thread { 95 | // Log tag 96 | final String TAG = "LpmsB"; 97 | 98 | // Standard Bluetooth serial protocol UUID 99 | final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 100 | 101 | // LpBus identifiers 102 | final int PACKET_ADDRESS0 = 0; 103 | final int PACKET_ADDRESS1 = 1; 104 | final int PACKET_FUNCTION0 = 2; 105 | final int PACKET_FUNCTION1 = 3; 106 | final int PACKET_RAW_DATA = 4; 107 | final int PACKET_LRC_CHECK0 = 5; 108 | final int PACKET_LRC_CHECK1 = 6; 109 | final int PACKET_END = 7; 110 | final int PACKET_LENGTH0 = 8; 111 | final int PACKET_LENGTH1 = 9; 112 | 113 | // LPMS-B function registers (most important ones only, currently only LPMS_GET_SENSOR_DATA is used) 114 | final int LPMS_ACK = 0; 115 | final int LPMS_NACK = 1; 116 | final int LPMS_GET_CONFIG = 4; 117 | final int LPMS_GET_STATUS = 5; 118 | final int LPMS_GOTO_COMMAND_MODE = 6; 119 | final int LPMS_GOTO_STREAM_MODE = 7; 120 | final int LPMS_GOTO_SLEEP_MODE = 8; 121 | final int LPMS_GET_SENSOR_DATA = 9; 122 | final int LPMS_SET_TRANSMIT_DATA = 10; 123 | final int LPMS_SET_STREAM_FREQ=11; 124 | final int LPMS_SET_GYR_RANGE=25; 125 | final int LPMS_SET_ACC_RANGE=31; 126 | final int LPMS_SET_MAG_RANGE=33; 127 | 128 | // State machine states. Currently no states are supported 129 | final int STATE_IDLE = 0; 130 | 131 | // Class members 132 | int rxState = PACKET_END; 133 | byte[] rxBuffer = new byte[512]; 134 | byte[] txBuffer = new byte[512]; 135 | byte[] rawTxData = new byte[1024]; 136 | byte[] rawRxBuffer = new byte[1024]; 137 | int currentAddress; 138 | int currentFunction; 139 | int currentLength; 140 | int rxIndex = 0; 141 | byte b = 0; 142 | int lrcCheck; 143 | boolean isConnected = false; 144 | boolean imposible_conectarme=false; 145 | int nBytes; 146 | int timeout; 147 | boolean waitForAck; 148 | boolean waitForData; 149 | int state; 150 | byte inBytes[] = new byte[2]; 151 | InputStream mInStream; 152 | OutputStream mOutStream; 153 | BluetoothSocket mSocket; 154 | BluetoothAdapter mAdapter; 155 | String mAddress; 156 | BluetoothDevice mDevice; 157 | LpmsBData mLpmsBData = new LpmsBData(); 158 | private BufferedOutputStream mBuffer; 159 | boolean isGetGyroscope = true; 160 | boolean isGetAcceleration = true; 161 | boolean isGetMagnetometer = true; 162 | boolean isGetQuaternion = true; 163 | boolean isGetEulerAngler = true; 164 | boolean isGetPressure = true; 165 | boolean isGetTemperature = true; 166 | boolean isGetLPMSTimeStamp = false; 167 | long time0,receivedMeassurements=0; 168 | private Handler handlerLPMSIMU; 169 | private String mName="LPMS_IMU"; 170 | private Thread thread_connect=null; 171 | public Thread thread_read=null; 172 | private long receivedBytes=0; 173 | String MAC_address_string; 174 | boolean en_thread_read=false; 175 | private UUID uuid; 176 | private Boolean uuid_obtained=false; 177 | 178 | //----------------------------Constructores-------------------------------- 179 | /** 180 | * Initializes the LPMS object 181 | * 182 | * @param adapter Bluetooth adapter 183 | */ 184 | LPMSB_IMU(BluetoothAdapter adapter) { 185 | mAdapter = adapter; 186 | mBuffer = null; 187 | handlerLPMSIMU=null; 188 | } 189 | 190 | /** 191 | * Initializes the LPMS object with BluetoothAdapter adapter and saves the info in the buffer specified in the buffer item 192 | * @param adapter Bluetooth adapter 193 | * @param buffer Data writing buffer 194 | */ 195 | LPMSB_IMU(BluetoothAdapter adapter, BufferedOutputStream buffer) { 196 | mAdapter = adapter; 197 | mBuffer = buffer; 198 | handlerLPMSIMU=null; 199 | } 200 | 201 | /** 202 | * Initializes the LPMS object sending the received information as messages to the specified handler 203 | * @param adapter Bluetooth adapter 204 | * @param handler Handler to receive the messages 205 | */ 206 | public LPMSB_IMU(BluetoothAdapter adapter, String MacAddress, Handler handler) { 207 | mAdapter = adapter; 208 | mBuffer = null; 209 | handlerLPMSIMU=handler; 210 | MAC_address_string=MacAddress; 211 | } 212 | /** 213 | * Initializes the LPMS object sending the received information as messages to the specified handler and saves in the specified file 214 | * 215 | * @param adapter Bluetooth adapter 216 | * @param handler Handler to receive the messages 217 | * @param buffer Data writing buffer 218 | */ 219 | public LPMSB_IMU(BluetoothAdapter adapter, Handler handler, BufferedOutputStream buffer) { 220 | mAdapter = adapter; 221 | mBuffer = buffer; 222 | handlerLPMSIMU=handler; 223 | } 224 | 225 | //--------------------connect--------------------------------------- 226 | public void connect(boolean isGetLPMSTimeStamp,boolean isGetGyroscope,boolean isGetAcceleration,boolean isGetMagnetometer, 227 | boolean isGetQuaternion,boolean isGetEulerAngler,boolean isGetPressure, boolean isGetTemperature) { 228 | 229 | this.isGetLPMSTimeStamp = isGetLPMSTimeStamp; 230 | this.isGetGyroscope = isGetGyroscope; 231 | this.isGetAcceleration = isGetAcceleration; 232 | this.isGetMagnetometer = isGetMagnetometer; 233 | this.isGetQuaternion = isGetQuaternion; 234 | this.isGetEulerAngler = isGetEulerAngler; 235 | this.isGetPressure = isGetPressure; 236 | this.isGetTemperature = isGetTemperature; 237 | 238 | // Starts new Connection thread 239 | thread_connect = new Thread(new ConnectThread()); 240 | if (thread_connect.isAlive()==false) 241 | { 242 | thread_connect.start(); 243 | } 244 | } 245 | 246 | //-------------Class to connect to LPMS-B----------------------------- 247 | public class ConnectThread implements Runnable { 248 | public void run() { 249 | Log.i(TAG, "[LpmsBConnectThread] Checking Bluetooth Adapter"); 250 | if (mAdapter == null) { 251 | Log.e(TAG, "[LpmsBConnectThread] Didn't find Bluetooth adapter"); 252 | return; 253 | } 254 | 255 | 256 | mAddress = MAC_address_string; 257 | Log.i(TAG, "[LpmsBConnectThread] Getting device with address " + mAddress); 258 | try { 259 | mDevice = mAdapter.getRemoteDevice(mAddress); 260 | } catch (IllegalArgumentException e) { 261 | Log.e(TAG, "[LpmsBConnectThread] Invalid Bluetooth address", e); 262 | return; 263 | } 264 | 265 | mSocket = null; 266 | Log.i(TAG, "[LpmsBConnectThread] Creating socket"); 267 | try { 268 | // Forma como lo hace Francisco, y funciona bien en la Tablet Xoom2: 269 | //mSocket = mDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); 270 | 271 | // De esta otra forma, que es como lo hace Antonio va igualmente bien con la tableta Xoom2 pero no bien con S3 272 | // if ( mDevice.getBondState()==BluetoothDevice.BOND_BONDED ) 273 | // { 274 | // ParcelUuid[] uuids=mDevice.getUuids(); 275 | // if (uuids.length>0) 276 | // { 277 | // uuid=uuids[0].getUuid(); 278 | // Log.i(TAG,"Object RFIDReader Created. Got UUID"); 279 | // uuid_obtained=true; 280 | // } 281 | // } 282 | // mSocket = mDevice.createRfcommSocketToServiceRecord(uuid); 283 | 284 | 285 | // Segun un foro: http://stackoverflow.com/questions/12274210/android-bluetooth-spp-with-galaxy-s3 286 | // Hay un bug de Android con el Galaxy S3 que dificulta la conexion de Bluetooth. 287 | // Lo resuelven asi: 288 | //device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress); 289 | //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 290 | //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); 291 | 292 | Method m = mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 293 | mSocket = (BluetoothSocket)m.invoke(mDevice, Integer.valueOf(1)); 294 | 295 | 296 | } catch (Exception e) { 297 | Log.e(TAG, "[LpmsBConnectThread] Socket create() failed", e); 298 | return; 299 | } 300 | 301 | Log.i(TAG, "[LpmsBConnectThread] Trying to connect.."); 302 | Integer intentos; 303 | 304 | try { 305 | mAdapter.cancelDiscovery(); // Lo recomiendan antes de llamar a "connect" 306 | mSocket.connect(); // Blocking function 307 | isConnected=true; // indica al hilo de lectura "threadread" que ya esta el socket conectado 308 | } catch (IOException e) { 309 | //Log.e(TAG, "[LpmsBConnectThread] Couldn't connect to device", e);// Saca el mensaje en texto rojo en "LogCat" 310 | Log.e(TAG, "[LpmsBConnectThread] Couldn't connect to device. "); 311 | //System.out.println("RFIDM220Reader ERROR: Socket NOT connected"); 312 | imposible_conectarme=true; 313 | return; 314 | } 315 | 316 | 317 | 318 | if (isConnected) 319 | { 320 | Log.i(TAG, "[LpmsBConnectThread] Connected!"); 321 | 322 | try { 323 | mInStream = mSocket.getInputStream(); 324 | mOutStream = mSocket.getOutputStream(); 325 | } catch (IOException e) { 326 | Log.e(TAG, "[LpmsBConnectThread] Streams not created", e); 327 | return; 328 | } 329 | 330 | configura(); // Una vez conectado, configura sensor LPMS poniendolo en modo comando 331 | 332 | if(mBuffer!=null){ 333 | try { 334 | time0=System.currentTimeMillis(); 335 | mBuffer.write(("Time (ms): " + time0 + "\nData counter, System Time (ns), -Acceleration[3] (g) , TurnRate[3] (rad/s), MagneticField[3] (mT), IMU time (s)\n").getBytes()); 336 | } catch (IOException e) { 337 | Log.e(TAG, "[LpmsBConnectThread] Failed file writing", e); 338 | } 339 | } 340 | if(handlerLPMSIMU!=null){ 341 | Message mensaje= new Message(); 342 | Bundle data = new Bundle(); 343 | data.putString("MensajeType","Connect"); 344 | data.putString("ReaderName",mName); 345 | data.putBoolean("Connected",true); 346 | mensaje.setData(data); 347 | handlerLPMSIMU.sendMessage(mensaje); 348 | } 349 | Log.i(TAG, "[LpmsBConnectThread] Concetado Socket Bluetooth"); 350 | } 351 | 352 | } 353 | } 354 | 355 | 356 | //---------------configura---------------------------------- 357 | void configura(){ 358 | 359 | // Asumo que ya hay conexion establecida 360 | int config=0x00000000; // 32 bits (el bit 0 es el de la derecha, y el 31 el de la izquierda) 361 | 362 | // Configurar LPMS 363 | Log.i(TAG, "Enviar comando: LPMS_GOTO_COMMAND_MODE"); 364 | sendData(0, LPMS_GOTO_COMMAND_MODE, 0); // modo comando 365 | try { 366 | Thread.sleep(400); 367 | } catch (InterruptedException e1) { 368 | // TODO Auto-generated catch block 369 | e1.printStackTrace(); 370 | } 371 | 372 | config=0x000007D0; // Poner rango Gyro: 2000�/s (4 bytes: 7D0 hex = 2000 dec) 373 | convertIntToTxbytes(config, 0, rawTxData); 374 | sendData(0, LPMS_SET_GYR_RANGE, 4); 375 | 376 | config=0x00000004; // Poner rango Acc: 4g (4 bytes: 4 hex = 4 dec) 377 | convertIntToTxbytes(config, 0, rawTxData); 378 | sendData(0, LPMS_SET_ACC_RANGE, 4); 379 | 380 | config=0x000000FA; // Poner rango Mag: 250uT (4 bytes: FA hex = 250 dec) 381 | convertIntToTxbytes(config, 0, rawTxData); 382 | sendData(0, LPMS_SET_MAG_RANGE, 4); 383 | 384 | config=0x00000064; // Poner Sampling Freq: 100 Hz (4 bytes: 64hex = 100 dec) 385 | convertIntToTxbytes(config, 0, rawTxData); 386 | sendData(0, LPMS_SET_MAG_RANGE, 4); 387 | 388 | Log.i(TAG, "Eviar comando: LPMS_SET_TRANSMIT_DATA"); 389 | config=0x00000000; // 32 bits (el bit 0 es el de la derecha, y el 31 el de la izquierda) 390 | if (isGetPressure) // pressure bit 9 391 | { config= config | 0x00000200; } 392 | if (isGetMagnetometer) // Mag bit 10 393 | { config= config | 0x00000400; } 394 | if (isGetAcceleration) // Acc bit 11 395 | { config= config | 0x00000800; } 396 | if (isGetGyroscope) // Gyro bit 12 397 | { config= config | 0x00001000; } 398 | if (isGetTemperature) // Temp bit 13 399 | { config= config | 0x00002000; } 400 | if (isGetEulerAngler) // Euler bit 17 401 | { config= config | 0x00020000; } 402 | if (isGetQuaternion) // Quat bit 18 403 | { config= config | 0x00040000; } 404 | convertIntToTxbytes(config, 0, rawTxData); 405 | sendData(0, LPMS_SET_TRANSMIT_DATA, 4); 406 | 407 | try { 408 | Thread.sleep(400); 409 | } catch (InterruptedException e1) { 410 | // TODO Auto-generated catch block 411 | e1.printStackTrace(); 412 | } 413 | 414 | 415 | } 416 | //---------------------startreading------------------------------ 417 | void startreading(){ 418 | thread_read = new Thread(new ClientReadThread()); 419 | if (thread_read.isAlive()==false) 420 | { 421 | // Starts new reader thread 422 | thread_read.start(); 423 | } 424 | } 425 | //---------------------ReadThread------------------------------ 426 | // Class to continuously read data from LPMS-B 427 | public class ClientReadThread implements Runnable { 428 | 429 | public void run() { 430 | // He quitado la llamada a este hilo ya que no parece muy util !!!!!!!!!!!!!!!!!!!! 431 | // Starts state machine thread 432 | // Thread t = new Thread(new ClientStateThread()); 433 | // t.start(); 434 | en_thread_read=true; 435 | 436 | //----- esperar a que se conecte------- 437 | while (isConnected==false && en_thread_read && imposible_conectarme==false) 438 | { 439 | Log.i(TAG,"=============Loop LPMS====================="); 440 | try { 441 | Thread.sleep(1000); 442 | } catch (InterruptedException e) { 443 | // TODO Auto-generated catch block 444 | e.printStackTrace(); 445 | } 446 | } // Esperar a que el socket (en "ConnectThred") se conecte de verdad 447 | if (isConnected) 448 | { 449 | //----- poner en modo medida continua------ 450 | Log.i(TAG, "Enviar comando: LPMS_GOTO_STREAM_MODE"); 451 | sendData(0, LPMS_GOTO_STREAM_MODE, 0); // modo stream 452 | 453 | try { 454 | Thread.sleep(200); 455 | } catch (InterruptedException e1) { 456 | // TODO Auto-generated catch block 457 | e1.printStackTrace(); 458 | } 459 | 460 | //----leer sin parar---------------********* 461 | while (en_thread_read) { 462 | try { 463 | nBytes = mInStream.read(rawRxBuffer); 464 | 465 | } catch (Exception e) { 466 | break; 467 | } 468 | receivedBytes+=nBytes; 469 | //Log.i("LPMS-B","Num bytes leidos: "+nBytes); 470 | // Parses received LpBus data 471 | parse(); //---PARSE----- 472 | } 473 | } 474 | } 475 | } 476 | 477 | 478 | //-------------------StopReading-------------------------- 479 | public void stopreading(){ 480 | en_thread_read=false; // para indicarle que salga del loop en el "thread_read" 481 | if (isConnected) // si conectado 482 | { 483 | try { 484 | if (thread_read.isAlive()) 485 | { 486 | thread_read.interrupt(); 487 | } 488 | Log.i(TAG,"StopReading: ReadingThread interrupted"); 489 | } catch (Exception e) {}; 490 | 491 | Log.i(TAG, "Enviar comando: LPMS_GOTO_SLEEP_MODE"); 492 | sendData(0, LPMS_GOTO_SLEEP_MODE, 0); // modo SLEEP 493 | //sendData(0, LPMS_GOTO_COMMAND_MODE, 0); // modo COMMAND 494 | try { 495 | Thread.sleep(200); 496 | } catch (InterruptedException e1) { 497 | // TODO Auto-generated catch block 498 | e1.printStackTrace(); 499 | } 500 | } 501 | else 502 | { 503 | System.out.println("LPMS IMU. Info: No stopping done since it was not connected nor reading"); 504 | } 505 | } 506 | 507 | //-------------Disconnect----------------------------- 508 | public void disconnect(){ 509 | if (isConnected) // si conectado 510 | { 511 | try { 512 | if (thread_connect.isAlive()) 513 | { 514 | thread_connect.interrupt(); 515 | } 516 | Log.i(TAG,"[LpmsBThread]disconnect: ConnectThread interrupted"); 517 | } catch (Exception e) {}; 518 | 519 | try { 520 | Log.i(TAG,"[LpmsBThread]INI:Socket closed on disconnetct method"); 521 | if (mSocket.isConnected()) 522 | { 523 | mSocket.close(); 524 | isConnected = false; 525 | } 526 | Log.i(TAG,"[LpmsBThread]END:Socket closed on disconnetct method"); 527 | } catch (IOException e) { 528 | // TODO Auto-generated catch block 529 | e.printStackTrace(); 530 | } 531 | } 532 | else 533 | { 534 | System.out.println("LPMSB IMU. Info: No disconnection done since it was not connected"); 535 | } 536 | } 537 | 538 | //--------------------------------------- 539 | public boolean isReading(){ 540 | if(thread_read==null) 541 | return false; 542 | else 543 | return thread_read.isAlive(); 544 | } 545 | //--------------------------------------- 546 | public long readedBytes(){ 547 | return receivedBytes; 548 | } 549 | 550 | //-------------------------No la uso-------------- 551 | /** 552 | * State machine thread class 553 | * 554 | */ 555 | private class ClientStateThread implements Runnable { 556 | public void run() { 557 | try { 558 | while (true) { 559 | if (waitForAck == false && waitForData == false) { 560 | switch (state) { 561 | case STATE_IDLE: 562 | break; 563 | } 564 | } else if (timeout > 100) { 565 | Log.e(TAG, "[LpmsBThread] Receive timeout"); 566 | timeout = 0; 567 | state = STATE_IDLE; 568 | waitForAck = false; 569 | waitForData = false; 570 | } else { 571 | Thread.sleep(10); 572 | ++timeout; 573 | } 574 | } 575 | } catch (Exception e) { 576 | Log.d(TAG, "[LpmsBThread] Connection interrupted"); 577 | isConnected = false; 578 | } 579 | } 580 | } 581 | 582 | //---------------------------parse (state machine)------------------------------------- 583 | /** 584 | * Parses LpBus raw data 585 | */ 586 | private void parse() { 587 | int lrcReceived = 0; 588 | 589 | for (int i=0; i0) 93 | { 94 | uuid=uuids[0].getUuid(); 95 | Log.i(TAG,"Object MIMU22BT Created. Got UUID"); 96 | uuid_obtained=true; 97 | } 98 | } 99 | } 100 | else 101 | { 102 | System.out.println("MIMU22BT Error: Bluetooth not activated"); 103 | } 104 | } 105 | 106 | 107 | //----------------Connect----------------- 108 | public void connect(){ 109 | if (uuid_obtained) 110 | { 111 | try { 112 | // Forma como lo hago yo, y que funciona perfectamente en el S3 113 | // mSocket = IMU_BluetoothDevice.createRfcommSocketToServiceRecord(uuid); 114 | mSocket = IMU_BluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); 115 | 116 | 117 | // Forma como lo hace Francisco para el LPMS-B: 118 | // mSocket = IMU_BluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); 119 | 120 | // Segun un foro: http://stackoverflow.com/questions/12274210/android-bluetooth-spp-with-galaxy-s3 121 | // Hay un bug de Android con el Galaxy S3 que dificulta la conexion de Bluetooth. 122 | // Lo resuelven asi: 123 | //device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress); 124 | //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 125 | //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); 126 | 127 | // Method m = IMU_BluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 128 | // mSocket = (BluetoothSocket)m.invoke(IMU_BluetoothDevice, Integer.valueOf(1)); 129 | 130 | System.out.println("MIMU22BT OK: Socket created"); 131 | } catch (Exception e1) { 132 | // TODO Auto-generated catch block 133 | e1.printStackTrace(); 134 | } 135 | ConnectThread = new Thread(new Runnable() { 136 | public void run() 137 | { 138 | try { 139 | // Block until server connection accepted. 140 | bluetooth.cancelDiscovery(); // Lo recomiendan antes de llamar a "connect" 141 | mSocket.connect(); // Blocking function 142 | socket_connected=true; 143 | System.out.println("MIMU22BT OK: Socket connected"); 144 | // Enviar notificacion al Handler encargado de pintar en UI 145 | Message mensaje= new Message(); 146 | Bundle data = new Bundle(); 147 | data.putString("MensajeType","Connect"); 148 | data.putString("ReaderName",IMU_bluetoothName); 149 | data.putBoolean("Connected",true); 150 | mensaje.setData(data); 151 | handlerIMU.sendMessage(mensaje); 152 | } catch (IOException e) { 153 | //System.out.println("MIMU22BT ERROR: Socket NOT connected"); 154 | //Log.e(TAG, "ERROR: Socket NOT connected", e); // Saca el mensaje en texto rojo en "LogCat" 155 | Log.e(TAG, "ERROR: Socket NOT connected"); 156 | imposible_conectarme=true; 157 | } 158 | } 159 | }); 160 | if (ConnectThread.isAlive()==false) 161 | { 162 | ConnectThread.setName("Hilo ConnectThread - MIMU22BT"); 163 | ConnectThread.start(); 164 | } 165 | } 166 | else { 167 | System.out.println("MIMU22BT Error: No UUID obtained"); 168 | } 169 | } 170 | 171 | 172 | //------------StartReading--------------------- 173 | public void startreading(){ 174 | if (uuid_obtained) 175 | { 176 | ReadingThread = new Thread(new Runnable() { 177 | public void run() 178 | { 179 | en_ReadingIMU_Thread=true; 180 | try { 181 | // Put IMU reader in measurement mode 182 | // Configurar lector IMU 183 | while (socket_connected==false && en_ReadingIMU_Thread==true && imposible_conectarme==false) 184 | { 185 | Log.i(TAG,"=============Loop====================="+IMU_bluetoothName); 186 | sleep(1000); 187 | } // Esperar a que el socket (en "ConnectThred") se conecte de verdad 188 | Log.i(TAG,"=============Start Reading====================="+IMU_bluetoothName); 189 | 190 | if (socket_connected) 191 | { 192 | // Asignar los Streams de entrada y salida: 193 | try { 194 | mInStream = mSocket.getInputStream(); 195 | mOutStream = mSocket.getOutputStream(); 196 | } catch (IOException e) { 197 | Log.e("MIMU22BT", "Streams not created", e); 198 | return; 199 | } 200 | 201 | 202 | 203 | // Enviar comando inicio lectura 204 | comando_empezar_lectura_PDR(); 205 | 206 | 207 | // Listen the Incoming DATA 208 | Log.i(TAG,"Start ListenforMessages"+IMU_bluetoothName); 209 | listenForDataIMU(); // Blocking or very long (infinite) process 210 | Log.i(TAG,"End ListenforMessages"+IMU_bluetoothName); 211 | } 212 | } catch (Exception e) { 213 | Log.e(TAG, "listenForDataIMU Exception", e); 214 | } 215 | } 216 | }); // end-thread 217 | 218 | if (ReadingThread.isAlive()==false) 219 | { 220 | ConnectThread.setName("Hilo ReadingThread - MIMU22BT"); 221 | ReadingThread.start(); 222 | Log.i("MIMU22BT", "ReadingThread.start();"); 223 | // SystemClock.sleep(400); // Para que de tiempo a ReadingThread a comenzar y no se ejecute esto 2 veces o mas 224 | } 225 | } 226 | } 227 | 228 | 229 | 230 | 231 | //---------------- 232 | private void comando_empezar_lectura_PDR() 233 | { 234 | // Parar llegada de datos desde la IMU al movil 235 | byte[] output_off={0x22, 0x00, 0x22}; // {34,0,34} 236 | SendDataSocket(output_off); 237 | 238 | // Vaciar buffer entrada: 239 | try { 240 | int bytes_basura = mInStream.available(); 241 | Log.i("MIMU22BT", "Bytes basura en buffer:" + bytes_basura); 242 | while (mInStream.available() > 0) { 243 | mInStream.read(); // Leer 1 solo byte ( Blocking function ) 4 veces 244 | } 245 | }catch (IOException e) { } 246 | 247 | 248 | // ............Enviar comando inicio lectura PDR............ 249 | 250 | if (IMUstream==false) { // .............PDR_mode................. 251 | Log.i(TAG, "Config MIMU22BT reader" + IMU_bluetoothName); 252 | byte[] PDR_on = {0x34, 0x00, 0x34}; //{52,0,52} 253 | SendDataSocket(PDR_on); // Send command 254 | 255 | //Read ACK de 4 bytes 256 | Read_4_bytes_as_ACK(); 257 | Log.i("MIMU22BT", "read 4bytes ACK after {52,0,52} command sent"); 258 | } else // ..................IMU stream mode................... 259 | { 260 | byte[] IMU_sampling = {0x30, 0x13, 0x00, 0x00, 0x43}; //{48,19,0,0,67} // sampling mode 261 | SendDataSocket(IMU_sampling); // Send command 262 | 263 | //Read ACK de 4 bytes 264 | Read_4_bytes_as_ACK(); 265 | Log.i("MIMU22BT", "read 4bytes ACK after {48,19,0,0,67} command sent"); 266 | 267 | byte[] IMU_on = {0x40, 0x04, 0x00, 0x44}; //{64,4,0,68} // sampling 125 Hz 268 | SendDataSocket(IMU_on); // Send command 269 | 270 | //Read ACK de 4 bytes (solo la primera vez tras mandar el comanmdo de lectura IMU_on={64,4,0,68} // start output at sampling rate of 125 Hz 271 | Read_4_bytes_as_ACK(); 272 | Log.i("MIMU22BT", "read 4bytes ACK after {64,4,0,68} command sent"); 273 | 274 | 275 | 276 | } 277 | } 278 | 279 | 280 | 281 | 282 | //------------------------listenForDataIMU----------------------------------- 283 | private void listenForDataIMU() 284 | { 285 | int byteLeido; 286 | byte mibyte; 287 | byte[] linea = new byte[64]; //64 288 | byte [] ack = new byte[5]; 289 | int package_number_1,package_number_2; 290 | int bytes_disponibles; 291 | int index=0; 292 | 293 | 294 | while (en_ReadingIMU_Thread) //LOOP 295 | { 296 | int bytes_packet; 297 | if (IMUstream==false) { // .............PDR_mode.......... 298 | bytes_packet=64; //Total 64 bytes= header (4 bytes)+ payload (56 bytes)+ Step counter (2 bytes)+checksum (2 bytes) : 299 | }else{ // .............stream mode.............. 300 | bytes_packet=34; //Total 34 bytes= header (4 bytes)+ timestamp(4 bytes)+ Gyr/Acc(24 bytes)+ checksum (2 bytes) : 301 | } 302 | 303 | int counter=0; 304 | while(counter= 4) { 567 | for (int i = 1; i <= 4; i++) { 568 | mInStream.read(); // Leer 1 solo byte ( Blocking function ) 4 veces 569 | } 570 | } 571 | } catch (IOException e) { 572 | Log.i("MIMU22BT", "comamdo empezar_lectura_IMUstream failed", e); 573 | } 574 | } 575 | } 576 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/java/es/csic/getsensordata/MTi_XSens_IMU.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package es.csic.getsensordata; 5 | 6 | import java.util.HashMap; 7 | import java.util.Iterator; 8 | 9 | import android.app.Activity; 10 | import android.app.PendingIntent; 11 | import android.hardware.usb.UsbConstants; 12 | import android.hardware.usb.UsbDevice; 13 | import android.hardware.usb.UsbDeviceConnection; 14 | import android.hardware.usb.UsbEndpoint; 15 | import android.hardware.usb.UsbInterface; 16 | import android.hardware.usb.UsbManager; 17 | import android.os.Bundle; 18 | import android.os.Handler; 19 | import android.os.Message; 20 | import android.util.Log; 21 | 22 | /** 23 | * 24 | * Class that handles the USB communication and parse of the data coming from an MTi IMU from XSens 25 | * The IMU must be previously configured to submit, Temperature, Acc, Gyr, Mag, Quaternions 26 | * (all in IEEE single precision float) and a 2 bytes counter (in total 58 bytes of information). 27 | * It has been tested at 100 Hz without lost information. 28 | * Other configurations and support for other devices will be added in the future. 29 | * 30 | * For accessing the MTi it is necessary to: 31 | * - Create a handler to manage the messages from the class 32 | * private void createMTiHandler(){ 33 | handlerMTi=new Handler() { 34 | 35 | @Override 36 | public void handleMessage(Message msg) { 37 | * handle MTi data and connection messages 38 | Bundle data=msg.getData(); 39 | String mensajetype=data.getString("MensajeType"); 40 | String readername=data.getString("ReaderName"); 41 | if ( mensajetype.equals("Connect") ){... 42 | dataIMU.acceleration[0]=data.getFloat("Accelerations_x"); 43 | dataIMU.acceleration[1]=data.getFloat("Accelerations_y"); 44 | dataIMU.acceleration[2]=data.getFloat("Accelerations_z"); 45 | dataIMU.turnRate[0]=data.getFloat("TurnRates_x"); 46 | dataIMU.turnRate[1]=data.getFloat("TurnRates_y"); 47 | dataIMU.turnRate[2]=data.getFloat("TurnRates_z"); 48 | dataIMU.magneticField[0]=data.getFloat("MagneticFields_x"); 49 | dataIMU.magneticField[1]=data.getFloat("MagneticFields_y"); 50 | dataIMU.magneticField[2]=data.getFloat("MagneticFields_z"); 51 | dataIMU.temperature=data.getFloat("Temperature"); 52 | dataIMU.counter=data.getShort("Counter"); 53 | dataIMU.time=data.getLong("Time"); 54 | } 55 | } 56 | }; 57 | } 58 | * - Create the UsbManager. 59 | * manager = (UsbManager) getSystemService(Context.USB_SERVICE); 60 | * - Create the request permission broadcast: 61 | * mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); 62 | IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); 63 | registerReceiver(mUsbReceiver, filter); 64 | 65 | and the broadcaster: 66 | private static final String ACTION_USB_PERMISSION = 67 | "com.csic.xoom_usb.USB_PERMISSION"; 68 | 69 | public final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { 70 | public void onReceive(Context context, Intent intent) { 71 | String action = intent.getAction(); 72 | if (ACTION_USB_PERMISSION.equals(action)) { 73 | synchronized (this) { 74 | UsbDevice localdevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); 75 | if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { 76 | //If the permission was granted 77 | } 78 | else{ 79 | //If the permission was denied 80 | } 81 | } 82 | } 83 | } 84 | }; 85 | 86 | - Create MTi element 87 | XSens =new MTi_XSens_IMU(handlerMTi,mPermissionIntent); 88 | - Get the Device (if permission is needed the program will call the broadcast receiver, a system call) 89 | mUsbDevice=XSens.getDevice(manager); 90 | - Connect to the Device(if permission is needed, this step must be done after the broadcast receiver is called or it will not connect and return false) 91 | XSens.connect(mUsbDevice); (return true if correctly connected) 92 | - Start the measurements 93 | XSens.startMeassurements(); 94 | * 95 | * 96 | * The Manifest must include: 97 | * 98 | before the uses-sdk and the min sdk must be at least 12 99 | */ 100 | public class MTi_XSens_IMU { //extends Activity 101 | private static final String TAG = "MTi XSens"; 102 | private Handler handlerMTiIMU; 103 | private UsbManager manager; 104 | private Thread ReadingThread; 105 | private boolean readingIMU=false; 106 | private String MTiIMU_Name="XSens MTi IMU"; 107 | private UsbDevice device; 108 | private UsbEndpoint out_ep,in_ep; 109 | private UsbInterface intf; 110 | private UsbDeviceConnection connection; 111 | private PendingIntent mPendingIntent; 112 | private int mVendorId=0x0403; 113 | private int mProductId=0x0D38B; 114 | private int MTiPackageSize=63; 115 | private int receivedPackages=0; 116 | private byte dataLength=(byte)(MTiPackageSize-5); 117 | private int maxPackages=100*1*1; //10 minutes data, 1 seg 118 | private short temperatureIndex=4; 119 | private short accelerationIndex=8; 120 | private short turnRateIndex=20; 121 | private short magneticFieldIndex=32; 122 | private short quaternionsIndex=44; 123 | private short counterIndex=60; 124 | private int maxErrors=30; 125 | private IMUdata[] receivedData; 126 | 127 | public static byte preamble=(byte)0xFA; 128 | public static byte BID=(byte)0xFF; 129 | public static byte MID_MTData=50; 130 | public static byte MID_goToConfig=48; 131 | public static byte MID_goToMeasurement=16; 132 | public static byte MID_reqDID=00; 133 | public static byte MID_reqProductCode=28; 134 | public static byte MID_reqFWRev=18; 135 | public static byte MID_reqDataLength=10; 136 | public static byte MID_reqBaudrate=24; 137 | public static byte MID_SetPeriod=4; 138 | public static byte MID_SetOutputMode=(byte) 208; 139 | public static byte MID_SetOutputSettings=(byte) 210; 140 | 141 | public static final byte Baudrate_921k6=(byte)0x80; 142 | public static final byte Baudrate_460k8=(byte)0x00; 143 | public static final byte Baudrate_230k4=(byte)0x01; 144 | public static final byte Baudrate_115k2=(byte)0x02; 145 | public static final byte Baudrate_76k8=(byte)0x03; 146 | public static final byte Baudrate_57k6=(byte)0x04; 147 | public static final byte Baudrate_38k4=(byte)0x05; 148 | public static final byte Baudrate_28k8=(byte)0x06; 149 | public static final byte Baudrate_19k2=(byte)0x07; 150 | public static final byte Baudrate_14k4=(byte)0x08; 151 | public static final byte Baudrate_9k6=(byte)0x09; 152 | 153 | 154 | /** 155 | * Starts the MTi class, it does not request the permission to the USB Device, it must completely me implemented in the main 156 | * 157 | * @param handlerIMU 158 | * @param maxPackages 159 | */ 160 | public MTi_XSens_IMU(Handler handlerIMU, int maxPackages){ 161 | this.mPendingIntent=null; 162 | this.handlerMTiIMU=handlerIMU; 163 | this.maxPackages=maxPackages; 164 | this.receivedData = new IMUdata[maxPackages]; 165 | 166 | } 167 | 168 | /** Starts the MTi class 169 | * 170 | * @param handlerIMU handler for receiving the messages from the class 171 | * @param mPermissionIntent Pending intent for handling the permission request (the broadcast must be implemented in the main) 172 | */ 173 | public MTi_XSens_IMU(Handler handlerIMU, PendingIntent mPermissionIntent){ 174 | this.mPendingIntent=mPermissionIntent; 175 | this.handlerMTiIMU=handlerIMU; 176 | this.receivedData = new IMUdata[this.maxPackages]; 177 | 178 | } 179 | 180 | /** 181 | * 182 | * Scan for the MTi IMU, if it is detected, request permission to the UsbDevice (a broadcast receiver must be implemented in the main) and return the UsbDevice, null if not detected. 183 | * 184 | * @param mmanager Must provide the UsbManager: UsbManager mmanager = (UsbManager) getSystemService(Context.USB_SERVICE) 185 | */ 186 | public UsbDevice getDevice(UsbManager mmanager){ 187 | 188 | manager = mmanager; 189 | 190 | HashMap deviceList = manager.getDeviceList(); 191 | Iterator deviceIterator = deviceList.values().iterator(); 192 | while(deviceIterator.hasNext()){ 193 | Log.i(TAG, "USB device detected"); 194 | UsbDevice device = deviceIterator.next(); 195 | if(device.getVendorId()==this.mVendorId & device.getProductId()==this.mProductId){ 196 | if(mPendingIntent!=null) 197 | manager.requestPermission(device, mPendingIntent); 198 | return device; 199 | } 200 | } 201 | Log.e(TAG, "USB not connected"); 202 | return null; 203 | } 204 | 205 | /** 206 | * Initiate connection with the device, setting the data rate and sending a message to 207 | * the handler indicating the connection ("MensajeType"->"Connect", "ReaderName"->"XSens MTi IMU", "Connected"->true) 208 | * @param UsbDevice of the MTi 209 | * @return true if connected, false otherwise 210 | */ 211 | public boolean connect(UsbDevice localdevice){ 212 | device=localdevice; 213 | int count = device.getInterfaceCount(); 214 | for(int ii=0;ii"IMU_Data" 253 | "ReaderName"->"XSens MTi IMU" 254 | "Time"-> System time in nanoseconds (long) 255 | "Accelerations_x"-> float 256 | "Accelerations_y"-> float 257 | "Accelerations_z"-> float 258 | "TurnRates_x"-> float 259 | "TurnRates_y"-> float 260 | "TurnRates_z"-> float 261 | "MagneticFields_x"-> float 262 | "MagneticFields_y"-> float 263 | "MagneticFields_z"-> float 264 | "Temperature"-> float 265 | "Counter"-> MTi internal counter (short) 266 | 267 | If it receive more than 30 packages without information it assume that the MTi is disconnected and sends a message to the handler("MensajeType"->"MTiConnect", "Connected"->false). 268 | 269 | If the USB connection is interrupted it sends a message to the handler("MensajeType"->"Connect", "Connected"->false) 270 | */ 271 | public void startMeassurements(){ 272 | 273 | this.ReadingThread = new Thread(new Runnable() { 274 | public void run() 275 | { 276 | readingIMU=true; 277 | byte msg_buffer[] = new byte[64]; 278 | int in_count,roundCounter=0; 279 | byte MTi_pkg[] = new byte[MTiPackageSize*2]; 280 | for(int ii=0;ii2) // compruebo que son datos frescos 288 | for(int i=2;i0 & loops_counts=maxErrors){ 330 | Message mensaje= new Message(); 331 | Bundle data = new Bundle(); 332 | data.putString("MensajeType","MTiConnect"); 333 | data.putString("ReaderName",MTiIMU_Name); 334 | data.putBoolean("Connected",false); 335 | mensaje.setData(data); 336 | handlerMTiIMU.sendMessage(mensaje); 337 | readingIMU=false; 338 | } 339 | } 340 | }); 341 | if (ReadingThread.isAlive()==false) 342 | { 343 | ReadingThread.setName("Thread ReadingThread - XSens MTi IMU"); 344 | ReadingThread.start(); 345 | } 346 | } 347 | 348 | /** 349 | * Stop reading the IMU 350 | */ 351 | public void stopReading(){ 352 | readingIMU=false; // indicates the IMUreading thread to stop reading from the USB 353 | try { 354 | if (ReadingThread.isAlive()){ 355 | ReadingThread.interrupt(); 356 | } 357 | } catch (Exception e) {}; 358 | 359 | } 360 | 361 | 362 | /** 363 | * Indicates that the reading thread is alive 364 | * @return true if the reading thread is alive 365 | */ 366 | public boolean isReading(){ 367 | return readingIMU; 368 | } 369 | 370 | /** 371 | * Release the interface and the USB device connection 372 | */ 373 | public void disconnect(){ 374 | if (connection!=null) 375 | { 376 | connection.releaseInterface(intf); 377 | connection.close(); 378 | } 379 | 380 | } 381 | 382 | /** 383 | * Enter the configuration mode and interrupt the reading thread if any 384 | * @return integer array of received bytes from the IMU 385 | */ 386 | public int[] goToConfig(){ 387 | byte[] msg_buffer=new byte[64]; 388 | byte[] out_buffer={preamble,BID,MID_goToConfig,0,0}; 389 | int[] out=new int[5]; 390 | int loops=0,out_l=0; 391 | 392 | 393 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 394 | msg_buffer[1]=2; 395 | if(readingIMU==false) 396 | while(connection.bulkTransfer(in_ep, msg_buffer, 64, 1000)>=2 & (msg_buffer[1]&0x02)>0); //Clean the buffer 397 | connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 398 | connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 399 | do{ 400 | connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000); // Mandar comando de pasar a modo configuracion 401 | if(readingIMU==true) 402 | { 403 | while(readingIMU==true); 404 | } 405 | else 406 | { 407 | out_l = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 408 | for(int i=0;i=11){ 468 | byte sum=msg_buffer[3]; 469 | for(int i=4;i<11;i++) 470 | sum+=msg_buffer[i]; 471 | if (msg_buffer[2]==preamble&msg_buffer[3]==BID&msg_buffer[4]==(MID_reqDID+1)&msg_buffer[5]==4&sum==0){//&((int)msg_buffer[3]+(int)msg_buffer[4]+(int)msg_buffer[5]+(int)msg_buffer[6]+(int)msg_buffer[7]+(int)msg_buffer[8]+msg_buffer[9]+msg_buffer[10])==0){ 472 | out[0]=msg_buffer[6]; 473 | out[1]=msg_buffer[7]; 474 | out[2]=msg_buffer[8]; 475 | out[3]=msg_buffer[9]; 476 | return out; 477 | } 478 | loops_counts=0; 479 | }else 480 | loops_counts++; 481 | }while(in_count>0 & loops_counts<10); 482 | } 483 | out_loop++; 484 | }while(out_loop<3); 485 | return msg_buffer; 486 | } 487 | 488 | /** 489 | * Request the product code of the IMU 490 | * 491 | * @return The received product code of the IMU as a char array, use String.copyValueOf(char[]) 492 | * to generate the String 493 | */ 494 | public char[] reqProductCode(){ 495 | byte[] msg_buffer=new byte[64]; 496 | byte[] out_buffer={preamble,BID,MID_reqProductCode,0,0}; 497 | int in_count=0,loops_counts=0,out_loop=0; 498 | 499 | 500 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 501 | do{ 502 | connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000); 503 | if(readingIMU==true){ 504 | return null; 505 | } 506 | else{ 507 | loops_counts=0; 508 | do{ 509 | in_count = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 510 | if(in_count>=7){ 511 | byte sum=msg_buffer[3]; 512 | for(int i=4;i0&loops_counts<10); 524 | } 525 | out_loop++; 526 | }while(out_loop<3); 527 | return null; 528 | } 529 | 530 | /** 531 | * Request the FirmWare Revision 532 | * 533 | * @return 3 byte array containing the FirmWare Revision (Major,Minor,Revision part) 534 | */ 535 | public byte[] reqFWRev(){ 536 | byte[] msg_buffer=new byte[64]; 537 | byte[] out_buffer={preamble,BID,MID_reqFWRev,0,0}; 538 | int in_count=0,loops_counts=0,out_loop=0; 539 | 540 | 541 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 542 | do{ 543 | connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000); 544 | if(readingIMU==true){ 545 | return null; 546 | } 547 | else{ 548 | loops_counts=0; 549 | do{ 550 | in_count = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 551 | if(in_count>=7){ 552 | byte sum=msg_buffer[3]; 553 | for(int i=4;i0&loops_counts<10); 565 | } 566 | out_loop++; 567 | }while(out_loop<3); 568 | return msg_buffer; 569 | } 570 | 571 | /** 572 | * Request the Data length of the MTData message (without headers or crc) 573 | * 574 | * @return Data length (0 if error) 575 | */ 576 | public int reqDataLength(){ 577 | byte[] msg_buffer=new byte[64]; 578 | byte[] out_buffer={preamble,BID,MID_reqDataLength,0,0}; 579 | int in_count=0,loops_counts=0,out_loop=0; 580 | 581 | 582 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 583 | do{ 584 | connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000); 585 | if(readingIMU==true){ 586 | return 0; 587 | } 588 | else{ 589 | loops_counts=0; 590 | do{ 591 | in_count = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 592 | if(in_count>=7){ 593 | byte sum=msg_buffer[3]; 594 | for(int i=4;i0&loops_counts<10); 603 | } 604 | out_loop++; 605 | }while(out_loop<3); 606 | return 0; 607 | } 608 | 609 | /** 610 | * Request the baudrate of the communication 611 | * 612 | * @return code of the active baudrate (example Baudrate_115k2) -1 if error 613 | */ 614 | public byte reqBaudrate(){ 615 | byte[] msg_buffer=new byte[64]; 616 | byte[] out_buffer={preamble,BID,MID_reqBaudrate,0,0}; 617 | int in_count=0,loops_counts=0,out_loop=0; 618 | 619 | 620 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 621 | do{ 622 | connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000); 623 | if(readingIMU==true){ 624 | return -1; 625 | } 626 | else{ 627 | loops_counts=0; 628 | do{ 629 | in_count = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 630 | if(in_count>=7){ 631 | byte sum=msg_buffer[3]; 632 | for(int i=4;i0&loops_counts<10); 641 | } 642 | out_loop++; 643 | }while(out_loop<3); 644 | return -1; 645 | } 646 | 647 | /** 648 | * Send a message to the IMU 649 | * @param MID Message to send 650 | * @return received MTComm message (up to 57 data bytes) 651 | */ 652 | public byte[] writeMessage(byte MID){ 653 | byte[] msg_buffer=new byte[64]; 654 | byte[] out_buffer={preamble,BID,MID,0,0}; 655 | int in_count=0,loops_counts=0,out_loop; 656 | 657 | 658 | out_buffer[4]=crc_calculation(out_buffer,out_buffer.length); 659 | out_loop=0; 660 | do{ 661 | if(connection.bulkTransfer(out_ep, out_buffer, out_buffer.length, 1000)<0) 662 | return null; 663 | loops_counts=0; 664 | do{ 665 | in_count = connection.bulkTransfer(in_ep, msg_buffer, 64, 1000); 666 | if(in_count>=7){ 667 | byte sum=msg_buffer[3]; 668 | for(int i=4;i0&loops_counts<10); 680 | 681 | out_loop++; 682 | }while(out_loop<3); 683 | return msg_buffer; 684 | } 685 | 686 | /** 687 | * Send a message with a Data 688 | * @param MID Message ID 689 | * @param Data Data to be send with the MID 690 | * @return Received MTComm message 691 | */ 692 | public byte[] Setting(byte MID,byte[] Data){ 693 | byte[] msg_buffer=new byte[64]; 694 | byte[] out_buffer=new byte[5+Data.length]; 695 | int in_count=0,loops_counts=0,out_loop; 696 | 697 | out_buffer[0]=preamble; 698 | out_buffer[1]=BID; 699 | out_buffer[2]=MID; 700 | if(Data.length>59) 701 | return null; 702 | out_buffer[3]=(byte)(Data.length&0x00FF); 703 | for(int i=0;i=7){ 716 | byte sum=msg_buffer[3]; 717 | for(int i=4;i0&loops_counts<10); 729 | 730 | out_loop++; 731 | }while(out_loop<3); 732 | return msg_buffer; 733 | } 734 | 735 | /** 736 | * 737 | * @param Circular buffer array with the information to interpret 738 | * @param Position of the first byte of the package 739 | * @return Received information 740 | */ 741 | private IMUdata parse(byte[] msg,int pointer) { 742 | byte MTData=0x32; //Message identifier for a MT data 743 | 744 | IMUdata receivedMessage=new IMUdata(); 745 | byte sum=0; 746 | byte Package[]=new byte[MTiPackageSize]; 747 | Package[0]=preamble; 748 | for(int i=1;iminBufferSize ) 42 | { Log.i("Audio","minBufferSize: "+minBufferSize); } 43 | try{ 44 | recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, audiosamplerate, 45 | AudioFormat.CHANNEL_IN_MONO, 46 | AudioFormat.ENCODING_PCM_16BIT, bufferSize*2); 47 | recorder.setPositionNotificationPeriod(audioReadRate); 48 | Log.i("Audio","Setting Audio Record Listener"); 49 | recorder.setRecordPositionUpdateListener(mRecordListener); 50 | 51 | } catch(Exception E){ 52 | Log.i("Audio","No puedo leer, no bien configurado MIC"); 53 | } 54 | 55 | Log.i("Audio","+1.5End Start Audio Recording inside Thread"); 56 | } 57 | 58 | //===========read============== 59 | public void start_read_audio_Thread() 60 | { 61 | final AudioRecord recorder_in_thread=recorder; // copio referencia a objeto y lo pongo "final" (no copio el objeto) 62 | 63 | 64 | Thread readingThread = new Thread() { 65 | @Override 66 | public void run() { 67 | 68 | 69 | recorder_in_thread.startRecording(); 70 | leer_audio=true; 71 | while (leer_audio) 72 | { 73 | recorder_in_thread.read(buffer, 0, bufferSize); // bloquea mientras lee o llena el buffer (por eso en nuevo thread) 74 | //Log.i("Audio","READ Audio Recording inside Thread"); 75 | try { 76 | //Log.i("Audio","SLEEP Audio Recording inside Thread"); 77 | Thread.sleep(500); 78 | } catch (InterruptedException e) { 79 | // TODO Auto-generated catch block 80 | e.printStackTrace(); 81 | } 82 | } // end-while 83 | } 84 | }; 85 | readingThread.setName("Hilo Leer Microfono"); 86 | readingThread.start(); 87 | } 88 | 89 | //============================= 90 | public void stop_audio_thread() 91 | { 92 | Log.i("Audio","Audio Interrupted"); 93 | leer_audio=false; 94 | if (recorder.getState()==AudioRecord.STATE_INITIALIZED && recorder.getRecordingState()==AudioRecord.RECORDSTATE_RECORDING) 95 | { 96 | recorder.stop(); 97 | //recorder.release(); 98 | } 99 | } 100 | 101 | //============================== 102 | public void release() 103 | { 104 | Log.i("Audio","Audio Interrupted"); 105 | if (recorder.getState()==AudioRecord.STATE_INITIALIZED && recorder.getRecordingState()==AudioRecord.RECORDSTATE_RECORDING) 106 | { 107 | //recorder.stop(); 108 | recorder.release(); 109 | } 110 | } 111 | 112 | } 113 | 114 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/java/es/csic/getsensordata/MyApplication.java: -------------------------------------------------------------------------------- 1 | package es.csic.getsensordata; /** 2 | * Created by Antonio on 27/10/2016. 3 | */ 4 | 5 | import android.app.Application; 6 | import com.estimote.sdk.BeaconManager; 7 | 8 | public class MyApplication extends Application { 9 | 10 | private BeaconManager beaconManager; 11 | 12 | @Override 13 | public void onCreate() { 14 | super.onCreate(); 15 | 16 | beaconManager = new BeaconManager(getApplicationContext()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/java/es/csic/getsensordata/PantallaPreferencias.java: -------------------------------------------------------------------------------- 1 | package es.csic.getsensordata; 2 | 3 | import android.os.Bundle; 4 | import android.preference.EditTextPreference; 5 | import android.preference.Preference; 6 | import android.preference.Preference.OnPreferenceChangeListener; 7 | import android.preference.PreferenceActivity; 8 | import es.csic.getsensordata.R; 9 | 10 | public class PantallaPreferencias extends PreferenceActivity { 11 | 12 | static int frecuencia=50; 13 | 14 | @Override 15 | public void onCreate(Bundle savedInstanceState) { 16 | super.onCreate(savedInstanceState); 17 | addPreferencesFromResource(R.xml.pantalla_preferencias); 18 | 19 | 20 | Preference.OnPreferenceChangeListener changeListener_OPT2 = new Preference.OnPreferenceChangeListener() { 21 | public boolean onPreferenceChange(Preference preference, Object newValue) { 22 | // Code goes here 23 | frecuencia=Integer.parseInt(newValue.toString()); 24 | preference.setSummary("Select desired update rate (Now "+frecuencia+" Hz)"); 25 | return true; 26 | } 27 | }; 28 | EditTextPreference pref_OPT2 = (EditTextPreference)findPreference("opcion2"); 29 | pref_OPT2.setOnPreferenceChangeListener(changeListener_OPT2); 30 | pref_OPT2.setSummary("Select desired update rate (Now "+frecuencia+" Hz)"); 31 | 32 | 33 | } // end-on create 34 | 35 | } -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/java/es/csic/getsensordata/RFIDM220Reader.java: -------------------------------------------------------------------------------- 1 | package es.csic.getsensordata; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | import java.lang.reflect.Method; 7 | import java.util.UUID; 8 | 9 | import android.bluetooth.BluetoothAdapter; 10 | import android.bluetooth.BluetoothDevice; 11 | import android.bluetooth.BluetoothSocket; 12 | import android.os.Bundle; 13 | import android.os.Handler; 14 | import android.os.Message; 15 | import android.os.ParcelUuid; 16 | import android.util.Log; 17 | 18 | /* ----------------Example of use:------------------ 19 | 1) First Create an "RFIDM220Reader" object: 20 | RFIDM220Reader mRFIDM220Reader=new RFIDM220Reader(handlerRFID,Bluetooth_MAC); 21 | where: 22 | - "handlerRFID" is a "Handler" object that processes (e.g. to update your UI with RFID data) the data sent by the object in a message. 23 | You have to create this code: for.example: 24 | Handler handlerRFID=new Handler() { 25 | @Override 26 | public void handleMessage(Message msg) { 27 | Bundle data=msg.getData(); 28 | String mensajetype=data.getString("MensajeType"); 29 | String readername=data.getString("ReaderName"); 30 | int RSS_A=data.getInt("RSS_A"); 31 | int RSS_B=data.getInt("RSS_B"); 32 | long TagID=data.getLong("TagID"); 33 | // Do something with this data (e.g. update your UI) 34 | } 35 | } 36 | - "Bluetooth_MAC": is the MAC address of the RFID reader 37 | 2) Connect a socket to the Bluetooth RFID reader device 38 | mRFIDM220Reader.connect(); 39 | 3) Start reading the RFID reader (put the reader in Measurement mode): 40 | mRFIDM220Reader.startreading(); 41 | 4) Now all the processing of data is done in the handlerRFID (in your activity) 42 | 5) When you do not need the RFID reader anymore stop and disconnect it: 43 | mRFIDM220Reader.stopreading(); 44 | mRFIDM220Reader.disconnect(); 45 | 46 | */ 47 | 48 | public class RFIDM220Reader extends Thread{ 49 | 50 | // Standard Bluetooth serial protocol UUID 51 | final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 52 | 53 | private static String TAG="RFIDM220Reader"; 54 | private BluetoothAdapter bluetooth; 55 | private BluetoothDevice RFID_BluetoothDevice; 56 | private BluetoothSocket mSocket; 57 | private InputStream mInStream; 58 | private OutputStream mOutStream; 59 | private Thread ConnectThread; 60 | private Thread ReadingThread; 61 | private Handler handlerRFID; 62 | private String RFID_bluetoothName; 63 | private UUID uuid; 64 | private Boolean uuid_obtained=false; 65 | private Boolean en_ReadingRFID_Thread=false; 66 | Boolean socket_connected=false; 67 | private Boolean imposible_conectarme=false; 68 | 69 | 70 | //----------------- Constructor--------------------- 71 | RFIDM220Reader(Handler handlerRFID,String RFIDBluetooth_MAC){ 72 | this.handlerRFID= handlerRFID; 73 | bluetooth = BluetoothAdapter.getDefaultAdapter(); 74 | if (bluetooth.isEnabled()==true) 75 | { 76 | RFID_BluetoothDevice = bluetooth.getRemoteDevice(RFIDBluetooth_MAC); 77 | RFID_bluetoothName = RFID_BluetoothDevice.getName(); 78 | if ( RFID_BluetoothDevice.getBondState()==BluetoothDevice.BOND_BONDED ) 79 | { 80 | ParcelUuid[] uuids=RFID_BluetoothDevice.getUuids(); 81 | if (uuids.length>0) 82 | { 83 | uuid=uuids[0].getUuid(); 84 | Log.i(TAG,"Object RFIDReader Created. Got UUID"); 85 | uuid_obtained=true; 86 | } 87 | } 88 | } 89 | else 90 | { 91 | System.out.println("RFIDM220Reader Error: Bluetooth not activated"); 92 | } 93 | } 94 | 95 | 96 | //----------------Connect----------------- 97 | public void connect(){ 98 | if (uuid_obtained) 99 | { 100 | try { 101 | // Forma como lo hago yo, y que funciona perfectamente en el S3 102 | //mSocket = RFID_BluetoothDevice.createRfcommSocketToServiceRecord(uuid); 103 | mSocket = RFID_BluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid); 104 | 105 | // Forma como lo hace Francisco para el LPMS-B: 106 | // mSocket = RFID_BluetoothDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); 107 | 108 | // Segun un foro: http://stackoverflow.com/questions/12274210/android-bluetooth-spp-with-galaxy-s3 109 | // Hay un bug de Android con el Galaxy S3 que dificulta la conexion de Bluetooth. 110 | // Lo resuelven asi: 111 | //device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress); 112 | //Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 113 | //socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1)); 114 | 115 | // Method m = RFID_BluetoothDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class }); 116 | // mSocket = (BluetoothSocket)m.invoke(RFID_BluetoothDevice, Integer.valueOf(1)); 117 | 118 | System.out.println("RFIDM220Reader OK: Socket created"); 119 | } catch (Exception e1) { 120 | // TODO Auto-generated catch block 121 | e1.printStackTrace(); 122 | } 123 | ConnectThread = new Thread(new Runnable() { 124 | public void run() 125 | { 126 | try { 127 | // Block until server connection accepted. 128 | bluetooth.cancelDiscovery(); // Lo recomiendan antes de llamar a "connect" 129 | mSocket.connect(); // Blocking function 130 | socket_connected=true; 131 | System.out.println("RFIDM220Reader OK: Socket connected"); 132 | // Enviar notificacion al Handler encargado de pintar en UI 133 | Message mensaje= new Message(); 134 | Bundle data = new Bundle(); 135 | data.putString("MensajeType","Connect"); 136 | data.putString("ReaderName",RFID_bluetoothName); 137 | data.putBoolean("Connected",true); 138 | mensaje.setData(data); 139 | handlerRFID.sendMessage(mensaje); 140 | } catch (IOException e) { 141 | //System.out.println("RFIDM220Reader ERROR: Socket NOT connected"); 142 | //Log.e(TAG, "ERROR: Socket NOT connected", e); // Saca el mensaje en texto rojo en "LogCat" 143 | Log.e(TAG, "ERROR: Socket NOT connected"); 144 | imposible_conectarme=true; 145 | } 146 | } 147 | }); 148 | if (ConnectThread.isAlive()==false) 149 | { 150 | ConnectThread.setName("Hilo ConnectThread - RFIDM220Reader"); 151 | ConnectThread.start(); 152 | } 153 | } 154 | else { 155 | System.out.println("RFIDM220Reader Error: No UUID obtained"); 156 | } 157 | } 158 | 159 | 160 | //------------StartReading--------------------- 161 | public void startreading(){ 162 | if (uuid_obtained) 163 | { 164 | ReadingThread = new Thread(new Runnable() { 165 | public void run() 166 | { 167 | en_ReadingRFID_Thread=true; 168 | try { 169 | // Put RFID reader in measurement mode 170 | // Configurar lector RFID 171 | while (socket_connected==false && en_ReadingRFID_Thread==true && imposible_conectarme==false) 172 | { 173 | Log.i(TAG,"=============Loop====================="+RFID_bluetoothName); 174 | Thread.sleep(1000); 175 | } // Esperar a que el socket (en "ConnectThred") se conecte de verdad 176 | Log.i(TAG,"=============Start Reading====================="+RFID_bluetoothName); 177 | 178 | if (socket_connected) 179 | { 180 | // Asignar los Streams de entrada y salida: 181 | try { 182 | mInStream = mSocket.getInputStream(); 183 | mOutStream = mSocket.getOutputStream(); 184 | } catch (IOException e) { 185 | Log.e("MIMU22BT", "Streams not created", e); 186 | return; 187 | } 188 | 189 | Log.i(TAG,"Config M220 reader"+RFID_bluetoothName); 190 | SendDataSocket("M,0\r"); 191 | SendDataSocket("M,0\r"); 192 | SendDataSocket("G,LOCATE,4\r"); 193 | SendDataSocket("S,2\r"); 194 | // SendDataSocket("YT,20\r"); 195 | Log.i(TAG,"Put RFID reader in measurement mode"+RFID_bluetoothName); 196 | SendDataSocket("M,433\r"); 197 | SendDataSocket("M,433\r"); 198 | 199 | // Listen the Incoming DATA 200 | Log.i(TAG,"Start ListenforMessages"+RFID_bluetoothName); 201 | listenForDataRFID(); // Blocking or very long (infinite) process 202 | Log.i(TAG,"End ListenforMessages"+RFID_bluetoothName); 203 | } 204 | } catch (Exception e) { 205 | Log.e(TAG, "listenForDataRFID Exception", e); 206 | } 207 | } 208 | }); // end-thread 209 | 210 | if (ReadingThread.isAlive()==false) 211 | { 212 | ConnectThread.setName("Hilo ReadingThread - RFIDM220Reader"); 213 | ReadingThread.start(); 214 | } 215 | } 216 | } 217 | 218 | //----------------SendDatatoSocket---------------- 219 | private void SendDataSocket(String comando_str) 220 | { 221 | byte[] buffer=comando_str.getBytes(); 222 | try { 223 | 224 | mOutStream.write(buffer); 225 | Log.i(TAG, "Data "+ comando_str+" sent to socket."); 226 | } catch (IOException e) { 227 | Log.i(TAG, "Data Send failed.", e); 228 | } 229 | } 230 | 231 | //------------------------listenForDataRFID----------------------------------- 232 | private void listenForDataRFID() 233 | { 234 | byte mibyte; 235 | int byteLeido; 236 | Boolean sincronizado=false; 237 | String linea=""; 238 | try { 239 | 240 | while (en_ReadingRFID_Thread) 241 | { 242 | byteLeido = mInStream.read(); // Leer 1 solo byte ( Blocking function ) 243 | mibyte=(byte) byteLeido; 244 | if (sincronizado==false && mibyte==13 ) 245 | { // Resetear la linea y empezar a recoger lineas 246 | linea=""; 247 | sincronizado=true; 248 | Log.i("ListenRFID","Linea sincronizada"); 249 | } 250 | else 251 | { 252 | if (sincronizado==true) 253 | { 254 | if (mibyte!=13) 255 | { // Estoy en linea, la continuo rellenando 256 | linea=linea+(char)mibyte; 257 | } 258 | else 259 | { // encontrará el final de linea => parsear 260 | //Log.i("ListenRFID","Linea leida: "+linea); 261 | Bundle data=parsear_linea_RFID(linea); // .......PARSEAR......data contiene los datos RSS_A, RSS_B y TagID... 262 | int RSS_A=data.getInt("RSS_A"); 263 | int RSS_B=data.getInt("RSS_B"); 264 | long TagID=data.getLong("TagID"); 265 | 266 | // Enviar datos RFID a Handler en hilo UI para que los pinte 267 | Log.i("ListenRFID","Tag ID: "+TagID+" RSS_A: "+RSS_A+" RSS_B: "+RSS_B); 268 | Message mensaje= new Message(); 269 | data.putString("MensajeType","RFID_Data"); 270 | data.putString("ReaderName",RFID_bluetoothName); 271 | mensaje.setData(data); 272 | handlerRFID.sendMessage(mensaje); 273 | // reseteo linea para coger la siguiente 274 | linea=""; 275 | } 276 | } 277 | } 278 | } // end-while 279 | Log.i("ListenRFID","Salgo de LOOP listenForMessages"); 280 | } catch (IOException e) { 281 | Log.i(TAG, "Message received failed.", e); 282 | } 283 | } 284 | 285 | //-----------------------------parsear_linea_RFID--------------------- 286 | private Bundle parsear_linea_RFID(String linea) //,long ID, int RSS_A, int RSS_B) 287 | { 288 | Boolean linea_erronea=false; 289 | Bundle bundle = new Bundle(); 290 | 291 | // Procesamos la línea 292 | int posH=linea.indexOf("H,"); 293 | int posG=linea.indexOf(",GLOCATE,"); 294 | int posP=linea.toUpperCase().indexOf(",P"); // a veces viene P y otras p 295 | int posA=linea.indexOf(",A"); 296 | int posB=linea.indexOf(",B"); 297 | 298 | // Varias comprobaciones 299 | if( linea.length()<23 || posH!=0 || posH==-1 || posG==-1 || posP==-1 || (posA==-1 && posB==-1)) 300 | { 301 | linea_erronea=true; // continue: "Pass control to next iteration of for or while loop" 302 | } 303 | 304 | if (linea_erronea==false) 305 | { 306 | // Extraemos el tag ID 307 | long tagID=0; 308 | try{ 309 | tagID=Long.parseLong(linea.substring(posH+2, posH+10)); 310 | } catch (Exception e) {}; 311 | 312 | int SS1=-1; // -1 indica que no hay lectura RSS válida 313 | int SS2=-1; 314 | if(posA!=-1) // si valor A -> hay numero de 2 o 3 cifras (entre 40 y 120 dB),(si 3 cifras el primero es un 1; ciento y pico) 315 | { 316 | if ( (linea.charAt(posA+2))=='1' ) // leo numero de 3 cifras 317 | { 318 | try{ 319 | SS1=Integer.parseInt(linea.substring(posA+2, posA+5)); //SS1 320 | } catch (Exception e) {}; 321 | } else // leo numero de 2 cifras 322 | { 323 | try { 324 | SS1=Integer.parseInt(linea.substring(posA+2, posA+4)); //SS1 325 | } catch (Exception e) {}; 326 | } 327 | } 328 | else 329 | { SS1=-1; 330 | } 331 | 332 | if(posB!=-1) 333 | { 334 | if ( (linea.charAt(posB+2))=='1' ) // leo numero de 3 cifras 335 | { 336 | try{ 337 | SS2=Integer.parseInt(linea.substring(posB+2, posB+5)); //SS2 338 | } catch (Exception e) {}; 339 | } else // leo numero de 2 cifras 340 | { 341 | try { 342 | SS2=Integer.parseInt(linea.substring(posB+2, posB+4)); //SS2 343 | } catch (Exception e) {}; 344 | } 345 | } 346 | else 347 | { SS2=-1; 348 | } 349 | 350 | // última comprobación 351 | if (SS1 >0 || SS2 >0) 352 | { 353 | bundle.putInt("RSS_A", SS1); 354 | bundle.putInt("RSS_B", SS2); 355 | bundle.putLong("TagID", tagID); 356 | } 357 | 358 | } 359 | return bundle; 360 | } 361 | 362 | //-------------------StopReading-------------------------- 363 | public void stopreading(){ 364 | en_ReadingRFID_Thread=false; // para indicarle que salga del loop en el thread "ReadingRFID" 365 | if (socket_connected) 366 | { 367 | try { 368 | if (ReadingThread.isAlive()) 369 | { 370 | ReadingThread.interrupt(); 371 | } 372 | Log.i(TAG,"StopReading: ReadingThread interrupted"); 373 | } catch (Exception e) {}; 374 | 375 | Log.i(TAG,"StopReading: Send M,0"); 376 | SendDataSocket("M\r"); 377 | SendDataSocket("M,0\r"); 378 | } 379 | else 380 | { 381 | System.out.println("RFIDM220Reader. Info: No stopping done since it was not connected nor reading"); 382 | } 383 | } 384 | 385 | //-------------Disconnect----------------------------- 386 | public void disconnect(){ 387 | if (socket_connected) 388 | { 389 | try { 390 | if (ConnectThread.isAlive()) 391 | { 392 | ConnectThread.interrupt(); 393 | } 394 | Log.i(TAG,"disconnect: ConnectThread interrupted"); 395 | } catch (Exception e) {}; 396 | 397 | try { 398 | Log.i(TAG,"INI:Socket closed on disconnetct method"); 399 | if (mSocket.isConnected()) 400 | { 401 | mSocket.close(); 402 | } 403 | Log.i(TAG,"END:Socket closed on disconnetct method"); 404 | } catch (IOException e) { 405 | // TODO Auto-generated catch block 406 | e.printStackTrace(); 407 | } 408 | } 409 | else 410 | { 411 | System.out.println("RFIDM220Reader. Info: No disconnection done since it was not connected"); 412 | } 413 | 414 | } 415 | //--------- 416 | } 417 | -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-hdpi/ic_action_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-hdpi/ic_action_search.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-ldpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-ldpi/ic_launcher.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-mdpi/action_settings_black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-mdpi/action_settings_black.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-mdpi/ic_action_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-mdpi/ic_action_search.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-xhdpi/ic_action_search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-xhdpi/ic_action_search.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lopsi/GetSensorData_Android/d86ac2dab66aaf272b01a5b9c2472e603e862b6b/GetSensorData20/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /GetSensorData20/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | 14 | 21 | 22 | 29 | 30 | 37 | 38 | 39 | 40 | 44 | 47 | 48 | 52 | 53 | 54 | 62 | 63 | 64 | 68 | 69 | 74 | 75 | 80 | 81 | 86 | 87 | 91 | 92 | 97 | 98 | 103 | 104 | 109 | 110 | 114 | 115 | 120 | 121 | 126 | 127 | 132 | 133 | 137 | 138 | 143 | 144 | 149 | 150 | 155 | 156 | 160 | 161 | 166 | 167 | 172 | 173 | 178 | 179 | 183 | 184 | 189 | 190 | 195 | 196 | 201 | 202 | 206 | 207 | 212 | 213 | 218 | 219 | 224 | 225 | 229 | 230 | 235 | 236 | 241 | 242 | 247 | 248 | 252 | 253 | 258 | 259 | 264 | 265 | 270 | 271 | 275 | 276 | 281 | 282 | 287 | 288 | 293 | 298 | 299 | 303 | 304 | 309 | 310 | 315 | 316 | 321 | 322 | 327 | 328 | 332 | 333 | 338 | 339 | 344 | 345 | 350 | 351 | 356 | 357 | 361 | 362 | 367 | 368 | 373 | 374 | 379 | 380 | 384 | 385 | 390 | 391 | 395 | 396 | 401 | 402 | 407 | 408 | 413 | 414 | 422 | 423 | 427 | 428 | 433 | 434 | 439 | 440 | 445 | 446 | 451 | 452 | 456 | 457 | 462 | 463 | 468 | 469 | 474 | 475 | 479 | 480 | 485 | 486 | 491 | 492 | 497 | 498 | 502 | 503 | 508 | 509 | 514 | 515 | 520 | 521 | 525 | 526 | 531 | 532 | 536 | 537 | 538 | 539 | 540 | 545 | 546 |