· 2020. 9. 13. · i acknowledgements firstly, i want to thank my teacher and supervisor henry...

108
A FRAMEWORK FOR ENHANCED INDOOR LOCALIZATION BASED ON BLE BEACONS FOR IMPROVING VISITORS EXPERIENCE TIZIANO LOMBARDI Università degli Studi Dell’Aquila Dipartimento di Ingegneria e Scienze dell’Informazione e Matematica Laurea Magistrale in Informatica Candidato Relatore Tiziano Lombardi Prof. Henry Muccini Anno Accademico 2016 / 2017

Upload: others

Post on 28-Sep-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

A FRAMEWORK FOR ENHANCED

INDOOR LOCALIZATION BASED ON

BLE BEACONS FOR IMPROVING

VISITORS EXPERIENCE

TIZIANO LOMBARDI

Università degli Studi Dell’Aquila

Dipartimento di Ingegneria e Scienze dell’Informazione e Matematica

Laurea Magistrale in Informatica

Candidato Relatore Tiziano Lombardi Prof. Henry Muccini

Anno Accademico 2016 / 2017

Page 2:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

i

Ai miei genitori,

che hanno continuato a credere in me anche nei miei momenti

bui e di incertezza.

Ai miei nonni,

che sono sempre con me, perché finché vivrò saranno nel mio

cuore.

Page 3:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

i

ACKNOWLEDGEMENTS

Firstly, I want to thank my teacher and supervisor Henry Muccini, who have

given me the possibility to explore this emerging research field of BLE beacons

interacting with Android native Mobile Application, as well as all knowledges to deal

with real IT projects, from the problem/idea to the final implementation, following

rules and guidelines to avoid confusion and create always good final products.

Secondly, I want to thank my family, starting from my parents who supported me

by money, time, patience. I have really been lucky because I didn‟t miss anything such

as the possibility to bring “my” car, and this is all their merit. My thought goes also to

all my “acquired” family: my uncle Otello, my aunt Loretta, my cousin Aurora, my

baptism cronies Antonio and Silvia, my confirmation cronies Tonino and Maria

Paola.

Another important thanksgiving goes to all my friends, each one is special and

represents a “lego block” of my life. I should ask forgiveness to who I met in the very

last years (expecially in 2014 and 2016), that clashed with the worst part of my soul.

And I must, in the same way, thank who, among all my friends, supported me in this

black period. So, I thank all from Residenza San Carlo who shared all these years with

me and (without names) get me out of the kitchen for every *bad* told joke of mine.

I thank friends of all time, now spread along Italy, who continue to be present in my

life.

I‟m not such a cold person to have been ever having just collegues yet; all people

I met in the University have become friends or nothing. But, considering all project

exams I did, I thank all of my friends with whom I have collaborated to achieve some

projects‟ deliveries.

Talking about people, I necessarily have to thank all people I knew: who I

missed, who I met, who I met and then I missed. Because each one has had a role in

my life, both for better or for worse.

Page 4:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

ii

Then I have to thank Università de L’Aquila and all professors that taught me a

lot and formed my knowledge and spurred my desire for new knowledge. I have to

thank the city of L‟Aquila, which makes me taste what does it mean to live apart from

home for a long period of time, in a place with different dialects and traditions, but

contemporary not so noisy and confusing as a metropolis.

Last but not least I thank my high-school professor M. Cellucci who gave me the

basics for all my next scientific journey, not just referring to learned knowledge

themselves but rather for study method and problems approaches.

It‟s now my tradition, but I have to conclude with a thanksgiving to something

very important for my study courses: Google, Wikipedia and also StackOverflow and

GitHub.

( Traduzione in italiano )

Prima di tutto, voglio ringraziare il mio docente e supervisore Henry Muccini che mi ha dato la

possibilità di esplorare questo emergente campo di ricerca dei BLE beacons che interagiscono con

un'Applicazione nativa Android, e che mi ha dato tutte le conoscenze per poter trattare veri progetti

Informatici, dal problema/idea all'implementazione finale, seguendo regole e linee guida per evitare

confusione e creare sempre ottimi prodotti finali.

In secondo luogo, voglio ringraziare la mia famiglia, partendo dai miei genitori che mi hanno

supportato con soldi, tempo e pazienza. Sono stato davvero fortunato perché non mi è mai mancato

niente, come la possibilità di portare la "mia" auto, e questo è tutto merito loro. Il mio pensiero va

anche a tutta la mia famiglia "acquisita": mio zio Otello, mia zia Loretta, mia cugina Aurora, i

miei compari di battesimo Antonio e Silvia, i miei compari di cresima Tonino e Maria Paola.

Un altro importante ringraziamento va a tutti i miei amici, ognuno dei quali è speciale e

rappresenta un "blocco lego" della mia vita. Devo chiede perdono a coloro i quali ho conosciuto negli

ultimi anni (specialmente nel 2014 e 2016), the si sono scontrati con la parte peggiore della mia

anima. Devo anche, allo stesso modo, ringraziare chi, fra tutti i miei amici, mi ha supportato in

questo scuro periodo. Quindi ringrazio tutti gli amici della Residenza San Carlo che hanno condiviso

tutti questi anni con me e (senza fare nomi) mi hanno cacciato dalla cucina per ogni mia battutaccia.

Ringrazio gli amici di sempre, ora sparsi in giro per l'Italia, che continuano ad essere presenti nella

mia vita.

Page 5:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

iii

Non sono una persona così fredda da aver mai ancora avuto solo colleghi; tutte le persone che ho

incontrato nell'Università sono diventati amici o niente. Ma considerando tutti gli esami a progetto

che ho fatto, ringrazio fra tutti i miei amici quelli con cui ho collaborato per arrivare alle consegne.

Parlando di persone, devo necessariamente ringraziare tutte le persone che ho conosciuto: quelle che

ho perso, quelle che ho incontrato, quelle che ho incontrato e poi ho perso. Perché ognuno di loro ha

avuto un ruolo nella mia vita, sia nel bene che nel male.

Devo poi ringraziare l'Università de L'Aquila e tutti i professori che mi hanno insegnato molto

formando la mia conoscenza e spronato il mio desiderio di conoscere nuove cose. Devo ringraziare la

città de L'Aquila, che mi ha fatto assaggiare cosa vuol dire vivere lontano da casa per lunghi periodi,

in un posto con differenti dialetti e usanze, ma contemporaneamente non così rumorosa e

confusionaria come può esserlo una metropoli.

Ultimo, ma non certo per importanza, voglio ringraziare il mio professore di Liceo M. Cellucci

che mi ha dato le basi per tutto il mio successivo percorso scientifico, non tanto per le conoscenze stesse

imparate quanto piuttosto per il metodo di studio e l'approccio ai problemi.

E' ora una mia tradizione, ma devo concludere con un ringraziamento a qualcosa davvero

importante per i miei corsi di studi: Google, Wikipedia ed anche StackOverflow e GitHub.

Page 6:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

iv

TABLE OF CONTENTS

INTRODUCTION ...................................................................................................................... 1

1 INDOOR POSITIONING SYSTEMS .................................................................................... 1

1.1 EXPLAINING INDOOR POSITIONING ...................................................................................... 1

1.2 TECHNIQUES AND TECHNOLOGIES TO ESTIMATE POSITION ....................................................... 3

1.3 NOISE MEASUREMENT REDUCTION .................................................................................... 10

1.4 SENSORS TECHNOLOGIES ................................................................................................. 12

2 BLUETOOTH LOW ENERGY ............................................................................................ 17

2.1 REASONS ..................................................................................................................... 17

2.2 BLE BEACONS .............................................................................................................. 19

2.3 INDOOR NAVIGATION ..................................................................................................... 23

3 SYSTEM REQUIREMENTS .............................................................................................. 26

3.1 PREVIOUS WORK ........................................................................................................... 26

3.2 HARDWARE TESTING ...................................................................................................... 28

3.3 RSSI MEASUREMENT ERROR MANAGEMENT STUDY ............................................................ 30

4 SYSTEM DESIGN ............................................................................................................ 44

4.1 DESIGN CHANGES .......................................................................................................... 44

4.2 PROPOSED SCENARIO ..................................................................................................... 45

4.3 SYSTEM ARCHITECTURE ................................................................................................... 46

5 SYSTEM IMPLEMENTATION .......................................................................................... 60

5.1 BEACON MEASUREMENT FRAMEWORK ............................................................................... 60

5.2 MOBILE APPLICATION (ANDROID NATIVE) .......................................................................... 70

5.3 WEB APPLICATION INTERFACES ........................................................................................ 87

5.4 SERVER CRUD APIS ...................................................................................................... 91

5.5 DATABASE TABLES ......................................................................................................... 95

6 SYSTEM TESTING .......................................................................................................... 97

CONCLUSIONS ...................................................................................................................... 99

BIBLIOGRAPHY .................................................................................................................... 100

Page 7:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

1

INTRODUCTION

Despite GPS technology is quite recent, people around the world rely onto satellite

navigation more and more, mainly because individual positioning is assuming an

increasingly important role. Unfortunately, this wide-spread technology is not reliable

inside buildings, firstly due to materials used to build them and secondly due to the

scarse precision in calculating the height from the ground, which makes impossible to

distinguish with certain among buildings floors. In order to find better solutions for

these problems, nowadays Research is focusing on finding specific alternatives, which

is now categorized as “Indoor Positioning Systems”.

To date there is no universal accepted alternative that is able to adapt itself in a

generic environment or user need; in fact, it is possible to find plenty of products,

possibly realized with different architectures and technologies, resulting in different

costs and obtainable precision. This heterogeneity unavoidably leads to a deep

analysis for each project in order to meet customer requirements, comparing available

products with respect to its initial cost, the amount of environmental modifications to

deploy the system and relative time and money costs, and last but not least the

precision obtainable.

Many different studies1 put in evidence that people stay 80% and more of their day

indoor on average; considering activities doable in common spaces, it is possible to

imagine many various scenarios. For example, in Shopping Centers such systems

make possible proximity marketing, or otherwise an interactive personalized navigator

which drives users directly to the desired market. Another example could be a guided

exploration among museum spaces, in which each user can explore the different

rooms getting informed only about artworks of interest through visual and audio

information. Proceeding this way, plenty of other examples could easily be provided.

1 wiseGeek: http://www.wisegeek.com/how-much-time-do-americans-spend-indoors.htm

BuildingGreen: https://www.buildinggreen.com/blog/we-spend-90-our-time-indoors-says-who

Page 8:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INTRODUCTION

2

Figure: Investigation over 74 study cases of applicability for IPS

Mainly due to the large cases of applicability of such systems, IPS (Indoor Positioning

System) development increased a lot last years. According to a recent report redacted

by Market research Zone it is expected a 58.9% growth in IPIN (Indoor Positioning and

Indoor Navigation) systems, so that big industries as Apple, Microsoft, Sony, Google

and others are investing money in developing such kind of systems and related

services2.

This thesis aims to continue and evolve the work previously started for building a

working Indoor Navigation System based onto BLE (Bluetooth Low Energy)

Beacons, considered a good technological solution, better discussed later.

2 Market research Zone consultant and services proving company:

https://issuu.com/marketresearchzone/docs/global_indoor_positioning_and_indoo

Page 9:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

1

1 INDOOR POSITIONING SYSTEMS

1.1 EXPLAINING INDOOR POSITIONING

GPS (Global Positioning System) signal is affected by construction materials in buildings,

resulting in power loss (attenuation) and/or reflections (multi-path propagation)

which introduce uncontrollable errors. This is the starting point to develop specific

alternative solutions for indoor environments.

A general IPS (Indoor Positioning System) consists of an infrastructure able to determine

the location of devices (or people) inside a closed or limited environment, using

various technologies like radio waves, magnetic fields, acoustic signals and/or other

telemetric sensors. There are several commercial systems on the market, but any

standard has not been defined yet.

Based on the chosen technology the system can either measure the device distance

among a set of anchor nodes or incrementally estimate the actual position using

telemetric sensed data. The usage of different non-standard methods and

technologies results in a design fragmentation.

In case of an anchor-nodes based System, its designs must consider as mandatory a

minimum of three independent measurements in order to find a location (i.e.

trilateration). Then, in any case but specific to involved sensors, smart methods have to

be implemented to compensate stochastic (unpredictable) errors and increase measure

quality. Moreover, quality can be increased even more if it is possible to know device

orientation (i.e. using internal compass sensor). Obviously, incremental estimation of

newer positions based on the older ones can lead to cumulative errors (that can even

derive a lot the estimated position from the real value); in this case it‟s needed to

detect landmarks (of known position) regularly to mitigate the global error.

Page 10:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

2

Location process it‟s expressed through an algorithm which acts in three phases:

1) Receiving: involved devices obtain specific characterization of sensed signals

(strength, delay, etc.) and eventually packed information (sensor data)

2) Distance estimation: for every anchor node (or telemetry sensor) signals

data were transformed in an uniform kind of measure

3) Location: integrating information from all sensors it‟s estimated the device

position (or distance from sensors). In this case an environmental knowledge

(maps, constraints, etc.) can help in case of non-unique result.

While an IPS surely can detect the location (even approximated) of an object, it‟s not

trivial to calculate its orientation or direction. A simple way that do not require any

improvement of the hardware result in just tracking a sequence of positions of the

observed object. This way it‟s possible to guess orientation and direction through

time.

Typically it‟s used a Cartesian bi-dimensional plane as reference, where objects and

anchor nodes are located by a pair (x,y) of coordinates. Since objects and anchors can

have different scopes and tasks, it‟s possible to “segregate” interesting entities from

non-interesting ones.

Research in IPS is focused on the development of new techniques and algorithms

among available technologies to improve as much as possible the location estimation.

Page 11:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

3

1.2 TECHNIQUES AND TECHNOLOGIES TO ESTIMATE

POSITION

Techniques refers to different concepts built upon existent technologies and capable

to make use of them in order to locate a target in the considered environment; mainly

existent technologies can be divided into non-radio and wireless. Techniques are able to

use just one technology to work properly, and can be sorted into four categories:

Inertial, Multilateration, Proximity and Fingerprinting. Eventually, it‟s possible to combine

techniques and technologies in order to improve measurement precision.

1.2.1 INERTIAL MEASUREMENTS

The basic idea is to calculate the current position starting from a known point sensing

the variation in movement of observed object and integrating it over time. Sensed

data involves a specific device called IMU (Inertial Measurement Unit) which contains

accelerometers, gyroscopes and sometimes magnetometers. This unit reports linear

and rotational acceleration over the three Cartesian axis. Assuming to know initial

conditions of the object (position and initial vector speed, eventually projected over

Cartesian axis) it‟s used IMU data to modify this information and calculate (estimate)

the new conditions (position and vector speed).

Mathematically, integrating acceleration function over

time, speed function it‟s obtained. Integrating again

speed function over time, position function it‟s

obtained.

The main advantage of this technique is not to require any external anchor or

reference, but all calculation is made locally. However, the main disadvantage consist

of accumulated error, because the system continuously integrate acceleration over

time to estimate new velocity and position starting from older ones. This method

(called dead reckoning) accumulated measurement errors (even small) over time, drifting

the estimation from real values. Periodically, it‟s needed to correct drift errors (with

some external reference or checkpoint).

Page 12:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

4

1.2.1 MULTILATERATION

Multilateration make use of geometric properties of the travelling signal. Based on the

observed characteristics, position it‟s obtained with different methods: ToA(Time of

Arrival), TDoA (Time Difference of Arrival), AoA (Angle of Arrival), RSSI (Received Signal

Strength Indication).

It‟s needed a minimum of three

references to identify an object on a

plane (in optimal conditions). In fact,

each anchor outlines a circle around it; as

shown in figure, two sources are not

sufficient in case of multiple intersection

to disambiguate position. Using three

anchors it‟s called Trilateration.

Time of Arrival (ToA) identifies the radio signal travel time from a single

transmitter to a single receiver. A set of preconditions are required in order to have

the system works. First of all, consider signal velocity constant in space and equals

to light speed ( ⁄ ). Secondly, every node of the network must be

time-synchronized:

Exact synchronous clock on both sides. Every inaccuracy translate directly

to imprecise location.

Triggering from a common reference point

Analyzing and compensating clock phase differences

At this point, calculating the time of propagation it‟s possible to calculate

directly the extimated distance, which is .

Page 13:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

5

Time Difference of Arrival (TDoA) it‟s similar to ToA because it works

onto signal‟s time of propagation, but the main difference consist of how distance

is calculated: while in ToA it‟s sensed each

signal‟s time needed to reach the receiver,

in TDoA it‟s sensed only differences in

time from each signal received to the

others. In the simple case of three

anchors and a receiver, the operation is

