BLEService.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. package com.doorknocker.bluetooth;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import android.annotation.SuppressLint;
  7. import android.app.Service;
  8. import android.bluetooth.BluetoothAdapter;
  9. import android.bluetooth.BluetoothDevice;
  10. import android.bluetooth.BluetoothGatt;
  11. import android.bluetooth.BluetoothGattCallback;
  12. import android.bluetooth.BluetoothGattCharacteristic;
  13. import android.bluetooth.BluetoothGattDescriptor;
  14. import android.bluetooth.BluetoothGattService;
  15. import android.bluetooth.BluetoothManager;
  16. import android.bluetooth.BluetoothProfile;
  17. import android.bluetooth.le.BluetoothLeScanner;
  18. import android.bluetooth.le.ScanCallback;
  19. import android.bluetooth.le.ScanResult;
  20. import android.content.BroadcastReceiver;
  21. import android.content.Context;
  22. import android.content.Intent;
  23. import android.content.IntentFilter;
  24. import android.content.SharedPreferences;
  25. import android.os.Binder;
  26. import android.os.Handler;
  27. import android.os.IBinder;
  28. import android.os.Message;
  29. import android.os.PowerManager;
  30. import android.os.PowerManager.WakeLock;
  31. import android.util.Log;
  32. import com.doorknocker.Constant;
  33. import com.doorknocker.model.DoorItem;
  34. public class BLEService extends Service {
  35. public static final String SERVERSBROADCASTINF = "com.mt.service_inf";
  36. public static final String SERVERSBROADCASTINF_KEY = "key";
  37. private int currentVersion;
  38. /**
  39. * 开门的距离,正式上线之后要从配置文件中获取
  40. */
  41. private int openDistance = -75;
  42. @Override
  43. public void onCreate() {
  44. super.onCreate();
  45. System.out.println("onCreate BLEService");
  46. // mHandler.sendEmptyMessage(REFLASH_PROTECT_SERVICE);
  47. if (!initBle()) {
  48. return;
  49. }
  50. /**
  51. * 如果安卓版本低于4.3就不要往下执行了。
  52. */
  53. currentVersion = android.os.Build.VERSION.SDK_INT;
  54. if (Constant.MIN_OS_VERSION > currentVersion) {
  55. return;
  56. }
  57. // 默认开门距离
  58. SharedPreferences preferences = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE);
  59. openDistance = preferences.getInt(Constant.KEY_DOOR_DISTANCE_DEFAULT, -75);
  60. initBroadcastReceiver();
  61. getDoorInfFromDB();
  62. scanBle();
  63. acquireWakeLock();
  64. }
  65. // 申请电源锁,禁止休眠
  66. private WakeLock mWakeLock = null;
  67. private void acquireWakeLock() {
  68. if (null == mWakeLock) {
  69. PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
  70. mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
  71. .getClass().getCanonicalName());
  72. if (null != mWakeLock) {
  73. mWakeLock.acquire();
  74. }
  75. }
  76. }
  77. // 释放设备电源锁
  78. private void releaseWakeLock() {
  79. if (null != mWakeLock) {
  80. mWakeLock.release();
  81. mWakeLock = null;
  82. }
  83. }
  84. @Override
  85. public int onStartCommand(Intent intent, int flags, int startId) {
  86. System.out.println("onStartCommand1");
  87. return START_STICKY;
  88. }
  89. // 获取门列表
  90. private DBAdapter db;
  91. private SharedPreferences prefs;
  92. private Map<String, DoorItem> doormap = new HashMap<String, DoorItem>();
  93. private void getDoorInfFromDB() {
  94. db = new DBAdapter(getApplicationContext());
  95. // 查看是否有权限
  96. SharedPreferences preferences = getSharedPreferences(
  97. Constant.NAME_CONFIG, Context.MODE_PRIVATE);
  98. boolean hasPermission = preferences.getBoolean(
  99. Constant.HAS_DOOR_PERMITION, false);
  100. if (!hasPermission) {
  101. return;
  102. }
  103. // 获取列表
  104. db.open();
  105. doormap = db.getAllClockListMap();
  106. if (doormap == null) {
  107. System.out.println("has no doors");
  108. }
  109. db.close();
  110. }
  111. public BluetoothManager mBluetoothManager;
  112. public BluetoothAdapter mBluetoothAdapter;
  113. //private BluetoothLeScanner scanner;
  114. public BluetoothGatt mBluetoothGatt;
  115. private List<MTBeacon> scan_devices = new ArrayList<MTBeacon>();
  116. // 初始化BLE
  117. @SuppressLint("NewApi")
  118. private boolean initBle() {
  119. System.out.println("initBle");
  120. mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  121. if (null == mBluetoothManager) {
  122. System.out.println("获取 mBluetoothManager失败");
  123. return false;
  124. }
  125. mBluetoothAdapter = mBluetoothManager.getAdapter();
  126. if (null == mBluetoothAdapter) {
  127. System.out.println("获取 mBluetoothAdapter失败");
  128. return false;
  129. }
  130. //scanner = mBluetoothAdapter.getBluetoothLeScanner();
  131. return true;
  132. }
  133. // 扫描设备
  134. private Handler search_timer = new Handler() {
  135. @Override
  136. public void handleMessage(Message msg) {
  137. super.handleMessage(msg);
  138. new OpenDoorThread().start();
  139. }
  140. };
  141. @SuppressLint("NewApi")
  142. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
  143. @Override
  144. public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
  145. int i = 0;
  146. MTBeacon beacon_tmp = new MTBeacon(device, rssi, scanRecord);
  147. // 是否为ibeacon
  148. if (!beacon_tmp.isIsClock()) {
  149. return;
  150. }
  151. for (i = 0; i < scan_devices.size(); i++) {
  152. if (0 == device.getAddress().compareTo(
  153. scan_devices.get(i).GetDevice().getAddress())) {
  154. scan_devices.get(i).ReflashInf(device, rssi, scanRecord); // 更新信息
  155. return;
  156. }
  157. }
  158. // 如果没有,就添加
  159. scan_devices.add(beacon_tmp);
  160. }
  161. };
  162. //扫描回调
  163. /*@SuppressLint("NewApi")
  164. private ScanCallback mScanCallback = new ScanCallback() {
  165. public void onBatchScanResults(List<ScanResult> results) {
  166. for (int index = 0, size = results.size(); index < size; index++) {
  167. ScanResult result = results.get(index);
  168. MTBeacon beacon_tmp = new MTBeacon(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes());
  169. // 是否为ibeacon
  170. if (!beacon_tmp.isIsClock()) {
  171. return;
  172. }
  173. if (0 == result.getDevice().getAddress().compareTo(
  174. scan_devices.get(index).GetDevice().getAddress())) {
  175. scan_devices.get(index).ReflashInf(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes()); // 更新信息
  176. return;
  177. }
  178. // 如果没有,就添加
  179. scan_devices.add(beacon_tmp);
  180. }
  181. };
  182. };*/
  183. private void scanBle() {
  184. search_timer.sendEmptyMessage(0);
  185. }
  186. // 开门操作
  187. private boolean connect_flag = false;
  188. private boolean notification_flag = false;
  189. private boolean openclock_flag = false;
  190. private boolean scan_flag = false; // 是否正在扫描
  191. private boolean has_permition_clock_flag = false;
  192. private boolean timeout_flag = false; // 超时标志
  193. private final int REFLASH_PROTECT_SERVICE = 1;
  194. private Handler mHandler = new Handler() {
  195. public void handleMessage(Message msg) {
  196. if (msg.what == 0) {
  197. timeout_flag = true;
  198. return;
  199. }
  200. if (msg.what == REFLASH_PROTECT_SERVICE) {
  201. Intent intent = new Intent(getApplicationContext(),
  202. ProtectService.class);
  203. startService(intent);
  204. mHandler.sendEmptyMessageDelayed(REFLASH_PROTECT_SERVICE, 10000);
  205. return;
  206. }
  207. };
  208. };
  209. @SuppressLint("NewApi")
  210. private class OpenDoorThread extends Thread {
  211. @Override
  212. public void run() {
  213. super.run();
  214. try {
  215. if (!mBluetoothAdapter.isEnabled()) {
  216. search_timer.sendEmptyMessageDelayed(0, 1000);
  217. scan_flag = true;
  218. return;
  219. }
  220. if (scan_flag) {
  221. // System.out.println("停止扫描");
  222. LogText.writeStr(" 设备数量->" + scan_devices.size());
  223. Log.i("bluetooth", "设备数量==================================" + scan_devices.size());
  224. mBluetoothAdapter.stopLeScan(mLeScanCallback);
  225. //scanner.stopScan(mScanCallback);
  226. for (MTBeacon mtbeacon : scan_devices) {
  227. // System.out.println("getClockID-->"
  228. // + mtbeacon.getClockID());
  229. DoorItem clock = doormap.get(mtbeacon.getClockID());
  230. System.out.println("ID->" + mtbeacon.getClockID());
  231. if (clock == null) { // 判断此锁是否存在于权限中
  232. LogText.writeStr("没有权限->" + mtbeacon.getClockID());
  233. Log.i("bluetooth", "没有权限===================================");
  234. continue;
  235. }
  236. has_permition_clock_flag = true;
  237. if (mtbeacon.GetAveragerssi() < openDistance) { // 判断距离
  238. LogText.writeStr("距离太远->"
  239. + mtbeacon.GetAveragerssi());
  240. Log.i("bluetooth", "距离太远===================================");
  241. continue;
  242. }
  243. if ((System.currentTimeMillis() - clock
  244. .getLast_open_time()) < 10000) { // 判断距离上次开锁多久了
  245. LogText.writeStr("距离上次开锁还不到10s");
  246. Log.i("bluetooth", "距离上次开锁还不到10s===================================");
  247. continue;
  248. }
  249. if (!connectBLETimeout(mtbeacon, 5000)) {
  250. LogText.writeStr(" 连接超时");
  251. disConectBle();
  252. Log.i("bluetooth", "连接超时===================================");
  253. continue;
  254. }
  255. if (getService()) { // 获取通道
  256. if (!setNotifiTimeout(500)) {
  257. LogText.writeStr(" 设置通知超时");
  258. disConectBle();
  259. Log.i("bluetooth", "设置通知超时===================================");
  260. continue;
  261. }
  262. // 密码验证
  263. if (!writeData(cmdCharacteristic,
  264. "AT+PWD[" + clock.getPassword() + "]", 500)) {
  265. LogText.writeStr(" 密码验证超时");
  266. disConectBle();
  267. Log.i("bluetooth", "密码验证超时===================================");
  268. continue;
  269. }
  270. if (!recive_msg.equals("You Are User\r\n")) {
  271. LogText.writeStr(" 密码配对错误");
  272. Log.i("bluetooth", "密码配对错误===================================");
  273. continue;
  274. }
  275. // 开门命令
  276. // writeData(cmdCharacteristic, "AT+SOPEN", 500);
  277. if (!writeData(cmdCharacteristic, "AT+SOPEN", 500)) {
  278. LogText.writeStr(" 开门超时");
  279. disConectBle();
  280. Log.i("bluetooth", "开门超时===================================");
  281. continue;
  282. }
  283. if (!recive_msg.equals("OK+SOPEN\r\n")) {
  284. LogText.writeStr(" 开门失败");
  285. Log.i("bluetooth", "开门失败===================================");
  286. continue;
  287. }
  288. broadcastUpdate(SERVERSBROADCASTINF, "开锁成功");
  289. LogText.writeStr("开锁成功");
  290. Log.i("bluetooth", "开锁成功===================================");
  291. clock.setLast_open_time(System.currentTimeMillis()); // 设置这次开锁时间
  292. }
  293. disConectBle();
  294. sleep(500);
  295. }
  296. scan_devices.clear();
  297. if (has_permition_clock_flag) {
  298. // search_timer.sendEmptyMessage(0);
  299. search_timer.sendEmptyMessageDelayed(0, 100);
  300. } else {
  301. search_timer.sendEmptyMessageDelayed(0, 5000);
  302. }
  303. has_permition_clock_flag = false;
  304. scan_flag = false; // 设置为没有扫描状态
  305. } else {
  306. broadcastUpdate(SERVERSBROADCASTINF, "开始扫描");
  307. LogText.writeStr(" 开始扫描");
  308. Log.i("bluetooth", "开始扫描===================================");
  309. mBluetoothAdapter.startLeScan(mLeScanCallback);
  310. //scanner.startScan(mScanCallback);
  311. search_timer.sendEmptyMessageDelayed(0, 900); // 扫描1s
  312. scan_flag = true; // 设置为真正扫描状态
  313. }
  314. } catch (InterruptedException e) {
  315. e.printStackTrace();
  316. }
  317. }
  318. // 连接超时判断函数
  319. private boolean connectBLETimeout(MTBeacon mtbeacon, int millsec) {
  320. timeout_flag = false;
  321. connect_flag = false;
  322. if (!mBluetoothAdapter.isEnabled()) {
  323. return false;
  324. }
  325. conectBle(mtbeacon.GetDevice()); // 连接设备
  326. mHandler.sendEmptyMessageDelayed(0, millsec);
  327. while (!connect_flag) {
  328. if (timeout_flag) {
  329. return false;
  330. }
  331. }
  332. mHandler.removeMessages(0);
  333. return true;
  334. }
  335. // 设置可通知超时判断函数
  336. private boolean setNotifiTimeout(int millsec) {
  337. timeout_flag = false;
  338. notification_flag = false;
  339. mBluetoothGatt.setCharacteristicNotification(cmdCharacteristic, true);
  340. return true;
  341. }
  342. // 写数据超时判断
  343. private boolean writeData(BluetoothGattCharacteristic cmdChara,
  344. String data, int millsec) {
  345. timeout_flag = false;
  346. openclock_flag = false;
  347. if (!mBluetoothAdapter.isEnabled()) {
  348. return false;
  349. }
  350. cmdChara.setValue(data);
  351. mBluetoothGatt.writeCharacteristic(cmdChara);
  352. try {
  353. sleep(millsec);
  354. } catch (InterruptedException e) {
  355. // TODO Auto-generated catch block
  356. e.printStackTrace();
  357. }
  358. if (!openclock_flag) {
  359. return false;
  360. }
  361. return true;
  362. }
  363. }
  364. //
  365. private String recive_msg;
  366. private BluetoothGattCharacteristic cmdCharacteristic;
  367. @SuppressLint("NewApi")
  368. private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
  369. @Override
  370. public void onConnectionStateChange(BluetoothGatt gatt, int status,
  371. int newState) {
  372. super.onConnectionStateChange(gatt, status, newState);
  373. if (newState == BluetoothProfile.STATE_CONNECTED) {
  374. System.out.println("CONNECTED");
  375. mBluetoothGatt.discoverServices();
  376. } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
  377. System.out.println("UNCONNECTED");
  378. connect_flag = false;
  379. }
  380. }
  381. @Override
  382. public void onServicesDiscovered(BluetoothGatt gatt, int status) {
  383. super.onServicesDiscovered(gatt, status);
  384. if (status == BluetoothGatt.GATT_SUCCESS) {
  385. System.out.println("onServicesDiscovered");
  386. connect_flag = true;
  387. } else {
  388. System.out.println("onServicesDiscovered fail-->" + status);
  389. }
  390. }
  391. @Override
  392. public void onDescriptorRead(BluetoothGatt gatt,
  393. BluetoothGattDescriptor descriptor, int status) {
  394. super.onDescriptorRead(gatt, descriptor, status);
  395. }
  396. @Override
  397. public void onCharacteristicRead(BluetoothGatt gatt,
  398. BluetoothGattCharacteristic characteristic, int status) {
  399. super.onCharacteristicRead(gatt, characteristic, status);
  400. if (status == BluetoothGatt.GATT_SUCCESS) {
  401. }
  402. }
  403. @Override
  404. public void onCharacteristicChanged(BluetoothGatt gatt,
  405. BluetoothGattCharacteristic characteristic) {
  406. super.onCharacteristicChanged(gatt, characteristic);
  407. recive_msg = characteristic.getStringValue(0);
  408. openclock_flag = true;
  409. System.out.println("read->" + characteristic.getStringValue(0));
  410. }
  411. @Override
  412. public void onCharacteristicWrite(BluetoothGatt gatt,
  413. BluetoothGattCharacteristic characteristic, int status) {
  414. if (status == BluetoothGatt.GATT_SUCCESS) {
  415. System.out.println("write OK");
  416. } else {
  417. System.out.println("write fail");
  418. }
  419. super.onCharacteristicWrite(gatt, characteristic, status);
  420. }
  421. @Override
  422. public void onDescriptorWrite(BluetoothGatt gatt,
  423. BluetoothGattDescriptor descriptor, int status) {
  424. super.onDescriptorWrite(gatt, descriptor, status);
  425. notification_flag = true;
  426. }
  427. };
  428. @SuppressLint("NewApi")
  429. private boolean conectBle(BluetoothDevice mBluetoothDevice) {
  430. disConectBle();
  431. BluetoothDevice device_tmp = mBluetoothAdapter
  432. .getRemoteDevice(mBluetoothDevice.getAddress());
  433. if (device_tmp == null) {
  434. System.out.println("device == null");
  435. return false;
  436. }
  437. mBluetoothGatt = device_tmp.connectGatt(getApplicationContext(), false,
  438. mGattCallback);
  439. return true;
  440. }
  441. // 获取通道号
  442. @SuppressLint("NewApi")
  443. private boolean getService() {
  444. for (BluetoothGattService service : mBluetoothGatt.getServices()) {
  445. // System.out.println("service_uuid->"+service.getUuid().toString().toUpperCase());
  446. if (service.getUuid().toString().toUpperCase()
  447. .equals(MTBeaconUUID.SERVICE_UUID)) {
  448. for (BluetoothGattCharacteristic gattCharacteristic : service
  449. .getCharacteristics()) {
  450. if (gattCharacteristic.getUuid().toString().toUpperCase()
  451. .equals(MTBeaconUUID.CMD_UUID)) {
  452. cmdCharacteristic = gattCharacteristic;
  453. return true;
  454. }
  455. }
  456. }
  457. }
  458. return false;
  459. }
  460. // 断开连接
  461. @SuppressLint("NewApi")
  462. private void disConectBle() {
  463. if (!mBluetoothAdapter.isEnabled()) {
  464. return;
  465. }
  466. if (mBluetoothGatt != null) {
  467. mBluetoothGatt.disconnect();
  468. mBluetoothGatt.close();
  469. mBluetoothGatt = null;
  470. }
  471. connect_flag = false;
  472. }
  473. // 发送广播消息
  474. private void broadcastUpdate(final String action, String value) {
  475. final Intent intent = new Intent(action);
  476. intent.putExtra(SERVERSBROADCASTINF_KEY, value);
  477. sendBroadcast(intent);
  478. }
  479. // 初始化广播接收器
  480. private MyBroadcastReceiver receviver = null;
  481. private void initBroadcastReceiver() {
  482. // 创建一个IntentFilter对象,将其action指定为BluetoothDevice.ACTION_FOUND
  483. IntentFilter intentFilter = new IntentFilter();
  484. intentFilter.addAction(Constant.RELOAD_DATA);
  485. intentFilter.addAction(Constant.RELOAD_OPEN_DOORS_DISTANCE);
  486. receviver = new MyBroadcastReceiver();
  487. // 注册广播接收器
  488. registerReceiver(receviver, intentFilter);
  489. }
  490. private class MyBroadcastReceiver extends BroadcastReceiver {
  491. @Override
  492. public void onReceive(Context context, Intent intent) {
  493. String action = intent.getAction();
  494. if (action.equals(Constant.RELOAD_DATA)) {
  495. // 重新加载数据库
  496. System.out.println("get RELOAD_DATA");
  497. getDoorInfFromDB();
  498. return;
  499. } else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE)) {
  500. // 这里得到实际距离,要将实际距离进行转化
  501. /**
  502. * 0========-5
  503. * 10=======-85
  504. */
  505. openDistance = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE).getInt(Constant.KEY_DOOR_DISTANCE, -85);
  506. if (openDistance > -50) {
  507. openDistance = -50;
  508. }
  509. return;
  510. } else if (action.equals(Constant.RELOAD_OPEN_DOORS_DISTANCE_DEF)) {
  511. SharedPreferences preferences = getSharedPreferences(Constant.NAME_CONFIG, Context.MODE_PRIVATE);
  512. openDistance = preferences.getInt(Constant.KEY_DOOR_DISTANCE_DEFAULT, -75);
  513. return;
  514. }
  515. }
  516. }
  517. @Override
  518. public void onDestroy() {
  519. LogText.writeStr(" onDestroy");
  520. super.onDestroy();
  521. if (receviver != null) {
  522. unregisterReceiver(receviver);
  523. }
  524. // if (receiver != null)
  525. // unregisterReceiver(receiver);
  526. // releaseWakeLock();
  527. releaseWakeLock();
  528. stopForeground(true);
  529. }
  530. public class LocalBinder extends Binder {
  531. public BLEService getService() {
  532. return BLEService.this;
  533. }
  534. }
  535. private final IBinder mBinder = new LocalBinder();
  536. @Override
  537. public IBinder onBind(Intent intent) {
  538. return mBinder;
  539. }
  540. }