@SuppressLint("DefaultLocale")
        @Override
        public void onReceive(Context context, Intent intent) {
          final String action = intent.getAction();
          System.out.println("mGattUpdateReceiver->onReceive->action=" + action);
          if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            mHandler.removeCallbacks(mConnectingOverTimeRunnable);

          } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            mConnectionState = connectionStateEnum.isToScan;
            onConectionStateChange(mConnectionState);
            mHandler.removeCallbacks(mDisonnectingOverTimeRunnable);
            mBluetoothLeService.close();
          } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the user interface.
            for (BluetoothGattService gattService :
                mBluetoothLeService.getSupportedGattServices()) {
              System.out.println(
                  "ACTION_GATT_SERVICES_DISCOVERED  " + gattService.getUuid().toString());
            }
            getGattServices(mBluetoothLeService.getSupportedGattServices());
          } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            if (mSCharacteristic == mModelNumberCharacteristic) {
              if (intent
                  .getStringExtra(BluetoothLeService.EXTRA_DATA)
                  .toUpperCase()
                  .startsWith("DF BLUNO")) {
                mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, false);
                mSCharacteristic = mCommandCharacteristic;
                mSCharacteristic.setValue(mPassword);
                mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                mSCharacteristic.setValue(mBaudrateBuffer);
                mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                mSCharacteristic = mSerialPortCharacteristic;
                mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
                mConnectionState = connectionStateEnum.isConnected;
                onConectionStateChange(mConnectionState);

              } else {
                Toast.makeText(mainContext, "Please select DFRobot devices", Toast.LENGTH_SHORT)
                    .show();
                mConnectionState = connectionStateEnum.isToScan;
                onConectionStateChange(mConnectionState);
              }
            } else if (mSCharacteristic == mSerialPortCharacteristic) {
              onSerialReceived(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }

            System.out.println(
                "displayData " + intent.getStringExtra(BluetoothLeService.EXTRA_DATA));

            //
            //	mPlainProtocol.mReceivedframe.append(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)) ;
            //            	System.out.print("mPlainProtocol.mReceivedframe:");
            //            	System.out.println(mPlainProtocol.mReceivedframe.toString());

          }
        }
示例#2
0
  private void startProgramming() {
    mLog.append("Programming started\n");
    mProgramming = true;
    updateGui();

    // Prepare image notification
    byte[] buf = new byte[OAD_IMG_HDR_SIZE + 2 + 2];
    buf[0] = Conversion.loUint16(mFileImgHdr.ver);
    buf[1] = Conversion.hiUint16(mFileImgHdr.ver);
    buf[2] = Conversion.loUint16(mFileImgHdr.len);
    buf[3] = Conversion.hiUint16(mFileImgHdr.len);
    System.arraycopy(mFileImgHdr.uid, 0, buf, 4, 4);

    // Send image notification
    mCharIdentify.setValue(buf);
    mLeService.writeCharacteristic(mCharIdentify);

    // Initialize stats
    mProgInfo.reset();

    // Start the packet timer
    mTimer = null;
    mTimer = new Timer();
    mTimerTask = new ProgTimerTask();
    mTimer.scheduleAtFixedRate(mTimerTask, 0, PKT_INTERVAL);
  }
  public void writeCharacter(String address) {

    BluetoothGattService alarmService = null;

    BluetoothGattCharacteristic alarmCharacter = null;

    if (mBluetoothGatt != null) {
      alarmService = mBluetoothGatt.getService(SERVIE_UUID);
    }
    if (alarmService == null) {
      showMessage("link loss Alert service not found!");
      return;
    }
    alarmCharacter =
        alarmService.getCharacteristic(UUID.fromString("00002a06-0000-1000-8000-00805f9b34fb"));
    if (alarmCharacter == null) {
      connect(address);
      showMessage("link loss Alert Level charateristic not found!");
      return;
    }
    alarmCharacter.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
    byte[] value = {0x01};
    alarmCharacter.setValue(value);
    mBluetoothGatt.writeCharacteristic(alarmCharacter);
  }
 private boolean sendData(byte[] data) {
   if (target_character != null) {
     target_character.setValue(data);
     return mBluetoothLeService.writeCharacteristic(target_character);
   }
   return false;
 }
