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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
| import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import static android.R.layout.*;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
BluetoothAdapter bluetoothAdapter;
ArrayList<String> pairedDeviceArrayList;
ListView listViewPairedDevice;
FrameLayout ButPanel;
ArrayAdapter<String> pairedDeviceAdapter;
private UUID myUUID;
ThreadConnectBTdevice myThreadConnectBTdevice;
ThreadConnected myThreadConnected;
private StringBuilder sb = new StringBuilder();
public TextView textInfo, d10;
TextView tvText;
TextView tvText1;
TextView tvText2;
TextView tvText3;
SensorManager sensorManager;
Sensor sensorAccel;
Sensor sensorLinAccel;
Sensor sensorGravity;
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
StringBuilder sb3 = new StringBuilder();
StringBuilder sb4 = new StringBuilder();
Timer timer;
private float xy_angle;
private float xz_angle;
private int x;
private int y;
public int direction = 100;
byte output = 22; //пример
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final String UUID_STRING_WELL_KNOWN_SPP = "00001101-0000-1000-8000-00805F9B34FB";
textInfo = (TextView)findViewById(R.id.textInfo);
d10 = (TextView)findViewById(R.id.d10);
listViewPairedDevice = (ListView)findViewById(R.id.pairedlist);
ButPanel = (FrameLayout) findViewById(R.id.ButPanel);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)){
Toast.makeText(this, "BLUETOOTH NOT support", Toast.LENGTH_LONG).show();
finish();
return;
}
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this hardware platform", Toast.LENGTH_LONG).show();
finish();
return;
}
String stInfo = bluetoothAdapter.getName() + " " + bluetoothAdapter.getAddress(); //норм
textInfo.setText(String.format("Это устройство: %s", stInfo));
tvText = (TextView) findViewById(R.id.tvText);
tvText1 = (TextView) findViewById(R.id.tvText1);
tvText2 = (TextView) findViewById(R.id.tvText2);
tvText3 = (TextView) findViewById(R.id.tvText3);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorLinAccel = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
} // END onCreate
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(listener, sensorAccel, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorLinAccel, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorGravity, SensorManager.SENSOR_DELAY_NORMAL);
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
showInfo();
}
});
}
};
timer.schedule(task, 0, 20);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
timer.cancel();
}
String format(float values[]) {
return String.format("%1$.1f\t\t%2$.1f\t\t%3$.1f", values[0], values[1],
values[2]);
}
float[] valuesAccel = new float[3];
float[] valuesAccelMotion = new float[3];
float[] valuesAccelGravity = new float[3];
float[] valuesLinAccel = new float[3];
float[] valuesGravity = new float[3];
SensorEventListener listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
for (int i = 0; i < 3; i++) {
valuesAccel[i] = event.values[i];
valuesAccelGravity[i] = (float) (0.1 * event.values[i] + 0.9 * valuesAccelGravity[i]);
valuesAccelMotion[i] = event.values[i]
- valuesAccelGravity[i];
}
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
for (int i = 0; i < 3; i++) {
valuesLinAccel[i] = event.values[i];
}
break;
case Sensor.TYPE_GRAVITY:
for (int i = 0; i < 3; i++) {
valuesGravity[i] = event.values[i];
}
break;
}
xy_angle = event.values[0]*10; //Плоскость XY
xz_angle = event.values[1]*10; //Плоскость XZ
x=-(int) xy_angle*1;
y=-(int) xz_angle*1;
if(y>-40&&y<-20){
direction=100;// скорость вперед ноль, никуда не едем, смотрим есть ли повороты
if (x>10){//скорость вправо от 10 до 30 диапазон 20 единиц
direction=(byte)(x+30);
if (direction>60){direction=60;}
}
if(x<-10){
direction=(byte)(-x+50);
if (direction>80){direction=80;}
}
}
else {
if (y > -20) {// едем вперед, диапазон -20: 20 итого 40 единиц
direction = (byte) (y / 2 + 10);
if (direction > 20) {
direction = 20;
}
}
if (y < -40) {// едем назад, диапазон -40: -80 итого 40 единиц
direction = (byte) (-y - 20);
if (direction > 40) {
direction = 40;
}
}
}
}
};
void showInfo() {
sb1.setLength(0);
sb1.append("Accelerometer: " + format(valuesAccel))
// .append("\n\nAccel motion: " + format(valuesAccelMotion))
// .append("\nAccel gravity : " + format(valuesAccelGravity))
// .append("\n\nLin accel : " + format(valuesLinAccel))
// .append("\nGravity : " + format(valuesGravity))
;
tvText.setText(sb1);
sb2.setLength(0);
sb2.append(xy_angle + " " + xz_angle);
tvText1.setText(sb2);
sb3.setLength(0);
sb3.append(xy_angle + " " + xz_angle);
tvText2.setText(sb3);
sb4.setLength(0);
sb4.append(direction);
tvText3.setText(sb4);
}
@Override
protected void onStart() { // Запрос на включение Bluetooth
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT); //норм
}
setup();
}
private void setup() { // Создание списка сопряжённых Bluetooth-устройств
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); //норм
if (pairedDevices.size() > 0) { // Если есть сопряжённые устройства
pairedDeviceArrayList = new ArrayList<>();
for (BluetoothDevice device : pairedDevices) { // Добавляем сопряжённые устройства - Имя + MAC-адресс
pairedDeviceArrayList.add(device.getName() + "\n" + device.getAddress()); //норм
}
pairedDeviceAdapter = new ArrayAdapter<>(this, simple_list_item_1, pairedDeviceArrayList);
listViewPairedDevice.setAdapter(pairedDeviceAdapter);
listViewPairedDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() { // Клик по нужному устройству
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listViewPairedDevice.setVisibility(View.GONE); // После клика скрываем список
String itemValue = (String) listViewPairedDevice.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17); // Вычленяем MAC-адрес
BluetoothDevice device2 = bluetoothAdapter.getRemoteDevice(MAC);
myThreadConnectBTdevice = new ThreadConnectBTdevice(device2);
myThreadConnectBTdevice.start(); // Запускаем поток для подключения Bluetooth
}
});
}
}
@Override
protected void onDestroy() { // Закрытие приложения
super.onDestroy();
if(myThreadConnectBTdevice!=null) myThreadConnectBTdevice.cancel();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { //норм
if(requestCode == REQUEST_ENABLE_BT){ // Если разрешили включить Bluetooth, тогда void setup()
if(resultCode == Activity.RESULT_OK) {
setup();
}
else { // Если не разрешили, тогда закрываем приложение
Toast.makeText(this, "BlueTooth не включён", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private class ThreadConnectBTdevice extends Thread { // Поток для коннекта с Bluetooth
private BluetoothSocket bluetoothSocket = null;
private ThreadConnectBTdevice(BluetoothDevice device) {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID); //норм
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() { // Коннект
boolean success = false;
try {
bluetoothSocket.connect(); //норм
success = true;
}
catch (IOException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Нет коннекта, проверьте Bluetooth-устройство с которым хотите соединица!", Toast.LENGTH_LONG).show();
listViewPairedDevice.setVisibility(View.VISIBLE);
}
});
try {
bluetoothSocket.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
if(success) { // Если законнектились, тогда открываем панель с кнопками и запускаем поток приёма и отправки данных
runOnUiThread(new Runnable() {
@Override
public void run() {
ButPanel.setVisibility(View.VISIBLE); // открываем панель с кнопками
}
});
myThreadConnected = new ThreadConnected(bluetoothSocket);
myThreadConnected.start(); // запуск потока приёма и отправки данных
}
}
public void cancel() {
Toast.makeText(getApplicationContext(), "Close - BluetoothSocket", Toast.LENGTH_LONG).show();
try {
bluetoothSocket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
} // END ThreadConnectBTdevice:
private class ThreadConnected extends Thread { // Поток - приём и отправка данных
private final InputStream connectedInputStream;
private final OutputStream connectedOutputStream;
private String sbprint;
public ThreadConnected(BluetoothSocket socket) {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
}
catch (IOException e) {
e.printStackTrace();
}
connectedInputStream = in;
connectedOutputStream = out;
}
@Override
public void run() { // Приём данных
while (true) {
try {
byte[] buffer = new byte[1];
int bytes = connectedInputStream.read(buffer);
String strIncom = new String(buffer, 0, bytes);
sb.append(strIncom); // собираем символы в строку
int endOfLineIndex = sb.indexOf("\r\n"); // определяем конец строки
if (endOfLineIndex > 0) {
sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
runOnUiThread(new Runnable() { // Вывод данных
@Override
public void run() {
switch (sbprint) {
case "D10 ON":
d10.setText(sbprint);
break;
case "D10 OFF":
d10.setText(sbprint);
break;
default:
break;
}
}
});
}
} catch (IOException e) {
break;
}
}
}
public void write(int buffer) {
try {
connectedOutputStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/////////////////// Нажатие кнопок /////////////////////
/////////////////////////D10////////////////////////////
public void onClickBut1(View v) {
if(myThreadConnected!=null) {
int bytesToSend = direction;
myThreadConnected.write(bytesToSend );
}
}
public void onClickBut2(View v) {
if(myThreadConnected!=null) {
int bytesToSend = output;
myThreadConnected.write(bytesToSend );
}
}
} // END |