computed for each pair of anchors.

The resulting time difference defines

an hyperbolic place of points, with

anchors in focuses. Using three anchors will be generated three hyperboles; the

intersection will provide the position of the receiver. Normally, the process is

iterated multiple times using

different sets of three anchors to

guarantee much more precision.

In this kind of system only anchors

need to be perfectly synchronized,

relaxing constraints over receiver.

Angle of Arrival (AoA) determine the

direction of propagation of a radio-

frequency signal incident to a specific

antenna array. An antenna array is a set of

multiple connected antennas which works

together as a single one, but each single

element has its own receiver/transmitter.

This way it‟s possible to superpose

frequencies (it makes them interfere) to

Page 14:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

6

enhance or cancel power radiation in specific

directions. On the other hand, it‟s possible to

discriminate among signal from different

directions and or enhance/reduce power of

signals in a desired direction.

The real angle is measured starting from the

TDoA measure of the signal at the individual

elements of the antenna array. The delay is

not measured in time (seconds), but in phase

difference (radiant or degrees) between array

elements; it‟s important to know the distance from elements. For example,

elements are far of one-half wavelength; if the signal is incident bore-sight it

arrives with the same phase on each element (0° AoA); if the signal is incident at

broad-sight, then it arrives with a 180° phase difference (90° AoA).

Typically, this system is used to locate cell phones, which sends a signal

omnidirectional, and it‟s received from a set of stations. They have directional

antennas, which calculate the AoA; intersecting lines passing through the anchors

with the calculated angle it‟s possible to locate the device.

The main advantage is the total absence of synchronization among nodes; but on

the other side, the infrastructure required is very complex and make the cost

increase a lot.

RSSI (Received Signal Strength Indicator) involves the power measurement

of the received signal. Usually, it‟s done by all devices but transparently to the

users; since it affects wireless functionalities, sometimes the value is shown to the

user. The calculation is done in hardware in the IF (Intermediate Frequency) stage of

the receiver, and it‟s sampled as an analogue DC level by an ADC.

RSSI values are expressed by arbitrary measure units (usually dBm) and there‟s no

standardization even in the value range; the value is reported in a negative form

(the more value raises 0 dBm the more it is strong).

The research is trying to find advanced techniques to improve capabilities of RSSI

measurement in order to let them reliable to be used daily in location.

Page 15:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

7

The advantage of this method is that radio

waves power propagate according to the

inverse-square law, so the distance depends

only on signal strength; but indoor

environments are not free-space, so reflection

and absorption can impact significatively onto

the error. Moreover, error is proportional

with the distance and result can be

inconsistent at distance limits (too near or too far). Finally, non-stationary objects

can impact measurement in an unpredictable way.

Main factors which impact RSSI measurements are:

Metals and other reflective materials

Liquid elements (which absorb signal)

Objects which are/passes through anchor and receiver

Differences in height (it‟s assuming to operate in a bi-dimensional space,

so distance can vary if heights are different)

Orientation between anchor and receiver (which influence signal strength

because of antennas directions)

A good estimation for the distance could be obtained using Friis equation:

( )

where:

PR: Power of received signal

PT: Power of transmitted signal

GT: Gain of sender antenna

GR: Gain of receiver antenna

I: Wavelength

d: distance in meters

n: Propagation signal constant (it depends from the environment)

Then, knowing how to calculate distance from RSSI, it‟s just needed to use

multilateration to locate the target.

Page 16:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

8

1.2.2 PROXIMITY

This technique consist of sense whether target is near a particular known position

equipped with a specific proximity sensor. Usually, this approach is used when it‟s not

so important the measurement precision (with error greater than one meter), but it‟s

only needed to know whether target cross some checkpoint or is inside a defined

region. This require an accurate sensor deployment over the environment with

consequent mapping, being carefully not to overlap sensors, avoiding position

ambiguity.

Approaches are divided into two main typologies:

Physical contact: it deals with sensing real contact between target and

sensor, typically touch or capacitive. It‟s not suitable for many application by the

need to have physical contact between target and sensor; moreover, the

architecture become complex in case of multiple targets, where it has to exist

a method to distinguish between different targets.

In-range detection: it deals with the detection of a target presence in a

determined region associated to a sensor (with known action range). Usually,

this approach uses Bluetooth (i.e. Smartphone), RFID (i.e. tags) or NFC. It‟s

not required a sophisticated infrastructure and it scales very well in case of

multiple targets. Mainly for this reason and for low hardware costs, this is the

choice used the most in a commercial products.

Page 17:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

9

1.2.3 FINGERPRINTING

Fingerprinting is a methodology which creates a map of the entire environment along

one or a set of properties. Usually, RSSI values or magnetic field values are used.

The critical part of this method consist of creating the environmental mapping, which has

to be as accurate as possible. Then, live RSSI values are compared with mapped ones

through a probabilistic algorithm,

which report the predicted

location. As said before, RSSI

values are not stable and can

change with respect to many

factors: for example, a change in

the environment can lead to a

complete remap of the area.

However, having an accurate map

and a smart probabilistic algorithm,

this method could be enough

precise (relatively to the grid resolution of the samples mapped).

Mostly Fingerprinting is implemented on a Wi-Fi infrastructure due to the high power

of its signals. In any case the precision is less than expected (order of meters), which

suggest to use it in combination with other methods. In alternative to Wi-Fi access

points, Bluetooth beacons can used for this scope. It has been demonstrated also the

possibility to use variation of Earth magnetic field, which are inducted from the

building structure.

This is an open Research space in which it has been searching for newer

methodologies and strategies to improve precision and mostly simplifying

configuration phase.

Page 18:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

10

1.3 NOISE MEASUREMENT REDUCTION

Even if a limited indoor environment it‟s not perturbed by weather conditions, other

obstacles and stochastic disturbs can interfere with the measurements (as outlined in

previous sections). For example, just moving objects can drift sensed values in an

unpredictable way.

In order to avoid such problems, there were developed various filters to reduce signal

drifts and linearize the measurements to better enhance the precision of the measure

itself. Most important filters are explained here below.

Kalman Filter: in theory is a tool used to estimate next states of a dynamic

linear system perturbed with noise, based onto measures (and observations)

linearly dependents from the state itself and corrupted by noise. This

algorithm is optimal with respect of any quadratic function over error: it uses

all information available.

It‟s not a filter in the strict sense: it evolves over time, adapting its behavior

using new information available (measures).

Page 19:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

11

1. Prediction: model equations project the actual state and covariance of

estimation error from time instant k-1 to k.

2. Correction: firstly it‟s calculated Lk (Kalman‟s Gain Matrix); then new

measures are used to calculate the newer state aposteriori. Finally it‟s

computer covariance of error.

At each iteration new aposteriori estimation is used for the next apriori

prediction of system evolution. This intrinsic recursive characteristic of

the Kalman Filter guide to easy practical implementations.

Particle Filter: the objective of this kind of filter is to estimate the posterior

density of the state variables given the observation variables. The hypothesis

is that observables are related to hidden variables in some known functional

form. It is an iterative process which sequentially estimate values of hidden

states Xk given values of observables Y0,..,Yk at any step k.

Median Filter: probably the most intuitive and simple filter: it computes the

average among a set of values collected in a predetermined time window.

Every time the windows is outdated the process is iterated again in a new

step.

Page 20:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

12

1.4 SENSORS TECHNOLOGIES

In this section it‟s going to be analyzed different technologies for indoor positioning

systems available today. They‟re classified depending on signal typology: radio-waves,

magnetic fields, light-waves, audio-waves.

1.4.1 RADIO SIGNALS

This is a common type of sensor mainly because radio signal is capable to walking

through walls and extend sensor‟s coverage. Another reason resides in their

popularity, which let a wide reuse of products leading dejection of infrastructure

costs.

RFID (Radio Frequency IDentification): this is a technology developed to

identify, memorize and retrieve data through electromagnetic radiation. An RFID

system is composed by three elements: a tag (or transponder), a reader and an

antenna. The tag is a little transponder which contains information. The reader,

using the antenna, is capable of read (or also write) information stored in the tag

whether is in the range. RFID tag can

be passive or active: the first one is

powered over the same data antenna,

but contains a little amount of data and

has a short operative range; the second

one, instead, needs its own power

source, but can contains much more

data and has a wider operative range

(till meters). Tags are very small

resulting easily transportable; however, since they require a strict proximity to

operate, it‟s hard to build and maintain the appropriate infrastructure to use this

technology for IPS. A test example of RFID technology in IPS is the

Page 21:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

13

LANDMARK system, which makes use of an active RFID tag combined with

other static tags of known coordinates to reduce location error.

UWB: (Ultra WideBand) is a radio technology initially developed in „70s that

can transmit signals using very short pulses in radio-frequency over a large

portion of the radio spectrum. Unlike other solutions, using short timings let the

signal to be filtered from refractions and let accuracy in the range of decimeters.

An example of system using this solution is Ubisense: it uses UWB tags on target

and it‟s able to computer position with a 10-15cm of error, with a combination of

AoA and TDoA techniques; on the other hand, it has an elevated cost.

Wi-Fi: nowadays it‟s a spread technology present almost everywhere. Most

common standard is IEEE 802.11 which is continuously evolving, reaching a

maximum speed of 6750Mb/s (802.11ad) and an operating range 180 mt

(802.11n). Using this technology in IPS let accuracy be in the order of 3-30 mt

with update timing of a couple of seconds. Even if the error is still quite high,

MIT it‟s developing Chronos project which aim to increase RSSI precision and

limit measure error in the order of decimeters.

Bluetooth: using the same wavelength of Wi-Fi, it‟s its direct competitor in IPS

usage; the diffusion of BLE (Bluetooth Low Energy) it enhance power-savings

with low costs, letting systems work for years without changing batteries. Thanks

to this reason and the default presence of BLE on smartphones, this is the most

used technology for IPSs. ( Because of this great availability of cheap hardware it‟s

been chosen as base for our project )

Page 22:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

14

1.4.2 MAGNETIC FIELDS

Although there are approaches which creates ad-hoc magnetic fields with proper

extra components, modern systems uses Earth magnetic field and its variations

induced by the building itself (as outlined in previous chapters).

Operating environment has been scanned, creating a magnetic map of the area; using

magnetometer it‟s possible to sense the actual position value and, comparing to values

in map, it‟s possible to locate the target.

A very advanced company working with

this technology is IndoorAtlas; in order

to build an IPS is just sufficient to

provide planimetric map of the desired

area and install their provided App,

which will automatically measure

magnetic anomalies. It‟s a pure software-

based infrastructure, because no extra-

components are needed. The error is in

the range of 2-3 mt and the only cost resides in the Application.

1.4.3 LIGHT WAVES

Even if light is no more than a section of electromagnetic radiation, it is treated

separately mainly because technologies are based onto different principles.

Infrared: infrared radiation is

positioned in the electromagnetic

spectrum slightly under visible light. The

system is composed of a IR led-diode,

which emits signals, and a IR

photodiode, which collects signals ready

to be elaborated. This kind of systems

Page 23:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

15

are affected from optical laws (refraction, dispersion, etc.); moreover, they need

free field between transmitter and receiver. Because of this, very few IPSs have

been developed, and they are not so reliable.

VLC (Visible Light Communication): it uses visible light as data vehicle; every

kind of lamp can be used, but LED are preferred for their speed in turning

on/off and extended lifetime. Data

transmission is possible due to the

capability of the light source to turn

itself on/off rapidly. Sometimes

this intermittence can be so fast to

be imperceptible for human eyes;

various kind of modulation

techniques can be used. Using

different code sequences for each

lamp, target can distinguish among sources and so associate target position to

lamp position. This technology is being studied because it‟s permitted to reuse

existing light sources, limiting infrastructure costs

1.4.4 AUDIO WAVES

Audio waves have a propagation speed much lower than electromagnetics, resulting

in an easier way to compute traveling time from source to target. Usually, there are

techniques which combines audio waves and radio signals, computing time difference

from the fast arrival of radio signal with respect to audio waves. (The very same

principle used by farmers to estimate thunderbolt distance).

Ultrasound: IPSs based on this method make use of frequencies above

human audible ones, resulting not annoying. They can be used in active or

passive configuration: in the active one, target has the source and

microphones are placed into receivers; in the passive one, sources are placed

in known positions and target has a microphone as receiver. Although

Page 24:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

INDOOR POSITIONING SYSTEMS

16

precision is in the order of centimeters, there are troubles with signals

overlaps, which result in difficulties to locate different targets in the same

environment and the increasing cost of scaling infrastructure with respect to

environment size.

Sounds: it‟s possible to use also audible sounds to compute distance, but

can be annoying for people staying in the environment; an idea to mitigate

this issue can be using music modulated over different frequencies.

Obviously, this approach is avoided also because it‟s easy to interfere with

the system.

Page 25:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

17

2 BLUETOOTH LOW ENERGY

2.1 REASONS

As a result of pro and cons of various technologies, their spread in the market, their

state of the art, the availability of components ready-to-use already stocked in

university‟s warehouse, the choice has fallen onto BLE Beacons.

Among all technologies, this has been found as the best compromise between user

experience and system costs.

Next, main reasons are explained in details.

Receiver: today almost all smartphones uses Bluetooth technology (in particular

BLE, Bluetooth Low Energy); that

means, from users point of view, no

need for additional hardware and/or

devices. Moreover, various software

libraries have been developed to

interact with Beacons technology, to

receive and process their signal in order

to obtain the distance; so, a Mobile

Application, using these libraries, can

use this kind of technology to achieve

scoped scenario.

Page 26:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

18

Precision: referred to the requirements, precision needed by the system is not so

critical to require an advanced and expensive technology; during the development,

one of the aim of the project is to identify how can be stressed BLE Beacons

technology to increase precision the most.

Infrastructure: BLE Beacons on the market has various covered areas, which range

from 30 up to 100 mt; this way, it‟s possible to use them for various scenarios, also in

wide indoor areas (i.e. big industrial sheds). Moreover, their low power consumption

let them use batteries, with money saving in not creating ad-hoc electrical power grid

and free or easily positioning around monitored area.

Costs: the most significative cost reside in beacons their selves, which is in range

from 10 to 30€ each. Different providers equip their products with batteries that

assure a lifetime lasting for months or years.

Page 27:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

19

2.2 BLE BEACONS

Technology based onto BLE Beacons let devices transmit or receive small amount of

data in covered area (typically not over 100 mt for best products). Sophisticated

products can perform advanced

actions or can be connected to extra

hardware components to extend their

functionalities. The standard protocol

define what are the minimum details

a broadcast message should contain,

letting readers identify transmitter

and some signal properties.

Next sections explain this devices in

details.

2.2.1 FEATURES

BLE Beacons uses Bluetooth standard transmission technology, which operate onto

2.4 GHz frequency, sharing radio-spectrum with Wi-Fi signals. As known, Wi-Fi is

overbearing, so can slow down Bluetooth packet forwarding. The main beacon

feature is to send periodically small packets (Advertising) in a small temporal window

(which typically starts from 100ms delay among packets on). Minimum required

information onboard packets are three identifiers: UUID, Major and Minor. These

three values are associated with a specific beacon of a specific region, and are used to

identify one beacon in a busy and noisy area.

The Universally Unique Identifier (UUID) is a 128-bit number used to identify

information in computer systems. They are for practical purposes unique, without

depending for their uniqueness on a central registration authority or coordination

between the parties generating them. In its canonical textual representation, the

sixteen octets of a UUID are represented as 32 hexadecimal (base 16) digits,

Page 28:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

20

displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36

characters (i.e. 123e4567-e89b-12d3-a456-426655440000 ).

Major and Minor, instead, are intended to identify a region and a section of the region.

This three values let beacons be configured in every scenario, avoiding problems of

numerous device population and relative conflicts (sometimes can be useful to have

multiple beacons with same parameter, i.e. to extend the identification of an area

above one beacon radio range).

Packet payload can vary whether different protocols are used. For example,

EddyStone protocol (developed by Google) let beacons transmit URLs; other

protocols have been developed specifically for Indoor Positioning. The majority of

products used in localization can transmit a value of Average RSSI over 1 mt, used

most cases to calculate smartphone-beacon distance.

2.2.2 ARCHITECTURE

The use of multiple chips is in contrast with BLE design, both for dimension and

power consumption; because of this, it‟s needed a SoC (System on-a Chip) low

consumption which combines the innovative architecture with a multiprotocol in-

hardware radio circuit to reduce costs, dimension and power supply.

This SoC are designed such that integrated processor manages also control functions,

as the power management that dynamically change based on operating conditions.

Page 29:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

21

Then, with limited processing and memory resources, it executes Bluetooth Advanced

