What Is Context Aware Computing

Print   

02 Nov 2017

Disclaimer:
This essay has been written and submitted by students and is not an example of our work. Please click this link to view samples of our professional work witten by our professional essay writers. Any opinions, findings, conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of EssayCompany.

Many people use some kind of reminder function on their mobile devices to remind them of events or meetings that they have to attend. Sometimes these meetings are not always in the same location, and therefore we have to travel to the location of the meeting. Because of this we need the foresight, that when entering the reminder information to allow the travel time from where we will be to the location we need to be. The problem with this is; what if we did not know that we would be in another location, different to that of the location of our meeting? The main aim of this research is to come up with a solution for a reminder application that uses context aware computing which will allow us to enter simply the details of or meeting and the application will notify us in time to allow travel to the location of our meeting.

Acknowledgements

I would like to acknowledge the help and support that I have received throughout my project and throughout final year from:

My project supervisor Mr Derek Woods, for all his guidance and support with helping to steer me in the correct direction.

My partner, for his understanding and support during this stressful time.

My friends and fellow students Amanda and Declan who have helped to keep me focused.

Finally my parents who have given guidance and support throughout the entire project.

Declaration

I declare that this is all my own work and does not contain unreferenced material copied from any other source. I have read the University’s policy on plagiarism and understand the definition of plagiarism. If it is shown that material has been plagiarised, or I have otherwise attempted to obtain an unfair advantage for myself or others, I understand that I may face sanctions in accordance with the policies and procedures of the University. A mark of zero may be awarded and the reason for that mark will be recorded on my file.

List of Figures

List of Tables

Table of Contents

Introduction

When looking at context aware computing, we have to look at the context in which the user is in, i.e. the location of the user, resources nearby, who the user is with, etc… It would be nice if when we come back from lunch, we were to sit down at our computer and find that we have been automatically logged in, or after leaving work, we get into a car where the mirrors, steering wheel height and seat height are all automatically adjusted for us. It is in this area that I am proposing to focus my research, in particular context aware computing on a smart phone.

If you take the context that you have a meeting to attend in a certain location and you require a reminder regarding the meeting, the problem then is: what if you are in another location and need to travel to the location of your meeting. How do you ensure that you get prompted with enough time allowed for you to travel?

Rationale

When looking at location aware applications that already exist, most work on the basis that you input the details of an event, meeting, etc… that you wish to be reminded of, plus the location of the reminder, then the application would monitor your location, and when you would get near to the location of the reminder the application would notify you.

If you take a reminder application and make it context aware, then it is possible that it could then solve this problem, by monitoring your location then based on the context; the application will prompt you with a reminder. Thus giving enough time to allow you to travel to the location of the event, and arrive before the date and time of that event.

Overall objective

My overall objectives of this project are:

To design and create a context aware mobile application that will remind the user of a meeting or appointment with enough time to travel to the location of that meeting.

To research what the term ‘Context aware computing’.

To look at how the shortest path can be calculated between two paths.

Methodology

Research has already been carried out into context aware computing, and has shown what the term context aware actually means. There are also location aware mobile applications that have already been developed that user are currently using on various mobile devices.

Nevertheless this project aims to merge together both the location aware reminder application and context aware computing to research how an application like this can be developed. Research will have to be carried out into being able to identify the length of time required to travel from one location to another and presenting this to the user. Also along with this how the context can possibly change while travelling e.g. diversions etc…

There will be a need for the use of both hardware and software for this project which will include the use of; visual studio using the windows 7 software development kit, and using a Windows 7 mobile device to testing purposes.

Literature review

What is Context aware computing?

Context aware computing first appeared in 1994 and has been of great interest since, but what is context aware computing? The first part of this is the term context. The context is a collection of things that surround the user:

The hardware that the user is working with.

The software that the user is using.

The user customisation of both the hardware and the software.

The location of the user.

The situation that the user is currently in e.g. the people, noise levels, etc…

The resources available at the time.

The dynamics of the above context can change from place to place and therefore this is one of the major aspects of context aware computing. For computing to be truly context aware, the system that the user is using needs to be able to adapt to all of the above contextual elements [1].

The interest in this area was fuelled by the introduction of mobile computing and the developments that have been made in pervasive / ubiquitous computing [2]. As computing is no longer necessarily centralised to a local machine, and with Service-oriented computing becoming very popular since 2005 [3], this means that users will be "computing on the go".

To give an example of how context aware computing has become very important to mobile computing; if you take a user who has a tablet device, the user is at work, which has several wireless networks, which span across different buildings. The user is connected to one network and needs to print a document from an application, so the application needs to be able to work with the resources available on that network i.e. the nearest available printer. Then the user moves to another building and connects to another network, the application needs to be able to adapt to the new context and be able to work with the resources on the new network like discovering the nearest available printer again [2].

The context aware cycle

Context aware computing is seen to happen in a cycle which has three steps [4]. As shown in Figure Context Aware Cycle below these three steps are:

Discovery

Selection

Use

Figure Context Aware Cycle

Discovery: this happens when the computing context changes, the system must find out about its new context e.g. its new location, what resources are available within this new context, what people are nearby, etc… So in terms of the example above, when the user moves to the new building, the system must discover what resources are now available e.g. printers.

Selection: the system should be able to select resources based on the current context that the user is in. So relating to our example again, the system should be able to select the nearest printer based on the new location of the user.

Use: employ the selected resource. So based on the new location of the user, the selected resource (in this case a printer), the system can now employ the use of this.

Information types

For a system to be context aware it needs information about the context that it is currently in. As stated in Shilit 1995[4] the types if information can be categorised as shown in Table Summary of information types (Shilit 1995).

Category

Examples

Physical Objectives

People, computers, displays

Conditions & State

Available, in-use

Spatial Relations

With, near

Phenomena

Dimly lit, noisy

Ways & Means

Instructions , network address

Customisations

Hold calls

Table Summary of information types (Shilit 1995)

