Так что я пытаюсь создать приложение android, чтобы иметь возможность удаленного управления моим Arduino. Прямо сейчас все, что я хочу, это иметь возможность включать и выключать свет.
Arduino имеет модуль Bluetooth (H C -05) и уже запрограммирован таким образом, что если модуль Bluetooth получает «1», он включает свет, а если он получает «0», он поворачивается свет снова выключен.
Теперь мое приложение android уже может:
Теперь у меня следующий вопрос: если я уже подключился к модулю Bluetooth Arduino через мое приложение, как Могу ли я передать ему «1» или «0» через приложение к Bluetooth-модулю HC05? Это кажется простым вопросом, но я ничего не нахожу. Вот мой код:
Android Манифест:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.fernsteuerung">
<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"
tools:ignore="ProtectedPermissions" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".RemoteControl"></activity>
<activity android:name=".ChooseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ChooseActivity. java:
package com.example.fernsteuerung;
import androidx.annotation.LongDef;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class ChooseActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
//Funktionen und Part fuer unseren Discoverability Button
//Bluetooth Broadcoast receiver für den Button
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,BluetoothAdapter.ERROR);
switch(mode)
{
//Wenn das Device in Discoverable Mode ist
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Enabled.");
break;
//Wenn das Device nicht im discoverable mode ist:
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG,"mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG,"mBroadcastReceiver2: Connecting...");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG,"mBroadcastReceiver2:Connected.");
break;
}
}
}
};
//wird ausgeführt wenn wir auf den Button klicken
public void btnEnableDisable_Discoverable(View view)
{
Log.d(TAG,"btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
//Ende Funktionen und Part fuer unseren Discoverability Button
//Broadcast Receiver 3 für discover devices list
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG,"onReceive: Action Found");
if(action.equals(BluetoothDevice.ACTION_FOUND))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter((mDeviceListAdapter));
}
}
} ;
//Broadcast Receiver 4
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
{
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases
//case 1: It detects a device that is already bonded
if(mDevice.getBondState() == BluetoothDevice.BOND_BONDED)
{
Log.d(TAG,"BroadcastReceiver: BOND_BONDED");
}
// case 2: Device creating a bond
if(mDevice.getBondState() == BluetoothDevice.BOND_BONDING)
{
Log.d(TAG,"BroadcastReceiver: BOND_BONDING");
}
//case 3: device breaking a bond
if(mDevice.getBondState() == BluetoothDevice.BOND_NONE)
{
Log.d(TAG,"BroadcastReceiver: BOND_NONE");
}
}
}
};
@Override
protected void onDestroy()
{
Log.d(TAG,"onDestroy: called");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose);
Button btnONOFF = (Button) findViewById(R.id.ConnectDevice);
btnEnableDisable_Discoverable = (Button)findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcast wenn der Status verändert wird
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4,filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(ChooseActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Log.d(TAG,"OnClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
}
public void btnDiscover(View view)
{
Log.d(TAG,"btnDiscover: Looking for unpaired Devices");
if(mBluetoothAdapter.isDiscovering())
{
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG,"btnDiscover:Cancelling discovery.");
//Checkt ob die Berechtigungen im Manifest für BT vorliegen
checkBTPermissions();
//start discovery again
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);
}
if(!(mBluetoothAdapter.isDiscovering()))
{
//another check
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3,discoverDevicesIntent);
}
}
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
public void enableDisableBT()
{
if (mBluetoothAdapter == null) // Wenn das Gerät keinen Bluetooth Adapter hat
{
Log.d(TAG,"enableDisableBT: Does not have Bluetooth capabilities");
}
if(!(mBluetoothAdapter.isEnabled())) // Wenn Bluetooth ausgeschaltet ist
{
Log.d(TAG,"enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()) //Wenn bluetoothAdapter bereits enabled ist
{
Log.d(TAG,"enableDisbaleBTW:disabling BT");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void openRemoteControl(View view)
{
Intent intent = new Intent(this, RemoteControl.class);
startActivity(intent);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//cancel discovery because it is very memory intensive
mBluetoothAdapter.cancelDiscovery();
String deviceName = mBTDevices.get(position).getName();
String deviceAddress = mBTDevices.get(position).getAddress();
Log.d(TAG, "onItemClick: You clicked on a device");
Log.d(TAG,"onItemClick: deviceName: " + deviceName);
Log.d(TAG,"onItemClick: deviceAdress: " + deviceAddress);
//creates the bond
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2 )
{
Log.d(TAG,"Trying to pair with: " + deviceName);
mBTDevices.get(position).createBond();
}
}
}
activity_choose. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChooseActivity">
<Button
android:id="@+id/ConnectDevice"
android:layout_width="225dp"
android:layout_height="49dp"
android:layout_marginStart="93dp"
android:layout_marginLeft="93dp"
android:layout_marginTop="73dp"
android:layout_marginEnd="93dp"
android:layout_marginRight="93dp"
android:layout_marginBottom="123dp"
android:background="#020202"
android:text="Bluetooth ON/OFF"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toTopOf="@+id/remoteButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/connectionStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="102dp"
android:layout_marginLeft="102dp"
android:layout_marginEnd="96dp"
android:layout_marginRight="96dp"
android:layout_marginBottom="46dp"
android:ems="10"
android:gravity="center"
android:hint="No Device Connected "
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/remoteButton"
android:layout_width="207dp"
android:layout_height="43dp"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginEnd="101dp"
android:layout_marginRight="101dp"
android:layout_marginBottom="9dp"
android:onClick="openRemoteControl"
android:text="Remote Control"
app:layout_constraintBottom_toTopOf="@+id/temperatureButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/temperatureButton"
android:layout_width="207dp"
android:layout_height="43dp"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginEnd="101dp"
android:layout_marginRight="101dp"
android:layout_marginBottom="9dp"
android:text="Temperature Monitor"
app:layout_constraintBottom_toTopOf="@+id/historyButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/historyButton"
android:layout_width="207dp"
android:layout_height="43dp"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginEnd="101dp"
android:layout_marginRight="101dp"
android:layout_marginBottom="9dp"
android:text="History"
app:layout_constraintBottom_toTopOf="@+id/button5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/button5"
android:layout_width="207dp"
android:layout_height="43dp"
android:layout_marginStart="104dp"
android:layout_marginLeft="104dp"
android:layout_marginEnd="101dp"
android:layout_marginRight="101dp"
android:layout_marginBottom="195dp"
android:text="Terminal"
app:layout_constraintBottom_toTopOf="@+id/connectionStatus"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btnDiscoverable_on_off"
android:layout_width="216dp"
android:layout_height="49dp"
android:layout_marginStart="97dp"
android:layout_marginLeft="97dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="98dp"
android:layout_marginRight="98dp"
android:layout_marginBottom="62dp"
android:onClick="btnEnableDisable_Discoverable"
android:text="Enable Discoverable"
app:layout_constraintBottom_toTopOf="@+id/remoteButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ConnectDevice" />
<Button
android:id="@+id/btnFindUnpairedDevices"
android:layout_width="218dp"
android:layout_height="43dp"
android:layout_marginStart="96dp"
android:layout_marginLeft="96dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="97dp"
android:layout_marginRight="97dp"
android:layout_marginBottom="10dp"
android:onClick="btnDiscover"
android:text="Discover"
app:layout_constraintBottom_toTopOf="@+id/ConnectDevice"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="@+id/lvNewDevices"
android:layout_width="319dp"
android:layout_height="169dp"
android:layout_marginStart="46dp"
android:layout_marginLeft="46dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="46dp"
android:layout_marginRight="46dp"
android:layout_marginBottom="14dp"
app:layout_constraintBottom_toTopOf="@+id/connectionStatus"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button5"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
DeviceListAdapter. java
package com.example.fernsteuerung;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
super(context, tvResourceId,devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = tvResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflater.inflate(mViewResourceId, null);
BluetoothDevice device = mDevices.get(position);
if (device != null) {
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
if (deviceName != null) {
deviceName.setText(device.getName());
}
if (deviceAdress != null) {
deviceAdress.setText(device.getAddress());
}
}
return convertView;
}
}