tasks like multiple profiles and security issues. Similarly to standard Bluetooth stack,

BLE stack is structured in two main levels: Controller and Host.

Controller level cover both Physical and Link Layers and it‟s implemented as hardware

SoC with integrated antennas.

Host level is a firmware application executed onto processor which manages high-

level features.

Communication between the two levels is realized with Host Controller Interface (HCI);

the most commonly used are USB (for PCs) and UART (for embedded devices).

2.2.3 RANGE

Beacon‟s range depends on Radio Class used in the implementation:

Class 1 is used in industrial environment and applications and has a

maximum coverage of 100 mt. Signal power is 100mW.

Class 2 is used by the majority of devices and has a maximum coverage of 10

mt. Signal power is 2.5mW.

Class 3 is the weakest one and has maximum coverage of 1 mt. Signal power

is 1mW.

2.2.4 SIGNAL

The best transmission quality is in 1 mt range: firstly, as every electromagnetic

radiation, signal power decrease with the square of distance; moreover, at this

proximity is difficult to have obstacles between source and target. Numerically, the

measure error increase quadratically with distance: for example, if we have some

centimeters of error in proximity of the beacon, this result in meters of error at edges

of ranged area.

As already said, Bluetooth uses 2.4GHz frequency: this is critical because human body

can absorb it, resulting in signal attenuation. Since most applications are realized in

Page 30:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

22

public areas, probably human crowded, and the distance is computer starting from

signal power, this measurements can be poor precise.

The figure on the right reports typical RSSI values at certain distances from

transmitter respectively in

presence and absence of human

body. This experiment

demonstrate an approximate 10dB

attenuation with human presence;

this means that the error can result

in a couple of meters of error at

short distances. Being not

neglectable, some techniques

should be used to avoid (or

mitigate) this problems.

Page 31:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

23

2.3 INDOOR NAVIGATION

2.3.1 LOCATION TYPOLOGIES

Actual implementation of indoor location systems uses mainly three beacons

topologies, based on information needed about the environment: one beacon per

room, many beacons per room, beacons scattered in specific zones of the area.

One beacon per room: used only combined with a virtual map of the indoor

environment, this approach is used when the only information needed is the room in

which the user is. This focus the attention onto the movement among rooms leaving

out specific objects contained into them. The usual aim of such systems is to guide

user through rooms with the shortest path possible, or to track and profile user

movements in monitored environment.

Many beacons per room: in this approach the focus moves from room to a set of

“point of interest” inside rooms (i.e. a set of object present in the same room). A

common scenario could be a museum, in which artworks are equipped with beacons

and user can get information about the specific artwork with the identification

through the associated

beacon. Another common

scenario could be a pure

indoor location, where only

beacons are used as

anchors, and user can be

located in the area using

references given by the

beacons their selves. This is

a tricky scenario under study, because of the instability of the Bluetooth signal and

other previous described problems which make this approach difficult to work

precisely.

Page 32:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

24

Beacons scattered in the area: the

idea is to merge other approaches (i.e.

dead reckoning) with anchor beacons,

in the way that anchor beacons help

other systems to reduce their error

working as checkpoints of known

coordinates; instead, sensors used in mixed systems used give data to estimate

position. Since, it‟s easier to check whether you‟re very near or not instead of the

precise distance from a beacon transmitter, the accuracy of this solution resides onto

the other one chosen as main positioning system.

The choice among previous discussed solutions is driven by the aim of the ongoing

IPS implementing. Another parameter to be considered is the chosen technique to

use for computing position; obviously, in case of multilateration or fingerprinting a

large number of beacons is required. However, considering that the error increase

quadratically with distance, the more number of beacons the more accuracy can be

provided by the system.

2.3.2 STATE OF THE ART

Searching for commercial solution available on the market, until now the best BLE

Beacons based IPS has been developing by Estimote. With the usage of proprietary

devices and Software Development Kit, Estimote Indoor Location is able to compute

real time user position with discrete precision.

With respect to other products, Estimote beacons has additional hardware onboard,

containing a set of environmental sensors (i.e. temperature, magnetometer, light, etc.)

and the possibility to sustain strong power transmission for long time with their

provided battery. Moreover, it has four GPIO pins, which let it be connected with

other external hardware and subsystems to extend even more its capabilities. A new

version is in development phase, which integrates Ultra Wide Band (UWB)

Page 33:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

BLUETOOTH LOW ENERGY

25

transmission technique and should be able to auto generate a map of the monitored

area.

Since they have to transmit additional information about their own extra hardware

and GPIO data, an ad-hoc protocol have been developed. For a matter of fact, it‟s

not known how Estimote can compute very precise (x, y) coordinates, because no

details have been revealed till now. Anyway, after the area has been mapped into the

SDK and it‟s inserted punctual position of beacons, it‟s possible to get real time user

coordinates and his ongoing path.

Page 34:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

26

3 SYSTEM REQUIREMENTS

3.1 PREVIOUS WORK

This project aims to evolve the system built in a previous work, analyzing failing

results and try to adjust some faults as resolve problems intrinsic to some design

choices.

3.1.1 DESCRIPTION

In the previous work it has been chosen to use a cross-platform open-source SDK

for hybrid mobile App development (Ionic), with the purpose to develop once the

logics to be installed on different mobile Operating Systems, and have consequently a

bigger market for the developing IPS.

Resuming, this first prototype consists of a mobile application, which acts as the main

interface and logic controller, and an information database, which contains mapping

of BLE beacons with the environment and their linked information. As a matter of

fact, user navigates through monitored areas using the application to be guided for

reaching its target object(s) inside specific room(s).

This first prototype revealed some limitation, subjected to the cross-platform design

decision, resulting in an incomplete match with desired system requirements.

Mobile application was compiled both for iOS and Android, best running on the first

one. BLE Beacons chosen were iBKS105, an economic class of products which

implements iBeacon and EddyStone protocols. In the next section, problems and

limitation will be analyzed in details.

Page 35:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

27

3.1.2 ANALYSIS AND LIMITS

A first working prototype (compiled for both iOS and Android) has been tested in a

quite real environment, characterized by radio noise and people crowd; during the test

running, users experienced some troubles such as delays or incorrect information

retrieval or beacon detection missing too. This unexpected behavior that had not

occurred during laboratory tests focused the attention into a deeper analysis about

used technology issues (even in the iOS context, whose restricted set of hardware

used in device gives some facilitations).

Exploring involved technology in a deeper way, previous announced issues have been

raised up by different aspects of the system design and implementation choices,

which are described better in details.

Ionic SDK: the main limit led by

the usage of this tool is the

constraint in the variety of libraries

or plugin that can be used for the

purpose; in fact, the critical part of

the application designed for the covered scenario runs on the right beacon

library and its exposed configuration. In this case, the plugin provided

exposes a poor interface which did not allow to configure some critical

parameters client-side, stirring up a set of side effects.

Beacon detection missing: this is one of the side effects of the Ionic

beacon plugin, born due to packets‟ buffer and scanning delays, which cannot

be modified by programmers. As a matter of fact, some packet was not

received (or discarded) and so the corresponding beacon was not identified.

Information retrieval delays: for the same set of parameters, there was a

delay between the packet receiving and the information providing out of the

library; just having a fixed set of packet to be received before processing data

and/or to have enough packets to elaborate, this introduce delays and a

stepping behavior in measuring distances.

Low distance’s precision: Ionic plugin for beacons contains a module

which can also convert signal power into distance (in meters); unfortunately,

Page 36:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

28

apart from very few device models, it requires manual configuration in order

to convert values properly. This configuration is not trivial, and needs long

time and tricky actions to perform. By default, the module is initialized with

some average values, which works but not assuring any range of precision,

that can vary a lot from device model to model.

Hardware configuration: in this first prototype beacon configuration just

follows some general guidelines, which is very general and can be not

appropriate for the need scenario. Values were set more or less empirically,

which is not the best solution ever.

In order to understand and resolve these problems a wide analysis was conducted:

firstly, hardware was deeply investigated to know exactly its limits, whether and how

to resolve them or the need of changing some technology or product used; secondly a

mathematic study revealed some interesting properties onto the BLE beacon

ecosystem; from this study a special kind of filter has been developed to reduce

measurement errors, with the expected success; thirdly, limits in Ionic libraries led to

the native implementation with other libraries, which revealed the possibility of a

better configuration and the resolution of some delays and precision problems.

Next sections will discuss about hardware tests conducted (with obtained results) and

the mathematical study performed onto beacons ecosystem (with obtained results).

3.2 HARDWARE TESTING

Once main problems have been identified, the first step to resolve them was

hardware checking. In the most general sense, both functional and performance

check was needed: firstly, it has to be sure that all involved hardware did not have

functional problems (i.e. exhaust

batteries); then, it has to be checked

that hardware is really capable to match

project requirements. Critical project

components are: BLE Beacons and

Page 37:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

29

Mobile Application. Subsequent sections explain hardware checking.

3.2.1 BLE BEACONS

Since during prototype execution some beacon seems not to work properly, the first

check involved every beacon battery; only a couple of them resulted in a power

supply failure.

A second test was run to check packet transmission, coverage range and signal

quality; it was conducted in a noisy environment just to run in the worst condition,

but ended with positive results.

The last check concerned the signal stability: it was monitored for long time windows,

reporting RSSI data; it was expected that signals do not have to change significatively

during time. What emerged from this analysis was an unpredictable instability of the

signal; some kind of filter was absolutely needed in between Application and Beacon

Library in order to linearize the measurements.

3.2.2 ANDROID NATIVE LIBRARY

The second critical component in the system is the Beacon Library, and more

precisely what parameter can be changed in configuration.

Mainly two alternatives were identified: from one side, Estimote SDK can be a

solution which has lots of integrated functionalities but runs only with Estimote

beacons; from the other side, Android Beacon Library is a freeware solution, which

is more general but sufficient for our purposes.

The second option was chosen for the new prototype: among its features, there‟s now

the possibility to set some parameters to adjust timings in reading beacon‟s packets

and resolve this way a part of problems.

Through a testing void application it has been demonstrated that target device it‟s

able to detect beacons and correctly report needed information from their packets,

result in a positive device hardware test.

Page 38:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

30

3.3 RSSI MEASUREMENT ERROR MANAGEMENT STUDY

The last step made to complete the study of problems and generation of needed

solutions is a mathematical observation of the beacon environment, strategies or

filters to stabilize signal measure over noise and other interference factors, both from

static and dynamical point of view (i.e. standing or moving device), extending the

basic concept of signaling beacon to context-dependent beacon, which is regulated by

some rule or guideline in its configuration and role in the IPS. All this information is

explained in details in the next subsections.

3.3.1 RSSI AND KNOWN PROBLEMS

In telecommunications, Received Signal Strength Indicator (RSSI) is a

measurement of the power present in a received radio signal.

RSSI is usually invisible to a user of a receiving device. However, because signal

strength can vary greatly and affect functionality in wireless networking, IEEE 802.11

devices often make the measurement available to users.

RSSI is often derived in the intermediate frequency (IF) stage before the IF

amplifier. In zero-IF systems, it is derived in the baseband signal chain, before the

baseband amplifier. RSSI output is often a DC analog level. It can also be sampled by

an internal ADC and the resulting codes available directly or via peripheral or internal

processor bus.

In an IEEE 802.11 system, RSSI is the relative received signal strength in

a wireless environment, in arbitrary units. RSSI is an indication of the power level being

received by the receive radio after the antenna and possible cable loss. Therefore, the

higher the RSSI number, the stronger the signal. Thus, when an RSSI value is

represented in a negative form (e.g. −100), the closer the value is to 0, the stronger

the received signal has been.

There is no standardized relationship of any particular physical parameter to the RSSI

reading. The 802.11 standard does not define any relationship between RSSI value

and power level in milliwatts or decibels referenced to one milliwatt. Vendors and

Page 39:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

31

chipset makers provide their own accuracy, granularity, and range for the actual

power (measured as milliwatts or decibels) and their range of RSSI values (from 0 to

RSSI maximum).

Nevertheless, RSSI does not always provide measurements that are sufficiently

accurate to properly determine the location.

3.3.2 BEACONS IN REAL ENVIRONMENT – MEASUREMENT ISSUES

Bluetooth beacons are hardware transmitters - a class of Bluetooth low energy

(LE) devices that broadcast their identifier to nearby portable electronic devices. The

technology enables smartphones, tablets and other devices to perform actions when

in close proximity to a beacon.

Bluetooth beacons use Bluetooth low energy proximity sensing to transmit a

universally unique identifier picked up by a compatible app or operating system. The

identifier and several bytes sent with it can be used to determine the device's physical

location, track customers, or trigger a location-based action on the device such as a

check-in on social media or a push notification.

The first step is to check and test the BLE beacons technology, in order to

establish its capabilities in (mostly) indoor location scenarios, trying to resolve

common problems.

Page 40:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

32

3.3.3 ISSUE 1: MEASURE OF A FIXED BEACON FROM A FIXED DEVICE

The aim of this first test is to establish the accuracy of the RSSI measure, in a real

environment (with radio noise not known and variable) between a fixed beacon (i.e.

Beacon stand on a table) and a fixed user device (i.e. User‟s smartphone of arbitrary

vendor stand on another table). We analyze the scenario as represented in the below

figure.

Configuration data:

Test Beacon

iBKS 105 – Accent System

Tx Power: 0dB

Advertising time: 1000ms (1s)

Test User device Nexus 5 – Google Inc.

Android v6.0.1

Page 41:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

33

Results:

#sample Measured RSSI

(dBm) ( )

1 -53 0,0289

2 -53 0,0289

3 -49 14,6689

4 -54 1,3689

5 -54 1,3689

6 -53 0,0289

7 -53 0,0289

8 -53 0,0289

9 -54 1,3689

10 -54 1,3689

11 -53 0,0289

12 -53 0,0289

13 -53 0,0289

14 -52 0,6889

15 -52 0,6889

#sample Measured RSSI

(dBm) ( )

16 -53 0,0289

17 -53 0,0289

18 -52 0,6889

19 -52 0,6889

20 -53 0,0289

21 -52 0,6889

22 -52 0,6889

23 -53 0,0289

24 -52 0,6889

25 -52 0,6889

26 -54 1,3689

27 -54 1,3689

28 -54 1,3689

29 -53 0,0289

30 -53 0,0289

Page 42:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

34

Proposed solution:

Analyzing above result data, we can see that the measurement is not stable, and it‟s

possible to calculate errors, taking in consideration various types of indices.

Accepted measure ∑

-52,83 dB

Absolute error

2,5 dB

Relative error

-4,73 %

Standard deviation √∑( )

1,003 dB

The calculated accepted measure can be rounded to the nearest integer (-53dB) to

be conformant with the convention that RSSI is an integer value.

The prominent weight of the absolute error is given by the only different measure of

0

2

4

6

8

10

12

14

16

Signal power

-49

-52

-53

-54

Page 43:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

35

-49 dB, which occurred once. For this reason, this index it‟s not much relevant in this

case of application, in which we found Standard Deviation more suitable; in fact, it

says that the real measure has a neighborhood of 1dB per side (which is notably

right).

At the end of this analysis we can conclude that the instant measure of RSSI it‟s not

appropriate. We have to calculate an accepted measure over time of various samples;

but, considering delays among samples and the need to have quickly a measure, we

have to find a method to speed up the measurement.

In order to mitigate the error, but avoiding too much delay from one accepted

measure to the next, the proposed solution is to have a real-time adaptive calculation

of the accepted measure, using two values per time (old measure and new instant

measure), updating the older result with the new one, rounding it to the nearest

integer.

(One of the hypothesis is that the user device is moving “slowly”, said in the order of

a man walking).

Configuration data:

Test Beacon

iBKS 105 – Accent System

Tx Power: 0dB

Advertising time: 1000ms (1s)

Test User device Nexus 5 – Google Inc.

Android v6.0.1

Page 44:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

36

Results:

#sample Measured RSSI

(dB) ( )

1 -56

2 -53

3 -53

4 -53

5 -53

6 -53

7 -53

8 -53

9 -53

10 -53

11 -53

12 -53

13 -53

14 -53

15 -53

#sample Measured RSSI

(dB) ( )

16 -53

17 -53

18 -53

19 -53

20 -53

21 -53

22 -53

23 -53

24 -53

25 -53

26 -53

27 -53

28 -53

29 -53

30 -53

-53 -56 ∑

As it‟s shown in tables above, applying the chosen adaptive method, after the first

initial phase, result tend to stabilize (very fast) to the real measure (specific for the

radio of the device).

OBSERVATION

Advertising time of the beacon is not relevant for the precision of this measure;

it‟s reported as parameter of configuration and to underline the time window used for