Again to use our example, when the user moves to the new building and the new network, apart from the system being able to detect printers on the network it will also require information to decide which printer is the nearest but that is also available.

Types of context aware computing

There are two different types of context aware computing systems that have been defined; active or passive [1]. The difference between these are that in an active context aware system, when the system retrieves data it will actively perform some task with this data unlike in a passive system where the system will retrieve the data and then store it until the user requires it or the user needs to perform a task. The mobile application that I am designing would be classed as active, as the application would automatically update, adjust, configure, or take action based upon the context it was in.

Location aware

One of the major elements of context aware computing is location, this can be critical to most context aware systems. The main obvious choice of location tracking is by using GPS, for some systems though this is not an option as the GPS signal is not strong enough to penetrate buildings, and therefore other forms of location tracking is required[1].

Shortest path analysis

For the application that I am developing there is the requirement to track the user’s location, for this I plan to use the GPS sensor on the phone. Apart from the location of the user the location of the appointment is also a factor that has to be included in the context surrounding the user. In order for the user to be alerted with enough time to travel to the location of the appointment there are certain factors that have to be worked out:

The distance from the current location of the user and the location of the appointment.

The travel time based on the shortest path to the location of the appointment.

There are several ways in which the shortest path can be calculated, but each of these ways is fairly similar with subtle differences. Two algorithms that are well known for working out the shortest path are:

A * (star) search algorithm

Dijkstra's algorithm

A* Search Algorithm

The A star algorithm is used in Satellite Navigation systems, it is known as "Street Aware" as it uses dynamic street map information. It is also used in games and mapping robotic movement.

This algorithm deals with moving round obstacles and finding the shortest path while doing so. You can see an example of this in Figure A - Star Algorithm where the grey squares are an obstacle, but the algorithm finds the shortest path around it.

Fig.1 The ring is the object to be moved to the target x signed node. The grayed nodes are obstacle (wall)

Figure A - Star Algorithm

You can see the pseudo code for the A-Star algorithm in Error: Reference source not found [5]

Figure Pseudo code of A-STAR algorithm [5]

You can see the contents of each node in Error: Reference source not found below

Fig2 The nodes in the neighborhood with calculated total cost

Figure A-Star Node

Dijkstra’s Algorithm

Dijkstra’s algorithm was created by a Dutch computer scientist Edsger Dijkstra in 1959. It is an algorithm that works with graphs that have non-negative edge path costs, in order to find the shortest path from one node to another [6].

It does this by:

Set the distance of the start node to itself as zero and then the distance to every other node is set to infinity (this identifies nodes that have not been visited).

Create an array to hold the shortest distances.

Starting from the source (start node) and mark the distance as zero

For each of the adjacent vertices

Compute which edge has the lowest weight

Move to that node and mark as visited

If the node has already been visited

Compare the current distance travelled with the distance associated with that node.

If current distance travelled is less than distance already associated with node

Update the nodes parent with new parent travelled from

Update the distance travelled to new distance travelled

else

Set the distance to that node as the total travelled

Set the parent of that node to the node travelled from

Repeat until final node has been reached.

Starting from final node back track to each parent node finally arriving at start point.

Shortest path has now been traversed.

You can see an example in Figure Dijkstra’s algorithm example of where the graph has been traversed from A to H using Dijkstra’s algorithm.

Figure Dijkstra’s algorithm example

C:\Users\Francis\Desktop\dijkstraRoute.png

Native Vs. web based

When looking at developing an application for a smart phone or mobile device, we have to decide if the application will be a web application, or a native application based on the mobile device. This question has been on-going and known as "The Battle of The Decade" [9] if the application was a mobile web based application, then theoretically, any mobile device which contained a web browser could operate the application. It is also possible for a web application to become location aware [7], but the question then is which function on the mobile device are also required and can these be accessed via a web application.

With the emergence of HTML5 it has made it easier to develop web based applications that are able to integrate with mobile devices. The question still exists can a web based application become fully integrated with a mobile device and all of its sensors? This question implies that for full sensor integration with a mobile device then the application would have to be native to the device and not browser based. This would also be backed up by the need to access other low level functions on the mobile device like alarm or calendar functions etc…

Requirements analysis

Problem

If you take the normal reminder application, you enter a date and time and you then receive a reminder at that specified date and time. Using an application like this means that you may need to question "Where will I likely be when this alarm goes off?" or "how much head start do I need to allow myself?"

What’s available currently?

Currently there is the normal reminder application, which allows you to enter the date and time to be reminded at the date and time of the appointment. If you want a reminder application that is location aware, the only the applications available allow you to enter an appointment with a location, but the way the application works is that it will monitor your location, and remind you when you get near to the location of the appointment.

Solution

My solution is to design and build an application that monitors your location, and then compares that with the location of appointments that you have already entered.

The application will then compute the shortest time that it would take you to travel to the locations of your appointments, The application would then remind you giving you enough time to travel to the location of the appointment.

Functional requirements.

The functional requirements of the application are:

Allow the user to enter an appointment, along with a location

Allow the user to be able to view all appointments that have already been added.

Allow the user to be able to update and delete an appointment

Allow the user to be able to specify the mode of transport

Non – Functional requirements

Must have access to the internet

Mobile device must have GPS enabled

Hardware required

A windows phone 7 is required that has a GPS sensor and is able to connect to the internet.

Software required

Microsoft Visual Studio

Microsoft Expression Blend

Windows phone 7.5 SDK

Design Methodology

The design methodology is vital to ensuring that you get the project flow and control from the start. It is also critical that you are able to adapt to change throughout the design and development process. To that end the methodology that I have chosen to use is from the Agile family and is called Kanban.

The reason behind this choice is that Kanban allows you to limit the work in progress in any particular stage in the development life cycle. It also allows you to identify bottlenecks which allow you to quickly deal with these and ensure your project continues to flow.

Project management

Figure Gantt chartProject Plan.gif