示例#5
0
        /*
         * Send an enable command to each sensor by writing a configuration
         * characteristic.  This is specific to the SensorTag to keep power
         * low by disabling sensors you aren't using.
         */
        private void enableNextSensor(BluetoothGatt gatt) {
          BluetoothGattCharacteristic characteristic;
          gatt2 = gatt;
          Log.wtf("mState is", mState + "");
          switch (mState) {
            case 0:
              Log.wtf(TAG, "Renaming");
              characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(ERROR_CHAR);

              gatt.readCharacteristic(characteristic);
              break;

            case 1:
              Log.d(TAG, "Enabling pressure cal");
              characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(CONFIG_CHAR);
              characteristic.setValue(new byte[] {0x01});
              gatt.writeCharacteristic(characteristic);
              break;

            default:
              mHandler.sendEmptyMessage(MSG_DISMISS);
              Log.i(TAG, "All Sensors Enabled");
              return;
          }
        }
 /** Function for writing value to characteristic */
 public void writeCharacteristic(int index, UUID service, UUID characteristic, byte[] value) {
   BluetoothGattService Service;
   BluetoothGattCharacteristic Characteristic;
   if (index < 0 || index > mBluetoothGatt.length) {
     Log.e(TAG, "Read char index out of bound");
     return;
   }
   if (mBluetoothGatt[index] == null) {
     Log.e(TAG, "GATT isn't connected");
     return;
   }
   if (service != null && characteristic != null) {
     Service = mBluetoothGatt[index].getService(service);
     if (Service == null) {
       Log.e(TAG, "Service not found");
       return;
     }
     Characteristic = Service.getCharacteristic(characteristic);
     if (Characteristic == null) {
       Log.e(TAG, "Characteristic not found");
       return;
     }
     Characteristic.setValue(value);
     // Characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
     mBluetoothGatt[index].writeCharacteristic(Characteristic);
   }
 }
  @Override
  public void onWriteToA007(byte[] data) {

    if ((data[3] == 0x72 || data[3] == 0x73) && isBtnFlag) {
      isBeginFlag = true;
      isBtnFlag = false;
    } else {
      isBeginFlag = false;
    }
    LogUtil.e(
        "send commond is:"
            + LogUtil.byte2HexString(data)
            + " ; isBtnFlag="
            + isBtnFlag
            + " ; isBeginFlag="
            + isBeginFlag);

    if (gattCharacteristics != null) {
      if (data != null && data.length > 0 && data[data.length - 1] != (byte) 0x00) {
        final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(2);
        //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
        byte[] bytes = currentCmdPacket.getInputDataPacket();
        if (bytes != null) {
          characteristic.setValue(bytes);
        }
        bluetoothGatt.writeCharacteristic(characteristic);
      } else {
        final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(0);
        //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
        bluetoothGatt.readCharacteristic(characteristic);
      }
    }
  }
示例#8
0
 public synchronized void send(UUID uuid, byte[] value) {
   if (bluetoothGattService != null) {
     BluetoothGattCharacteristic characteristic = bluetoothGattService.getCharacteristic(uuid);
     characteristic.setValue(value);
     bluetoothGatt.writeCharacteristic(characteristic);
   }
 }
 /**
  * sendMessage will send a message represented as a String, over the BLE if server was
  * successfully started and client has connected.
  *
  * @param msg message to be sent
  */
 public void sendMessage(String msg) {
   if (mConnectedDevice != null) {
     BluetoothGattCharacteristic characteristic =
         ServiceFactory.generateService()
             .getCharacteristic(UUID.fromString(Constants.CHAT_CHARACTERISTIC_UUID));
     characteristic.setValue(msg);
     mGattserver.notifyCharacteristicChanged(mConnectedDevice, characteristic, false);
   }
 }
  private void writeData(byte[] tx) {
    if (mConnected && characteristicTX != null) {
      if (DEBUG) Log.d(TAG, "Sending data: " + tx + " # bytes: " + tx.length);

      characteristicTX.setValue(tx);
      writeCharacteristic(characteristicTX);
    } else {
      if (ERROR) Log.e(TAG, "Invalid connection: " + mConnected + " " + characteristicTX);
    }
  }
示例#11
0
  public void writeLetter() {

    char letter = motEcrit.charAt(indiceMotEcrit);
    Log.i(tag, "         envoie  = " + letter);
    sendByte = new String(new char[] {letter}).getBytes();
    BluetoothGattCharacteristic characteristic =
        bluetoothGatt.getService(SERVICE).getCharacteristic(CHARACTERISTIC);
    characteristic.setValue(sendByte);
    bluetoothGatt.writeCharacteristic(characteristic);
  }