the test (30 seconds = 30 samples * 1s).

Page 45:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

37

3.3.4 ISSUE 2: MEASURE OF A FIXED BEACON FROM A MOVING DEVICE

In spite of the static case, in which the user device is fixed in a location, when it‟s

moving the signal power is crucial to identify the distance from the beacon.

In this case, keeping in mind the instability of the RSSI measure, it‟s important to

decide the right advertisement timing to be set on the beacon in order to push

enough samples to the user device for calculating the right estimate measure.

Firstly, we have to remind you that a moving device has its own speed (vu); unless

user device is moving in circle at a certain radius from the beacon, its speed affects

how fast changes the distance from the beacon.

Secondly, considering the fluctuating value of the RSSI measure, we know that it‟s

needed a certain number (Ns) of samples in order to estimate an accurate distance. In

practical cases, a number in the closed range of [5; 10] samples are sufficient.

Finally, we have to define how this parameters are related to each other, in order

to establish a rule between the maximum admitted user speed and the right beacon

timing. In this analysis, other parameters must be considered (the exponential decay

Page 46:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

38

of the radio signal, the limit of an integer RSSI value, the precision we desire(pu),

etc.).

The speed of the user is how far he moved in a desired period of time.

If we substitute ∆su with our desired precision pu, we can resolve respecting to

time. We now have an equation in two unknowns. This let us calculate the ∆tu for

each selected maximum admitted speed vu.

This express the relation between the total number of samples in a

certain period T of time, each sent every ∆ts.

Summing up, we can relate the two equations, taking in mind:

∆su = pu ∆T = ∆tu

vu is the maximum admitted user

speed

Ns is the desired number of sample to

be received in each position

pu is the desired precision in

calculation

∆ts is the timing to be set on beacons

OBSERVATIONS

As we said before, Ns is a parameter to be practically evaluated. In our

opinion, it‟s realistic to use a value in the closed range [5; 10].

The parameter pu is influenced by the RSSI measurement mainly for two

reasons:

a. Value is reported as an integer (typically between -100 and 0), so

the measure in “quantized”; moreover, the decay of radio signal is

exponential (not linear), which implies less precision with bigger

distances.

Page 47:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

39

b. Every BLE radio onboard into devices can differs from each other

in precision, minimum RSSI value, and other parameters. So it‟s

not recommended to choose very small pu values.

The vu parameter is context-driven, in the sense that every scenario can admit a

different maximum user speed. But, for the purpose of the system (indoor

positioning and navigation), a value in the range of a man walking is the optimal

(≈2 – 4 Km/h, more precisely ≈ 0,5 – 1 m/s).

3.3.5 ISSUE 3: CLASSES OF BEACONS – ENVIRONMENTAL VS. SINGLE-OBJECTS

In the most general case a beacon is just a device which emits regularly a packet of

information to be identified by a device for some purpose. In this general scenario,

it‟s important to calculate device distance in both cases of a fixed or a moving device.

But in real scenarios, not every beacon is always useful to achieve the present sub-

goal; in this case, beacons play different roles even if they‟re part of the very same

system.

For this reason, it‟s useful to distinguish them in different groups, which acts

differently. This is concretized in multiple configurations, each belonging to a specific

group of beacons. For example, different beacons are required to use different

transmission powers to cover areas of distinct sizes. In this case, it‟s necessary to have

some guidelines and rules to decide which is the best fit power for the specific group

scope.

Taking in mind a power-saving policy, in order to achieve this issue we have to

analyze what is the relation between power transmission and the size of covered area.

One common model used for our purposes is the Log-Distance Path Loss, which

follows the formula:

( ) ( ) (

)

Page 48:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

40

Rewriting the formula in other forms, we have:

( ( ) ( )

) (1)

( ) ( )

(

)

(2)

Formula (1) is useful to estimate distance by a configured device based on

the sensed RSSI value.

Formula (2) is useful in configuration phase, to calculate the specific

environment-driven n parameter, based on known [d, RSSI(d)] couples.

The table above shows RSSI references for an example beacon, based on distance

and TX-power configured on the same beacon.

Summing up, we can now explain our idea. Every class of beacon has its own

configuration, involving not only advertisement delay (which leads maximum user

speed, as described in a previous chapter) but also in its transmission power (which

leads maximum covered distance).

This way, knowing RSSI reference value for each TX-power class, we can estimate

distance using formula (1); in the other hand, we can calibrate Tx-power and

advertisement delay to reach a compromise between UX (user experience) and

Power-Saving (beacons‟ life).

Page 49:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

41

Using above table, we can define 2 or 3 beacon classes, distinguishing their Tx-

power:

Tx-Power Beacon class Description

-30dB Class 1 (Near-Field)

With a maximum coverage of 5 meters, it‟s

useful to identify single objects in a crowded

space.

-20dB

-16dB

-12dB

Class 2 (Room-Size)

With a maximum coverage between 20 and

30 meters, it‟s useful to identify single spare

objects or combined to create trilateration

positioning systems.

-8dB

-4dB

0dB

+4dB

Class 3 (Large-Hall)

With a maximum coverage between 50 and

70 meters (depending on beacon‟s vendor) it‟s

recommended to be used for creating a

(trilateration) positioning system.

From the above table, we put in evidence typical Tx-Power suggested for each

defined class of beacon. However, the deployment environment can lead to choose

other values for the selected class.

Page 50:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

42

3.3.6 ISSUE 4: USER DEVICE’S CONFIGURATION DATA AND PROCEDURE

Supposing that we don‟t have data to configure each possible device, we propose a

method describing how to set the n parameter for the specific device for calculating

distance starting from sensed RSSI and a RSSI reference for the selected class of

beacon.

The idea starts from the assumption that we know the distance of the minimum

RSSI value (-100dBm) that can be sensed for each beacon‟s class. Using results

obtained in Issue 1 we can conclude that after a certain number of samples we have

an acceptable RSSI value. So, knowing the configuration distance between the user

device and the beacon, and all the previous consideration, we can calculate a possible

n value for the operating environment to use in formula (1) when calculating the

distance.

Page 51:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM REQUIREMENTS

43

Recalling:

( ) ( )

(

)

From the table above we can extract [d, RSSI(d)] couples for each Tx-Power class;

thus, knowing the configuration distance (default 1 meter) and using the sensed RSSI

over time (as explained in the Issue 1) for a certain time (i.e. 5 seconds, with a adv.

delay time of 100ms give 50 samples), the device can estimate the environmental n

parameter accurate w.h.p. From this time on, the device is able to calculate an

accurate distance using RSSI value.

Page 52:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

44

4 SYSTEM DESIGN

4.1 DESIGN CHANGES

Considering all previous analysis and conclusions, it was needed some design

changes:

Changing from Ionic SDK to

Native Implementation of the

Application to use more

configurable libraries; it was chosen

the Android environment for the

prototype.

Inserting a Smart Data Filter

between beacon library and

application logics; it were

implemented considerations explained in previous RSSI study.

Starting from the study, both filter and beacons classes concepts were

concretized in an all-inclusive Framework to be imported and used in the final

application.

Database Interfaces for beacons data were needed: one for management staff

and the other for user navigation “profile”, a

sort of personalization in the navigation

experience.

Page 53:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

45

4.2 PROPOSED SCENARIO

Within the context of proceeding from the work already done in the previous

product, to evolve it in order to fully cover the desired system requirements, the

proposed scenario involves two class of beacons:

[Large-Hall] Environmental – Defines beacons to identify places (i.e. rooms,

aisles, etc.)

[Near-Field] Exposing Objects – Defines beacons to identify objects

exposed to users

The idea behind the application is to guide user “in some way” around places

(using Large-Hall beacons as references), illustrating specific objects when user is

“near enough” to them, even if they are not discernable (i.e. consider objects as

closed uniform boxes). There is a supporting DB in which objects are associated with

places.

Page 54:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

46

4.3 SYSTEM ARCHITECTURE

The above picture describe the architecture of the developing IPS system, what are

the main components and how they are connected to interact with each other.

As it is shown, the system is divided into four parts:

Beacons

Mobile Application

Database and CRUD APIs

Web Interfaces to DB

In between Beacons and Mobile Application, dashed line stands for a wireless

communication (in this case Bluetooth); the channel is managed by iBeacon protocol.

The low level communication has been implemented in the third-party library

(Android Beacon Library), used in the mobile develop to receive and decode beacon

packets.

In the middle of the diagram, there is the centralized Database, which contains

information about every beacon and data of relative objects (or rooms). This

component is the data repository for user Mobile Application; it is also connected to

two Web Interfaces for data manipulation.

Page 55:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

47

The management Web Interface is used by system administrators to check/update

information and system deployment; in fact, it is used to insert, modify or delete data

associated with each beacon, and mapping among beacons (i.e. if a set of beacons is

used to represent rooms and another set is used to represent objects, a mapping can

relate which object is in which room).

The user Web Interface is exposed to user their selves to create personalized profiles,

which are used to restrict the set of “interesting objects” from all. This set identify

which objects will be detected by the mobile application during user navigation;

others will be discarded and not displayed.

It‟s not specified how Mobile Application communicates with Database, neither

how Web Interfaces communicate with Database; usually, the user is expected to use

Wi-Fi (or UMTS/LTE data connection) on his mobile phone, and Wi-Fi or Cabled

connection if using Web Interface from Desktop computer. Similarly, management

Web Interface is expected to be accessed from Wi-Fi or Cabled connection through

system admin Desktop computer.

Next sections will describe more in details each part of the system.

Page 56:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

48

4.3.1 BEACON MEASUREMENT FRAMEWORK

This is the intermediate layer set in between beacons and mobile application. It‟s

composed by a Smart Filter and a Data Structure which describes beacons‟ roles

and additional information associated. In some sense, it‟s the core of mobile

application, which firstly adapts and filters received packets and then organize them in

a way useful for the rest of application.

In the above class diagram it‟s shown how the initial concept of Beacon is firstly

extended to insert role information and then is extended again with the

BeaconMesurer smart filter.

Page 57:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

49

More specifically, the Beacon class exposed by external library is encapsulated in a

more detailed class called AmbientBeacon. This class add information about the role

(and relative data) of the specific beacon. This abstract class is extended in real

present types of beacon used in the system: in this case, ConfigBeacon, RoomBeacon and

ObjectBeacon. This three types are used in the entire system to identify rooms, objects

and a special kind of item which can be used to configure application in a specific

device (used for the conversion between power signal and distance).

This AmbientBeacon objects can be listed through AmbientBeaconList class; it‟s

useful to have a sorted set of mixed type of objects, with some specific methods.

The initial concept of “Ambient Beacon” is surrounded by the smart filter,

BeaconMesurer, which process punctual received data about power signal to obtain a

stable measure. Also for this component is provided a class, BeaconMesurerList, which

can collect some BeaconMesurer objects in a list, and operates some actions onto

them.

Another class has been designed with the objective to map objects into rooms:

DataLinks. This class contains a map with rooms as keys and a list of objects ad value.

So, for each room can be provided a list of objects contained. Data for this structure

are extracted from the database.

Page 58:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

50

4.3.2 MOBILE APPLICATION (ANDROID NATIVE)

It‟s a mobile interface running onto user device which guide user navigation

through beacon measures, displaying retrieved information from database. It can be

configured to filter only information of interest from all.

The above diagram describes the navigation flow among mobile application views,

which in Android world are called Activities. As it is possible to see, the starting point

is a splash screen, which redirect the control to the main activity. This view continue

initializing the application, asking for user personal code, which is an identifier used

to refer to his personalization. From this view, if required, the control passes to the

configuration activity: this is used to configure the beacon library for the specific

device, using a set of beacons deployed for the purpose. Then, in any case, control

passes to the exploration activity, which exposes a GUI to the user, in order to show

information about what is around: detailing, it shows downloaded attributes for the

room with a list of objects detected, sorted by name or nearness. As soon this activity

opens, it downloads profiles data from database, specific to the user: this data

includes beacons of interesting objects and relative rooms containing them. When the

user stops walking (or by manual action through tapping the element) the control

passes to another view which shows entire information about specific object

(downloaded from the database too), including an image, some attributes and an

audio file (i.e. audio description of the object).

Page 59:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

51

Main Activity: its scope is to acquire user identification code, eventually

launch the configuration activity and then launch the exploration activity.

It‟s the entry point of the control flow.

Configuration Activity: its scope is limited to scenarios which requires a

conversion of power signal to metrical distances: for this purpose, since

every device usually have different Bluetooth chipset with different

characteristics, a configuration procedure starts in order to analyze signal

under known situations to adapt the conversion into low error values.

Exploring Activity: this is the critical point of flow in the application,

since the user passes time here the most; its scope is to identify room, to

show a list of objects contained and that are interesting for the specific

user, sorting them with a priority criteria (i.e. nearness). Each element in

the list can be explored with the help of a specialized view. When this view

starts, it assign a Step Detector listener, which is used to automatically

display details of item in top of the list when it‟s detected the user stops.

Anyway, it‟s possible to display details also manually.

Object Detail Activity: its scope is simply retrieve information about

selected object and show them to the user in a comfortable way. Data

includes some text, an image and an audio. When starts, also this view

assign a Step Detector listener, used to automatically go back to exploring

activity when user restart walking. Anyway, it‟s possible to go back

manually.

Page 60:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

52

4.3.3 WEB APPLICATION INTERFACES

These two components, designed respectively for system managers and users, are

used to insert, update and delete data onto system database. There are two distinct

web interfaces (one for administrators and the other for users) that are described

separately.

Database Management Interface:

The above picture is a sketch of the appearance for the Database Management

Interface, used by system administrators to manage objects, rooms and their links.

Detailing more, the web application is composed by two tabs: the first is related to

objects and the second to rooms (the UX design is the same for both, so it‟s reported

only once).

At the top of the page there‟s the application title (fixed and centered). It follows

the two tabs. Each tab is organized into two sections.

The top first displays the list of items dropdown (in order to let selecting

only one item per time) and list contextual commands (open, delete).

The second displays item‟s information, letting them to be changed, with

item commands at the bottom (new, save).

Page 61:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

53

Considering the usage scenario (desktop computers of system administrators) this

UX design have to be Responsive, even if it‟s not a must that it has to run fine onto

mobile devices. This feature can be tested deeper in future developments.

User Wishlist:

The above picture is a sketch of the appearance for the User Wishlist Interface,

used by the majority of users to personalize their navigation guidance. Detailing more,

the web application is composed by two tabs: the first contains the unique user code,

a string associated to a specific user; the second lets the user create, modify and delete

his “wishlist”, an unordered list of interesting objects. This list is used to filter from

all sensed object only the group which is selected by the user.

At the top of the page there‟s the application title (fixed and centered). It follows

the tab to manage user-specific list. This tab contains the field(s) to specify the User

Code and the commands to proceed with the user associated wishlist. Then after,

there‟s another tab in which takes place the definition of the wishlist. It is composed

by three main sections.

Page 62:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

54

Firstly, a multi-selectable list of the all available objects: they can be

selected individually or all together to be added. It is possible to add

objects in more than one step.

Secondly, a multi-selectable list of the selected objects: they can be

selected individually or all together to be deleted. It is possible to delete

objects in more than one step. The first (or the unique) object selected

from this list can be viewed in details, displaying information in the third

section.

The third section is on the right of the tab and displays the essential

information of the object, sufficient to decide whether it is interesting

enough or not.

At the bottom of the tab there are commands to save, delete or close the

wishlist.

Considering the usage scenario (desktop computers or even mobile devices of

users) this UX design must be Responsive, and has to run fine onto mobile devices

too. This feature has a great importance, since the user can modify his preferences

even few minutes before entering the monitored area, and so he has to be able to

modify his wishlist from his mobile device on the fly.

Page 63:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

55

4.3.4 SERVER CRUD APIS

The database component is a SQL-compatible relational database which contains

all information associated to beacons; it can be accessed low level through CRUD

compliant http interface. They will be queried by Web Interfaces and Mobile

Application.

As shown in this figure, CRUD is a data-driven paradigm to interact with a

database server; it is used to simplify the communication through a well-defined

structure for the API and also to let the database be independent from the actual

implementation; in fact, every technology client-side must only encode/decode data

in a certain format (JSON in this case), regardless the specific technology used in the

client (Java in this case).

In this design the server has to expose a defined set of APIs to get or push data

from/to the application in a certain form. This APIs must be able to store or retrieve

data for the two Web Interfaces and to provide the required subset of data to the

Mobile Application.

The entire set of APIs are divided into three groups, depending on the consumer.

Page 64:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

56

Web Management Interface: this group contains all APIs available for the

management interface. They are explained in the table below.

API name API

input parameters

API

output parameters Description

upload_audio