Figure Work breakdown structure

Project plan

In

Project management above you can see the Gantt chart that I created to span the project showing the tasks needed to be carried out throughout the project. The tasks needed are:

Interim Report

The parts of this task are:

Literature Search – Carry out a search of literature in the area of context aware computing.

Literature Review – Review the literature found during the literature search.

Write report – Write the interim report using the literature review and research that has already been carried out.

Submit Report – Submit the report by deadline set out.

Technology / algorithm Research

The parts of this task are:

Technology Research – Research the technology that will be used in the project.

Algorithm Research

The parts of this task are:

Algorithm Design – Research the best way to implement the shortest path algorithm.

Prototype Application Design

The parts of this task are:

GUI Design – Design the graphical interface that will be used in the project.

Build Gui – Build the graphical interface that has been designed in the previous step.

Implement Data Structures – Implement the background data structures that will be needed to make the application function.

Prototype Application Completed

Application Testing

The parts of this task are:

Develop Unit Tests – Develop unit tests to test the functionality of the classes and methods created.

Compare Handset and Emulator tests

Emulator integration tests – Carry out End to End tests using the emulator.

Handset Tests – Carry out End to End test using a physical handset.

Test results analysis – Analyse the test results from the previous tests.

Testing Completed

Final Report

The parts of this task are:

Write report – Write the overall final report showing findings.

Submit Report – Submit final report

Milestones

To enable me to keep track of progress throughout my project I have set milestones which have to be achieved. The following are the milestones throughout my project:

Submit interim report

Prototype Application Completed

Testing Completed

Submit Report

Deliverables

Throughout my project and upon completion of the project the following are the deliverables:

Completed interim report

Prototype Application

Completed Final Report

Risk management

Time management

Looking at Figure Work breakdown structure you will see the work breakdown structure where I have taken the tasks to be carried out throughout the project and I have broken them down into their lowest levels. I have done this in order to help with the management of the project as these tasks can now be completed in manageable chunks.

Due to the fact that my time is limited and I have a lot of work to complete within the time period that has been set out for the project I have taken an average day to perform a critical analysis of how my time is spent throughout the day. I have made a log of my activities throughout the day along with their effectiveness and any comments which might improve the effectiveness of my activities.

Table Activity log

Time

Activity

Effectiveness

Comments

8.00 – 9.00

Prepare for university

50%

Could do this within 30 minutes

9.05 – 12.05

Class

100%

Required

12.05 – 14.00

Lunch / Relax

50%

Could take less time for lunch and review project material

14.15 – 17.15

Practical

100%

Required

18.00 – 20.00

Eat / Watch TV

25%

Time to relax and breaks are needed but work also needs to be completed

20.00 – 23.30

Work on project

65%

Not as effective as it could be as late night and growing tired.

When I look at my activities for a typical day, I can see where there are areas that I can switch or tighten up on to improve my effectiveness throughout the day. For example, during the afternoon lunch break, I can prepare some materials that I can use for the project in the evening. When it comes to the evening, the time I spend eating and watching TV can be made more effective in such a way that, I can work on my project after eating and maybe watch TV later in the evening.

Working with my supervisor

At the start of my project I was allocated a project supervisor, from the start it was agreed that we would meet once a week (usually on a Friday). During this time my supervisor is able to check on my progress from the previous week. We are able to discuss any issues that may have cropped up and how we can side step these or deal with them.

I find this time extremely useful as sometimes it will refocus me if my attention has been drawn away on other things. With the help from my supervisor I am also able to hone in on specific subject areas rather than my focus being too widespread.

Before attending a meeting I would put together information on the following points:

What progress has been made since the last meeting

Any problems that have arisen

What I am planning to do next.

These points allow me to prepare for the meeting so as to maximise the usefulness of the time. I have on occasions, had the need to contact my supervisor by email outside of our regular meeting times due to issues that have arose, for example not being able to gain access to journals that are essential to the project.

Risks identified

As with all projects there are elements of risk that are inherent, in Table Risk factorsbelow I have identified those risk factors that could have potential effects to my project. I have given them a rating and detailed how I would deal with these factors.

Table Risk factors

Risk

Risk Type

Classification

Rating (using RAG Grading)

Triggers

Possible Action

Loosing work due to virus or crash

Event Driven

Non-Technical

10

None

Avoidance – I am using Dropbox along with a subversion repository as a backup

Illness

Event Driven

Non – Technical

7

Noticing deterioration of my health

Avoidance – Early diagnosis and treatment of any aliments

Project slippage

Evolving

Non – Technical

13

Over shooting milestone deadlines

Avoidance – Keep to project plan

Deflection – Discuss with supervisor changing the nature of the project

Family Issues

Event Driven

Non - Technical

7

N/A

Avoidance – Keeping to schedule with project plan to minimise impact

Deflection – Where possible refer to other family members to deal with issues.

Lack of Knowledge

Evolving

Technical

13

Having problems with coding etc…

Avoidance – Source knowledge from tutorials

Contingency – Seek help from my supervisor

Semester 2

Design

This chapter is concerned about the design of an application using the theoretical knowledge gained in the previous chapters. At the core of the application is an algorithm, which was designed from scratch. As part of the design of the application, the development was split into:

Application logic design

Algorithm design

Graphical Interface Design

Application Logic design

The first stage in the design process was to look at the application logic design, along with how the end user would interact with the application.

"The logical model is the design phase that identifies how the business policies, rules, and services your application requires are broken out into logical "business objects."  These abstract business objects combine to define a three-tier logical model of the application. This logical model is the precursor of the physical component model you will design later."

"Microsoft 2013"

User Requirements

After careful consideration of what the end user would require of this application, the following is the list of requirements:

The ability to add a reminder

The ability to remove a reminder

The ability to edit a reminder

The ability to have that reminder updated automatically without any further intervention from the user

System Architecture

Figure : High Level Architectural Overview

Reminder

GPS Sensor

GUI

