Browse Source

基于google nearby实现

liuyuqi-dellpc 2 years ago
parent
commit
11b4e15c97
6 changed files with 217 additions and 76 deletions
  1. 116 1
      README.md
  2. 3 0
      lib/dio/api.dart
  3. 24 0
      lib/dio/track_dao.dart
  4. 59 75
      lib/pages/track_page.dart
  5. 7 0
      pubspec.lock
  6. 8 0
      pubspec.yaml

+ 116 - 1
README.md

@@ -3,4 +3,119 @@
 追踪者app,基于蓝牙提供疫情追踪功能。
 
 
-flutter_blue 依赖安卓19,编译28,其他版本都会出错
+## 基于 google nearby 功能实现
+
+google nearby 基于蓝牙,wifi,gps 等综合信息来发现周围用户:
+
+1、用户注册登录
+``` 注册
+  void register() async {
+    MessageModel messageModel = await LoginDao.register(_userName, _pwd);
+    if (messageModel != null) {
+      if (messageModel.success) {
+        Navigator.of(context).pushNamed(Routes.loginPage);
+      }
+      AppUtil.buildToast(messageModel.msg);
+    } else {
+      AppUtil.buildToast("注册失败,请检查网络");
+    }
+  }
+```
+
+``` 登录
+  void login() async {
+    SharedPreferences prefs = await SharedPreferences.getInstance();
+
+    if (_formKey.currentState.validate()) {
+      _formKey.currentState.save();
+      LoginEntity loginEntity = await LoginDao.login(_username, _password);
+      if (loginEntity.msgModel.success) {
+        prefs.setString('username', _username);
+        prefs.setString('password', _password);
+        prefs.setBool('isLogin', true);
+        Navigator.of(context).pushNamed(Routes.indexPage);
+      }
+      AppUtil.buildToast(loginEntity.msgModel.msg);
+    }
+  }
+```
+
+``` 登出
+  void logout() async {
+    var sharedPreferences = await SharedPreferences.getInstance();
+    String token = sharedPreferences.getString("token");
+    try {
+      MessageModel messageModel = await LoginDao.logout(token);
+      if (messageModel != null) {
+        AppUtil.buildToast(messageModel.msg);
+      }
+    } catch (e) {
+      AppUtil.buildToast("退出异常" + e.toString());
+    }
+    Navigator.of(context).pushNamed(Routes.loginPage);
+    sharedPreferences.remove("token");
+    sharedPreferences.setBool("isLogin", false);
+  }
+
+```
+
+2、进入跟踪页面,用户点击追踪按钮,云端获取最近15天遇到的人(姓名,健康状态)。
+```
+    try {
+      bool a = await Nearby().startAdvertising(
+        currentUser.username,
+        strategy,
+        onConnectionInitiated: null,
+        onConnectionResult: (id, status) {
+          print(status);
+        },
+        onDisconnected: (id) {
+          print('Disconnected $id');
+        },
+      );
+      // 上传追踪数据
+      SharedPreferences sharedPreferences =
+          await SharedPreferences.getInstance();
+      String token = sharedPreferences.getString("token");
+      TrackDao.uploadContact(token);
+      print('ADVERTISING ${a.toString()}');
+    } catch (e) {
+      print(e);
+    }
+```
+
+3、开始周围追踪,上传当前用户遇到的人
+
+```
+  void startTrack(bool flag) async {
+    try {
+      bool a = await Nearby().startAdvertising(
+        currentUser.username,
+        strategy,
+        onConnectionInitiated: null,
+        onConnectionResult: (id, status) {
+          print(status);
+        },
+        onDisconnected: (id) {
+          print('Disconnected $id');
+        },
+      );
+      // 上传追踪数据
+      TrackDao.
+
+      print('ADVERTISING ${a.toString()}');
+    } catch (e) {
+      print(e);
+    }
+    discovery();
+  }
+
+```
+
+## 注意
+
+1、flutter_blue 依赖min19,编译30,其他版本都会出错
+
+2、  nearby_connections: ^1.0.3
+
+3、需要 google service 服务,国内安卓系统有问题。