maior

minor

audiofile

audiofile

(name)

This function is used to async uploading of audio

file associated with each object.

list_rooms maior array([maior,

minor, title])

This function returns the list of all rooms stored

in the group having the specified maior.

rooms_details maior

minor

[maior, minor,

title, floor,

note, img,

audiofile]

This function returns all details about a single

room.

save_room

maior

minor

title

floor

note

img

This function stores (or update) information

about a single room, which is identified through

its maior and minor.

del_room maior

minor

This function deletes a specific room and its

information.

list_objects maior array([maior,

minor, title])

This function returns the list of all objects stored

in the group having the specified maior.

object_details maior

minor

[maior, minor,

title, artist,

value, note,

img, audiofile,

room_maior,

room_minor]

This function returns all details about a single

object.

save_object

obj_maior

obj_minor

obj_title

obj_artist

obj_value

note

img

room_maior

room_minor

This function stores (or update) information

about a single object, which is identified through

its maior and minor, except its audiofile.

del_object maior

minor

This function deletes a specific object and its

information.

Page 65:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

57

Web User Interface: this group contains all APIs available for the user

personalization interface. They are explained in the table below.

API name API

input parameters

API

output parameters Description

list_objects maior

array([maior,

minor, title,

artist])

This function returns the list of all objects stored

in the group having the specified maior.

object_details maior

minor

[maior, minor,

title, artist,

value, note,

img,

room_maior,

room_minor]

This function returns all details about a single

object.

load_wishlist user

array([maior,

minor, title,

artist])

This function returns the wishlist of specified

user (the list of interesting objects)

save_wishlist

user

array([maior,

minor])

This function saves the actual selected wishlist

onto the server

canc_wishlist user This function deletes the wishlist associated to

the specified user

Mobile Application: this group contains all APIs available for the mobile

application. They are explained in the table below.

API name API

input parameters

API

output parameters Description

test This function tests the availability of server

connection.

get_rooms array([maior,

minor]) This function returns the whole list of rooms.

get_allobjects maior

minor

array([maior,

minor])

This function returns the whole list of objects

contained in a specified room.

get_objectsofint

erest

user

maior

minor

array([maior,

minor])

This function returns the list of objects

contained in a room but selected in the user

wishlist.

get_objectinfo maior

minor

[title, artist,

value, img,

note,

audiofile]

This function returns all details about the

specified object.

Page 66:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

58

get_roomshorti

nfo

maior

minor [title, note]

This function returns a preview of information

of a specified room.

get_objectshorti

nfo

maior

minor

[title, artist,

value]

This function returns a preview of information

of a specified object.

4.3.5 DATABASE ER-DIAGRAM

This section describes the Database structure previous APIs refer to. In order to

explain its structure, it is used a standard notation called Entity-Relationship Diagram

(ERD).

As it is possible to notice, the diagram exposes three entities (User, RoomBeacon,

ObjectBeacon) and two relationships among them (BeaconMap, Interests). Ellipses

represents attributes, which refers both to entities and/or relationships; if underlined,

they stays for Primary Key.

Page 67:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM DESIGN

59

Diagram elements are now discussed in details.

Entities

o RoomBeacon: this describes those kind of beacons specific to

identify rooms, with respectively details (i.e. floor, title, etc.).

o ObjectBeacon: this describes those kind of beacons specific to

identify objects, with respectively details (i.e. title, artist, value, etc.).

o User: this describes an user of the system, which has decided to

experience a personalized usage of itself. It contains at least a

unique code which identifies the user and let him decide a subset

of all objects that are considered interesting among all.

Relationships

o BeaconMap: this is the relation which maps objects into rooms. It

is possible to have many objects in a room, but not the other way

around (obviously). Even if each line is unique (because we cannot

have duplicate associations), a unique identifier is included, mainly

for future purposes.

o Interests: this is the relation used to personalize user usage of the

system. The association between an user and a set of objects, let his

application show only “interesting objects”.

The ER-diagram shows also cardinality among elements. In particular, it is

possible to see that BeaconMap has as many entries as the number of objects (each

object has to be associated to just one room). Instead, Interests can have a quadratic

number of entries with respect to the number of objects (i.e. each user is interested in

every object).

Page 68:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

60

5 SYSTEM IMPLEMENTATION

5.1 BEACON MEASUREMENT FRAMEWORK

Starting from the design decisions, it‟s now presented the implementation of the

Framework. First of all, for prototyping purposes and device availability, Android OS

has been chosen; because of this, the entire framework has been implemented in Java

language. Each designed class was coded into a Java class, with private attributes,

setters, getters and special actions methods.

Relatively to the constructors, it was chosen a particular kind of Build pattern. It

is structured as shown below.

public class Aclass {

/* Class attributes */

private Type attr1;

/* Public Builder and private constructor */

Public static Aclass Build() { return new Aclass(); }

private Aclass() {

// constructor istructions...

}

/* Setters */

public Aclass setPar(Type par1) {

this.attr1 = par1;

return this;

}

// other methods...

}

The main advantage of such pattern is the simplification in the creation of the

object, the clearness of the code through the possibility to put in cascade various

methods, the not necessity of declaring multiple constructors with different signs: just

Build (or refer) the object and set cascading all needed parameters.

Page 69:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

61

The two enumeration (DistValues, TxPowerValues) were included into the

BeaconMesurer class as “public static” variables.

There is now the detailed description of the two framework‟s parts: the first layer,

that extends the concept of beacon into “ambient beacon”; the second layer, that is

the filter which clean the measurement from noise.

Beacon Types:

public abstract class AmbientBeacon {

/* Class constant */

public static final Identifier NO_UUID = null;

/* Object attributes */

private Beacon beacon;

private String name;

private String photo;

private String description;

// Setters and Getters...

// Other Methods

public boolean equals(AmbientBeacon beacon) {

return this.getBeacon().getId2().equals(beacon.getBeacon().getId2()) &&

this.getBeacon().getId3().equals(beacon.getBeacon().getId3());

}

public boolean UUIDequals(AmbientBeacon beacon) {

return (this.getBeacon().getId1() == null) ||

this.getBeacon().getId1().equals(beacon.getBeacon().getId1());

}

}

This abstract class is the first encapsulation of beacons. The composition with a

Beacon class became an internal parameter, adding all extra information (generic for a

general beacon). The two last methods overrides the equality check among objects,

dealing separately with UUID and Major/Minor pair. Being an abstract class, no

object can be generated from it; instead, for each kind of ambient beacon it‟s needed

to create a particular class extending this.

In this prototype an Ambient Beacon was extended three times: ConfigBeacon,

RoomBeacon, ObjectBeacon.

Page 70:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

62

public class ConfigBeacon extends AmbientBeacon {

/* Class constant */

public static final int IGNORE_TXPOWER = -1;

/* Object attributes */

private int TxPower;

/* Public Builder and private constructor */

@NonNull

public static ConfigBeacon Build() { return new ConfigBeacon(); }

private ConfigBeacon() {}

/* Setters */

public ConfigBeacon setTxPower(int txPower) {

TxPower = txPower;

return this;

}

/* Getters */

public int getTxPower() { return TxPower; }

}

public class ObjectBeacon extends AmbientBeacon {

/* Object attributes */

private String artist;

private double value;

private String notes;

/* Public Builder and private constructor */

@NonNull

public static ObjectBeacon Build() { return new ObjectBeacon(); }

private ObjectBeacon() {}

/* Setters */

public ObjectBeacon setArtist(String artist) {

this.artist = artist;

return this;

}

public ObjectBeacon setValue(double value) {

this.value = value;

return this;

}

public ObjectBeacon setNotes(String notes) {

this.notes = notes;

return this;

}

/* Getters */

public String getArtist() { return artist; }

public double getValue() { return value; }

public String getNotes() { return notes; }

}

Page 71:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

63

public class RoomBeacon extends AmbientBeacon {

/* Object attributes */

private int floor;

/* Public Builder and private constructor */

@NonNull

public static RoomBeacon Build() { return new RoomBeacon(); }

private RoomBeacon() {}

/* Setters */

public RoomBeacon setFloor(int floor) {

this.floor = floor;

return this;

}

/* Getters */

public int getFloor() { return floor; }

}

Then it was implemented the concept of list; because it has to work with possibly

mixed collections of beacon typologies, it is derived from the most general type of

Ambient Beacon, resulting in AmbientBeaconList. The basics of a list management

(add, remove, etc..) is demanded to a casted java list (<AmbientBeacon>List); this

layer add some functions specific to this kind of list, as searching for a beacon of

checking its presence.

public class AmbientBeaconList {

/* Internal list */

private List<AmbientBeacon> abList;

/* Public Builder and private constructor */

@NonNull

public static AmbientBeaconList Build(){ return new AmbientBeaconList(); }

private AmbientBeaconList(){

abList = new ArrayList<>();

}

/* Getters */

public List<AmbientBeacon> getList() { return abList; }

/* Actions */

public boolean isBeaconPresent(Beacon beacon) {

return findAmbientBeacon(beacon) != null;

}

public boolean isAmbientBeaconPresent(AmbientBeacon beacon) {

return isBeaconPresent(beacon.getBeacon());

}

public AmbientBeacon findAmbientBeacon(Beacon beacon) {

if ((abList != null) && (beacon != null)) {

for (AmbientBeacon ab : abList) {

if (ab.getBeacon().equals(beacon)) return ab;

}

}

return null;

}

public AmbientBeacon findAmbientBeacon(AmbientBeacon beacon) {

return findAmbientBeacon(beacon.getBeacon());

}

}

Page 72:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

64

Control Logics:

In order to relate objects and rooms (noticing that in the database there is such

relation), it was implemented a class for this purpose which contains a map, with

RoomBeacons as key and a list of ObjectBeacons as value. There are also methods to

search into the map, retrieve values and set (or update) values. In this implementation

the structure cannot be accessed outside, resulting transparent to the programmer.

public class Datalinks {

/* object relation using maps */

private Map<RoomBeacon, List<ObjectBeacon>> structure;

/* Public Builder and private constructor */

@NonNull

public static Datalinks Build() { return new Datalinks(); }

private Datalinks() {

this.structure = new HashMap<>();

}

/* Actions */

public List<ObjectBeacon> getRoomObjects(RoomBeacon roomBeacon) {

if (this.getRoom(roomBeacon) != null)

return structure.get(this.getRoom(roomBeacon));

else return null;

}

public void setRoomObjects(RoomBeacon roomBeacon,

List<ObjectBeacon> objectBeacons) {

if (this.getRoom(roomBeacon) != null)

structure.put(this.getRoom(roomBeacon), objectBeacons);

else

structure.put(roomBeacon, objectBeacons);

}

public ObjectBeacon findObjectById(RoomBeacon roomBeacon,

Identifier id) {

if (this.getRoom(roomBeacon) != null)

if (structure.get(this.getRoom(roomBeacon)) != null) {

for (ObjectBeacon ob : structure

.get( this.getRoom(roomBeacon) )

) {

if (ob.getBeacon().getId3().equals(id)) return ob;

}

}

return null;

}

public RoomBeacon findRoomById(Identifier id) {

for (RoomBeacon key : structure.keySet()) {

if (key.getBeacon().getId3().equals(id)) return key;

}

return null;

}

public RoomBeacon getRoom(RoomBeacon roomBeacon) {

for(RoomBeacon rb: structure.keySet()) {

if (rb.getBeacon().equals(roomBeacon.getBeacon())) return rb;

}

return null;

}

public boolean isRoomPresent(RoomBeacon roomBeacon) {

return this.getRoom(roomBeacon) != null;

}

}

Page 73:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

65

Then, the filter was implemented in a specific class called BeaconMesurer. It is an

upper layer extending the Ambient Beacon concept, in a compositional way: each

BeaconMesurer object contains an attribute with the last Ambient Beacon used in the

measurement and other attributes for the resulting computation and configuration

parameters.

// STATIC CLASS ATTRIBUTES

// TxPower

private final static int txPowerValues = 8;

public final static int TXPwr30 = 0; // 0: -30 dBm

public final static int TXPwr20 = 1; // 1: -20 dBm

public final static int TXPwr16 = 2; // 2: -16 dBm

public final static int TXPwr12 = 3; // 3: -12 dBm

public final static int TXPwr8 = 4; // 4: -8 dBm

public final static int TXPwr4 = 5; // 5: -4 dBm

public final static int TXPwr0 = 6; // 6: 0 dBm

public final static int TXPwrMax = 7; // 7: +4 dBm

public final static int NEAR_FIELD = TXPwr30;

public final static int ROOM_SIZE = TXPwr16;

public final static int LARGE_HALL = TXPwr4;

// Ref. Distances

private final static int distValues = 10;

public final static int Dist0 = 0; // 0: 0 mt

public final static int Dist1 = 1; // 1: 1 mt

public final static int Dist3 = 2; // 2: 3 mt

public final static int Dist5 = 3; // 3: 5 mt

public final static int Dist10 = 4; // 4: 10 mt

public final static int Dist15 = 5; // 5: 15 mt

public final static int Dist20 = 6; // 6: 20 mt

public final static int Dist30 = 7; // 7: 30 mt

public final static int Dist40 = 8; // 8: 40 mt

public final static int Dist50 = 9; // 9: 50 mt

// Static configuration

private static int[][] pwrDist = new int[txPowerValues][distValues];

private static double envFactor = 2;

// Update factors

public final static float FAST_UPDATE = (float) 2.0;

public final static float NORMAL_UPDATE = (float) 1.0;

public final static float SLOW_UPDATE = (float) 0.5;

// Beacon types

public static final int CONFIG_BEACON = 0x08;

public static final int ROOM_BEACON = 0x10;

public static final int OBJECT_BEACON = 0x12;

public static final int UNKNOWN_BEACON = -1;

In the first part of the class there are the declaration of static constants accessible

from outside; the two designed enumerations are implemented here as a list of static

class constants. Then, there are also two static non-constant parameters, used for the

RSSI – Distance conversion.

Page 74:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

66

/*

Update measure

*/

public BeaconMeasurer updateRssi(AmbientBeacon ambientBeacon) {

if (ambientBeacon != null) {

this.updateRssi(ambientBeacon.getBeacon());

}

return this;

}

public BeaconMeasurer updateRssi(Beacon beacon) {

if (beacon != null) {

this.beacon.setBeacon(beacon);

this.rssiAvg = (int) Math.round(

( this.rssiAvg + ( beacon.getRssi() * this.updateFactor) )

/

( 1 + this.updateFactor )

);

}

return this;

}

The tricky point of the filter is the computation of the measure. In fact, through

above functions it is possible to calculate adaptively and continuously an averaged

measure starting from a noisy signal, which is supposed to follow a linear succession.

In other words, since measures cannot vary a lot frequently, it is reasonable that

averaging them continuously over time can return an reliable value. Moreover, since

the distance between two measures can scale (because the measurer can move with

different speeds) an adjusting factor can give a weight to the new measure and the

impact that it can have on the reliable value.

/*

Calculate distance

*/

public double getDistance(int txPower) {

final double refDist = 1.0;

return refDist * Math.pow(

10,

( BeaconMeasurer.pwrDist[txPower][Dist1] - this.rssiAvg ) /

( BeaconMeasurer.envFactor * 10 )

) ;

}

/*

Calculate Enviromental factor

*/

public double getEnvFactor( double distance, int txPower) {

final double refDist = 1.0;

return ( BeaconMeasurer.pwrDist[txPower][Dist1] - this.rssiAvg ) /

( 10 * Math.log10( distance / refDist ));

}

Page 75:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

67

The first of the above functions is used to convert the filtered RSSI value into a

metric distance. It uses the Log-Distance Path Loss empiric formula which performs

well; it uses a reference table with RSSI - Distance value, the measured RSSI and an

environmental factor, returning the estimated distance.

The second function is another form of the same formula, which can computer

the environmental factor starting from a known situation. This factor is influenced by

every change in the area, from moving objects to people crowding. Every significant

change reflects with the need of reconfigure this factor.

The entire class skeleton is reported here below.