Background monitoring

Web API

Phone Storage

Phone Alarm Clock

Figure : High Level Architectural Overview demonstrates a high-level overview of the application and its components. The GUI allows the user to add and manipulate reminders, to stipulate the method of travel to the event, and enter the location of the event. As part of the customisation options available to the user, the GUI will allow a choice from a selection of alarm sounds; also give the ability to set the minimum amount of time that an alarm will sound before an event.

For each Reminder, the details that the user enters are attached. The Reminder contains the algorithm that will calculate the time when the alarm should sound based on information that it receives from other components.

The reminder will access the GPS Sensor of the phone to gain the latitude and longitude co-ordinates of the users current position. The reminder will then use the location information entered by the user in the GUI, the GPS co-ordinates of the current location, and will contact the Web API where it will find out the distance between the two locations. This distance is used in the calculation of the alarm time.

Once the reminder has calculated the alarm time it then gets added to the Phone Alarm Clock, where then the phone scheduling service will take care of sounding the alarm at the allotted time. A copy of the entire reminder details get added to the Phone Storage where they can be retrieved at a later time if the user decides to update the reminder, or the background monitoring service needs to change the alarm time.

The Background monitoring service will run approximately every thirty minutes as decided by the phone operating system. This will force the reminder to access all the details stored in the phone storage, check if the user has moved from the position they were in previously when the alarm time was calculated, and if so, check the distance again from where the user currently is, to the location of the event and recalculate the alarm time. The reminder will then find the alarm in the Phone alarm clock and update the alarm time, and will update the details stored in the phone storage.

Class Diagrams

Figure Main Classes diagram

Figure Main Classes diagram shows the three main classes that were created for the application, but these may be altered during implementation. The following is a brief description of the purpose of each of the classes and their function within the application.

Location Class

The location class is implemented to allow for holding the event and the current location details, which include the latitude and longitude.

Reminder Class

The reminder class will use an algorithm to calculate an alarm time; this will take place in the getAlarmTime method. It also contains methods like saveData and readData, which are responsible for writing and reading the reminder details to the phone storage. The methods addAlarm, findAlarm, updateAlarm and removeAlarm all deal with manipulating the alarms in the sechedule service of the phone. The final method getAllAlarms is used to bring back all the alarms form the phone storage.

Location Results Class

The location results class is to be used to take the location information supplied by the user, get the current information from the GPS sensor, interrogate the web API with these details, and return co-ordinate details for both the event and current location. In addition, this class will return the distance between both locations that the reminder class can use for the algorithm to calculate the alarm time.

Algorithm design

One of the core objectives of this project was to develop the algorithm that resides at the core of the application. Various different paths could be followed when designing this algorithm. While looking at the ‘A Star’ and ‘Dijkstra’s algorithm’ these could have been adapted for use in this application but this was decided against, and in place the decision was made to develop an algorithm from scratch that would be more suitable. To start building an algorithm from scratch for the nature of this application, there was a need to ask what factors would affect the result of the algorithm. Not all of the factors were obviously apparent, but the list that was derived was:

The location of the user

The location of the event

The distance to be travelled

The mode of transport

If the user changes location between the time of setting the original alarm and the time of the event

The algorithm would have to take all of these factors into consideration when calculating the alarm time. So based on these factors the following algorithm was developed:

do every 30 mins

get current location

if current location has not been stored

Store current location

else if current location is different to stored location

update stored location

get mode of transport(default being travel by car)

// used to define the average travel time i.e car = 50mph

// travel by public transport = 40mph

get user min alarm time (default = 30mins)

loop for each event

check how much distance between current location and event location

if travelling within the same country

alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer)

else if current location and event location within western Europe

alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer + 72 hrs(3days))

else

alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer + 168 hrs(7days))

end if

if event alert time is between current time and (current time + 30 mins)

// the amount of time until the next loop

alert user

else if event alert time is in the past

alert user

End loop

while thread / app is active

The algorithm may be refined more when the time comes to implement it.

Graphical user interface design

To design the graphical interface the first thing that had to be considered was the device that was going to be used to host the application, and in this instance, it was a Windows Phone with a windows phone 7.1 operating system. From looking at various design ideas for windows phone applications and researching what the windows phone evangelists recommend, there were certain aspects that were incorporated into the design of the user interface:

Animation

Windows Phone 7 controls

Live tiles

The ability to switch between light and dark themes

The first step in the GUI design process was to mock up how the application would look, this was done using Balsamiq Mockups and can be seen in

These live tiles are animated containing both text and an icon.

Figure : Main Page

These pivot controls allow the user to enter the details of the event

Figure : Add event page

This page is populated with each alarm that the user adds. And by selecting one allows the user to view the details of the alarm.

Figure : View Events page

When the user selects an event from the view events page the details of the event are displayed to allow the user to edit or remove the event

Figure : View Event Details page

Implementation

This chapter looks at how the application went from design to being implemented on the Windows Phone 7 platform. The application was given the name Predicate, so named due to the definition of the word; ‘Logic To make (a term or expression) the predicate of a proposition.’ There was a requirement to change the design slightly in order to make the application work more effectively these have been documented within this chapter.

Developing for Windows Phone – libraries and namespaces used

Development for the Windows phone is carried out within the Visual Studio IDE using either C# or Visual Basic language to develop a Silverlight application to be deployed on to a Windows Phone. You are presented with various types of page types that you can create, but for this application, portrait pages were selected along with the C# language. When using the C# language for windows phone not the entire C# libraries were available, and on some occasions, it was required to add external libraries due to functionality that was required. The Silverlight and Windows Phone development kits gave access to some of the core functionality of the Windows Phone device that was required by this application.

The System.Device.Location library gives access to the GPS sensor on the Windows Phone in particular the GeoCoordinateWatcher class, which is used to give a location based on the latitude, and longitude coordinates. The accuracy level for this class can be set for default or high. The difference is; on default level, there is a combination of different methods used to acquire the position:

Assisted GPS (cell tower triangulation)

WIFI Triangulation (IP Lookup)

When the accuracy level is set to High, the above methods are used along with GPS

Assisted GPS is battery friendly & locks on the location fast since it uses the cell radio, which is already on. I can be accurate to the city block or building level in urban areas, but accuracy degrades in rural areas where the density of cell towers decreases. It also works well inside buildings.

GPS is slower to acquire a satellite lock and consumes more battery power since the GPS radio must be turned on as needed. Once locked in, it is the most accurate positioning method within just a few feet. It is virtually useless inside buildings since you need line of sight with the sky. Dense urban areas in places like Manhattan can also cause GPS inaccuracies.

Wi-Fi / IP Lookup is the least accurate since the IP address of an Wi-Fi hotspot can sometimes be registered at a different address.

For this application, the accuracy level is set to Default instead of high, as only the Latitude and Longitude are required. If set on high, the sensor is also calibrated to get the altitude, how fast you are traveling, horizontal and vertical accuracy, along with other details, but these details are not required. Another benefit of setting the accuracy level to default is that the drain on the battery is less.

Within the System.Net Library is the WebClient class containing methods for sending and receiving data from a URI source. Within this application, the WebClient class is used to communicate with and get information from the Google API.

Predicate also makes use of the System.IO.IsolatedStorage namespace, in particular the IsolatedStorageFile class, which contains methods for dealing with the isolated storage area along with the directories and files contained there.

In the Microsoft.Phone.Scheduler namespace is the ScheduledActionService Class. This class contains the methods to maintain scheduled actions. This class is what Predicate will use to manage alarms.

Solution Breakdown

Figure : Predicate Solution Breakdown shows how the project solution is made up from three projects:

The GUI

Class Library

Predicate Background Agent

Figure : Predicate Solution Breakdown

The class library is where custom classes can be housed or code that is common across the project. Four classes have been added to this project:

Location class: this is designed to hold the location details including the position coordinates, location name, country etc…

PredicateEvent class: this class is designed to hold all of the information relating to each event. It also contains the method with the algorithm for generating the alarm time, and methods for reading from and writing to the phone storage.

LocationResults class: this class contains all the methods for contacting and extracting information from the Google API.

TreeHelper class: this class was added to allow for finding and identifying components of the interface using the visual tree helper.

Another project that was added is the Predicate Background Agent. This is where the scheduled agent is housed. The scheduled agent contains one method that is invoked by the phone operating system (OS) to perform a task approximately every thirty minutes (dependent on the OS). Two different types of task can be run by the scheduled agent:

A Periodic Task:

Will run for about 25 seconds before it is shut down by the OS.

Maximum amount of memory that can be used is less than or up to six megabytes.

If the task crashes twice consecutively then the OS will unscheduled it.

A Resource Intensive Task:

Run when the OS is in a position to let the task run e.g., when the resources are available.

When the battery is greater than 90% charged

When the phone is connected to WIFI

When the phone is not being used (Lock screed displayed)

Can run for up to ten minutes

Maximum amount of memory that can be used is less than or up to six megabytes.

If the task crashes twice consecutively then the OS will unscheduled it.

There are certain things that the background agent is allowed to carry out and others are restricted:

Allowed

Restricted

Tiles

Toast

Location

Network

Read / Write Isolated Storage

Sockets

Display UI

XNA Libraries

Microphone & Camera

Sensors

Play Audio(may only use background audio APIs)

The background agent is of type Scheduled Task and has some properties that are compulsory to set when you instantiate it. One of those properties is the number of days until it expires, where the maximum allowed is 20 days. The reasoning behind this is that if the user stops using the application then there is no point in running the background agent. Therefore you must renew the background agent each time the user uses the application and thus will extend the life of the agent.

GUI Implementation

The implemented GUI contains four pages:

Main Page

Add Event

Settings

View Event

Each of the pages are a combination of two files, the first is the XAML file, which contains the details of each of the controls on the page. These controls range from text blocks to text boxes to buttons etc… The second file is the file containing the C# code. This is where all the event handlers and custom methods reside.

Main Page

The main page uses tiles to keep in-line with the Windows Phone 7 theme. They were added using the Tile slider control downloaded from Microsoft’s site Codeplex[8]. These tiles contain icons and then scroll to show text stating what each tile is for, this can be seen in Figure : Main page.

Figure : Main page

When submitting apps to the Microsoft App Store for testing, one of the test they carry out is to see if the icons and text are still legible if the user was to change the theme on the phone between light and dark. To that end, the tiles on the main page take direct input from the phone as to the colour and theme being employed.

Figure : Change of theme reflected in Predicate

Figure : Change of theme reflected in Predicate shows how by changing the theme and the accent colour on the phone settings that these are reflected in the Predicate application.

Upon loading the main page, the constructor calls to the method startTask, this is used to renew the background agent.

public MainPage()

{

InitializeComponent();

startTask();

}

private void startTask()

{

PeriodicTask t;

t = ScheduledActionService.Find("Predicate") as PeriodicTask;

bool found = (t != null);

if (!found)

{

t = new PeriodicTask("Predicate");

}

t.Description = "Agent to monitor location and update alarm times";

t.ExpirationTime = DateTime.Now.AddDays(10);

if (!found)

{

try

{

ScheduledActionService.Add(t);

#if DEBUG_AGENT

ScheduledActionService.LaunchForTest("Predicate", TimeSpan.FromSeconds(60));

#endif

}

catch (InvalidOperationException e)

{

if (e.Message.Contains("BNS Error: The action is disabled"))

MessageBox.Show("Please check that you have not disabled the background agent for this app in your device settings");

}

}

else

{

ScheduledActionService.Remove("Predicate");

try

{

ScheduledActionService.Add(t);

}

catch (InvalidOperationException e)

{

if (e.Message.Contains("BNS Error: The action is disabled"))

MessageBox.Show("Please check that you have not disabled the background agent for this app in your device settings");

}

}

}