示例#12
0
  private static boolean writeValue(
      BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] bytes) {
    if (gatt == null) {
      Log.e(TAG, "BluetoothAdapter not initialized");
      return false;
    }

    // PrintBytes(bytes);
    characteristic.setValue(bytes);
    return gatt.writeCharacteristic(characteristic);
  }
  private void turnOnService(BluetoothGatt gatt, UUID serviceUUID, UUID configUUID) {

    BluetoothGattService humService = gatt.getService(serviceUUID);
    BluetoothGattCharacteristic config = humService.getCharacteristic(configUUID);
    config.setValue(
        new byte[] {
          1
        }); // 01 for Humidity; 01 for +-2g deviation//NB: the config value is different for the
            // Gyroscope
    gatt.writeCharacteristic(config);
  }
示例#14
0
        private void disableSensors(BluetoothGatt gatt) {
          SICRunning = false;
          BluetoothGattCharacteristic characteristic;
          Log.d(TAG, "Disabling Sensors");
          characteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(CONFIG_CHAR);
          byte finisher = 0x00;
          characteristic.setValue(new byte[] {finisher});

          gatt.writeCharacteristic(characteristic);
          sicAct.stillRunning = true;
        }
示例#15
0
 // 发动到ble终端
 public void sendToBle(String cmd) {
   try {
     target_chara.setValue(cmd);
     // 调用蓝牙服务的写特征值方法实现发送数据
     mBluetoothLeService.writeCharacteristic(target_chara);
     //			log("sending to ble : "+cmd);
   } catch (Exception e) {
     log("sendToBle 异常");
     log(e.getMessage());
   }
 }
示例#16
0
        private void writeSecurity(BluetoothGatt gatt) {
          Log.wtf(TAG, "Security Written");
          BluetoothGattCharacteristic securityCharacteristic = null;
          byte[] packet = new byte[1];
          int i = 153;

          packet[0] = (byte) i;
          securityCharacteristic = gatt.getService(MAIN_SERVICE).getCharacteristic(SECURITY_KEY);
          securityCharacteristic.setValue(packet);
          Log.wtf(TAG, packet[0] + "");
          gatt.writeCharacteristic(securityCharacteristic);
        }
  public void doWrite(BluetoothGattCharacteristic characteristic, byte[] data) {

    // Log.d(LOG_TAG, "doWrite");

    characteristic.setValue(data);

    if (gatt.writeCharacteristic(characteristic)) {
      // Log.d(LOG_TAG, "doWrite completato");
    } else {
      Log.d(LOG_TAG, "errore doWrite");
    }
  }
 private void excuteCmd() {
   byte[] bytes = currentCmdPacket.getInputCmdPacket();
   //        LogUtil.i("executecmd=" + LogUtil.byte2HexString((bytes)));
   if (gattCharacteristics != null) {
     final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(1);
     characteristic.setValue(bytes);
     if (bluetoothGatt == null) {
       return;
     }
     bluetoothGatt.writeCharacteristic(characteristic);
   }
 }
  private void sendMessage(String msg) {
    Log.d(TAG, "Sending Result=" + msg);

    if (characteristicReady
        && (mBluetoothLeService != null)
        && (characteristicTX != null)
        && (characteristicRX != null)) {
      characteristicTX.setValue(msg);
      mBluetoothLeService.writeCharacteristic(characteristicTX);
      mBluetoothLeService.setCharacteristicNotification(characteristicRX, true);
    } else {
      Toast.makeText(DeviceControlActivity.this, "BLE Disconnected", Toast.LENGTH_SHORT).show();
    }
  }