public class BeaconMeasurer {

// STATIC CLASS ATTRIBUTES AND CONSTANTS

// TxPower

/* ... */

// Ref. Distances

/* ... */

// Static configuration

private static int[][] pwrDist = new int[txPowerValues][distValues];

private static double envFactor = 2;

// Update factors

/* ... */

// Beacon types

/* ... */

// DYNAMIC BEACON-SPECIFIC ATTRIBUTES

private AmbientBeacon beacon;

private int rssiAvg;

private double updateFactor;

/* Public Builder and private constructor */

@NonNull

public static BeaconMeasurer Build() {

return new BeaconMeasurer();

}

private BeaconMeasurer() {

this.rssiAvg = 0;

this.updateFactor = NORMAL_UPDATE;

}

/* Configuration and static methods */

public static void setPwrDist(int[][] pwrDist) {...}

public static int[][] getPwrDist() {...}

public static int getTxPowerIndex(int txPowerValue ) {...}

public static void configurePwrDistRSSI( int txPower,

int Dist, int RSSI ) {...}

/* Beacon checks */

public static boolean checkType(Beacon beacon, int type) {...}

public static int getType(Beacon beacon) {

if (beacon.getId2().equals(Identifier.fromInt(ROOM_BEACON)))

return ROOM_BEACON;

else if (beacon.getId2().equals(Identifier.fromInt(OBJECT_BEACON)))

return OBJECT_BEACON;

else if (beacon.getId2().equals(Identifier.fromInt(CONFIG_BEACON)))

Page 76:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

68

return CONFIG_BEACON;

else

return UNKNOWN_BEACON;

}

public static Identifier getBeaconId(Beacon beacon) {...}

public static String printBeaconId(Identifier id) {...}

// DYNAMIC OBJECT METHODS

/* Parameters setters */

public BeaconMeasurer setBeacon(AmbientBeacon beacon) {...}

public BeaconMeasurer setRssiAvg(int rssi) {...}

public BeaconMeasurer setUpdateFactor(double updateFactor) {...}

/* Data getters */

public int getRssiAvg() { return this.rssiAvg; }

public AmbientBeacon getBeacon() { return this.beacon; }

public Identifier getBeaconId() { return BeaconMeasurer

.getBeaconId( this.beacon.getBeacon() );

}

public String printBeaconId() {...}

/* Update measure */

public BeaconMeasurer updateRssi(AmbientBeacon ambientBeacon) {...}

public BeaconMeasurer updateRssi(Beacon beacon) {...}

/* Calculate distance */

public double getDistance(int txPower) {...}

/* Calculate Enviromental factor */

public double getEnvFactor( double distance, int txPower) {...}

/* Checks */

public boolean isRoom() {

return beacon instanceof RoomBeacon;

}

public boolean isObject() {

return beacon instanceof ObjectBeacon;

}

public boolean equals(BeaconMeasurer beaconMeasurer) {

return this.beacon.equals(beaconMeasurer.beacon);

}

}

For this class also was implemented a specific type of list, as reported in the code

below.

public BeaconMeasurer getNearest() {

if (bmList != null) {

BeaconMeasurer min = null;

for (BeaconMeasurer bm : bmList) {

if (min == null) min = bm;

// beacause of RSSI are negatives, I have to check the major

else if (bm.getRssiAvg() > min.getRssiAvg()) min = bm;

}

return min;

}

return null;

}

Page 77:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

69

This method is used to find the nearest beacon in the list. It uses only the RSSI

value (avoiding problems of conversions). Because RSSI values are in a negative form,

the code checks for the highest value (the nearest to 0dBm).

The following code is the entire skeleton of the class.

public class BeaconMesurerList {

/* Class constants */

public static final int STD_INV_THR = -86;

/* Object attributes */

private List<BeaconMeasurer> bmList;

private int invisibleThreshold;

/* Public Builder and private constructor */

@NonNull

public static BeaconMesurerList Build() { return new BeaconMesurerList(); }

private BeaconMesurerList(){

bmList = new ArrayList<>();

this.invisibleThreshold = STD_INV_THR;

}

/* Setters */

public BeaconMesurerList setInvisibleThreshold(int invisibleThreshold) {...}

/* Getters */

public List<BeaconMeasurer> getList(){ return bmList; }

/* Actions */

public boolean areInvisible() {

for( BeaconMeasurer bm: bmList ){

if (bm.getRssiAvg() > invisibleThreshold ) return false;

}

return true;

}

public boolean isBeaconMesurerPresent(Beacon beacon) {...}

public boolean isBeaconMesurerPresent(BeaconMeasurer beacon) {...}

public BeaconMeasurer findBeaconMesurer(Beacon beacon) {

if ((bmList != null) && (beacon != null)) {

for (BeaconMeasurer bm : bmList) {

if (bm.getBeacon().getBeacon().equals(beacon)) return bm;

}

}

return null;

}

public BeaconMeasurer findBeaconMesurer(BeaconMeasurer beacon) {...}

public BeaconMeasurer addOrUpdateList(Beacon beacon,

AmbientBeacon ambientBeacon) {

if (isBeaconMesurerPresent(beacon))

return findBeaconMesurer(beacon).updateRssi(beacon);

else {

BeaconMeasurer bm = BeaconMeasurer.Build();

bmList.add(bm

.setBeacon(ambientBeacon.setBeacon(beacon))

.setRssiAvg(beacon.getRssi())

);

return bm;

}

}

public boolean isEmpty() { return bmList.isEmpty(); }

public boolean emptyList() {...}

public BeaconMeasurer getNearest() {...}

}

Page 78:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

70

5.2 MOBILE APPLICATION (ANDROID NATIVE)

Starting from the design decisions, it‟s now presented the implementation of the

Mobile Application. First of all, for prototyping purposes and device availability,

Android OS has been chosen; because of this, the entire application has been

implemented in Java language.

With respect to a classical Java Application, Android OS put some restrictions in

coding practices: what impacted architecture the most is that it‟s not possible to use

JDBC (Java DataBase Connector) to retrieve data from databases; alternatively, it‟s

needed to build an HTTP – REST (REpresentational State Transfer) architecture.

For previous described reason it was created a separate package for the connector;

it consist of three classes: Api, PerformNetworkRequest and RequestHandler.

The core and UI of application resides in the main package: it consists of one class

for the Application Core and one class for each Activity (remind: an Activity is a java

class for a “page” of the application, containing code for managing the UI. (Possibly,

it‟s not recommended to put directly in an activity the application logics, to better

have a separation of concerns).

5.2.1 API.JAVA

public class Api {

// Server APIs URLs

private static final String ROOT_URL = “http://<server>/apps/”;

public static final String MULTIMEDIA_URL = "http://<server>/apps/";

// Test

public static final String URL_TEST = ROOT_URL + "test";

// CRUD Apis (Create, Read, Update, Delete)

public static final String URL_GET_ROOMS =

ROOT_URL + "get_rooms";

public static final String URL_GET_OBJECTS =

ROOT_URL + "get_allobjects";

public static final String URL_GET_INTERESTING_OBJECTS =

ROOT_URL + "get_objectsofinterest";

public static final String URL_GET_OBJECTINFO =

ROOT_URL + "get_objectinfo";

public static final String URL_GET_OBJECTSHORTINFO =

ROOT_URL + "get_objectshortinfo";

public static final String URL_GET_ROOMSHORTINFO =

ROOT_URL + "get_roomshortinfo";

// CRUD parameters

public static final String PARAM_USER = "user";

Page 79:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

71

public static final String PARAM_MAIOR = "maior";

public static final String PARAM_MINOR = "minor";

// CRUD reponse fields

public static final String RESPONSE_STATUS = "status";

public static final String REPONSE_ROOMLIST = "roomlist";

public static final String REPONSE_OBJECTLIST = "objectlist";

public static final String REPONSE_OBJECTTITLE = "title";

public static final String REPONSE_OBJECTIMG = "img";

public static final String REPONSE_OBJECTNOTE = "note";

public static final String REPONSE_OBJECTAUDIO = "audio";

public static final String REPONSE_MAIOR = "maior";

public static final String REPONSE_MINOR = "minor";

public static final String REPONSE_SHORTINFO = "shortinfo";

}

This is a static class containing all information to query APIs from the application.

As it is possible to see, textual requests are possibly different from multimedia ones;

this decision is to better scale the application in case of large amount of requests,

deploying multimedia files on separate specialized server, which can manage faster

and heavy data transfer for multimedia streaming. Then, APIs functions, parameters

and response fields were declared.

5.2.2 PERFORMNETWORKREQUEST.JAVA

public class RequestHandler {

//Method to send httpPostRequest

//This method is taking two arguments

//First argument is the URL of the script to which we will send the request

//Other is an HashMap with name value pairs containing the data to be send

with the request

public String sendPostRequest(String requestURL,

HashMap<String, String> postDataParams) {

//Creating a URL

URL url;

//StringBuilder object to store the message retrieved from the server

StringBuilder sb = new StringBuilder();

try {

//Initializing Url

url = new URL(requestURL);

//Creating an httmlurl connection

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

//Configuring connection properties

conn.setReadTimeout(15000);

conn.setConnectTimeout(15000);

conn.setRequestMethod("POST");

conn.setDoInput(true);

conn.setDoOutput(true);

//Creating an output stream

OutputStream os = conn.getOutputStream();

//Writing parameters to the request

//We are using a method getPostDataString which is defined below

Page 80:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

72

BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(os, "UTF-8"));

writer.write(getPostDataString(postDataParams));

writer.flush();

writer.close();

os.close();

int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader br = new BufferedReader(

new InputStreamReader(conn.getInputStream())

);

sb = new StringBuilder();

String response;

//Reading server response

while ((response = br.readLine()) != null) {

sb.append(response);

}

}

} catch (Exception e) {

e.printStackTrace();

}

return sb.toString();

}

public String sendGetRequest(String requestURL) {

StringBuilder sb = new StringBuilder();

try {

URL url = new URL(requestURL);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

BufferedReader bufferedReader = new BufferedReader(

new InputStreamReader(con.getInputStream())

);

String s;

while ((s = bufferedReader.readLine()) != null) {

sb.append(s + "\n");

}

} catch (Exception e) {

}

return sb.toString();

}

private String getPostDataString(HashMap<String, String> params)

throws UnsupportedEncodingException {

StringBuilder result = new StringBuilder();

boolean first = true;

for (Map.Entry<String, String> entry : params.entrySet()) {

if (first)

first = false;

else

result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));

result.append("=");

result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

}

return result.toString();

}

}

Page 81:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

73

This class is the low level connector which pushes really requests to the server

through an HTTP connection: at this point only GET and POST requests were

implemented; but for future API extensions, PUT and DELETE ones should be

defined here.

GET request takes only one string parameter representing complete URL with

eventually encoded parameters and returns a string which direct comes from the

server (it should be void, as well).

POST request takes two parameters, one string representing the complete URL

with eventually encoded parameters and another one HashMap representing the key-

value pairs representing post payload parameters; it returns a string which direct

comes from the server (it should be void, as well).

5.2.3 REQUESTHANDLER.JAVA

//inner class to perform network request extending an AsyncTask

public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {

public static final int CODE_GET_REQUEST = 1024;

public static final int CODE_POST_REQUEST = 1025;

//the url where we need to send the request

private String url;

//the parameters

private HashMap<String, String> params;

//the request code to define whether it is a GET or POST

private int requestCode;

// Graph

@SuppressLint("StaticFieldLeak")

private ProgressBar progressBar;

@SuppressLint("StaticFieldLeak")

private Context context;

// Response

private JSONObject object;

private Callable useResponse;

//constructor to initialize values

@NonNull

public static PerformNetworkRequest Build() {

return new PerformNetworkRequest();

}

private PerformNetworkRequest() {

}

public PerformNetworkRequest setUrl(String url) {

this.url = url;

return this;

}

Page 82:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

74

public PerformNetworkRequest setParams(HashMap<String, String> params) {

this.params = params;

return this;

}

public PerformNetworkRequest setReqCode(int requestCode) {

this.requestCode = requestCode;

return this;

}

public PerformNetworkRequest setProgressBar(ProgressBar progressBar) {

this.progressBar = progressBar;

return this;

}

public PerformNetworkRequest setContext(Context context) {

this.context = context;

return this;

}

public PerformNetworkRequest setResponseAction(Callable action) {

this.useResponse = action;

return this;

}

//when the task started displaying a progressbar

@Override

protected void onPreExecute() {

super.onPreExecute();

if (progressBar != null) progressBar.setVisibility(View.VISIBLE);

}

//this method will give the response from the request

@Override

protected void onPostExecute(String s) {

super.onPostExecute(s);

if (progressBar != null) progressBar.setVisibility(View.GONE);

try {

this.object = new JSONObject(s);

this.useResponse.call();

} catch (JSONException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

}

}

//the network operation will be performed in background

@Override

protected String doInBackground(Void... voids) {

RequestHandler requestHandler = new RequestHandler();

if (requestCode == CODE_POST_REQUEST)

return requestHandler.sendPostRequest(url, params);

if (requestCode == CODE_GET_REQUEST)

return requestHandler.sendGetRequest(url);

return null;

}

// Read the response (if present)

public JSONObject getResponse() {

return this.object;

}

}

Page 83:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

75

This is the high level interface usable from the Activities of the application. It uses

previous discussed handler to communicate with the server, and build a programmer-

friendly interface. Firstly, it uses the usual Build Pattern to build an object for each

request; in addition to the URL, parameters and type of request (GET, POST)

declarations, it offers the possibility to drive a progress bar (percentage or spinner), in

order to easily popup to the user the concept of “waiting for the response”.

Starting from the design, the server response is a JSON string: so, this class

converts automatically the response string into JSON object, presenting it to the

invoker class instead of a string through the getResponse method.

Finally, since server requests are treated asynchronously, programmer can define a

Callable object (setting it in construction phase) to take an action as soon as the

response is available. For example, this is useful in case of data retrieval: as soon as

data have been totally retrieved and converted into JSON object, the Callable method

is invoked and data can be used inside it to be elaborated.

5.2.4 APPLICATION.JAVA

This class is the core of an Android application; it is unique and it contains general

initialization and finalization code, as well as common methods used by activities,

shared listeners and similar.

public class BeaconReferenceApplication extends Application

