123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import 'dart:async';
- import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
- import 'package:path/path.dart';
- import 'package:sqflite/sqflite.dart';
- class BluetoothDB {
- static final BluetoothDB _instance = new BluetoothDB.internal();
- factory BluetoothDB() => _instance;
- static Database? _db;
- BluetoothDB.internal();
- Future<Database> get db async {
- if (_db != null) {
- return _db!;
- }
- _db = await initDb();
- return _db!;
- }
- static final String TABLE = 'bluetooth';
- static final String C_ID = 'id';
- static final String C_NAME = 'name';
- static final String C_MARK = 'mark';
- static final String C_TIMES = 'times';
- initDb() async {
- String databasesPath = await getDatabasesPath();
- String path = join(databasesPath, 'bluetooth.db');
- var db = await openDatabase(path, version: 2, onCreate: _onCreate, onUpgrade: _onUpgrade);
- return db;
- }
- FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
- if (newVersion > oldVersion) {
- try {
- await db.execute("drop table $TABLE");
- } catch (e) {
- print(e);
- }
- }
- await _onCreate(db, newVersion);
- }
- FutureOr<void> _onCreate(Database db, int version) async {
- await db.execute('CREATE TABLE $TABLE($C_ID VARCHAR PRIMARY KEY,$C_NAME VARCHAR, $C_MARK VARCHAR, $C_TIMES INTEGER)');
- }
- Future<int> insert(DiscoveredDevice item, {String? mark}) async {
- var dbClient = await db;
- var history = await find();
- if (history.any((element) => element[BluetoothDB.C_ID] == item.id)) {
- if (mark == null) {
- return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch}, where: "$C_ID = ?", whereArgs: [item.id]);
- } else {
- return await dbClient.update(TABLE, {C_TIMES: DateTime.now().millisecondsSinceEpoch, C_MARK: mark}, where: "$C_ID = ?", whereArgs: [item.id]);
- }
- } else {
- return await dbClient.insert(TABLE, {C_ID: item.id, C_NAME: item.name, C_MARK: mark, C_TIMES: DateTime.now().millisecondsSinceEpoch}, conflictAlgorithm: ConflictAlgorithm.replace);
- }
- }
- Future<List<Map<String, dynamic>>> findById(String id) async {
- var dbClient = await db;
- return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE where $C_ID = "$id"');
- }
- Future<List<Map<String, dynamic>>> find() async {
- var dbClient = await db;
- return await dbClient.rawQuery('SELECT $C_ID,$C_NAME,$C_MARK, $C_TIMES FROM $TABLE order by $C_TIMES desc');
- }
- }
|