-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbluetooth
More file actions
295 lines (198 loc) · 9.71 KB
/
Copy pathbluetooth
File metadata and controls
295 lines (198 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
This file will teach you about connecting mobile's bluetooth and arduino or to other devices
https://developer.android.com/develop/connectivity/bluetooth
Refer the above for complete documentation
My purpose is to build an app to communicate with arduino
1)A discovery process happens and both devices exchange security keys and after pairing and bonding both start exchanging information
2)Using bluetooth's api
*permissions
-------------------------------------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for android 12 or higher (my phone 9 only)
declare bluetooth_scan -> for scanning
bluetooth_advertise -> makes your phone discoverable . these are runtime permissions and should get from user
bluetooth_connect -> if communicates with already paired bluetooth devices
also set max_sdkVersion = 30 , so that this applies only for android 12 and higher
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for android 11 or lower
declare bluetooth_admin -> only for discovering bt devices
bluetooth ->enough for all communications
also declare uses-feature android.hardware.bluetooth and required = true
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
------------------------------------------------------------------------------------------------------------------------------------------------------
*checking and getting bluetoothadapter and then do 1)find devices 2)connect to a device 3)transfer data with connected device
*bluetooth api's in android.bluetooth package
3) Now let us start :
1)get bluetooth adapter:
first get bluetooth adapter . bluetooth adapter is required for all bluetooth functions and represents the device's bluetooth radio or adapter .
get it from bluetoothmanager systemservice's refernce and then create a bluetooth adapter object
code:
<<<<<<<<<<<<<
val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.getAdapter()
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
>>>>>>>>>>>>>>>>>>
2)enable bluetooth
code:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
else{
Toast.makeText(this, "bluetooth is on", Toast.LENGTH_SHORT).show()
}
private val REQUEST_ENABLE_BT = 1
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
// User enabled Bluetooth
Toast.makeText(this, "bluetooth enabled ok", Toast.LENGTH_SHORT).show()
}
if(resultCode== RESULT_CANCELED){
// User declined to enable Bluetooth
Toast.makeText(this, "bluetooth why not enable", Toast.LENGTH_SHORT).show()
finish()
}
}
}
//all in the main activity
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
3)Finding Bluetooth devices and discoverability
discoverable devices tells about user location .
pairing -> means two devices are aware of each other and then have a shared key
connected -> devices has RFCOMM channel and then use it to communicate
to see all paired devies use getBondedDevices .
Code :
<<<<<<<<<<<<<<<<<<<<
val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
pairedDevices?.forEach { device ->
val deviceName = device.name
val deviceHardwareAddress = device.address
>>>>>>>>>>>>>>>>>>>
Separate code exists to make your own mobile discoverable
4)Making a connection
To make a connection should put both sides sockets . Each obtain bluetoothsocket in different ways
The server and client are considered connected to each other when they each have a
connected BluetoothSocket on the same RFCOMM channel
One should act as server socket
UUID is like cryptography . connection happens when client also sends request with same uuid
here arduino gives well known uuid
private val NAME = "HC-05"
private val KNOWN_SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
-----------------------------------
we assume , that the arduino is the server. and we try to communicate as client
we create a socket and then connect and get outputstream and write data to it
code:
<<<<<<<<<<<<<<<<<<<<<<<<<<<
fun connectbtdevice(bluetoothAdapter: BluetoothAdapter?){
val device: BluetoothDevice = bluetoothAdapter!!.getRemoteDevice("58:56:00:00:F3:A1") //tells bluetooth adapter not null at this pt .address is of HC-05
try {
Log.d("try","yes rfcomm proces started")
bluetoothSocket = device!!.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
bluetoothSocket.connect()
Log.d("try","yes rfcomm connection done")
outputStream = bluetoothSocket.outputStream
outputStream.write("k".toByteArray())
} catch (e: IOException) {
Log.d("try","rf comm failed exception $e") //here socket closed is the problem
// Handle connection error
return
}
}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
---------------------------------
FULL CODE:
package com.example.bluetooth_app
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException
import java.io.OutputStream
import java.util.UUID
class MainActivity : AppCompatActivity() {
private val REQUEST_ENABLE_BT = 1
private lateinit var bluetoothSocket: BluetoothSocket
private lateinit var outputStream: OutputStream
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
// User enabled Bluetooth
Toast.makeText(this, "bluetooth enabled ok", Toast.LENGTH_SHORT).show()
}
if(resultCode== RESULT_CANCELED){
// User declined to enable Bluetooth
Toast.makeText(this, "bluetooth why not enable", Toast.LENGTH_SHORT).show()
finish()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//getting bluetooth adapter
val btadapter : BluetoothAdapter? = getbluetoothadapter()
if(btadapter==null){
finish() //finish the current activity
}
//enabling bluetooth
enablebluetooth(btadapter)
getalreadypairedbluetoothdevices(btadapter)
connectbtdevice(btadapter)
}
fun getbluetoothadapter() : BluetoothAdapter?{
val bluetoothManager: BluetoothManager = getSystemService(BluetoothManager::class.java)
val bluetoothAdapter: BluetoothAdapter? = bluetoothManager.getAdapter()
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(this, "no bluetoth", Toast.LENGTH_SHORT).show()
}
else{
Toast.makeText(this, "bluetooth compatible device", Toast.LENGTH_LONG).show()
}
return bluetoothAdapter
}
fun enablebluetooth(bluetoothAdapter:BluetoothAdapter?){
if (bluetoothAdapter?.isEnabled == false) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
else{
Toast.makeText(this, "bluetooth is on", Toast.LENGTH_SHORT).show()
}
}
fun getalreadypairedbluetoothdevices(bluetoothAdapter: BluetoothAdapter?){
Log.d("working","till here")
val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
pairedDevices?.forEach { device ->
val deviceName = device.name
val deviceHardwareAddress = device.address // MAC address
Log.d("success","name = $deviceName")
Log.d("success","add = $deviceHardwareAddress")
}
}
fun connectbtdevice(bluetoothAdapter: BluetoothAdapter?){
val device: BluetoothDevice = bluetoothAdapter!!.getRemoteDevice("58:56:00:00:F3:A1") //tells bluetooth adapter not null at this pt
try {
Log.d("try","yes rfcomm proces started")
bluetoothSocket = device!!.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
bluetoothSocket.connect()
Log.d("try","yes rfcomm connection done")
outputStream = bluetoothSocket.outputStream
outputStream.write("k".toByteArray())
} catch (e: IOException) {
Log.d("try","rf comm failed exception $e") //here socket closed is the problem
// Handle connection error
return
}
}
}