implements BootstrapNotifier {

// Application constants

private static final String TAG = "BeaconReferenceApp";

public static final String beaconUUID =

"000000aa-face-face-face-000000000000";

// Application attributes

private RegionBootstrap regionBootstrap;

private BackgroundPowerSaver backgroundPowerSaver;

// Beacon Layout Strings

/*public final static String ALTBEACON =

"m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25";

public final static String EDDYSTONE_TLM =

"x,s:0-1=feaa,m:2-2=20,d:3-3,d:4-5,d:6-7,d:8-11,d:12-15";

public final static String EDDYSTONE_UID =

"s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19";

public final static String EDDYSTONE_URL =

"s:0-1=feaa,m:2-2=10,p:3-3:-41,i:4-20v";*/

public final static String IBEACON =

"m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24";

Page 84:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

76

// Parameters exchanged between Activities

public final static String PARAM_USERCODE = "usercode";

public final static String PARAM_OBJECTID = "object_id";

public void onCreate() {

super.onCreate();

BeaconManager beaconManager =

org.altbeacon.beacon.BeaconManager

.getInstanceForApplication(this);

// initialization of the beacon library

BeaconManager.setRssiFilterImplClass(ArmaRssiFilter.class);

ArmaRssiFilter.setDEFAULT_ARMA_SPEED(0.1);

// setting scan periods for the beacon library

beaconManager.setForegroundScanPeriod(250L);

beaconManager.setForegroundBetweenScanPeriod(10L);

try {

beaconManager.updateScanPeriods();

} catch (RemoteException e) {

e.printStackTrace();

}

// setting beacon layout (it's used to recognize/parse beacon packets)

beaconManager.getBeaconParsers().clear();

beaconManager.getBeaconParsers().add(new BeaconParser()

.setBeaconLayout(IBEACON));

Log.d(TAG, "setting up background monitoring for beacons and power

saving");

// wake up the app when a beacon is seen

Region region = new Region("backgroundRegion",

null, null, null);

regionBootstrap = new RegionBootstrap(this, region);

// simply constructing this class and holding a reference to it in your

// custom Application class will automatically cause the BeaconLibrary

// to save battery whenever the application is not visible.

// This reduces bluetooth power usage by about 60%

backgroundPowerSaver = new BackgroundPowerSaver(this);

// If you wish to test beacon detection in the Android Emulator,

// you can use code like this:

// BeaconManager.setBeaconSimulator(new TimedBeaconSimulator() );

// ((TimedBeaconSimulator) BeaconManager.getBeaconSimulator())

// .createTimedSimulatedBeacons();

}

@Override

public void didEnterRegion(Region arg0) {/*...*/}

@Override

public void didExitRegion(Region region) {/*...*/}

@Override

public void didDetermineStateForRegion(int state, Region region) {/*...*/}

// shared method to show popup alerts in Android

public void popupMsg(Context context, String title, String msg,

DialogInterface.OnDismissListener listener) {

final AlertDialog.Builder builder = new AlertDialog.Builder(context);

builder.setTitle(title);

builder.setMessage(msg);

builder.setPositiveButton(android.R.string.ok, null);

builder.setOnDismissListener(listener);

builder.show();

}

Page 85:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

77

// shared method to show Push Notifications in Android

public void sendNotification(String title, String text) {

NotificationCompat.Builder builder =

new NotificationCompat.Builder(this)

.setContentTitle(title)

.setContentText(text)

.setSmallIcon(R.drawable.ic_launcher);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

stackBuilder.addNextIntent(new Intent(this, MainActivity.class));

PendingIntent resultPendingIntent =

stackBuilder.getPendingIntent(

0,

PendingIntent.FLAG_UPDATE_CURRENT

);

builder.setContentIntent(resultPendingIntent);

NotificationManager notificationManager =

(NotificationManager)

this.getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(1, builder.build());

}

}

Reporting the entire code of the application class implementation, it‟s possible to

see in the first part the declaration of static shared variables, usable among activities

too; then, the OnCreate method was overridden to initialize the beacon library, with

the possibility to have also the background monitoring (useful when the application is

running in background). At the end, two shared methods were declared in order to

send push notifications to Android OS and show popup alerts onto the screen; this

avoid the duplication of the same code among activities.

5.2.5 MAINACTIVITY.JAVA

This is the starting point of the application (as declared in the Manifest.xml file). In

fact, when the user start the app this activity is automatically shown first.

public class MainActivity extends Activity {

// References

private BeaconReferenceApplication app;

// Popup close actions

private DialogInterface.OnDismissListener terminateApp;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

app = (BeaconReferenceApplication) this.getApplicationContext();

Page 86:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

78

// Popup close actions

terminateApp = new DialogInterface.OnDismissListener() {

@Override

public void onDismiss(DialogInterface dialog) {

finish();

System.exit(0);

}

};

// Preconditions

verifyBluetooth();

verifyInternetConnection();

verifyLocationEnabled();

// Beacon init

Beacon.setDistanceCalculator(

new ModelSpecificDistanceCalculator(

getApplicationContext(), null, AndroidModel.forThisDevice()

)

);

/* Button events */

findViewById(R.id.config_btn).setOnClickListener(

new View.OnClickListener() {

@Override

public void onClick(View view) {

// Take action.

Intent myIntent = new Intent(MainActivity.this,

ConfigureActivity.class);

//myIntent.putExtra("key", value); //Optional parameters

MainActivity.this.startActivity(myIntent);

}

});

findViewById(R.id.start_btn).setOnClickListener(

new View.OnClickListener() {

@Override

public void onClick(View view) {

// Check User Code

EditText usercode = (EditText) findViewById(R.id.user_id);

if ( checkUserCode(usercode)) {

// Take action.

Intent myIntent = new Intent(MainActivity.this,

ExploringActivity.class);

myIntent.putExtra(BeaconReferenceApplication.PARAM_USERCODE,

getUserCode(usercode)); //Optional parameters

MainActivity.this.startActivity(myIntent);

}

else

app.popupMsg(MainActivity.this,

"UserCode requested!",

"You're required to insert your User Code to proceed",

null);

}

});

}

private void verifyBluetooth(){/*...*/}

private void verifyInternetConnection() {/*...*/}

private void verifyLocationEnabled() {/*...*/}

private boolean checkUserCode(EditText usercode) {/*...*/}

private String getUserCode(EditText usercode) {/*...*/}

}

Page 87:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

79

The scope of this activity is essentially to check device configuration for the

correct functioning of the library and recognize the user by its UserCode; it is passed

to the exploring activity in order to personalize the user experience.

5.2.6 CONFIGUREACTIVITY.JAVA

This activity is used to configure the distance calculation for the specific device. As

said before, each device can measure differently RSSI values for many reasons; this

activity provide a procedure (automatic) to configure the computation starting from a

known situation.

public class ConfigureActivity extends Activity implements BeaconConsumer {

// References

private BeaconReferenceApplication app;

// Beacon Library

private BeaconManager beaconManager =

BeaconManager.getInstanceForApplication(this);

// Beacon data

private AmbientBeaconList configBeacon;

private Map<ConfigBeacon, Integer> receivedConfigPkts;

private int receivedPackets;

private final int configurePackets = 20;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_configure);

app = (BeaconReferenceApplication) this.getApplicationContext();

// load config data (from server online) - now stub

configBeacon = AmbientBeaconList.Build();

configBeacon.getList().add( ConfigBeacon.Build()

.setTxPower(BeaconMeasurer.LARGE_HALL)

.setBeacon( new Beacon.Builder()

.setId1("00000000-0000-0000-0000-000000000000")

.setId2(String.valueOf(BeaconMeasurer.CONFIG_BEACON))

.setId3("1").build()

)

);

configBeacon.getList().add( ConfigBeacon.Build()

.setTxPower(BeaconMeasurer.LARGE_HALL)

.setBeacon( new Beacon.Builder()

.setId1("00000000-0000-0000-0000-000000000000")

.setId2(String.valueOf(BeaconMeasurer.CONFIG_BEACON))

.setId3("2").build()

)

);

// configuration

beaconManager.bind(this);

receivedPackets = 0;

receivedConfigPkts = new HashMap<>();

Page 88:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

80

for (AmbientBeacon aConfigBeacon : configBeacon.getList()) {

receivedConfigPkts.put((ConfigBeacon) aConfigBeacon, 0);

}

((ProgressBar) findViewById(R.id.progressBar_1)).setMax(configurePackets);

}

@Override

protected void onDestroy() {

super.onDestroy();

beaconManager.unbind(this);

}

@Override

public void onResume() { super.onResume(); }

@Override

public void onPause() { super.onPause(); }

@Override

public void onBeaconServiceConnect() {

beaconManager.addRangeNotifier(new RangeNotifier() {

@Override

public void didRangeBeaconsInRegion(Collection<Beacon> beacons,

Region region) {

// If in configuration phase

if (receivedPackets < configurePackets) {

if (beacons.size() > 0) {

for (Beacon b : beacons) {

ConfigBeacon cbt =

(ConfigBeacon) configBeacon.findAmbientBeacon(b);

try {

BeaconMeasurer.configurePwrDistRSSI(

cbt.getTxPower(),

BeaconMeasurer.Dist1,

b.getRssi()

);

receivedConfigPkts.put(cbt,

receivedConfigPkts.get(cbt) + 1);

}

catch (NullPointerException ignored) {}

}

if (receivedConfigPkts.values().size() > 0)

receivedPackets =

getMinReceivedPkts(receivedConfigPkts.values());

((ProgressBar) findViewById(R.id.progressBar_1))

.setProgress(receivedPackets);

app.sendNotification("Configuration",

"Progress: " + (100 * receivedPackets / configurePackets)

+ "%");

}

}

// If terminated

else {

beaconManager.removeRangeNotifier(this);

ConfigureActivity.this.finish();

}

}

});

Page 89:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

81

try {

beaconManager.startRangingBeaconsInRegion(

new Region("configureRegion",

// Identifier.fromUuid(UUID.fromString(

// BeaconReferenceApplication.beaconUUID )),

null, null, null));

} catch (RemoteException ignored) {}

}

private int getMinReceivedPkts(Collection<Integer> list) {/*...*/}

}

This activity starts creating a beacon manager (an object to read beacons packets)

and starts a listener which detects all configuration beacons present. Then, it uses

received packets to configure the BeaconMesurer power/distance table, waiting to

receive a certain number of packets for each beacon. So, knowing distance from

beacons apriori and collecting sufficient data, it can calculate the reliable RSSI

measure. During the process a percentage progress bar informs the user about the

overall state. At the end of the process, user is automatically redirected to the main

activity.

5.2.7 EXPLORINGACTIVITY.JAVA

This is one of the most important activities of the application because it is

displayed the longest. It informs user about actual room and interesting present

objects, as well as the nearest one. Apart from the usual initialization of the beacon

library, here below is reported firstly the core of beacon interaction, secondly the database

data retrieval and finally the step detector listener.

@Override

public void onBeaconServiceConnect() {

beaconManager.addRangeNotifier(new RangeNotifier() {

@Override

public void didRangeBeaconsInRegion(Collection<Beacon> beacons,

Region region) {

// Detection and Reaction

if ((beacons.size() > 0) && allDataLoaded) {

// divide beacons into Rooms and Objects, based on the Maior ID

for (Beacon beacon : beacons) {

// Set right updateFactor

float updateFactor;

if (userWaiting) updateFactor = BeaconMeasurer.SLOW_UPDATE;

else updateFactor = BeaconMeasurer.FAST_UPDATE;

Page 90:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

82

// Rooms

if (BeaconMeasurer.checkType(beacon, BeaconMeasurer.ROOM_BEACON))

rooms.addOrUpdateList(beacon,

RoomBeacon.Build()).setUpdateFactor(updateFactor);

// Objects

else if (BeaconMeasurer.checkType(beacon,

BeaconMeasurer.OBJECT_BEACON))

objects.addOrUpdateList(beacon,

ObjectBeacon.Build()).setUpdateFactor(updateFactor);

}

// clear object history if I see nothing now on

if (objects.areInvisible()) clearObjectHistory();

else cancClearObjectHistory();

// catch the nearest room, if present

BeaconMeasurer nearestRoom = rooms.getNearest();

if (nearestRoom != null) {

// information about room

cancClearRoomHistory();

updateRoomInfo(nearestRoom);

// fill the list with linked objects

List<ObjectBeacon> objectBeacons =

datalinks.getRoomObjects((RoomBeacon) nearestRoom.getBeacon());

if (objectBeacons != null) {

updateObjectsInfo(objects, objectBeacons);

// catch the nearest object (if exist)

try {

nearestObject = objects.getNearest().getBeaconId().toInt();

}

catch (NullPointerException e) {

nearestObject = BeaconMeasurer.UNKNOWN_BEACON;

}

}

else

nearestObject = BeaconMeasurer.UNKNOWN_BEACON;

}

//else {

//// You're not in a room, there is no information...

//

//}

if (prevNearestRoom == null) { prevNearestRoom = nearestRoom; }

else {

if (!prevNearestRoom.equals(nearestRoom)) {

// empty objects cache

objects.emptyList();

prevNearestRoom = nearestRoom;

}

}

}

else {

// decide what to do if no beacons found

clearRoomHistory();

}

}

});

Page 91:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

83

try {

beaconManager.startRangingBeaconsInRegion( new Region("exploringRegion",

// Identifier.fromUuid(UUID

//.fromString( BeaconReferenceApplication.beaconUUID )),

null,null, null));

} catch (RemoteException ignored) { }

}

When a set of beacons are detected (and all data has already been retrieved from

the database) they are divided into two categories: Rooms and Objects. The flow is

the following: the received beacon is transformed into an Environment specific

beacon (RoomBeacon or ObjectBeacon). Then, it is added or updated into the

relative BeaconMesurerList (rooms and objects respectively). This way the previous

filtered RSSI value is updated with the new measure. Moreover, based on the fact that

user is moving or not, the updateFactor tells how the new measure impacts in the

computer filtered measure.

Once lists are updated, nearest room beacon is identified and relative information

is displayed. From this, using information retrieved from database, it is extracted the

list of linked identified objects (which contains all the objects present in the specific

room that has been detected till now) and displayed; from this list the nearest object is

identified.

Timers combined with a beacon visibility threshold assures the deletion of old or

inconsistent displayed information.

// Load (user) data from server - Database connection

dbRoomLoaded = 0;

allDataLoaded = false;

objectListAction = new Callable() {

@Nullable

@Override

public Object call() throws Exception {

dbRoomLoaded++;

// and build the data structure when all is downloaded

if (dbRoomList.length() == dbRoomLoaded) {

for( Map.Entry<Integer, JSONArray> el : dbRoomObjects.entrySet() ) {

Integer key = el.getKey();

JSONArray value = el.getValue();

List<ObjectBeacon> ol = new ArrayList<>();

for( JSONObject vi: (List<JSONObject>) jsonArray2List(value)) {

ol.add((ObjectBeacon) ObjectBeacon.Build().setBeacon(

new Beacon.Builder().setId1("00000000-0000-0000-0000-000000000000")

.setId2(String.valueOf(BeaconMeasurer.OBJECT_BEACON))

.setId3(vi.getString(Api.REPONSE_MINOR))

.build()

)

);

dbLoadObjectShortInfo(

vi.getInt(Api.REPONSE_MINOR),

Page 92:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

84

usercode, null

);

}

datalinks.setRoomObjects((RoomBeacon) RoomBeacon.Build().setBeacon(

new Beacon.Builder().setId1("00000000-0000-0000-0000-000000000000")

.setId2(String.valueOf(BeaconMeasurer.ROOM_BEACON))

.setId3(String.valueOf(key))

.build()

), ol

);

dbLoadRoomShortInfo(key, usercode, null);

}

allDataLoaded = true;

}

return null;

}

};

roomListAction = new Callable() {

@Nullable

@Override

public Object call() throws Exception {

// For each room, retrieve the object list

for (int i = 0; i < dbRoomList.length(); i++) {

dbLoadInterestingObjectList(dbRoomList.getJSONObject(i)

.getInt(Api.REPONSE_MINOR), usercode, objectListAction);

}

return null;

}

};

testAction = new Callable() {

@Nullable

@Override

public Object call() throws Exception {

// Create data structure only if no errors

datalinks = Datalinks.Build();

dbRoomObjects = new HashMap<>();

// retrieve room list

dbLoadRoomList(roomListAction);

return null;

}

};

dbConnectionTest(testAction);

The above code implements the data retrieval from the database; it uses the

previous discussed classes to handle REST architecture. As it is possible to see,

subsequent requests require data from the preceding, so queries are organized as

nested calls. For a matter of style, Callables are declared inside the initialization

method in the reverse order with respect to calls (to be visible to the precedent call).

At the beginning of the chain there is a test on the connection, just to be confident

that the server is ready. At the end of the query chain the Room-Object data structure

is completely replicated locally in the datalink variable as an HashMap, with

RoomBeacons as keys and a list per key of ObjectBeacons as values.

// Sensors inizialization

private void setupStepDetector() {

sManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

Page 93:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

85

// Step Detector

stepDetectorListener = new SensorEventListener() {

@Override

public void onSensorChanged(SensorEvent event) {

// Time is in nanoseconds, convert to millis

//timestamp = event.timestamp / 1000000;

lastStepMade = System.currentTimeMillis();

/* actions every step taken */

app.sendNotification("I'm silent", "I stay silent while you're walking");

}

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

};

sManager.registerListener(

stepDetectorListener,

sManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),

SensorManager.SENSOR_DELAY_UI

);

}

This piece of code is responsible to setup the listener for the stepDetector sensor.

It is used for automatic displaying details and audio playing. In fact, when a step is

sensed the application update the timestamp variable which contains the time of last

detected step.

// Step Detector setup and moving checker

setupStepDetector();

movingCheck = new Runnable() {

@Override

public void run() {

if (( System.currentTimeMillis() - lastStepMade) >= movingInterval) {

if (!userWaiting) {

if (nearestObject != BeaconMeasurer.UNKNOWN_BEACON) {

// Put here actions when user stops

Intent myIntent = new Intent(ExploringActivity.this,

ObjectDetailsActivity.class);

myIntent.putExtra(BeaconReferenceApplication.PARAM_OBJECTID,

nearestObject); //Optional parameters

ExploringActivity.this.startActivity(myIntent);

// notify

app.sendNotification("Hey!",

"You're now waiting, I can talk");

}

else {

// notify

app.sendNotification("Hey!",

"You're now waiting, but I don'r know this object");

}

}

userWaiting = true;

}

else {

// Put here actions when user's walking

// notify

userWaiting = false;

}

stepDetectorWatchdog();

}

Page 94:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

86

};

stepDetectorWatchdog();

In the initialization phase it is setup a watchdog timer that ticks at a specific

interval and check how long passed from the last step; in case this exceeds a defined

threshold, the application reveals that user stopped and can run

ObjectDetailsActivity.

5.2.8 OBJECTDETAILSACTIVITY

This is another important activity which gives the user all details about an object of

interest. It is only a data display mask, and contains also an audio player which plays

in streaming the object associated audio file. It contains also its step detector listener

used to close itself and return to the ExploringActivity as soon as the user starts

walking again. Code used in this activity is just explained in the immediate previous

section; the only additional code is the media player.

// Multimedia stuff

private void playAudioStreaming(final String hostingServer, final String audioURL)

{

try {

mediaPlayer.setDataSource(hostingServer + audioURL);

} catch (IOException e) {

e.printStackTrace();

}

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){

@Override

public void onPrepared(MediaPlayer mp)

{

mp.start();

}

});

//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

mediaPlayer.prepareAsync();

}

It is used the default Android media player object, which lets use remote URL

audio streaming; in the initialization phase the media player object was created and let