Figure : Background Task Settings displays how you can see in the phone settings that the background agent has been activated.

Figure : Background Task Settings

public void settingsTileClick(object sender, RoutedEventArgs e)

{

NavigationService.Navigate(new Uri("/Views/Settings.xaml", UriKind.Relative));

}

private void addTileClick(object sender, RoutedEventArgs e)

{

NavigationService.Navigate(new Uri("/Views/AddEvent.xaml", UriKind.Relative));

}

private void ViewTileClick(object sender, RoutedEventArgs e)

{

NavigationService.Navigate(new Uri("/Views/viewEvents.xaml", UriKind.Relative));

}

private void editTileClick(object sender, RoutedEventArgs e)

{

String uri = String.Format("/Views/viewEvents.xaml?name={0}", "edit");

NavigationService.Navigate(new Uri(uri, UriKind.Relative));

}

private void deleteTileClick(object sender, RoutedEventArgs e)

{

String uri = String.Format("/Views/viewEvents.xaml?name={0}", "delete");

NavigationService.Navigate(new Uri(uri, UriKind.Relative));

}Clicking on any of the tiles invokes the navigation service, which will navigate to the prepared URI that has been defined in the event handler associated with that tile.

Add Event Page

The add event page is a Pivot style page containing two pivots. Contained within the first pivot the user enters the details of the event to be reminded of, e.g. the name, date, time.

The name is entered into a normal text box whereas for the date and time, these are entered using a date picker control and a time picker control these can be seen in Figure .

Figure : Add Event Pivot 1

Figure shows the second pivot, the user enters the location for the event, then on clicking the find button a canvas appears with a map showing the location they have entered. This is to allow the user to confirm that they have entered the correct location.

Figure : Add event page - second pivot

private void btnFind_Click(object sender, RoutedEventArgs e)

{

if (txtCity.Text.Length < 3)

{

MessageBox.Show("Please enter a Town / City");

}

else

{

locationDetails = new LocationResults();

locationDetails.formatEventAddress(txtBuildingNo.Text.ToString(),txtStreetName.Text.ToString(),txtCity.Text.ToString(),txtCountry.Text);

wbLocation.Navigate(new Uri("http://maps.google.com/maps?q="+locationDetails.AddressDetails));

canvas1.Visibility = System.Windows.Visibility.Visible;

ApplicationBar.IsVisible = false;

locationDetails.getCurrentLocation();

}

}

On clicking the find button there are several things that are started in the background. Firstly, the event handler is fired for that button

public void getCurrentLocation()

{

watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)

{

MovementThreshold = 20

};

watcher.PositionChanged += this.watcher_PositionChanged;

watcher.StatusChanged += this.watcher_StatusChanged;

watcher.Start();

}

The getCurrentLocation method is called

This uses the GeoCoordinateWatcher to get the current position of the user, then saves the latitude and longitude into variables to use at a later stage.

private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)

{

switch (e.Status)

{

case GeoPositionStatus.Disabled:

MessageBox.Show("Location Service is not enabled on the device");

break;

case GeoPositionStatus.NoData:

MessageBox.Show(" The Location Service is working, but it cannot get location data.");

break;

}

}

private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)

{

if (e.Position.Location.IsUnknown)

{

MessageBox.Show("Please wait while your position is determined....");

return;

}

currentLocation.Latitude = e.Position.Location.Latitude.ToString();

currentLocation.Longitude = e.Position.Location.Longitude.ToString();

watcher.Stop();

phoneAppService.State["lat"] = currentLocation.Latitude;

phoneAppService.State["lng"] = currentLocation.Longitude;

}

public void formatDistanceAddress()

{

String eventLoc = "" + eventLocation.Latitude + ',' + eventLocation.Longitude;

String currLoc = "" + currentLocation.Latitude + ',' + currentLocation.Longitude;

//String currLoc = "54.9966124,-7.3085748";//co-ords for derry using for temp location

String tmp = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins={0}&destinations={1}&mode=driving&language=en&units=imperial&sensor=false";

distanceAddress = String.Format(tmp, currLoc, eventLoc, transport);

}

Another method call is to locationDetails.formatEventAddress this method is used to build the URI for the Google API using the location details that the user has entered.

On clicking the Close button within the canvas, further event handlers are fired.

Two WebClients are created the first will use the coordinates from the GPS sensor to get the current country from the API the second will take the location details entered by the user and get the coordinates and country details from the API. These are then stored for use to get the distance between the two locations and for use in the algorithm to calculate the alarm time.

void getAdderssDetails(object sender, OpenReadCompletedEventArgs e)

{

String tmp;

var reader = new StreamReader(e.Result);

tmp = reader.ReadToEnd().ToString();

locationDetails.Results = tmp;

locationDetails.extractLocationDetails();

locationDetails.formatDistanceAddress();

locationDetails.getTravelDistance();

}

void getCurrentAddressDetails(object sender, OpenReadCompletedEventArgs e)

{

String tmp;

var reader = new StreamReader(e.Result);

tmp = reader.ReadToEnd().ToString();

locationDetails.Results = tmp;

locationDetails.extractCurrentAddress();

Save.IsEnabled = true;

}

private void btnClose_Click(object sender, RoutedEventArgs e)

{

canvas1.Visibility = System.Windows.Visibility.Collapsed;

ApplicationBar.IsVisible = true;

locationDetails.formatCoordsLocation();

// using cords generated by sensor, get country details for current location

webClient2 = new WebClient();

webClient2.OpenReadAsync(new Uri(locationDetails.CoordsAddress));

webClient2.OpenReadCompleted += new OpenReadCompletedEventHandler(getCurrentAddressDetails);

// using the entered address get the latatude and longatude

webClient = new WebClient();

webClient.OpenReadAsync(new Uri(locationDetails.LocatonUrl));

webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(getAdderssDetails);

}These are the WebClient Handlers associated with the WebClients

