我正在构建一个BLE远程控制器应用程序。
我正在使用带有经过测试和运行的代码的Android手机配备BLE设备。
Intent intentOpenBluetoothSettings = new Intent();
intentOpenBluetoothSettings.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intentOpenBluetoothSettings);
我想连接到配对列表中的一个设备,我知道名称,它始终是相同的。
稍后,我想以一个随机的间隔(从一个按钮的监听器)一次向该设备发送大约十两位数字,我不需要任何信息。仅限单工通信,Android手机到BLE设备。
答案 0 :(得分:1)
@Override
public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record )
{
String msg ;
String deviceName = device.getName() ;
String redRacer = "Red Racer" ;
if (redRacer.equals(deviceName))
{
boolean status ;
status = mBleWrapper.connect(device.getAddress().toString()) ;
if (status == false)
{
msg = "Sorry, could not connect to Red Racer" ;
Toast.makeText(SecondaryActivity.this,msg,Toast.LENGTH_SHORT).show() ;
}
else
{
msg = "Connected to Red Racer" ;
Toast.makeText(SecondaryActivity.this,msg + " " + deviceName + " " + redRacer,Toast.LENGTH_SHORT).show() ;
}
}
}
答案 1 :(得分:1)
在我研究解决这个问题的过程中,我发现了这篇简短而又内容丰富的文章,关于配对和绑定之间的差异,就BLE而言:
https://piratecomm.wordpress.com/2014/01/19/ble-pairing-vs-bonding/
在信用到期时给予信贷。解决了我的问题的上述代码来自蓝牙低功耗入门(O'REILLY),尽管直接从他们的书中复制的代码在调用时不断地使活动崩溃。在纠正问题之后,按照上面的代码,它可以完美地工作。现在已建立连接,我必须将控制代码从已建立的链接中移出到我的从属板上的Simblee芯片。
总的来说,代码是我定义的插件可重用代码,我认为这些代码适用于可能需要相同功能的其他人。一旦我完成并运行,我将发布完整的代码。
答案 2 :(得分:0)
以下是我自己的问题的答案,是否有任何副本粘贴代码来实现一个带BLE的简单开环控制系统,电话是主控制器,它将控制代码发送给BLE从站,可以控制几个现实世界的设备,如电机,灯,加热器等。
首先,我意识到开环控制系统是最不理想的控制系统,但在我的情况下,Simblee RFD77101没有一个特性会返回写入它的值,因此闭环控制系统是不可能的。
最终我想修饰此代码以包含读取功能等,但这对我来说不是当前的优先事项。
最后,我是Android / Java开发的新手,所以如果您有任何意见或问题,请保持愉快,我会尽我所能。
答案 3 :(得分:0)
package com.my_android_app.my_android_app;
import android.app.Activity ;
import android.content.Intent ;
import android.content.SharedPreferences ;
import android.content.pm.PackageManager ;
import android.os.Bundle ;
import android.os.Handler ;
import android.support.v7.app.AppCompatActivity ;
import android.util.Log ;
import android.view.Gravity ;
import android.view.View ;
import android.widget.Button ;
import android.widget.TextView ;
import android.widget.Toast ;
import java.util.List ;
import java.util.UUID ;
import java.util.Calendar ;
import android.bluetooth.BluetoothAdapter ;
import android.bluetooth.BluetoothDevice ;
import android.bluetooth.BluetoothGatt ;
import android.bluetooth.BluetoothGattCharacteristic ;
import android.bluetooth.BluetoothGattService ;
public class BLE_Test_Activity extends AppCompatActivity {
public BLE_Test_Activity.mSensorState mState ;
private enum mSensorState {IDLE, ACC_ENABLE, ACC_READ} ;
boolean connectedTo = false ;
boolean okButtonClicked = false ;
boolean receivedRSSI = false ;
private byte[] mRawValue = null ;
private int mIntValue = 0 ;
private String mAsciiValue = "" ;
private String mStrValue = "" ;
private String mLastUpdateTime = "" ;
private boolean mNotificationEnabled = false ;
private final String LOGTAG = "BLETEST" ;
private final String TARGET_BLE = "My BLE Device" ;
private String gattList = "" ;
private int rssi_1 = 0 ;
private int rssi_2 = 0 ;
private int rssi_3 = 0 ;
private int rssi_4 = 0 ;
private int valueRSSI = 0 ;
private String mDeviceRSSI ;
private TextView mDeviceStatus ;
private TextView mDeviceRssiView ;
private String mDeviceAddress ;
private static final long SCANNING_TIMEOUT = 5 * 1000; /* 5 seconds */
// The UUID variable values below are only applicable to the RFD77101 BLE chip.
// Enter values here which are applicable to the BLE device you are using.
private static final UUID
UUID_SIMBLEE_SERVICE = UUID.fromString("0000fe84-0000-1000-8000-00805f9b34fb") ,
UUID_SIMBLEE_CHARACTERISTIC_2 = UUID.fromString("2d30c083-f39f-4ce6-923f-3484ea480596") ;
private boolean mScanning = false ;
private Handler mHandler = new Handler() ;
private BleWrapper mBleWrapper = null ; // Add this line to instantiate the BLE wrapper
private BluetoothGattCharacteristic mCharacteristic = null ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState) ;
setContentView(R.layout.activity_ble__test_) ;
connectViewsVariables() ;
final String dataSentMessage = "Your " + TARGET_BLE + " put your transmitted message here." ;
mBleWrapper = new BleWrapper(this, new BleWrapperUiCallbacks.Null() {
@Override
public void uiDeviceFound(final BluetoothDevice device, final int rssi, final byte[] record) {
if (TARGET_BLE.equals(device.getName())) {
if (mBleWrapper.connect(device.getAddress())) {
// Toast.makeText(BLE_Test_Activity.this, device.getAddress(), Toast.LENGTH_SHORT).show(); // This is included for debugging purposes
} else {
Toast.makeText(BLE_Test_Activity.this, "Sorry, could not connect to " + TARGET_BLE, Toast.LENGTH_SHORT).show();
}
}
} // ********************** uiDeviceFound *************************************
public void uiDeviceConnected(final BluetoothGatt gatt, final BluetoothDevice device) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mDeviceStatus.setText ("connected ") ;
mDeviceRssiView.setText ("measuring .") ;
connectedTo = true;
}
});
} // ********************** uiDeviceConnected *************************************
public void uiDeviceDisconnected(final BluetoothGatt gatt, final BluetoothDevice device) // Takes about 20 seconds to display disconnected,
{ // then more than thirty minutes to reconnect.
runOnUiThread(new Runnable() {
@Override
public void run() {
mDeviceStatus.setText ("disconnected") ;
mDeviceRssiView.setText("disconnected") ;
connectedTo = false;
}
});
} // ********************** uiDeviceDisconnected *************************************
@Override
public void uiCharacteristicForService( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
List<BluetoothGattCharacteristic> chars)
{
super.uiCharacteristicForService(gatt, device, service, chars);
for (BluetoothGattCharacteristic c : chars)
{
String charName = BleNamesResolver.resolveCharacteristicName(c.getUuid().toString()) ;
gattList += "Characteristic: " + charName + "\n" ;
}
} // ********************** uiCharacteristicForService *************************************
public void uiNewRssiAvailable(final BluetoothGatt gatt, final BluetoothDevice device, final int rssi) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (rssi_4 == 0)
{
mDeviceRSSI = "measuring ....." ;
mDeviceRssiView.setText(mDeviceRSSI) ;
}
if (rssi_3 == 0)
{
mDeviceRSSI = "measuring ...." ;
mDeviceRssiView.setText(mDeviceRSSI) ;
}
if (rssi_2 == 0)
{
mDeviceRSSI = "measuring ..." ;
mDeviceRssiView.setText(mDeviceRSSI) ;
}
if (rssi_1 == 0)
{
mDeviceRSSI = "measuring .." ;
mDeviceRssiView.setText(mDeviceRSSI) ;
}
rssi_4 = rssi_3 ;
rssi_3 = rssi_2 ;
rssi_2 = rssi_1 ;
rssi_1 = rssi ;
if (rssi_4 != 0) {
valueRSSI = (rssi_1 + rssi_2 + rssi_3 + rssi_4) / 4 ; // This is a simple moving average to filter out noise
mDeviceRSSI = (valueRSSI) + " dBm" ;
mDeviceRssiView.setText(mDeviceRSSI) ;
}
receivedRSSI = true ;
}
}) ;
if (okButtonClicked)
{
okButtonClicked = false ;
// Build up newValue with the data you want to send out the BLE link.
// I have hard coded 0202 just for testing purposes.
// Make sure the contents of newValue is Hex only 0 - 9, A - F
String newValue = "0202" ;
byte[] dataToWrite = parseHexStringToBytes(newValue) ;
BluetoothGattCharacteristic mCharacteristic ;
mCharacteristic = gatt.getService(UUID_SIMBLEE_SERVICE).getCharacteristic(UUID_SIMBLEE_CHARACTERISTIC_2) ;
mBleWrapper.writeDataToCharacteristic(mCharacteristic, dataToWrite) ;
}
} // *************************** uiNewRssiAvailable ***********************************************
@Override
public void uiNewValueForCharacteristic(BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic ch,
String strValue,
int intValue,
byte[] rawValue,
String timestamp)
{
super.uiNewValueForCharacteristic(gatt, device, service, ch, strValue, intValue, rawValue, timestamp);
for (byte b:rawValue)
{
Log.d(LOGTAG,"Val: + b") ;
}
} // ********************** uiNewValueForCharacteristic *************************************
@Override
public void uiGotNotification( BluetoothGatt gatt,
BluetoothDevice device,
BluetoothGattService service,
BluetoothGattCharacteristic characteristic)
{
super.uiGotNotification(gatt, device, service, characteristic) ;
String ch = BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) ;
Log.d(LOGTAG,"uiGotNotification: " + ch) ;
} // *************************** uiNewValueForCharacteristic *************************************
} ) ; // *************************** new BleWrapper **************************************************
if (!mBleWrapper.checkBleHardwareAvailable()) {
Toast.makeText(this, "No BluetoothLE compatible hardware detected", Toast.LENGTH_SHORT).show() ;
finish() ;
} // ********************** checkBleHardwareAvailable *************************************
Button activity6Button = (Button) findViewById(R.id.button6); // Green check mark button
activity6Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (connectedTo)
{
okButtonClicked = true ;
if (receivedRSSI)
{
Toast toast = Toast.makeText(BLE_Test_Activity.this, dataSentMessage, Toast.LENGTH_SHORT) ;
TextView v = (TextView) toast.getView().findViewById(android.R.id.message) ;
if (v != null) v.setGravity(Gravity.CENTER) ;
toast.show() ;
receivedRSSI = false ;
}
}
SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit() ;
editor.putString("AppIsOn", "yes") ;
editor.apply() ;
}
}) ; // ********************** green check mark *************************************
Button activity7Button = (Button) findViewById(R.id.button7); // Blue back arrow
activity7Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setResult(Activity.RESULT_CANCELED) ; // Page 60 Sams
finish() ;
}
}) ; // ********************** back arrow *************************************
} // ********************************** onCreate ********************************************
public byte[] parseHexStringToBytes(final String hex) {
String tmp = hex.substring(2).replaceAll("[^[0-9][a-f]]", "") ;
byte[] bytes = new byte[tmp.length() / 2] ; // every two letters in the string are one byte finally
String part = "" ;
for(int i = 0; i < bytes.length; ++i) {
part = "0x" + tmp.substring(i*2, i*2+2) ;
bytes[i] = Long.decode(part).byteValue() ;
}
return bytes ;
} // ********************** parseHexStringToBytes *************************************
@Override
protected void onResume() {
super.onResume();
if (!mBleWrapper.isBtEnabled()) // Check for Bluetooth enabled on each resume
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) ;
startActivity(enableBtIntent) ;
Toast.makeText(BLE_Test_Activity.this, "Sorry but BluetoothLE is not supported on your phone", Toast.LENGTH_SHORT).show() ;
finish() ;
}
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(BLE_Test_Activity.this, "mBleWrapper.isBtEnabled", Toast.LENGTH_SHORT).show() ;
finish() ;
return ;
}
connectedTo = false ;
mBleWrapper.initialize() ;
mDeviceStatus.setText ("searching ...") ;
mDeviceRssiView.setText("searching ...") ;
mBleWrapper.startScanning() ;
} // ************************************ onResume **********************************************
@Override
protected void onStart() {
super.onStart();
} // *********************************** onStart *******************************
@Override
protected void onPause() {
connectedTo = false ;
super.onPause() ;
mBleWrapper.stopScanning() ;
mBleWrapper.diconnect() ;
mBleWrapper.close() ;
} // ********************** onPause *************************************
@Override
protected void onStop() {
SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE) ;
SharedPreferences.Editor editor = prefs.edit() ;
editor.putString("AppIsOn", "no") ;
editor.apply() ;
mBleWrapper.stopScanning() ;
mBleWrapper.diconnect() ;
mBleWrapper.close() ;
super.onStop() ;
} // ********************** onStop *************************************
@Override
protected void onDestroy() {
SharedPreferences prefs = getSharedPreferences("saveUserSettings", MODE_PRIVATE) ;
SharedPreferences.Editor editor = prefs.edit() ;
editor.putString("AppIsOn", "no") ;
editor.apply() ;
mBleWrapper.stopScanning() ;
mBleWrapper.diconnect() ;
mBleWrapper.close() ;
super.onDestroy() ;
} // ********************** onDestroy *************************************
private void connectViewsVariables() {
mDeviceStatus = (TextView) findViewById(R.id.peripheral_status) ;
mDeviceRssiView = (TextView) findViewById(R.id.peripheral_rssi) ;
} // ********************** connectViewsVariables ********************************
} // ***************************** BLE_Test_Activity *****************************