bluetooth_db.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import 'dart:async';
  2. import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
  3. import 'package:path/path.dart';
  4. import 'package:sqflite/sqflite.dart';
  5. class BluetoothDB {
  6. static final BluetoothDB _instance = new BluetoothDB.internal();
  7. factory BluetoothDB() => _instance;
  8. static Database? _db;
  9. BluetoothDB.internal();
  10. Future<Database> get db async {
  11. if (_db != null) {
  12. return _db!;
  13. }
  14. _db = await initDb();
  15. return _db!;
  16. }
  17. static final String TABLE = 'bluetooth';
  18. static final String C_ID = 'id';
  19. static final String C_NAME = 'name';
  20. static final String C_MARK = 'mark';
  21. static final String C_TIMES = 'times';
  22. initDb() async {
  23. String databasesPath = await getDatabasesPath();
  24. String path = join(databasesPath, 'bluetooth.db');
  25. var db = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
  26. return db;
  27. }
  28. FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
  29. if (newVersion > oldVersion) {
  30. try {
  31. await db.execute("drop table $TABLE");
  32. } catch (e) {
  33. print(e);
  34. }
  35. }
  36. await _onCreate(db, newVersion);
  37. }
  38. FutureOr<void> _onCreate(Database db, int version) async {
  39. await db.execute('CREATE TABLE $TABLE($C_ID VARCHAR PRIMARY KEY,$C_NAME VARCHAR, $C_MARK VARCHAR, $C_TIMES INTEGER)');
  40. }
  41. Future<int> insert(DiscoveredDevice item, {String? mark}) async {
  42. var dbClient = await db;
  43. var history = await find();
  44. if (history.any((element) => element[BluetoothDB.C_ID] == item.id)) {
  45. if (mark == null) {
  46. return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch}, where: "$C_ID = ?", whereArgs: [item.id]);
  47. } else {
  48. return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch, C_MARK: mark}, where: "$C_ID = ?", whereArgs: [item.id]);
  49. }
  50. } else {
  51. return await dbClient.insert(TABLE, {C_ID: item.id, C_NAME: item.name, C_MARK: mark, C_TIMES: DateTime.now().millisecondsSinceEpoch}, conflictAlgorithm: ConflictAlgorithm.replace);
  52. }
  53. }
  54. Future<List<Map<String, dynamic>>> findById(String id) async {
  55. var dbClient = await db;
  56. return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE where $C_ID = "$id"');
  57. }
  58. Future<List<Map<String, dynamic>>> find() async {
  59. var dbClient = await db;
  60. return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE order by $C_TIMES desc');
  61. }
  62. }