<GeocodeResponse>

<status>OK</status>

<result>

<type>locality</type>

<type>political</type>

<formatted_address>Omagh, UK</formatted_address>

<address_component>

<long_name>Omagh</long_name>

<short_name>Omagh</short_name>

<type>locality</type>

<type>political</type>

</address_component>

<address_component>

<long_name>Omagh</long_name>

<short_name>Omagh</short_name>

<type>administrative_area_level_2</type>

<type>political</type>

</address_component>

<address_component>

<long_name>Northern Ireland</long_name>

<short_name>Northern Ireland</short_name>

<type>administrative_area_level_1</type>

<type>political</type>

</address_component>

<address_component>

<long_name>United Kingdom</long_name>

<short_name>GB</short_name>

<type>country</type>

<type>political</type>

</address_component>

<address_component>

<long_name>Omagh</long_name>

<short_name>Omagh</short_name>

<type>postal_town</type>

</address_component>

<geometry>

<location>

<lat>54.5965700</lat>

<lng>-7.3069100</lng>

</location>

<location_type>APPROXIMATE</location_type>

<viewport>

<southwest>

<lat>54.5901053</lat>

<lng>-7.3229174</lng>

</southwest>

<northeast>

<lat>54.6030336</lat>

<lng>-7.2909026</lng>

</northeast>

</viewport>

</geometry>

</result>

</GeocodeResponse>Both WebClients get receive XML data back from the API, which looks like:

public void extractLocationDetails()

{

String status="OK";

String tmp="";

XmlReader reader = XmlReader.Create(new StringReader(results));

while (reader.Read() && (status == "OK")){

if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "status")){

XmlReader pReader = reader.ReadSubtree();

while (pReader.Read()){

if (pReader.NodeType == XmlNodeType.Text) {

status = pReader.Value;

}

}

}

if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "lat")){

XmlReader pReader = reader.ReadSubtree();

while (pReader.Read()){

if (pReader.NodeType == XmlNodeType.Text) {

eventLocation.Latitude = pReader.Value;

}

}

}

if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "lng")){

XmlReader pReader = reader.ReadSubtree();

while (pReader.Read()){

if (pReader.NodeType == XmlNodeType.Text){

eventLocation.Longitude= pReader.Value;

}

}

}

if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "address_component")){

XmlReader pReader = reader.ReadSubtree();

while (pReader.Read()){

if ((pReader.NodeType == XmlNodeType.Element) && (pReader.Name == "long_name")){

XmlReader pReader1 = pReader.ReadSubtree();

while (pReader1.Read()){

if (pReader1.NodeType == XmlNodeType.Text) {

tmp = pReader1.Value;

}

}

}

if (pReader.NodeType == XmlNodeType.Text) {

if (pReader.Value == "country"){

eventLocation.Country = tmp;

}

}

}

}

}

if (status =="ZERO_RESULTS")

MessageBox.Show("No results were found using the address details you have supplied");

else if(status =="UNKNOWN_ERROR")

MessageBox.Show("There has been a server error. Please try again");

}

After receiving this response, there is a call either extractLocationDetails or to extractCurrentAdderss to extract the required data from the XML

public void extractCurrentAddress()

{

String status = "OK";

String tmp = "";

XmlReader reader = XmlReader.Create(new StringReader(results));

while (reader.Read() && (status == "OK"))

{

if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "address_component"))

{

XmlReader pReader = reader.ReadSubtree();

while (pReader.Read())

{

if ((pReader.NodeType == XmlNodeType.Element) && (pReader.Name == "long_name"))

{

XmlReader pReader1 = pReader.ReadSubtree();

while (pReader1.Read())

{

if (pReader1.NodeType == XmlNodeType.Text)

{

tmp = pReader1.Value;

}

}

}

if (pReader.NodeType == XmlNodeType.Text)

{

if (pReader.Value == "country")

{

currentLocation.Country = tmp;

}

}

}

}

}

if (status == "ZERO_RESULTS")

MessageBox.Show("No results were found using the address details you have supplied");

else if (status == "UNKNOWN_ERROR")

MessageBox.Show("There has been a server error. Please try again");

}

Once the coordinates for both the event location and the current location have been retrieved then a query can be sent to the API to find out the distance between the two locations. This is done in a similar way to getting the coordinates.

At this stage enough information has been gathered for use by the algorithm to calculate the time that the alarm should sound. A call to getAlarmTime in the PredicateEvent class is made where the algorithm will then set the time for the alarm.

public void getAlarmTime()

{

Boolean inWesternEurope = false;

int speed, noMins;

for (int x = 0; x < westernEurope.Length; x++)

{

if (eventLocation.Country.Equals(westernEurope[x]))

inWesternEurope = true;

}

if (transportMode == "driving")

speed = 50;

else if (transportMode == "public")

speed=40;

else //walking

speed = 5;

if (eventLocation.Country.ToLower().Equals(currentLocation.Country.ToLower()))

{

// traveling in same country

//alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer)

noMins = (int)(((distance / speed) * 60) + buffer);

alarmTime = eventDateTime.Subtract(new TimeSpan(-0,noMins, 0));

}

else if (eventLocation.Country.ToLower().Equals(currentLocation.Country.ToLower()) || inWesternEurope)

{

// Traveling in different country but in western europe

// alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer + 72 hrs(3days))

noMins = (int)(((distance / speed) * 60) + buffer + (72 * 60));

alarmTime = eventDateTime.Subtract(new TimeSpan(-0,noMins, 0));

}

else

{

// traveling in different country outside western europe

//alert time = event time - (( distance(in miles) / mode of transport average speed(mph)) + user defined buffer + 168 hrs(7days))

noMins = (int)(((distance / speed)*60) + buffer + (168 * 60));

alarmTime = eventDateTime.Subtract(new TimeSpan(-0, noMins, 0));

}

}

The last stage to adding the alarm is:

Adding the rest of the alarm parameters

