IBeacon is a low-power Bluetooth technology launched by Apple. Bluetooth devices send signals containing specified information, which are received by mobile devices to achieve near-field communication. Wechat applet began to support iBeacon in 2017, which is realized based on iBeacon. In addition, iBeacon can also realize distance measurement. This paper will introduce how to achieve iBeacon ranging based on wechat applet.
IBeacon ranging principle
The signal intensity (RSSI) transmitted by Bluetooth beacon is positively correlated with the distance between the receiving device to some extent. Therefore, the distance between bluetooth beacon and the receiving device can be inversely deduced through the value of RSSI through reasonable operation transformation.
The RSSI value of bluetooth beacon is a reference value, there is no fixed standard. To calculate the distance of a Bluetooth beacon, you must also know the txPower value of the beacon device. TxPower refers to the RSSI value when it is 1m away from the Bluetooth beacon. Different Bluetooth devices or different working conditions of the same device or even different site environments will affect the txPower value. Therefore, although this value can be measured, it is an empirical value to some extent and cannot be measured accurately.
Rssi ranging formula
Once you know rSSI and txPower, you can calculate the distance. There are two formulas:
A,
The three variables A, B and C in this formula are all empirical values, which need to be accurately adjusted according to the mobile phone system or hardware model. Usually, the calibration results of all devices are saved into A device information table. The mobile terminal first checks the model of the machine, and then obtains the corresponding calculation configuration based on the device information. Obviously, this formula is more dependent on hardware tuning, and it will be difficult to use this formula without data storage.
Convert to js code:
Const calculateAccuracy = function (txPower, rssi) {return (0.89976) * math.pow (rssi/txPower, 7.7095) + 0.111}Copy the code
Distance measurement performance under the condition of not fine calibration:
So let’s talk about what this graph looks like.
The vertical axis represents the measured distance, and the horizontal axis represents the time. Samples are taken every second. The figure shows the numerical curve of nearly 10 samples. The green line is the RSSI value received by the device, reflecting the actual data received by the hardware. The red line is the instantaneous distance calculated by the formula; The yellow line is the instantaneous ranging result of wechat applets.
The actual distance between bluetooth beacon and mobile phone is 1m, and the test device is Redmi Note7.
As can be seen from the figure above, the RSSI value is relatively stable, indicating that there is no major problem with the hardware. The red line and the yellow line both fluctuate wildly, which means they’re not very accurate. The fluctuation trend of the two is almost the same, so there is reason to suspect that the micro channel small program is also used in the ranging formula. According to the results, the accuracy of this formula is relatively poor, which may be due to the lack of precision correction.
Second,
The A in this formula is RSSI, tx is txPower, n is the empirical value, and n depends on the physical environment.
Convert to js code:
const calculateAccuracy = function (txPower, rssi) {
return Math.pow(10, Math.abs(rssi - txPower) / (10 * 4))
}
Copy the code
Range finding performance of Formula 2:
More people die than people, more goods to throw away.
The yellow line in the figure is still as crazy as the fluctuation, but the red line is unusually stable, and shows the same fluctuation range as the green line, indicating that the ranging accuracy is reliable. This formula has only one parameter, and the adjustment in the production environment is relatively simple. Here, we choose Formula 2 as the ranging formula.
IBeacon Ranging stabilization program
Bluetooth signal itself has volatility, and many factors in the real environment will also affect the signal strength, such as object occlusion, device direction change, the stability of the hardware itself, so the RSSI value detected by the receiving device is usually “beat”, and the result calculated directly by the ranging formula is often not available. A stabilization program must be implemented to give continuity and stability to the results.
Data filtering
The stabilization program mainly does “peak clipping and valley filling” for the band data, also known as data filtering. The simplest filter processing, is the collection value and the average period of time, as long as the hardware is not a problem, fixed distance bluetooth beacon rssi values will always be in a relatively stable range of change, the longer the sampling time, the average of the sample will be more close to the real value, so in the static range scenario, the average is the best way.
Const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0)/arr.length; return arrayAverage([...] )Copy the code
The specific realization is that when the program continuously receives the RSSI of the beacon, it first calculates the instantaneous ranging result with the formula, and then saves the result into an array, and then calculates the average value of the array. Static ranging, the measurement results are very accurate, the distance error within 2m can be as low as 0.1m.
In practical applications, it is often dynamic ranging, so the length of sampling data should be limited, such as taking the latest 10 groups of data in the last in first out order. The specific sampling queue length depends on the actual requirements of the project. The longer the sampling queue is, the smoother the ranging result is, but the duller the dynamic capture of mobile terminal is. On the contrary, the shorter the sampling queue, the sharper the result, the more sensitive to the dynamic capture of mobile terminal.
Sometimes because of some accidental factors, sampling the queue will appear the “noise” of individual substantially deviates from the value of the real data, is difficult to effectively erase effect even for the average, to eliminate the effect, can be in average before using gaussian fuzzy algorithm of “large value” and “small” value, smoothing the maximum noise reduction.
The key of Gaussian blur algorithm is to calculate the weight according to the average difference. The weight calculation formula of one-dimensional Gaussian blur is as follows:
Convert to js code:
// Find the gaussian fuzzy weight @param(queue length, Const getOneGuassionArray = function (size, kerR, sigma) {if (size % 2 > 0) {size -= 1} if (! size) { return [] } if (kerR > size-1){ return [] } let sum = 0; let arr = new Array(size); for (let i = 0; i < size; i++) { arr[i] = Math.exp(-((i - kerR) * (i - kerR)) / (2 * sigma * sigma)); sum += arr[i]; } return arr.map(e => e / sum); }Copy the code
The concepts of “large” and “small” are described below, but it is important to know that our vague target is “extreme data”.
The time-weighted
The processing method based on sampling queue to seek the average will inevitably make the result lag, then we can introduce the time weighted compensation algorithm.
The so-called time weighting is to give higher weight to the value closer to the current time and lower weight to the value far from the current time when calculating the average value. It is also very simple to achieve.
Taking the simplest weight allocation as an example, the sampling queue is divided into two parts and is positioned as “current group” and “past group” in terms of time distance. For example, if I want the weight of the current group to be twice that of the past group, I just need to copy all the data of the current group and put it into the queue, and then calculate the average value of the new queue.
Queue = queue.slice(0, parseInt(queue.length / 2)).concat(queue) return arrayAverage(queue)Copy the code
Dynamic follow-up
After time weighted processing data lag will have certain inhibition, but if there are any more “steep” distance changes, this process will still be given a relatively “smooth” feedback, dynamic change in order to make stable program can better awareness, follow up and respond, also need to set up some special conditions.
First, how do you tell if a mobile device is moving away or closer?
Here is a simple idea to find the maximum and minimum values in the sample queue, and then find the partial large and partial small values at a certain threshold. For example, if the maximum value of the queue is 3, the minimum value is 1, and the threshold value is set to 0.1m, the data larger than 2.9m is considered to be larger than the maximum value, and the data smaller than 1.1 M is considered to be smaller than the minimum value. The maximum length of the larger and smaller queues should not exceed half of the total queue.
Then, if the larger values are concentrated in the first third of the queue, we can assume that mobile devices are decisively moving away; Otherwise, the smaller values are concentrated in the first third of the queue, which can be considered as mobile devices are approaching.
If (arrayAverage(maxCount) < parseInt(queueLength / 3)) {//queueLength < parseInt(queueLength / 3) { Console. log(' moving away ')} else if (arrayAverage(minCount) < parseInt(queueLength / 3)) {console.log(' moving away ')}Copy the code
Based on this tendency to move away and closer, we can artificially tilt the data more aggressively in the direction of motion. So how do we do that? Time weighting logic is skipped. If it is judged to be moving away, the smaller value in the queue will be filtered out; otherwise, the larger value will be filtered out and only the remaining data will be calculated. This would produce an obviously overzealous result, but given the inertia of movement in the real world, such a radical approach would probably be more in tune with real movement and make the data more “responsive”.
Effect of inspection
So what’s the effect so far? Let’s just look at the picture.
In the figure below, the green line is still THE RSSI value, the red line is the instantaneous ranging result calculated directly according to RSSI, and the yellow line is the ranging result after adding the stabilization program.
The first diagram shows the relative stationary conditions, and you can see that the yellow line is much more stable than the red line, indicating that the stabilization process is still working.
The second figure simulates the scene of rapid departure. It can be seen that the yellow line keeps up with the red line without being thrown off under the premise of ensuring stability, which mainly reflects the dynamic follow-up effect of the stabilization program.
The third picture is the scene simulated by shaking the phone with arm and blocking the signal, it seems that the stabilization program is also not set up, it is a bit erratic.
The above is a brief implementation of the stabilization program ideas, production environment will certainly face more complex situations, will inevitably have to do a lot of debugging, here is just a primer.
conclusion
Bluetooth range is simply the application of a formula, itself is simpler, based on distance measurement can realize a lot of near field application, such as the near-field check-in, near-field push, etc., can even further realize the localization of mobile devices, with the location information, a lot of indoor navigation positioning and the related application can be done, The next article will explain in detail how to implement location based on iBeacon technology.
Front-end road original technical article, reproduced please indicate the source: refined-x.com/2019/03/30/…
Unwilling to mediocre you, come to charge with me, pay attention to the scenery, get more wonderful content.