+ 3 - 0
lib/dio/api.dart

@@ -12,6 +12,9 @@ abstract class Api {
   static String getUserByDeviceId = _host + "'getUserByDeviceId";
   static String uploadImgUrl = _host + "/uploadImg";
   static String uploadTrackUrl = _host + "/uploadTrack";
+  static String uploadContactUrl = _host + "/uploadContact";
+
+  static String getContactListUrl = _host + "/getTrackList";
 
   Future<UserModel> login(String username, String password);
 }

+ 24 - 0
lib/dio/track_dao.dart

@@ -1,6 +1,7 @@
 import 'package:dio/dio.dart';
 import 'package:flutter_tracker/dio/api.dart';
 import 'package:flutter_tracker/model/submit_model.dart';
+import 'package:flutter_tracker/model/user_model.dart';
 
 /// Description:
 /// Time       : 2021年12月03日 Friday
@@ -36,4 +37,27 @@ class TrackDao {
     });
     return null;
   }
+
+// 返回最近15天用户的轨迹
+  static Future<List<UserModel>> getContactList(String token) async {
+    params.addAll({"token": token});
+
+    await Dio()
+        .post(Api.getContactListUrl, queryParameters: params)
+        .then((response) {
+      return UserModel.fromJson(response.data);
+    });
+    return null;
+  }
+
+  static Future<UserModel> uploadContact(String token) async{
+    params.addAll({"token": token});
+
+    await Dio()
+        .post(Api.uploadContactUrl, queryParameters: params)
+        .then((response) {
+      return UserModel.fromJson(response.data);
+    });
+    return null;
+  }
 }

+ 59 - 75
lib/pages/track_page.dart

@@ -1,9 +1,10 @@
 import 'package:flutter/material.dart';
 import 'package:flutter_blue/flutter_blue.dart';
-import 'package:flutter_tracker/dio/login_dao.dart';
+import 'package:flutter_tracker/dio/track_dao.dart';
 import 'package:flutter_tracker/model/user_model.dart';
-import 'package:flutter_tracker/utils/app_util.dart';
 import 'package:flutter_tracker/views/contact_card.dart';
+import 'package:nearby_connections/nearby_connections.dart';
+import 'package:shared_preferences/shared_preferences.dart';
 
 import 'bluetooth_off_page.dart';
 