示例#20
0
 /**
  * Make sure connection interval is long enough for OAD (Android default connection interval is
  * 7.5 ms)
  */
 private void setConnectionParameters() {
   byte[] value = {
     Conversion.loUint16(OAD_CONN_INTERVAL),
     Conversion.hiUint16(OAD_CONN_INTERVAL),
     Conversion.loUint16(OAD_CONN_INTERVAL),
     Conversion.hiUint16(OAD_CONN_INTERVAL),
     0,
     0,
     Conversion.loUint16(OAD_SUPERVISION_TIMEOUT),
     Conversion.hiUint16(OAD_SUPERVISION_TIMEOUT)
   };
   mCharConnReq.setValue(value);
   mBtLeService.writeCharacteristic(deviceAddress, mCharConnReq);
 }
  /**
   * Writes given operation parameters to the characteristic
   *
   * @param characteristic the characteristic to write. This must be the Record Access Control Point
   *     characteristic
   * @param opCode the operation code
   * @param operator the operator (see {@link #OPERATOR_NULL} and others
   * @param params optional parameters (one for >=, <=, two for the range, none for other operators)
   */
  private void setOpCode(
      final BluetoothGattCharacteristic characteristic,
      final int opCode,
      final int operator,
      final Integer... params) {
    final int size =
        2
            + ((params.length > 0) ? 1 : 0)
            + params.length
                * 2; // 1 byte for opCode, 1 for operator, 1 for filter type (if parameters exists)
    // and 2 for each parameter
    characteristic.setValue(new byte[size]);

    // write the operation code
    int offset = 0;
    characteristic.setValue(opCode, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
    offset += 1;

    // write the operator. This is always present but may be equal to OPERATOR_NULL
    characteristic.setValue(operator, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
    offset += 1;

    // if parameters exists, append them. Parameters should be sorted from minimum to maximum.
    // Currently only one or two params are allowed
    if (params.length > 0) {
      // our implementation use only sequence number as a filer type
      characteristic.setValue(
          FILTER_TYPE_SEQUENCE_NUMBER, BluetoothGattCharacteristic.FORMAT_UINT8, offset);
      offset += 1;

      for (final Integer i : params) {
        characteristic.setValue(i, BluetoothGattCharacteristic.FORMAT_UINT16, offset);
        offset += 2;
      }
    }
  }
示例#22
0
 private void setConnectionParameters() {
   // Make sure connection interval is long enough for OAD
   byte[] value = {
     Conversion.loUint16(OAD_CONN_INTERVAL),
     Conversion.hiUint16(OAD_CONN_INTERVAL),
     Conversion.loUint16(OAD_CONN_INTERVAL),
     Conversion.hiUint16(OAD_CONN_INTERVAL),
     0,
     0,
     Conversion.loUint16(OAD_SUPERVISION_TIMEOUT),
     Conversion.hiUint16(OAD_SUPERVISION_TIMEOUT)
   };
   mCharConnReq.setValue(value);
   boolean ok = mLeService.writeCharacteristic(mCharConnReq);
   if (ok) ok = mLeService.waitIdle(GATT_WRITE_TIMEOUT);
 }
 @Override
 public void onWriteToA008(byte[] data) {
   LogUtil.e("inputData is:" + LogUtil.byte2HexString(data));
   if (gattCharacteristics != null) {
     byte[] bytes = currentCmdPacket.getInputDataPacket();
     if (bytes != null) {
       final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(2);
       //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
       characteristic.setValue(bytes);
       bluetoothGatt.writeCharacteristic(characteristic);
     } else {
       final BluetoothGattCharacteristic characteristic = gattCharacteristics.get(0);
       //                LogUtil.e("准备请求uuid:" + characteristic.getUuid());
       bluetoothGatt.readCharacteristic(characteristic);
     }
   }
 }
示例#24
0
  /** Write the hello configuration characteristic to the device */
  private void writeHelloConfigurationCharacteristic() {
    BluetoothGattCharacteristic characteristic = null;

    int blinks = 0;
    try {
      blinks = Integer.parseInt(mEditTextHelloConfiguration.getText().toString());
      characteristic =
          GattUtils.getCharacteristic(
              mPickedDeviceGatt,
              Constants.HELLO_SERVICE_UUID,
              Constants.HELLO_CHARACTERISTIC_CONFIGURATION_UUID);
      characteristic.setValue(blinks, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
      mRequestQueue.addWriteCharacteristic(mPickedDeviceGatt, characteristic);
    } catch (Throwable t) {
      Log.w(TAG, "invalid number of notifications");
      mEditTextHelloConfiguration.setText("0");
    }
    mRequestQueue.addWriteCharacteristic(mPickedDeviceGatt, characteristic);
    mRequestQueue.execute();
  }
示例#25
0
  public void startProgramming() {
    mProgramming = true;
    packetsSent = 0;

    mCharIdentify.setValue(mFileImgHdr.getRequest());
    mBtLeService.writeCharacteristic(deviceAddress, mCharIdentify);

    this.reset();
    System.out.println("total blocks: " + nBlocks);
    mTimer = new Timer();
    mTimer.scheduleAtFixedRate(
        new TimerTask() {
          @Override
          public void run() {
            iTimeElapsed += TIMER_INTERVAL;
          }
        },
        0,
        TIMER_INTERVAL);
  }
 public synchronized void sendData(byte[] value) {
   if (targetGattCharacteristic != null && mBluetoothLeService != null && mConnected == true) {
     int targetLen = 0;
     int offset = 0;
     for (int len = (int) value.length; len > 0; len -= 20) {
       if (len < 20) targetLen = len;
       else targetLen = 20;
       byte[] targetByte = new byte[targetLen];
       System.arraycopy(value, offset, targetByte, 0, targetLen);
       offset += 20;
       targetGattCharacteristic.setValue(targetByte);
       mBluetoothLeService.writeCharacteristic(targetGattCharacteristic);
       try {
         Thread.sleep(5);
       } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
     }
   }
 }
示例#27
0
  private void activateLED(int led) {
    BluetoothGattCharacteristic characteristic;
    // new byte [] finisher = 0x01;

    characteristic = gatt2.getService(MAIN_SERVICE).getCharacteristic(FINISH);
    if (led == 1) {
      maintChar ^= 1 << 5;
    }
    if (led == 2) {
      maintChar ^= 1 << 4;
    }
    if (led == 3) {
      maintChar ^= 1 << 3;
    }
    if (led == 4) {
      maintChar ^= 1 << 2;
    }
    characteristic.setValue(new byte[] {maintChar});
    Log.wtf(TAG, "Value is: " + characteristic.getValue().toString());
    gatt2.writeCharacteristic(characteristic);
  }
示例#28
0
    /**
     * Executes the next initialization request. If the last element from the queue has been
     * executed a {@link #onDeviceReady()} callback is called.
     */
    private void nextRequest() {
      final Queue<Request> requests = mInitQueue;

      // Get the first request from the queue
      final Request request = requests.poll();

      // Are we done?
      if (request == null) {
        if (mInitInProgress) {
          mInitInProgress = false;
          onDeviceReady();
        }
        return;
      }

      switch (request.type) {
        case READ:
          {
            readCharacteristic(request.characteristic);
            break;
          }
        case WRITE:
          {
            final BluetoothGattCharacteristic characteristic = request.characteristic;
            characteristic.setValue(request.value);
            writeCharacteristic(characteristic);
            break;
          }
        case ENABLE_NOTIFICATIONS:
          {
            enableNotifications(request.characteristic);
            break;
          }
        case ENABLE_INDICATIONS:
          {
            enableIndications(request.characteristic);
            break;
          }
      }
    }
示例#29
0
  @Override
  public void run() {
    isRunning = true;

    while (isRunning) {
      try {

        if (oldPoint != pointAsString) {
          BluetoothGattCharacteristic characteristic =
              service.getSupportedGattServices().get(2).getCharacteristics().get(0);
          characteristic.setValue(pointAsString);
          // try writing a characteristic (data) to the BLE device.
          service.mBluetoothGatt.writeCharacteristic(characteristic);

          Log.e("SENT", "Characteristic sent.");
          Log.d("Value", pointAsString);
        }
      } finally {
        oldPoint = pointAsString;
      }
    }
  }
示例#30
0
  private void onBlockTimer() {

    if (mProgInfo.iBlocks < mProgInfo.nBlocks) {
      mProgramming = true;

      // Prepare block
      mOadBuffer[0] = Conversion.loUint16(mProgInfo.iBlocks);
      mOadBuffer[1] = Conversion.hiUint16(mProgInfo.iBlocks);
      System.arraycopy(mFileBuffer, mProgInfo.iBytes, mOadBuffer, 2, OAD_BLOCK_SIZE);

      // Send block
      mCharBlock.setValue(mOadBuffer);
      boolean success = mLeService.writeCharacteristic(mCharBlock);

      if (success) {
        // Update stats
        mProgInfo.iBlocks++;
        mProgInfo.iBytes += OAD_BLOCK_SIZE;
        mProgressBar.setProgress((mProgInfo.iBlocks * 100) / mProgInfo.nBlocks);
      } else {
        // Check if the device has been prematurely disconnected
        if (BluetoothLeService.getBtGatt() == null) mProgramming = false;
      }
    } else {
      mProgramming = false;
    }
    mProgInfo.iTimeElapsed += PKT_INTERVAL;

    if (!mProgramming) {
      runOnUiThread(
          new Runnable() {
            public void run() {
              displayStats();
              stopProgramming();
            }
          });
    }
  }