• 构建一个WIFI室内定位系统


    室内定位可以应用在很多场景,由于受到室内环境的限制,GPS信号无法有效的接收,这时可以利用室内的WIFI热点提供的信号强度来进行辅助定位。通常在室内都会有很多的WIFI热点,我们可以把室内的区域划分为多个网格,在每一个网格测量所接收到的WIFI热点的信号强度,根据这些信息来建立一个WIFI信号指纹库,以后我们就可以通过比对指纹库,来确定在室内的位置了。

    手机APP测量WIFI信号

    首先我们先编写一个APP,用于测量WIFI的信号强度并且上报给服务器保存。这里我采用了HBuilderX来编写,这个HBuilderX采用了HTML 5+的技术,可以快速的用我熟悉的网页+JS的方式来写Android和IOS的应用。

    新建一个HbuilderX的项目,在目录下新建一个index.html文件,内容如下:

    1. html>
    2. <html>
    3. <head>
    4. <meta charset="utf-8">
    5. <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    6. <title>title>
    7. <link rel="stylesheet" type="text/css" href="css/jquery.dataTables.min.css">
    8. <script src="js/vconsole.min.js">script>
    9. <script src="js/jquery-3.6.1.slim.js">script>
    10. <script type="text/javascript" charset="utf8" src="js/jquery.dataTables.min.js">script>
    11. <script src="js/axios.min.js">script>
    12. <script>
    13. // VConsole will be exported to `window.VConsole` by default.
    14. var vConsole = new window.VConsole();
    15. script>
    16. head>
    17. <body>
    18. <div id="inputlocation">
    19. <p>输入室内网格编号: <input type="text" id='gridId'>p>
    20. <button id="submit" onclick="submitMeasurement()" disabled>开始测量button>
    21. div>
    22. <div id="orientation">Device Orientation: div>-->
    23. <table id="wifilist" class="display">
    24. <thead>
    25. <tr>
    26. <th>BSSIDth>
    27. <th>Levelth>
    28. tr>
    29. thead>
    30. <tbody>
    31. tbody>
    32. table>
    33. body>
    34. <script>
    35. var Context;
    36. var wifiManager;
    37. document.addEventListener('plusready', function(){
    38. //console.log("所有plus api都应该在此事件发生后调用,否则会出现plus is undefined。")
    39. document.getElementById("submit").disabled = false;
    40. $('#wifilist').DataTable( {
    41. data: [],
    42. searching: false,
    43. paging: false,
    44. });
    45. Context = plus.android.importClass("android.content.Context");
    46. wifiManager = plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);
    47. if (window.DeviceOrientationEvent) {
    48. window.addEventListener('deviceorientation', deviceOrientionHandler, false);
    49. }else {
    50. alert('not support device oriention');
    51. }
    52. });
    53. function submitMeasurement() {
    54. var flag = plus.android.invoke(wifiManager, "startScan");
    55. if (flag) {
    56. var wifilist = plus.android.invoke(wifiManager, "getScanResults");
    57. var size = plus.android.invoke(wifilist, "size");
    58. var rows = [];
    59. var table = $('#wifilist').DataTable();
    60. var data = {
    61. "GridId": $('#gridId').val(),
    62. "Orientation": $('#orientation').text(),
    63. "WifiSignal": []
    64. }
    65. table.clear().draw();
    66. if (size>0) {
    67. for (var i=0;i
    68. var sr = plus.android.invoke(wifilist, "get", i);
    69. var bssid = plus.android.getAttribute(sr, "BSSID");
    70. var level = plus.android.getAttribute(sr, "level");
    71. rows.push([bssid, level]);
    72. data.WifiSignal.push({
    73. "BSSID": bssid,
    74. "Level": level
    75. });
    76. }
    77. table.rows.add(rows).draw();
    78. }
    79. axios.create().post(
    80. 'http://123.123.123.123:8080/senddata',
    81. data,
    82. {headers: {'Content-Type':'application/json'}}
    83. ).then(
    84. res=>{
    85. if (res.status!=202) {
    86. alert("Measurement data upload failure! Error code:"+res.status.toString());
    87. }
    88. else {
    89. alert("Measurement data upload Success!");
    90. }
    91. }
    92. )
    93. }
    94. }
    95. function deviceOrientionHandler(eventData) {
    96. $('#orientation').text(eventData.alpha.toString());
    97. }
    98. script>
    99. html>

    这里用到了plus.android来调用android的原生方法,例如通过调用WifiManager来对WIFI信号进行扫描,把扫描结果的BSSID和信号强度保存下来。另外HTML5的规范支持获取设备的方向信息,以0-360度来表示设备的朝向,因为设备指向不同的方向也会影响信号的强度,因此也需要记录这个信息。最后当点击开始扫描这个按钮的时候,就会把这些信息提交到后台的服务器,记录到数据库中。

    要支持WIFI扫描,还需要在manifest.json文件里面设置相应的权限,按照Android文档的说法,Android 10及以上的版本还需要开启ACCESS_FINE_LOCATION,ACCESS_WIFI_STATE,CHANGE_WIFI_STATE的权限,以及设备需要启用位置信息服务。另外Android默认会对startScan有节流限制,即一定时间内限制调用的次数,可以在开发者选项->网络->WIFI扫描调节下进行关闭,取消限制。

    以下是这个APP运行的效果:

    WIFI测量APP

    后台应用记录WIFI测量数据

    编写一个后台应用,暴露一个API接口,用于接收APP上报的WIFI测量数据。

    这里采用springboot+JPA+Postgresql的架构。

    在start.spring.io网站里面新建一个应用,artifact名字为wifiposition,依赖里面选择spring web, JPA,打开应用,在里面新建一个名为WifiData的Entity类,代码如下:

    1. package cn.roygao.wifiposition;
    2. import java.util.Date;
    3. import javax.persistence.Column;
    4. import javax.persistence.Entity;
    5. import javax.persistence.GeneratedValue;
    6. import javax.persistence.GenerationType;
    7. import javax.persistence.Id;
    8. import javax.persistence.Table;
    9. import org.hibernate.annotations.CreationTimestamp;
    10. import org.hibernate.annotations.Type;
    11. import org.hibernate.annotations.TypeDef;
    12. import com.alibaba.fastjson.JSONArray;
    13. import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
    14. @Entity
    15. @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
    16. @Table(name = "wifidata")
    17. public class WifiData {
    18. @Id
    19. @GeneratedValue(strategy=GenerationType.AUTO)
    20. private Long id;
    21. private String gridId;
    22. private Float orientation;
    23. @Type(type = "jsonb")
    24. @Column (name="measurement", nullable = true, columnDefinition = "jsonb")
    25. private JSONArray measureArray;
    26. @CreationTimestamp
    27. private Date createdTime;
    28. public WifiData() {
    29. }
    30. public WifiData(String gridId, Float orientation, JSONArray measureArray) {
    31. this.gridId = gridId;
    32. this.orientation = orientation;
    33. this.measureArray = measureArray;
    34. }
    35. public Long getId() {
    36. return this.id;
    37. }
    38. public void setId(Long id) {
    39. this.id = id;
    40. }
    41. public String getGridId() {
    42. return this.gridId;
    43. }
    44. public void setGridId(String gridId) {
    45. this.gridId = gridId;
    46. }
    47. public Float getOrientation() {
    48. return this.orientation;
    49. }
    50. public void setOrientation(Float orientation) {
    51. this.orientation = orientation;
    52. }
    53. public JSONArray getMeasureArray() {
    54. return this.measureArray;
    55. }
    56. public void setMeasureArray(JSONArray measureArray) {
    57. this.measureArray = measureArray;
    58. }
    59. }

    这个代码里面会保存measurement的JSON数组到PG的JSONB格式的数据列里面,因为hibernate默认没有提供这种类型,这里引入了com.vladmihalcea.hibernate.type.json.JsonBinaryType来提供支持。

    在pom.xml里面需要添加以下的依赖:

    1. com.vladmihalcea
    2. hibernate-types-52
    3. 2.3.4

    新建一个名为WifiRepository的接口类,代码如下:

    1. package cn.roygao.wifiposition;
    2. import org.springframework.data.repository.CrudRepository;
    3. public interface WifiDataRepository extends CrudRepository{
    4. }

    新建一个名为WifiController的类,实现HTTP接口,代码如下:

    1. package cn.roygao.wifiposition;
    2. import java.util.logging.Logger;
    3. import org.springframework.beans.factory.annotation.Autowired;
    4. import org.springframework.http.ResponseEntity;
    5. import org.springframework.web.bind.annotation.PostMapping;
    6. import org.springframework.web.bind.annotation.RequestBody;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import com.alibaba.fastjson.JSONArray;
    9. import com.alibaba.fastjson.JSONObject;
    10. @RestController
    11. public class WifiController {
    12. @Autowired
    13. private WifiDataRepository repository;
    14. private final static Logger LOGGER = Logger.getLogger(WifiController.class.getName());
    15. @PostMapping("/senddata")
    16. public ResponseEntity sendData(@RequestBody JSONObject data) {
    17. Float orientation = data.getFloat("Orientation");
    18. String gridId = data.getString("GridId");
    19. JSONArray wifiSignal = data.getJSONArray("WifiSignal");
    20. repository.save(new WifiData(gridId, orientation, wifiSignal));
    21. return ResponseEntity.accepted().body("OK");
    22. }
    23. }

    在application.properties里面增加postgres的相关配置,如下:

    1. spring.datasource.url= jdbc:postgresql://localhost:5432/wifidb
    2. spring.datasource.username= postgres
    3. spring.datasource.password= postgres
    4. spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
    5. spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
    6. # Hibernate ddl auto (create, create-drop, validate, update)
    7. spring.jpa.hibernate.ddl-auto= update

    运行./mvnw clean install进行编译打包,然后运行即可。

    生成WIFI指纹库

    现在有了测量的APP,我在家里选取了两个地点,分别测量WIFI的数据。每个地点我都分别对东、南、西、北四个方向测量十次,总共每个地点测量四十次。搜集到的数据都保存到后台的服务器。

    然后我们就可以读取这些测量数据,生成WIFI指纹了。下面用Python pandas来处理数据。

    1. import pandas as pd
    2. import pickle
    3. df = pd.read_sql_table('wifidata', 'postgresql://postgres@localhost:5432/wifidb')
    4. grids = ['home1', 'home2']
    5. orien_query = {
    6. 'north': 'orientation<10 or orientation>350',
    7. 'east': 'orientation<100 and orientation>80',
    8. 'south': 'orientation<190 and orientation>170',
    9. 'west': 'orientation<280 and orientation>260',
    10. }
    11. grid_measure = {}
    12. for grid in grids:
    13. df1 = df.query('grid_id=="'+grid +'"')
    14. grid_measure[grid] = {}
    15. for key in orien_query.keys():
    16. df2 = df1.query(orien_query[key])
    17. bssid_stat = {}
    18. for i in range(df2.id.count()):
    19. measure = df2.iloc[i].measurement
    20. for j in range(len(measure)):
    21. bssid = measure[j]['BSSID']
    22. level = measure[j]['Level']
    23. if bssid not in bssid_stat.keys():
    24. bssid_stat[bssid] = [1, level]
    25. else:
    26. count = bssid_stat[bssid][0]
    27. bssid_stat[bssid][0] = count+1
    28. bssid_stat[bssid][1] = (bssid_stat[bssid][1]*count+level)//(count+1)
    29. threshold = (int)(df2.id.count() * 0.8)
    30. delkeys = []
    31. for key1 in bssid_stat.keys():
    32. if bssid_stat[key1][0] < threshold:
    33. delkeys.append(key1)
    34. else:
    35. bssid_stat[key1][0] = bssid_stat[key1][0]/df2.id.count()
    36. for key1 in delkeys:
    37. del bssid_stat[key1]
    38. grid_measure[grid][key] = bssid_stat
    39. with open('wififingerprint.pkl', 'wb') as f:
    40. pickle.dump(grid_measure, f)

    处理后的wifi指纹数据如下格式:

    1. {'home1': {'north': {'14:ab:02:6f:31:5c': [1.0, -60],
    2. '50:21:ec:d7:4e:24': [1.0, -63],
    3. '14:ab:02:6f:31:60': [1.0, -74],
    4. '18:f2:2c:cb:31:e9': [0.8, -75],
    5. '1a:f2:2c:ab:31:e9': [0.8, -75],
    6. '42:97:08:72:81:48': [0.8, -83],
    7. '18:f2:2c:cb:31:eb': [0.9, -89]},
    8. 'east': {'14:ab:02:6f:31:5c': [1.0, -69],
    9. '50:21:ec:d7:4e:24': [1.0, -63],
    10. '14:ab:02:6f:31:60': [1.0, -75],
    11. '42:97:08:72:81:48': [0.8, -86],
    12. '74:c1:4f:29:27:35': [0.8, -80]},
    13. ...
    14. }}}

    解释一下,这个代码的作用是找出同一地点同一方向的多次测量中都有出现的BSSID,计算其出现概率以及多次信号强度测量的平均值。

    现在我们可以做一下测试,在室内选取其他的一些测量点,记录测量数据之后和这个指纹库进行比对。

    这里我选取多个测量点,其编号以及与我们的指纹库的两个地点的位置距离关系如下:

    Test1:与Home1在同一房间内,距离Home1大约为2米。

    Test2:在Home1旁边的房间,距离Home1大约为5米。

    Test3:  与Home2都在客厅内,距离Home2大约为2米。

    Test4:在走廊,大致位于Home1与Home2中间。

    采集这些测试点的BSSID和信号强度,然后和指纹库进行比对,以下是测试代码:

    1. df1 = df.query('grid_id=="test3"')
    2. measure_test1 = df1.iloc[1].measurement
    3. count = 0
    4. dev = 0
    5. orien = 'west'
    6. truth_count = len(grid_measure['home2'][orien].keys())
    7. for bssid in grid_measure['home2'][orien].keys():
    8. for item in measure_test1:
    9. if item['BSSID'] == bssid:
    10. count += 1
    11. dev += abs(item['Level']-grid_measure['home2'][orien][bssid][1])
    12. break

    这个代码是取测试点的某个方向的测量数据与指纹库比对,看看测试点所获取的BSSID有百分之多少和指纹库的点的BSSID吻合,然后对相吻合的BSSID的信号强度计算差值,最后计算平均值。

    从多次测试来看,当测试点在指纹库的点附近时,BSSID的吻合度大概在40%以上,信号强度的平均差值在5以内。因此可以根据这个阈值来把测试点的测量数据与指纹库的所有测量数据进行遍历,找到对应的指纹库的定位点。

    当然这个是一个很粗糙的WIFI指纹定位的方法,业界在这方面也做了很多的研究,有时间的话我将参考业界的理论来进一步改进这个定位方法。

  • 相关阅读:
    Flutter 中的 PerformanceOverlay 小部件:全面指南
    【JavaScript】用echarts绘制饼图
    ChatGPT国内镜像,以及如何使用ChatGPT帮你制作PPT
    vite+vue3+ts中的vue-router基本配置
    Flutter 绘制波浪移动动画效果,曲线和折线图
    【华为OD机试python】斗地主之顺子【2023 B卷|100分】
    每天五分钟机器学习算法:拉格朗日乘数法和KKT条件
    半桥BUCK电路—记录篇
    使用模拟退火(SA)和Matlab的车辆路径问题(VRP)(Matlab代码实现)
    [elastic 8.x]java客户端连接elasticsearch与操作索引与文档
  • 原文地址:https://blog.csdn.net/gzroy/article/details/127860197