Checking that the time being set is not in the past

Adding the alarm to the Scheduled Action Service

Writing the alarm details to the isolated storage

public void addAlarm()

{

myAlarm = new Alarm(eventName);

myAlarm.Sound = new Uri("/AlarmSounds/"+this.sound+".wav", UriKind.Relative);

getAlarmTime();

if (this.alarmTime < (DateTime.Now.AddMinutes(30)))

MessageBox.Show("To travel to the location of this event requires more travel time than you currently have. Please review your Event time.");

else

{

myAlarm.BeginTime = this.alarmTime;

myAlarm.Content = "You need to be in " + eventLocation.City + "for " + eventDateTime.ToShortTimeString() + " on " + eventDateTime.ToShortDateString();

if (ScheduledActionService.Find(this.eventName) != null)

{

MessageBoxResult r = MessageBox.Show("There is already an Alarm set for this event. Do you wish to modify this alarm?", "Alarm Exists!", MessageBoxButton.OKCancel);

if (r == MessageBoxResult.OK)

{

ScheduledActionService.Remove(this.eventName);

ScheduledActionService.Add(myAlarm);

saveData();

MessageBox.Show("Alarm Saved");

}

}

else

{

ScheduledActionService.Add(myAlarm);

saveData();

MessageBox.Show("Alarm Saved");

}

}

}

The following method writes the data to the isolated storage

private void saveData()

{

var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

String filename = eventName + ".txt";

if (!appStorage.FileExists(filename))

{

using (var file = appStorage.CreateFile(filename))

{

using (var writer = new StreamWriter(file))

{

writer.WriteLine(eventName);

writer.WriteLine(transportMode);

writer.WriteLine(eventLocation.City);

writer.WriteLine(sound);

writer.WriteLine(buffer.ToString());

writer.WriteLine(eventLocation.Latitude);

writer.WriteLine(eventLocation.Longitude);

writer.WriteLine(eventLocation.Country);

writer.WriteLine(distance.ToString());

writer.WriteLine(currentLocation.Country);

writer.WriteLine(eventDateTime.ToString());

writer.WriteLine(currentLocation.Latitude);

writer.WriteLine(currentLocation.Longitude);

}

}

}

else

{

appStorage.DeleteFile(filename);

using (var file = appStorage.CreateFile(filename))

{

using (var writer = new StreamWriter(file))

{

writer.WriteLine(eventName);

writer.WriteLine(transportMode);

writer.WriteLine(eventLocation.City);

writer.WriteLine(sound);

writer.WriteLine(buffer.ToString());

writer.WriteLine(eventLocation.Latitude);

writer.WriteLine(eventLocation.Longitude);

writer.WriteLine(eventLocation.Country);

writer.WriteLine(distance.ToString());

writer.WriteLine(currentLocation.Country);

writer.WriteLine(eventDateTime.ToString());

writer.WriteLine(currentLocation.Latitude);

writer.WriteLine(currentLocation.Longitude);

}

}

}

}

View Events Page

public viewEvents()

{

InitializeComponent();

populatePage();

}

private void populatePage()

{

Random rnd = new Random();

String[] alarms;

myEvent = new PredicateEvent();

myEvent.getAllAlarms();

alarms = myEvent.AllAlarms;The view events page is a panorama page that is dynamically populated with a button for each of the alarms that the user has added.

for (int x = 0; x < alarms.Length; x++)

{

Button b = new Button();

b.Background = new SolidColorBrush(Color.FromArgb(255, (byte)rnd.Next(256), (byte)rnd.Next(256), (byte)rnd.Next(256)));

b.Content = alarms[x];

b.BorderBrush = (SolidColorBrush)Resources["PhoneForegroundBrush"];

b.BorderThickness = new Thickness(2);

b.Margin = new Thickness(8);

b.MinHeight = 100;

b.MinWidth = 100;

b.Click += new RoutedEventHandler(viewAlarmDetails);

wrapPanel.Children.Add(b);

}

}

Figure : View Events Page

On clicking any of the buttons, the alarm details are shown using a canvas. The user is also presented with the option to edit or delete the alarm. If delete is chosen, the user is prompted to ensure they wish to delete.

Figure : Delete event

private void btnDelete_Click(object sender, RoutedEventArgs e)

{

MessageBoxResult result = MessageBox.Show("Are you sure you wish to delete this event?", "Delete?", MessageBoxButton.OKCancel);

if (result == MessageBoxResult.OK)

{

choosenEvent.removeAlarm(txtName.Text.ToString());

alarmDetails.Visibility = System.Windows.Visibility.Collapsed;

wrapPanel.Children.Remove(myButton);

}

}

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)

{

String name;

base.OnNavigatedTo(e);

NavigationContext.QueryString.TryGetValue("name", out name);

if (!String.IsNullOrEmpty(name))

{

update = true;

pivot1.Header = "Edit Event";

myEditedEvent = new PredicateEvent();

myEditedEvent.findAlarm(name);

txtAlarmName.Text = myEditedEvent.EventName;

txtCity.Text = myEditedEvent.LocationName;

txtCountry.Text = myEditedEvent.EventCountry;

dpEventDate.Value = myEditedEvent.EventDateTime;

tpEventTim



rev

Our Service Portfolio

jb

Want To Place An Order Quickly?

Then shoot us a message on Whatsapp, WeChat or Gmail. We are available 24/7 to assist you.

whatsapp

Do not panic, you are at the right place

jb

Visit Our essay writting help page to get all the details and guidence on availing our assiatance service.

Get 20% Discount, Now
£19 £14/ Per Page
14 days delivery time

Our writting assistance service is undoubtedly one of the most affordable writting assistance services and we have highly qualified professionls to help you with your work. So what are you waiting for, click below to order now.

Get An Instant Quote

ORDER TODAY!

Our experts are ready to assist you, call us to get a free quote or order now to get succeed in your academics writing.

Get a Free Quote Order Now