@@ -19,11 +20,14 @@ class TrackPage extends StatefulWidget {
 
 class _TrackPageState extends State<TrackPage> {
   String testText = '';
-
+  final Strategy strategy = Strategy.P2P_STAR;
+  UserModel currentUser;
   List<UserModel> blueList = [];
   List<BluetoothDevice> devices = [];
   List<ScanResult> myScanResult = [];
   List<String> updateTime = [];
+
+  List<UserModel> users = [];
   FlutterBlue flutterBlue = FlutterBlue.instance;
 
   @override
@@ -175,84 +179,64 @@ class _TrackPageState extends State<TrackPage> {
   @override
   void initState() {
     super.initState();
-    uploadMyId();
-    // startTrack(true);
+    addContactsToList();
+    getPermissions();
   }
 
-  void startTrack(bool flag) async {
-    if (flag) {
-      flutterBlue.stopScan();
-    } else {
-      setState(() {
-        blueList = [];
-        updateTime = [];
-        myScanResult = [];
+  void discovery() async {
+    try {
+      bool a = await Nearby().startDiscovery(currentUser.username, strategy,
+          onEndpointFound: (id, name, serviceId) async {
+        // 保存数据
+      }, onEndpointLost: (id) {
+        print(id);
       });
-      AppUtil.buildToast("正在搜索附近的人...");
-      flutterBlue.startScan(timeout: const Duration(seconds: 20));
-      //  扫描周围蓝牙设备
-      flutterBlue.scanResults.listen((scanResult) {
-        for (ScanResult scan in scanResult) {
-          if (!myScanResult.contains(scan)) {
-            print("-----------------id------:" + scan.device.id.toString());
-            setState(() {
-              myScanResult.add(scan);
-              blueList.add(UserModel(deviceid: scan.device.id.toString()));
-              updateTime.add(DateTime.now().toString().substring(0, 10));
-            });
-          }
-        }
-      });
-      // 扫描连接设备
-      List<BluetoothDevice> connectedDevices =
-          await flutterBlue.connectedDevices;
-      for (BluetoothDevice device in connectedDevices) {
-        if (!devices.contains(device)) {
-          devices.add(device);
-          AppUtil.buildToast("正在追踪设备\"" + device.id.toString() + "\"健康状态...");
-          // 云端检测用户状态
-          UserModel user =
-              await LoginDao.getUserByDeviceId(device.id.toString());
-          blueList.add(user);
-        }
-      }
-
-      //  String myDeviceId = await flutterBlue.localAdapter.deviceId;
+      print('DISCOVERING: ${a.toString()}');
+    } catch (e) {
+      print(e);
     }
+  }
 
-    // try {
-    //   bool a = await Nearby().startAdvertising(
-    //     loggedInUser.email,
-    //     strategy,
-    //     onConnectionInitiated: null,
-    //     onConnectionResult: (id, status) {
-    //       print(status);
-    //     },
-    //     onDisconnected: (id) {
-    //       print('Disconnected $id');
-    //     },
-    //   );
-    //
-    //   print('ADVERTISING ${a.toString()}');
-    // } catch (e) {
-    //   print(e);
-    // }
+  void getPermissions() {
+    Nearby().askLocationAndExternalStoragePermission();
   }
 
-  // upload my device BluetoothCharacteristic to server
-  void uploadMyId() async {
-    // String myDeviceId = await flutterBlue.localAdapter.deviceId;
-    // print("-----------------id------:" + myDeviceId);
-    // Map<String, dynamic> params = {
-    //   "userId": loggedInUser.email,
-    //   "deviceId": myDeviceId,
-    // };
-    // HttpUtil.post(
-    //   '/user/updateDeviceId',
-    //   (data) {
-    //     print(data);
-    //   },
-    //   params: params,
-    // );
+  Future<void> getCurrentUser() async {
+    // UserModel user=
+  }
+
+  void addContactsToList() async {
+    await getCurrentUser();
+    //  服务器获取当前用户数据
+    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
+    String token = sharedPreferences.getString("token");
+    setState(() async {
+      users = await TrackDao.getContactList(token);
+    });
+  }
+
+  void startTrack(bool flag) async {
+    try {
+      bool a = await Nearby().startAdvertising(
+        currentUser.username,
+        strategy,
+        onConnectionInitiated: null,
+        onConnectionResult: (id, status) {
+          print(status);
+        },
+        onDisconnected: (id) {
+          print('Disconnected $id');
+        },
+      );
+      // 上传追踪数据
+      SharedPreferences sharedPreferences =
+          await SharedPreferences.getInstance();
+      String token = sharedPreferences.getString("token");
+      TrackDao.uploadContact(token);
+      print('ADVERTISING ${a.toString()}');
+    } catch (e) {
+      print(e);
+    }
+    discovery();
   }
 }

+ 7 - 0
pubspec.lock

@@ -191,6 +191,13 @@ packages:
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "1.7.0"
+  nearby_connections:
+    dependency: "direct main"
+    description:
+      name: nearby_connections
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "1.1.1+1"
   path:
     dependency: transitive
     description:

+ 8 - 0
pubspec.yaml

@@ -17,6 +17,14 @@ dependencies:
   file_picker: ^2.1.7
   flutter_blue: ^0.8.0
   webview_flutter: ^0.3.24
+
+  nearby_connections: ^1.0.3
+#  firebase_core: ^0.4.4+3
+  #  firebase_auth: ^0.15.5+3
+  #  cloud_firestore: ^0.13.4+2
+  #  modal_progress_hud: ^0.1.3
+  #  location: ^3.0.2
+
 dev_dependencies:
   flutter_test:
     sdk: flutter