it play the audio during the information displaying.

Page 95:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

87

5.3 WEB APPLICATION INTERFACES

Starting from the design decisions, two Web Interfaces have been developed: one

management-side and the other user-side. The two interfaces have different priorities,

but both were developed in HTML5 and CSS3 technology. Again, both interfaces

make use of JQuery library to communicate with server backend in asynchronous way

limiting page reload.

Server side there are two different APIs, one specific to the Mobile Application

and one specific to the Web Interfaces. APIs exposes a CRUD interface implemented

in PHP language without any framework (but they will be discussed later).

5.3.1 MANAGEMENT WEB INTERFACE

Here above it‟s shown an example (raw HTML5 rendering) of the Web

Application onto the Object‟s Data tab. As it is possible to see, it is perfectly

Page 96:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

88

conforming to all positioning described in the sketch; it follows a “liquid design style”

which adapts itself for the majority of screen sizes. As said before, particular cases

(very small screens) will be tested and fixed in the near future. With the usage of

JQuery Ajax requests to retrieve/send data from/to server, there is a clean separation

of concerns among presentation and logics. It is a one-page application, that means

only one HTML page is sufficient to support all needed functionalities. Even if is not

recommended, but for a matter of practicality, CSS positioning or sizing about

elements specific for this page was done into the <style> tag of the page (without any

external file). Instead, external link to CSS file is a must for the graphical theme of the

applications, because it will be the same for both applications; using an external

common style file, it‟s ensured coherence among graphical styles, better

maintainability and evolution of the style itself and it is avoided the duplication of

code.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="generator" content="AlterVista - Editor HTML"/>

<title>Database Management Interface</title>

<link rel="stylesheet" type="text/css" href="common.css"/>

<style>

img {

min-height: 180px;

min-width: 330px;

width: 350px;

display: inline-block;

border: 1px solid black;

}

select {

min-width: 8em;

}

tr.fields td {

vertical-align: middle;

}

</style>

<script type="text/javascript" src="/jquery-3.2.1.min.js"></script>

As shown in the above code, the page is declared as DOCTYPE html (which

identify the HTML5 declaration); then there are some meta tags to add properties

used in general by internet bots and browsers; the <link> tag specify the common

stylesheet which describe the graphical theme used by both applications. The

incorporated <style> tag define (as said previously) some adjustments specific to the

same page: this choice derive from the fact that it‟s easier for programmers to correct

or change some positioning, bordering or similar of some specific element of the page

Page 97:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

89

without affecting the others. At the end of this extract, there is the import of the

JQuery library used to make async Ajax requests to the server.

function apriObjDet() {

$.get( "webapi.php", { sender: "dbman", action: "object_details",

maior: $('#object_list').find('option:selected').attr('maior'),

minor: $('#object_list').find('option:selected').attr('value')

})

.done(function(data) {

data = JSON.parse(data);

if ((data.object != undefined) && (data.object != null)) {

// Room reference

$("#room_ref").find('option:selected').removeAttr("selected");

$('#room_ref option[value='

+data.object.room_minor+'][maior='+data.object.room_maior+']')[0]

.selected = "true";

// Object data

$('#obj_maior').val(data.object.obj_maior);

$('#obj_minor').val(data.object.obj_minor);

$('#obj_title').val(data.object.obj_title.replace(/&apos;/g, "'"));

$('#obj_artist').val(data.object.obj_artist.replace(/&apos;/g, "'"));

$('#obj_value').val(data.object.obj_value);

$('#obj_img').attr('src', data.object.img);

$('#obj_audio').attr('src', data.object.audiofile);

$('#obj_note').val(data.object.note.replace(/&apos;/g, "'"));

}

})

.fail(function() {

alert("Error loading data from server...");

});

}

The above extract is an example of JQuery Ajax request used to retrieve object

details from server. As it is possible to see, it is an async request that makes a GET

HTTP query with parameters, waiting for the response and invoking the anonymous

function in the “.done” method as soon as data are available, filling elements with

corresponding values. In case the request fails, an alert is displayed and fields will not

be filled.

</body>

<script type="text/javascript">

/** Init **/

resetAllForms();

fillRoomMaiors();

fillObjectMaiors();

listAllObjects('object_list');

listAllRooms('room_list');

listAllRooms('room_ref');

</script>

</html>

Because this is considered a Rich Web Application (remind: it‟s said Rich Web

Application, a web application which makes use of Ajax queries instead of classical

Page 98:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

90

techniques to load/push data from/to server), when this page is loaded for the first

time it is empty; at the end of elements loading some Ajax calls should be made

automatically to load first data. Since elements should exist when loading data, an

inline <script> tag is put at the end of the page containing only data initialization calls

(and optionally graphical effects initialization).

5.3.2 USER WEB INTERFACE

The image above show (raw HTML5 implementation) of the User Web Interface.

As it is possible to see, it is perfectly conforming to all positioning described in the

sketch; it follows a “liquid design style” which adapts itself for the majority of screen

sizes. Differently from the previous, this application should adapt well also to small

screen sizes (with CSS responsive design) which makes it usable also on mobile

devices. In this case, the responsive design is very important to let usage confortable

to each user need. Technically, it follows the same rules as the other application, so

it‟s not discussed another time.

Page 99:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

91

5.4 SERVER CRUD APIS

In previous chapters it was described the client-side of the system. In this section,

instead, it‟s reported the implementation server-side of the system “engine”, meaning

the APIs which provide data to the rest of the system.

First of all, server is organized into a database and a presentation layer which

realized CRUD APIs. This kind of interface focuses the attention onto data and its

format: for this reason it could be possible to change the whole server technology

without change anything else just respecting data format (remind: JSON encoding

was the data format choice).

For a matter of simplicity, PHP was chosen as server programming technology,

interfacing with a MySQL database. To scale better the system and have a separation

of logics, two different APIs were built: one for the Mobile Application and the other

for the Web Interfaces.

5.4.1 MOBILE APPLICATION API

<?php

class ShortInfo {

public $title = "";

public $artist = "";

public $value = "";

public $note = "";

}

class Oggetto {

public $maior = 0;

public $minor = 0;

}

class Risposta {

public $status = "";

public $msg = "";

}

// Costanti

$_statusok = true;

$_statusfail = false;

At the beginning of PHP script there are definitions of such classes of objects used

to build the JSON response and a set of constants used along the script itself.

Page 100:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

92

// Importa il modulo del database

require reqRootDir() . "database.php";

//an array to display response

$response = new Risposta();

$response->status = $_statusfail;

$dbCon = new DBase();

$con = $dbCon->apri();

Then it is imported an external little script which implements an object-driven easy

interface to manage connection to the database and make queries. It is also initialized

the response object and opened the database connection.

if(isset($_GET['apicall'])){

switch($_GET['apicall']){

case "test":

$response->status = $_statusok;

$response->msg = "Test success";

break;

case "get_rooms":

$res = $dbCon->query($con,

"SELECT * FROM app_mappa GROUP BY room_maior, room_minor");

$response->roomlist = array();

while ($riga = mysql_fetch_array($res)) {

$el = new Oggetto();

$el->maior = $riga['room_maior'];

$el->minor = $riga['room_minor'];

$response->roomlist[] = $el;

}

$response->status = $_statusok;

$response->msg = "Rooms got";

break;

It follows the implementation of the CRUD APIs. For example, it is shown the

first two functions, a test function to check the connectivity with the server and the

query to retrieve the list of rooms stored into the database.

$dbCon->chiudi($con);

echo json_encode($response);

?>

The script ends with the close of database connection and the encoding of the

response object into JSON format before returning it to the caller.

Page 101:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

93

5.4.2 WEB INTERFACES API

<?php

class Risposta {

public $status = "";

public $msg = "";

}

class Oggetto {

public $maior = 0;

public $minor = 0;

}

// Costanti

$_statusfail = false;

$_statusok = true;

$_beaconobject = 18;

$_beaconroom = 16;

// Funzioni generali

function unnullString($s) {

return ($s!=null?$s:'');

}

Web Interfaces API script follows the same schema; in fact, at the beginning there

are definitions of such classes of objects used into the JSON response, a set of

constants used along the script itself and utility functions definitions.

// Importa il modulo del database

require reqRootDir() . "database.php";

// Crud Api

$risposta = new Risposta();

$risposta->status = $_statusfail;

$dbCon = new DBase();

$con = $dbCon->apri();

$action = addslashes($_REQUEST['action']);

$sender = addslashes($_REQUEST['sender']);

It follows the import of the external script for object-oriented database connection

and query, the initialization of the response object, the opening of database

connection and the securing of sender/action parameters.

Page 102:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

94

switch($sender) {

case "dbman":

switch($action) {

case "list_rooms":

$res = $dbCon->query($con,

"SELECT * FROM app_info WHERE maior='$_REQUEST[maior]'");

$risposta->objlist = array();

while ($riga = mysql_fetch_array($res)) {

$el = new Oggetto();

$el->room_maior = $riga['maior'];

$el->room_minor = $riga['minor'];

$el->room_title = unnullString($riga['titolo']);

$risposta->objlist[] = $el;

}

$risposta->status = $_statusok;

$risposta->msg = "Lista stanze ottenuta con successo";

break;

Since the system consist of different web interfaces which query server, it is better

to categorize functions with respect to their invoker. For this reason, two nested

“switches” access the right function firstly by selecting the sender (in this case

between “dbman” and “user”) and then selecting the real action. It is a method to

manage the overriding of the same function which can have different behaviors

whether it is called by an interface or another one. There are many ways to do that,

but this particular choice organizes functions in sets belonging to the specific caller.

break;

default:

$risposta->msg = "API non supportata";

}

break;

default:

$risposta->msg = "CLIENT non autorizzato";

}

$dbCon->chiudi($con);

echo json_encode($risposta);

?>

Again, the script ends with the closing of database connection and the conversion

of the response object into JSON format. Notice that, the “default” case in switches

assures control over not supported functions.

Page 103:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

95

5.5 DATABASE TABLES

The database designed previously was realized through a relational-database

implementation, built upon tables with multiple fields.

At a first glance, it can be noted that real tables are less than designed entities-

relations: this is explained with the fact that not every designed element corresponds

to a real table into the database.

Firstly, there is only one table for both RoomBeacon and ObjectBeacon entities;

this because they have common fields and are basically based onto the same

hardware: this can simplify a change of role of one beacon, or some possible

advanced usage in future developments. Single ID designed field was expanded into

two basic fields to represent separately Major and Minor IDs: this decision makes

possible to realize much more precise and optimized queries when searching for

some beacon data. As a matter of fact, merging RoomBeacon and ObjectBeacon

leads to have entries with possible NULL values into unused fields.

Secondly, in this first prototype implementation User entity has not been

implemented (which should consist in a separate table with personal user information,

i.e. profiling); this let us collapse the user id directly into the “Interests” designed

relation, which has been converted into a real DB table. So, for each user this table

Page 104:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM IMPLEMENTATION

96

contains a set of table entries consisting in foreign keys referring to “interesting”

objects and a string identifying the user.

Finally, the other relation was built as a table which has as many entries as the

number of objects, each of which is composed by two foreign keys referring

respectively the object and the containing room and a unique id field.

The chosen diagram syntax express also the expected cardinality among Primary

Keys and Foreign Keys; as it is possible to see, in the mapping table we have a one-

to-one association between objects references and objects‟ details; but a many-to-one

association between rooms references and rooms‟ details. From this it is possible to

conclude that mapping table has as many entries as the number of ObjectBeacons,

and that in each room can be present one or more ObjectBeacons.

For the same reason, it is possible to conclude that in the Interest table it is not

guaranteed that are present all of available ObjectBeacons (i.e. some object could be

considered not interesting for every user of the system). In another way, this table can

be also used to create statistics about average users interests over objects.

Page 105:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

97

6 SYSTEM TESTING

Testing phase is articulated into various steps, each used to determine system

capabilities under different conditions. It requires a discrete amount of time, different

locations and situations, and various users and devices.

Testing proceeded in steps.

STEP 0 – UNIT TESTS

The zero-step is to test the correctness of the implementation, testing every unit of

code (Unit Test). This was done incrementally during the implementation, correcting

eventually functioning bugs which was evident.

STEP 1 – MOBILE APPLICATION CRASH AVOIDING

After testing each function, the entire application was built and launched, in order

to check anomalies, unexpected crashes and graphical errors (Android OS follows

some rules in order to accept only “safe-code”; it could happen that a correct

compiled code can crash the application for some permission denied).

STEP 2 – CRUD APIS AND DATABASE TEST

First of all, database SQL queries were checked to ensure correct data retrieval,

storing and updating. This was done through MySQL provided interface.

Secondly, through manual HTTP interface, server APIs were tested to check

mainly that PHP scripts run properly; then this check involves correctness about

JSON data responses, success of SQL queries made by database connector and issues

Page 106:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

SYSTEM TESTING

98

related to some string symbol that require particular attention (i.e. single and double

apostrophe, etc…).

STEP 3 – WEB INTERFACE TEST

At this step web applications were checked; firstly, elements rendering and

positioning were checked, paying attention to images which can be stretched, or their

dimensions whether out of control can change significatively all elements positioning.

Then, all JQuery Ajax calls were tested to be assured that the interfaces work

properly, transmitting and receiving data correctly.

STEP 4 – SYSTEM TESTING IN A CONTROLLED ENVIRONMENT

This is the first real test of the system even though it is conducted in a limited and

controlled environment. That means this test lets system work in a such ideal world

when interferences and unpredictable errors are reduced to the minimum.

As testing area a couple of void rooms were chosen, with few furniture, few

obstacles around and only a Wi-Fi signal to be used as internet data connection,

making noise in the area. With respect to previous implementation, it can be reported

an augmented precision in beacon localization, which now stands apart for a

minimum of one meter.

Beacons‟ configuration follows rules defined as above, setting properly

transmission power and timing according to expected user behavior (speed, crowd,

etc…).

STEP 5 – SYSTEM TESTING IN A REAL ENVIRONMENT

In the near future the system will be tested in a real environment to check how it is

resilient to known issues given by obstacles, crowd, electromagnetic noise and

unpredictable variety of devices.

Page 107:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

99

CONCLUSIONS

In this thesis it has been analyzed previous conducted work in building an Indoor

Positioning System using BLE technology, focusing the attention on all evinced

problems of the first implementation. For this reason, it has been needed to study in a

deeper way the problem, as well as hardware chosen and its capabilities; moreover, it

was necessary to conduct a mathematical study to define rules over devices

configuration. Finally through some testing sessions it was investigated the intrinsic

precision of the chosen measurement methodology. The critical part of the whole

work was the mathematical study which successfully defined some rules to correctly

configure beacons and a smart filter over measurements which stabilizes measures

making them close to the real value.

Terminated this first phase, conscious of all limits, it was designed a system that

could have been matching with requirements, organizing it in a modular way, dividing

the whole system into subsystems, and identifying components for each subsystem.

As soon as the first sketch of the system was completed, it started the

implementation phase, which followed an incremental process: starting from the

interaction with beacons, continuing with final user interface(s) and lasting onto

backend logics and database.

With first working prototype started also the testing phase, which is used both to

correct bugs and to finish graphical interfaces and low priority features.

It is possible to conclude that BLE beacons have lots advantages mainly in low

costs and versatility, but it is not the right technology for some kind of very noisy

environments and/or when it is required a very high precision (under one meter). For

such critical situations it is strongly recommended to combine Beacon technology

with something else; elsewhere, this proved to be a good technology.

Page 108:  · 2020. 9. 13. · i ACKNOWLEDGEMENTS Firstly, I want to thank my teacher and supervisor Henry Muccini, who have given me the possibility to explore this emerging research field

100

BIBLIOGRAPHY

[1] Paltera F., “Sviluppo di un Indoor Positioning System basato su BLE

beacons”, Università de L‟Aquila, 2017

[2] Wikipedia, “Indoor Positioning System”, last edited 2018

[3] Faragher R., “Understanding the Basis of the Kalman Filter Via a Simple

and Intuitive Derivation”, IEEE Signal Processing Magazine, 2012

[4] Wikipedia, “Bluetooth Low Energy”, last edited 2018

[5] Thaljaoui A., Val T., Nasri N., Brulin D., “BLE Localization using RSSI

Measurements and iRingLA”, 2015

[6] Navarro E., Peuker B., Quan M., “Wi-Fi Localization Using RSSI

Fingerprinting”, 2010

[7] “How much time do americans spend indoors?”, wiseGeek, last edited

2018

[8] Roberts T., “We spend 90% of our time indoors. Says who?”,

BuildingGreen, 2016

[9] “Global Indoor Positioning and Indoor Navigation (IPIN)”, 2017