Development of a Location Based Reminder System Project by Ben Ribbink Department of Computer Science Rhodes University November 2003 Submitted in partial fulfilment of the requirements of the degree Bachelor of Science (Honours) of Rhodes University i Acknowledgements There are a few people who need to be thanked for their invaluable assistance throughout the course of this project: The Microsoft Corporation, for financial support as well as the tools used in the development of this project My supervisor, Greg Foster, for always making time for me, assisting in any way he possibly could – even when it wasn’t expected of him, encouragement, motivation and vision. My parents, for their support, guidance and encouragement, as well as the hours spent proof reading. Caro Watkins, for always keeping us well organised, and putting me in touch with Microsoft. Jody Balarin and the technical support staff for always sorting out our technical headaches. The Honours class of 2003 for their fellowship as well as the exchanging of ideas. The Lord God, for always bringing me though no matter how much of a mess I get myself into. ii Abstract This project developed a location based system for a smart device, in this case a Personal Digital Assistant (PDA), using a Global Positioning System (GPS) receiver to determine the position of the device. In the project a means of getting information from a GPS receiver through serial communication was developed; as well as a small reminder application to make use of this information. The reminder application was designed to allow the storing of locations and associated reminders for each location. Whenever the device was in the proximity of a location, the application would alert a user to the reminders stored for that location. The system was tested to determine the accuracy of the location based service section which was responsible for triggering the alerts for the reminders. These tests showed that the system was accurate in terms of following predetermined criteria to decide whether or not the device was in the proximity of a location, meaning that it could be used as a useful real time application. The main focus of the project was to enable the use of location information, resulting in a simple use of the technology. However, the potential applications of the work done in this project are vast, ranging from scientific research to tourism, sporting and domestic applications. iii Table of Contents Development of a Location Based Reminder System ................................................... 1 Acknowledgements ......................................................................................................... i Abstract ..........................................................................................................................ii Table of Contents ......................................................................................................... iii Chapter 1 Overview of Technologies ......................................................................... 1 1.1 GPS ................................................................................................................ 1 1.1.1 What is GPS? ......................................................................................... 1 1.1.2 How does GPS work? ............................................................................ 2 1.1.3 GPS accuracy ......................................................................................... 3 1.2 Other location identification technologies ..................................................... 4 1.2.1 Cell of origin (COO) .............................................................................. 4 1.2.2 Angle of arrival (AOA) .......................................................................... 4 1.2.3 Time difference of arrival (TDOA) ....................................................... 5 1.2.4 Enhanced observed time difference of arrival (E-OTD)........................ 5 1.2.5 Location pattern matching ..................................................................... 5 1.2.6 How GPS compares ............................................................................... 5 1.3 .NET Compact Framework and Pocket PC ................................................... 6 1.4 Location based services and how this project fits in...................................... 6 1.4.1 Motor vehicles ....................................................................................... 6 1.4.2 Personal tracking and assistance ............................................................ 7 1.4.3 Advertising ............................................................................................. 7 1.4.4 Security and theft ................................................................................... 8 1.4.5 This Project ............................................................................................ 9 1.5 Aim of the project .......................................................................................... 9 1.5.1 Primary objective ................................................................................... 9 1.5.2 Secondary objectives ............................................................................. 9 Chapter 2 Development of Core functionality ............................................................ 10 2.1 GPS connectivity ......................................................................................... 10 2.1.1 Methodology ........................................................................................ 10 2.1.2 How to communicate with a GPS ........................................................ 10 2.1.3 Plan of execution.................................................................................. 12 2.2 Detail of the main functionality ................................................................... 13 2.2.1 Opening the port .................................................................................. 13 2.2.2 Configuring the port ............................................................................. 13 2.2.3 Reading from the port .......................................................................... 16 2.2.4 Closing the port .................................................................................... 17 2.3 Building the Location Reminder (Locrem).................................................. 17 2.3.1 GUI design in the .Net environment .................................................... 17 2.3.2 Class design ......................................................................................... 23 2.3.3 Persisting Objects................................................................................. 27 2.3.4 Parsing GPS data.................................................................................. 30 2.3.5 Reminders ............................................................................................ 33 2.3.6 Deployment onto the device ................................................................ 36 Chapter 3 Application Environment and Field Trials .............................................. 38 3.1 A functional description of the application .................................................. 38 3.1.1 Startup .................................................................................................. 38 3.1.2 Front page (info and active reminders) ................................................ 39 iv 3.1.3 Screen flow .......................................................................................... 42 3.1.4 Error checking ...................................................................................... 44 3.2 Field Testing the application ........................................................................ 44 3.2.1 Aim ...................................................................................................... 44 3.2. 2 Method ................................................................................................. 45 3.2.3 Results .................................................................................................. 46 3.2.4 Conclusion ........................................................................................... 47 Chapter 4 Discussion and conclusion ....................................................................... 48 4.1 Peculiarities of the system ........................................................................... 48 4.1.1 Off centre problem ............................................................................... 48 4.1.2 Bouncing reminders ............................................................................. 49 4.1.3 Slow starting GPS ................................................................................ 49 4.2 Problems encountered .................................................................................. 49 4.2.1 Serial Communication ......................................................................... 49 4.2.2 Serialisation.......................................................................................... 50 4.2.3 Threads ................................................................................................. 50 4.3 Opinion of the .NET Compact Framework.................................................. 50 4.4 Features to be included in future versions ................................................... 51 4.5 Extensions .................................................................................................... 51 4.5.1 Enhancements ...................................................................................... 51 4.5.2 Extensions ............................................................................................ 52 4.6 Conclusion ................................................................................................... 54 References: ................................................................................................................... 55 Glossary ....................................................................................................................... 57 Appendix A: Test results ....................................................................................... 58 1 Chapter 1 1.1 Overview of Technologies GPS 1.1.1 What is GPS? The Global Positioning System (GPS) is a system for determining accurate position using a constellation of satellites and a receiver (Figure 1.1). This system was put in place by the US Department of Defence at the cost of 12 billion dollars for military use. The system was intended to improve the accuracy of Inter Continental Ballistic Missiles (ICBM). The targeting systems of these missiles could give precise trajectories; in order to hit a target, however, an accurate trajectory is useless unless the firing point is known. This would not have been a problem for the Soviet Union, as most of their missiles were in land based silos; but the Americans had most of their missiles on submarines, so they needed an accurate means of determining their firing location. [Trimble Navigation, 2003] The constellation consists of 27 satellites, such as the NAVSTAR satellite (Figure 1.3). 24 satellites are in use and 3 in reserve, in a 12,000 mile (19,300 km) high orbit at 55° to the equator [Brain & Harris, 1998]. The orbits of these 24 satellites are precisely monitored by five US Air Force ground stations in Hawaii, Ascension Island, Diego Garcia, Kwajalein, and Colorado Springs. The careful monitoring together with the high altitude orbit means the position of the satellites is always known [Trimble Navigation, 2003; Smithsonian Institution, 1998]. 2 Figure 1.1 The GPS Constellation Image from the Smithsonian Institution: http://www.nasm.si.edu/galleries/gps/work.html 1.1.2 How does GPS work? With the positions of the satellites known, the problem is that of determining the position of the receiver relative to the satellites. Each satellite transmits a unique timing signal. The GPS receiver uses the difference between the time the signal was sent by the GPS satellite and the time the signal was received to determine the travel time of the signal. By multiplying the travel time of the signal by the speed at which the signal travels (the speed of light) the receiver can determine how far it is from the satellite. The satellites have atomic clocks, so they can accurately determine and encode the time the signal was sent; however the relatively inexpensive clocks used in receivers do not have the same sort of accuracy. The receiver then has an uncertainty in the time which causes uncertainties in the distances to the three satellites it is using for trilateration – four unknowns. This is solved by getting timing information from a fourth satellite (Figure 1.2). Now the receiver has four simultaneous equations for four unknowns – and can therefore determine the accurate distances to the three satellites and the accurate time [Leick, 2002]. 3 Figure 1.2 Determining position using time delays in signals from four satellites Image from the Smithsonian Institution: http://www.nasm.si.edu/galleries/gps/work.html 1.1.3 GPS accuracy The accuracy of the current system (GPS II) is to within 2m [Ashley, 2003]. Originally the US Department of Defence inserted timing errors into the GPS system to limit commercial accuracy to about 100m. This deliberate introduction of errors, called Selective Availability, was stopped in May 2000 [Smithsonian Institution, 1998]. The next generation GPS (GPS III) will be more reliable, accurate and resistant to signal-jamming. There will be more frequencies in use, providing redundancy, including two military frequencies at higher power to resist jamming. The extra frequencies also allow one to compensate for refraction as the signal goes through the ionosphere by using the differences in refraction between frequencies to determine the overall refraction, producing greater accuracy. Another improvement will be the use of a signal pattern stored on the receiver to match the phase of the signal, this will reinforce the timing signal and help compensate for interference caused by radio frequency transmitters [Ashley, 2003]. 4 Figure 1.3 A NAVSTAR GPS satellite NASA photograph from: http://travel.howstuffworks.com/gps1.htm The first satellites for GPS III are expected to be launched in 2010 [Ashley, 2003]. 1.2 Other location identification technologies 1.2.1 Cell of origin (COO) A mobile device needs to make use of a tower in order to make a call or transmit data. The cellular network can tell which tower is being used by that device, and conclude that the device is somewhere in the area served by that tower. This is the least accurate of the technologies, but does not require any enhancements to be made to the mobile device or cellular network [Deitel et al, 2001]. 1.2.2 Angle of arrival (AOA) A more accurate technology uses the angle of arrival of an incoming signal from a device in the overlap of two towers. The point at which the lines drawn at hose angles to the two towers cross is the location of the device. This system is susceptible to interference such as the signal bouncing off buildings, but is still said to be fairly accurate (although no numbers are put to its accuracy) [Deitel et al, 2001]. 5 1.2.3 Time difference of arrival (TDOA) Instead of using the angle of arrival, TDOA uses how long the signal takes to get to each of three towers. Subsequently, by multiplying the time by the speed of the signal, a distance from each tower is determined. These distances form the radii of circles around towers which will intersect at the location of the mobile device. This is an accurate system and many companies combine it with AOA for improved accuracy [Deitel et al, 2001]. 1.2.4 Enhanced observed time difference of arrival (E-OTD) This is a system whereby the mobile device measures the time it takes a signal to reach it from multiple towers, and then determines its location. This is an accurate system that requires enhanced mobile devices [Deitel et al, 2001]. 1.2.5 Location pattern matching Most location identification technologies (such as GPS and AOA) are hindered by the signal bouncing off objects and arriving in a scattered pattern from multiple paths (known as multipath). Location pattern matching actually uses multipath to determine the location of a mobile device. It relies on the fact that different locations will have different multipath characteristics due to the physical features of that location. Location pattern matching will use a database of multipath fingerprints to determine from which location a signal is being received. So this system works best where there are a lot of features that would cause multipath errors and hinder other systems. The unfortunate drawback is that a database of multipath fingerprints needs to be maintained [Deitel et al, 2001]. 1.2.6 How GPS compares GPS is more accurate than any of these other technologies. However GPS does not work indoors due to the weakness of the satellite signal received. GPS is also a very expensive system, in terms of the system as a whole, due to the expense involved in the development and maintenance of the satellite constellation [Deitel et al, 2001]. 6 1.3 .NET Compact Framework and Pocket PC Visual Studio .NET 2003 development environment was chosen for this project due to its drag-n-drop approach to GUI development and extensive support through the MSDN library. .NET 2003 gives a developer the ability to do rapid application development on mobile devices though its use of the .NET Compact Framework. Part of the reason for choosing the .NET Compact Framework was that it is fairly new technology. Part of the project therefore was to test the suitability of the .NET Compact Framework to the task of developing a location based system on a mobile device. The .NET Compact Framework may be seen as a subset of the full .NET Framework (for desktop applications), designed with Smart devices in mind. It consists of a smart device compatible subset of the full .NET class libraries, but it also includes some smart device specific controls. The Compact Framework uses a special version of the Common Language Runtime (a interpretive type system) which has been designed to run efficiently on mobile devices – taking into account their limited processor and memory capabilities. The .NET Compact framework supports Pocket PC 2000 and above (Pocket PC 2002; Pocket PC 2002 Phone Edition; Pocket PC.NET; Windows CE.NET), but does not yet support Microsoft Smartphone 2002. Windows CE 3 and earlier, and Handheld PC 2000 and earlier, are also not supported [Wigley et al, 2003]. 1.4 Location based services and how this project fits in 1.4.1 Motor vehicles GPS receivers in motor vehicles allow them to be tracked, as well as helping with navigation. Some companies provide assistance using GPS tracking to locate the vehicle that has broken down or has been in an accident and dispatch appropriate services to the exact location, as well as being able to provide information on clients’ medical histories to emergency teams [OnStar, 2003]. 7 Together with wireless communication technology, some companies (e.g. Motorola) provide a service that can give real time diagnostics to a driver experiencing mechanical problems such as poor fuel consumption [OnStar, 2003]. Trucking companies use GPS to track their fleets. This gives them the ability to determine where goods are at all times, and take swift action in the case of an accident or breakdown. GPS receivers and tracking systems often come with navigational aids which attempt to plot the best route between points. As more and more vehicles are fitted with tracking systems it becomes possible to use them to monitor traffic levels, and to advise routes around areas of congestion. Shortening distances and time spent travelling reduces the amount of fuel used as well as wear and tear on the vehicles, thus lowering costs. The US military also use GPS to track their vehicles, weapons and supply trucks [Deitel et al, 2001]. 1.4.2 Personal tracking and assistance A company called Digital Angel has developed a device which is built into a wristwatch that allows tracking and monitoring of people. This has application in areas such as helping people with Alzheimer’s and autism, as well as locating young children. It gives family members the ability to instantly locate them, as well as being equipped with features such as heart rate monitors that can provide information on the person’s well being, or indicate levels of anxiety. Another feature of these devices is a panic button, which will call aid to their exact location [Digital Angel, 2002; Deitel et al, 2001]. 1.4.3 Advertising An element of relevancy can be introduced to advertising using this technology, since knowing a person’s location allows companies to give them advertising only for stores that are close to them. Lucent technologies and Profilium created a service that would deliver context sensitive advertising to subscribers [Deitel et al, 2001]. 8 Systems have also been developed to provide people with requested information relevant to their location e.g. the closest restaurant. One such system is the AmsterdamToGo project which is essentially Amsterdam’s tourist information in digital form which can be accessed by internet capable mobile devices, and includes location based technologies allowing users to: “ search on keywords search through a tree diagram of categories view the number of objects per category within the radius on the screen plan a route starting from the current position view maps of current position, of the point of interest and of the route personalize favorites, settings of radius and type of transport call telephone numbers of objects without pressing the numbers ” [Geodan, 2003] 1.4.4 Security and theft The tracking technology in motor vehicles can be used to track and recover stolen vehicles. If a small cheap location identification technology is developed it will be possible to track shop and household items in the same way. Tracking technology also allows law enforcement officials to track known criminals. Pro Tech Monitoring, Inc (www.ptm.com) has developed a system that reduces criminal activity though the use of GPS to track the movements of paroled criminals[Deitel et al, 2001]. An article from the South African Sunday Times on 2nd November 2003 (page 13) described how a gang of muggers were apprehended through the use of a GPS and PDA (Personal Digital Assistant) which an anthropologist used to profile their activities. Once this system revealed how the muggers operated the police were able to ambush them on their next attack, as well as use evidence against them such as images of distinguishing footprints taken from previous attacks [Sunday Times, 2003]. 9 1.4.5 This Project The system that was developed is a skeleton location based system done to gain familiarity with the concept. It could be used as the foundation for just about any location based system. 1.5 Aim of the project 1.5.1 Primary objective The primary objective of this project was the development of an electronic location based reminder system. This system should give notification of the proximity of a location at which a reminder is set before the location is reached, sufficiently in advance to allow appropriate action to be taken (e.g. to slow down car in time to stop at store). 1.5.2 Secondary objectives The use of a GPS (Global Positioning System) receiver on a PDA (Personal Digital Assistant) meant that knowledge of the communication between these two devices would be required. The development of this knowledge would lay the foundation for future research in this field within the Computer Science Department at Rhodes University. Another desirable outcome of the project in terms of software development was a code module to assist in retrieving information from a GPS receiver. The application being developed would require this functionality, as would many other applications which intended to use a GPS receiver on a PDA. Therefore, this section of project was developed as a separate entity to allow it to be used in other programmes. 10 Chapter 2 Development of Core functionality This chapter describes the development of the location reminder application that formed the basis of this project. There were two main sections to the project, namely the communication with the GPS receiver; and the GUI driven application that formed the reminder system. To provide for reusable modular code it was logical to split these into two separate entities: a reusable DLL for communicating with the GPS called PDAGPS and the GUI driven application that uses it, Locrem (Location reminder). 2.1 GPS connectivity 2.1.1 Methodology The first stage was to create the code to retrieve the necessary data from the GPS. Initially this was done by creating a small test application consisting of two buttons to open and close the GPS port and a list-box to show any output from the port. In this test application a GPS class was developed separate from the GUI front end in order to facilitate the removal of the GPS related code to create the DLL. The final stage was to compile the class into a DLL that could be used by any application that wished to make use of a GPS 2.1.2 How to communicate with a GPS GPS receivers use a format known as NMEA 0183 (National Marine Electronics Association) to transmit data using EIA-422A. According to Klaus H. Hirschelmann [Hirschelmann, 2002] EIA-422A is RS-232 compatible for most uses. This was confirmed by the manufacturer’s website of the GPS receiver being used for this project, which simply said that the GPS emulates serial communication using standard NMEA strings. Superficially, retrieving data from the GPS appears to be a trivial task. It involves opening a serial port and reading in a sequence of NMEA strings from the GPS receiver. Serial communication is a common task so it stands to reason that there should be standard class libraries to handle serial communications, especially in a 11 development environment as large as Visual Studio .Net 2003. However, no such class library was found in the .NET Compact Framework. It has been suggested that a possible work-around to this problem is to install the ActiveX controls from Visual Studio 6 that handle serial communication (the MSComm control) [Coad, 2002]. This control however, is intended for use in desktop applications and is not supported in smart device applications. The best solution was to make use of calls through the system API, as indicated in MSDN. The four primary functions which were needed for serial communication are: CreateFile() ReadFile() WriteFile() CloseHandle() It is clear from the names of these functions that the API makes use of the conventional file abstraction for serial communications. These functions needed to be imported from the Pocket PC equivalent of kernel32.dll which was discovered to be coredll.dll. At this stage the GPS receiver would only be used for reading, so WriteFile() was not used. The C# code for importing the DLL functions is shown in Listing 3.1 Listing 2.1 DLL imports [DllImport("coredll.dll")] static extern int CreateFile( string lpFileName, int dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile) ; [DllImport("coredll.dll")] static extern int ReadFile( int hFile, Byte[] Buffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, IntPtr x); // ref OVERLAPPED lpOverlapped ) ; [DllImport("coredll.dll")] static extern int CloseHandle(int hObject) ; 12 When compared to the function description in the MSDN Library there are a few interesting points to note as illustrated with ReadFile(): Listing 2.2 ReadFile() MSDN and C# versions MSDN: BOOL ReadFile( HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped ); C#: static extern int ReadFile( int hFile, Byte[] Buffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, IntPtr x ); In the MSDN Library all parameters are C types (Listing 2.2). Converting between C# types and C types proved to be challenging, for instance, to pass a C NULL pointer in C#, without getting type mismatch errors. For the most part integers could be used (they even worked as a NULL by passing 0), but it was only after many failed attempts at using more complicated types that this was discovered. The final parameter according to the MSDN Library is of LPOVERLAPPED type, this is of particular interest to a developer of Pocket PC applications because Windows CE does not support overlapped IO (asynchronous IO) so this parameter must always be passed NULL, or as defined in the C# version “new IntPtr(0).” 2.1.3 Plan of execution PDAGPS has been designed so that a single call to an open() method is all that was required to establish communication with the GPS. This method started a new thread which opened the port using CreateFile(), configured the port, and then repeatedly read from it, putting all data read into a string which could be accessed by a method called getString(). 13 2.2 Detail of the main functionality 2.2.1 Opening the port The first important section was the opening of the port using CreateFile(). This was done in a method called openPort() (Listing 2.3) which was the starting point of the thread created in the open() method. Listing 2.3 The openPort() Method public void openPort() { // Let's try to close the Port if we have a handle CloseComm(ref handleSerialPort, port); handleSerialPort = CreateFile(port, unchecked((int)0x80000000) | 0x40000000, 0, 0, 3, 0, 0); if (handleSerialPort == -1) { status = "Error: Unable to open port: " + port + " " +Convert.ToString(handleSerialPort); return; } status = "opened " + port + Convert.ToString(handleSerialPort); configure(); readData(); } // end openPort The CreateFile() parameters passed that are worth noting (i.e. the ones that aren’t set to zero) are: “port” this is set to “COM4:” which is the default - in order to set this to any other value pass the new value to a method called setPort() e.g. setPort(“COM1:”); the parameter that follows is the non human-readable version of GENERIC_READ|GENERIC_WRITE for dwDesiredAccess; the only other non zero parameter is for dwCreationDispostion which is set to 3 or OPEN_EXISTING. 2.2.2 Configuring the port Once the port had been opened it was necessary to configure it. This was done through the use of two structs: the DCB struct which dealt with settings such as baud rate and parity, and the COMMTIMEOUTS struct which, as the name suggests, held the timeout values (Listing 2.4). 14 Listing 2.4 The DCB and COMMTIMEOUTS structs public struct DCB { public int DCBlength; public int BaudRate; public int fBinary; ///* Binary Mode (skip EOF check) public int fParity; // Enable parity checking public int fOutxCtsFlow; // CTS handshaking on output public int fOutxDsrFlow; // DSR handshaking on output public int fDtrControl; // DTR Flow control public int fDsrSensitivity; // DSR Sensitivity public int fTXContinueOnXoff; //Continue TX when Xoff sent public int fOutX; //Enable output X-ON/X-OFF public int fInX; //Enable input X-ON/X-OFF public int fErrorChar; //Enable Err Replacement public int fNull; //Enable Null stripping public int fRtsControl; //Rts Flow control public int fAbortOnError; //Abort all reads and writes on Error public int fDummy; //Reserved public Int16 wReserved; //Not currently used public Int16 XonLim; //Transmit X-ON threshold public Int16 XoffLim; //Transmit X-OFF threshold public byte ByteSize; //Number of bits/byte, 4-8 public byte Parity; //0-4=None,Odd,Even,Mark,Space public byte StopBits; //0,1,2 = 1, 1.5, 2 public char XonChar; //Tx and Rx X-ON character public char XoffChar; //Tx and Rx X-OFF character public char ErrorChar; //Error replacement char public char EofChar; //End of Input character public char EvtChar; //Received Event character public Int16 wReserved1; //Fill for now. } // end DCB Struct private struct COMMTIMEOUTS { public int ReadIntervalTimeout; public int ReadTotalTimeoutMultiplier; public int ReadTotalTimeoutConstant; public int WriteTotalTimeoutMultiplier; public int WriteTotalTimeoutConstant; } code based on code found at http://www.aciss.com/justin/io.htm and http://msdn.microsoft.com/msdnmag/issues/03/09/EditorsNote/default.aspx A convenient way to set the values for these structs was to: 1 construct instances of the structs, set them to the current settings from the port, and 2 change those values that were of interest before telling the port to use the new settings. This can be seen in the code for the configure() method (Listing 2.5). The calls to GetCommTimeouts() and GetCommState() pass the relevant structs by reference; after these calls the structs should contain the current port settings. Once relevant values 15 for each struct had been reconfigured, the port settings were set through calls to SetCommTimeouts() and SetCommState(). Listing 2.5 The configure() method private void configure() { if (handleSerialPort != -1) { DCB dcb = new DCB(); COMMTIMEOUTS ctoGpsPort = new COMMTIMEOUTS(); // Not needed for NETCF //dcb.DCBlength = Marshal.SizeOf(dcb); // SET THE COMM TIMEOUTS. GetCommTimeouts(handleSerialPort,ref ctoGpsPort); ctoGpsPort.ReadTotalTimeoutConstant = readTimeout; ctoGpsPort.ReadTotalTimeoutMultiplier = 0; ctoGpsPort.WriteTotalTimeoutMultiplier = 0; ctoGpsPort.WriteTotalTimeoutConstant = 0; bool comResult = SetCommTimeouts(handleSerialPort,ref ctoGpsPort); // Get existing Comm State GetCommState (handleSerialPort, ref dcb); // Get the default port setting information. string oldbaud = dcb.BaudRate.ToString(); // Change the DCB structure settings. dcb.BaudRate = Baudrate; // Set Baud rate dcb.fBinary = 1; // Binary mode; no EOF check dcb.fParity = 1; // Enable parity checking dcb.fOutxCtsFlow = 0; // No CTS output flow control dcb.fOutxDsrFlow = 0; // No DSR output flow control dcb.fDtrControl = 1; // DTR_CONTROL_ENABLE = 1 // DTR flow control type dcb.fDsrSensitivity = 0; // DSR sensitivity dcb.fTXContinueOnXoff = 1; // XOFF continues Tx dcb.fOutX = 0; // No XON/XOFF out flow control dcb.fInX = 0; // No XON/XOFF in flow control dcb.fErrorChar = 0; // Disable error replacement dcb.fNull = 0; // Disable null stripping dcb.fRtsControl = 1; // RTS_CONTROL_ENABLE = 1 // RTS flow control dcb.fAbortOnError = 0;// Do not abort reads/writes on error dcb.ByteSize = 8; // Number of bits/byte, 4-8 dcb.Parity = 0; // 0-4=no,odd,even,mark,space dcb.StopBits = 0; // 0,1,2 = 1, 1.5, 2 // Attempt to set new Comm state int result = SetCommState(handleSerialPort, ref dcb); if (result != 0 && !(comResult)) { status = "Error Setting State. Result: " + result.ToString(); } else status = "was: " + oldbaud + " baud, setting to: " + Baudrate.ToString() + " baud."; } else status = "Error: Comm Port not open"; }//end configure 16 2.2.3 Reading from the port Reading from the file was the core functionality of this programme. The readData() reads from the port for as long as it had a valid handle (Listing 2.6). The ReadFile() method tries to read a specific number of characters from the file. It is easy to determine what a GPS string starts with and ends with, but not how long it will be. The problem of how many bytes to read was solved by looking at the maximum number of bytes that could be read in a second. Using 8 data bits and one stop bit there should be 9 bits per byte; at 4800 baud there should be 4800/9 bytes per second, which is equal to 533 bytes. A number slightly less than this, 450, was used, partly due to the fact no strings over 350 bytes had been noted. If there was a small error in calculation the following seconds data might be read, resulting in partial strings. Thus a more conservative value was chosen. Listing 2.6 The readData() method private void readData() { int iRc = -1; int BytesToRead = 450; int BytesActuallyRead = 0; byte[] Buffer; if (handleSerialPort != -1) { // Loop and grab data from COM buffer and display in Label control while (handleSerialPort != -1) { Buffer = new Byte[BytesToRead]; iRc = ReadFile(handleSerialPort, Buffer, BytesToRead, ref BytesActuallyRead, new IntPtr(0)); // ref O); if (iRc < 1) status = "Error: Unable to read from " + port + " " + Convert.ToString(iRc); else gpsData =Encoding.GetEncoding("ASCII").GetString( Buffer,0,BytesActuallyRead); } } else status = "Error: Comm Port not open"; }//end readData The last parameter passed to ReadFile() IntPtr(0), is the null pointer being passed for the OVERLAPPED type. Surprisingly the system API for Windows CE includes parameters that it doesn’t support, but IntPtr(0) is an example of a dummy parameter being passed. 17 When the programme was set up to open the port and then create a thread to read from it, all attempts to read from the port failed, even though all of the code for opening and reading from the port looked correct. A problem with the threading was suspected; a plausible explanation for the reads failing was that they were not getting access to the port that was created in a different thread. This theory was confirmed when the opening of the port was put in the same thread as reading from it, trying to run the test code with gave a type mismatch error – the read worked! All data read in the last second was put into the string, gpsData. This was the string which was returned by the getString() method. Access to this string should probably be controlled by semaphores (locking mechanisms), but instead it was protected by trying to keep the time using it small, lowering the probability of a conflict. 2.2.4 Closing the port Closing the port consisted of a call to CloseHandle() and setting the handle value to -1 to stop the read function (Listing 2.7). Listing 2.7 The CloseComm() method private void CloseComm(ref int hComm, string strPort) { // stop reading loop bCycle = false; if (hComm != -1 ) { int result = CloseHandle(hComm); if (result < 1) status = "Error: Failed to close " + strPort; else { status = "Closed " + strPort + " Successfully"; hComm = -1; } } } // end CloseComm 2.3 Building the Location Reminder (Locrem) 2.3.1 GUI design in the .Net environment The first part of the Locrem system to be designed was the human interface. The design of the interface was use case driven with the main use cases being: 18 remind – the system shows an alert to act as a reminder to the user add location – a location is added to a list of locations remove location – remove unnecessary locations view locations – show a list of locations add reminder - a reminder is added to a location’s list of reminders remove reminder – a reminder is removed from a location’s list of reminders view reminders – display a list of reminders Developing this part of the project was made easy with the Visual Studio .NET environment due to the drag-n-drop controls onto forms functionality (Figure 2.2). When the development environment starts it is possible to choose the type of application desired and then, in the case of GUI applications, a blank form appears (Figures 2.1 & 2.2). Figure 2.1 The application type selection screen 19 Figure 2.2 A view of the .NET environment and the Toolbox 2.3.1.1 Choice of controls The remind use case required that there should be a means of displaying reminders, it would also be necessary for the programme to be able to display many reminders at once should they arise. A list box was chosen to display the names of locations near to the receiver with active reminders. Similarly list boxes were used to view locations on the LocationForm and for reminders on the ReminderForm due to their ability to display many items at once. The main form in the Locrem system ended up consisting of: a listbox to show the location names for the remind use case; labels to show information such as the current position, speed, time, the number of satellites being used out of the number in view, the status of the GPS receiver, and in the most recent version, the distance to the closest location, 20 the range of the alert mechanism; buttons to get to the ReminderForm, LocationForm, and a button to close the application (Figure 2.3). Figure 2.3 The main Locrem Form ListBox Lables Buttons The LocationForm consisted of a listbox for the locations; and buttons to add and remove locations, show the open the ReminderForm and close the location form (Figure 2.4). The ReminderForm also had a listbox for its ability to show large amounts of simple data; buttons to add and remove reminders, as well as to close the form. Two buttons were put in near the top of the form to enable scrolling through the list of locations (Figure 2.5). 21 Figure 2.4 The LocationForm Figure 2.5 The ReminderForm The scroll buttons (the ones near the top of the ReminderForm) were designed to wrap around the list, so that it scrolls from the last element of the list of locations to the first and vice versa. The code for that is shown in Listing 2.8 22 Listing 2.8 Code to move to the next location in the list private void nextLoc_Click(object sender, System.EventArgs e) { currentIndex = (currentIndex+1)%lr.getLocations().Count; updateReminderDisplay(); } 2.3.1.2 An input box It was necessary to allow for input of strings for names of locations and reminders. In order to do this an input box was created. A simple form was developed for the task. This form consisted of a prompt label, a text box for the string to be entered into and ok and cancel buttons (Figure 2.6). Figure 2.6 the InputBox At this point a problem arose: how to open a form that will wait for user input and after capturing a button click return a string to the point that opened it. The solution proved to be quite simple: after setting up the form in the show method, insert a call to ShowDialog() as demonstrated in Listing 2.9 23 Listing 2.9 Show() method for the InputBox public static string Show(string promptLabel) { InputBox inp = new InputBox(); inp.prompt.Text = promptLabel; inp.input.Focus(); inp.inputPanel1.Enabled = true; inp.ShowDialog(); if (inp.good) { return inp.input.Text; } else { return "Cancel"; } } 2.3.1.3 Timers Two Timer controls were placed on the main Locrem form. Timers have an interval, specified in milliseconds. When a Timer is enabled, it will cause a specified piece of code to be executed every time that interval elapses i.e. if the interval is set to 1000 the code will be executed every second. The one Timer was used to get data from the GPS every second, and the other was used to check for reminders every 2 seconds. The code executed by these timers will be looked at in more detail in sections: 2.3.4 Parsing GPS data; and 2.3.5 Reminders 2.3.2 Class design Using the object oriented principle of abstraction; the data model was made to tie in closely with the real life problem space. Locrem had a number of locations; each location had information about itself: a name and a position; each location also had reminders associated with it (Figure 2.7). Storing the latitude and longitude coordinates as strings was not a first choice, however, it proved to be easier to convert between various coordinate representations of the coordinates if they were stored as strings as opposed to a numeric format. The characters for latDir and lonDir (latitude direction and longitude direction) were simply ‘N’ or ‘S’ and ‘E’ or ‘W’ (Listing 2.10) . 24 Listing 2.10 The Loctn class public class Loctn { public string name; public string lat = "0.0"; public char latDir = 'N'; public string lon = "0.0"; public char lonDir = 'E'; public ArrayList reminders; public Loctn(string aname, string newLat, char newLatDir, string newLon, char newLonDir) { name = aname; lat = newLat; latDir = newLatDir; lon = newLon; lonDir = newLonDir; reminders = new ArrayList(); } } In figure 2.7 the main classes of the Locrem system are shown. The GPSComm class was part of the PDAGPS namespace, which the first part of this chapter dealt with, it has been included as a resource in the Locrem namespace and the Locrem class holds a reference to an instance of the GPSComm class to which it makes calls to open the GPS port and retrieve GPS data. No Reminder class was coded, but showing it as a class is useful in demonstrating the relationship between reminders and locations; also it is not erroneous to depict it as a class, because reminders are instances of the string class. Unfortunately use the name ‘location’ for my class could not be used seeing as C# utilises entities with similar names to determine where to draw graphical objects, so I had to resort to using a strange abbreviation as the name: Loctn. (Listing 2.10) 25 Figure 2.7 The main classes, functions and attributes of the Locrem system Aggregations were made through use of the ArrayList class, to store a list of locations; and each location in turn contained an ArrayList for its reminders. The ArrayList class is a class in the C# library that deals with lists of objects. Because ArrayList deals with objects in a generic sense it is necessary to typecast any 26 objects that are removed from it in order to restore the specific functionality of that object. The typecasting can be done by putting the class name expected in round brackets in front of the object being retrieved from the ArrayList (Listing 2.11). Listing 2.11 getLocation() public Loctn getLocation(int index) { return (Loctn)locations[index]; } Adding objects to an ArrayList was achieved by simply calling the method ArrayList.Add(), where a check was done to determine if the ArrayList locations contained the new location before adding it to the ArrayList (Listing 2.12). Listing 2.12 addLocation() public void addLocation(Loctn newLoc) { int index = getLocationIndex(newLoc.name); if (index == -1) { locations.Add(newLoc); } else { MessageBox.Show("Location already exists remove previous entry first","Name conflict error"); } } Once there were more than five locations in the list the need to sort the list of locations became apparent. Sorting an ArrayList is achieved through a call to ArrayList.Sort() as in the sortLocations() method (Listing 2.13). This method was called after loading the locations from a file where they were saved (Listing 2.15). This sort was done in case the file contained an unsorted list – as was the case the first time the Locrem system was run after sorting was added. Sorts were also done after a location was added; and just before the locations were saved to the file (as a precaution). Listing 2.13 sortLocations() public void sortLocations() { locationComparer lc = new locationComparer(); locations.Sort(lc); } 27 ArrayList.Sort() takes a parameter of type IComparer of which locationComparer was a child . This was necessary seeing as the task required of ArrayList.Sort() was to sort a list of objects. Because objects are a complex type it was necessary to define a way of determining precedence between the objects that needed to be sorted. The locationComparer class does this by using the location name as the criterion against which to sort the locations (Listing 2.14). Listing 2.14 locationComparer class – used by sortLocations() public class locationComparer : IComparer { public int Compare(object x, object y) { // TODO: Add locationComparer.Compare implementation Loctn a = (Loctn)x; Loctn b = (Loctn)y; return((new CaseInsensitiveComparer()).Compare(a.name,b.name)); } } 2.3.3 Persisting Objects It would not make sense for a user to go to every location they needed and save its position, as well as adding in all the reminders for that location every time they started up the application. It would be necessary, therefore, to ensure that all created objects persist. This was not, however, a simple case of serializing the objects and writing them to a file, because serialization was not supported by the .NET Compact Framework. Instead, it could be done using IO streams (O’Brien & Eckel,2002). In order to write the objects, a FileStream was created which was passed to the constructor for a new BinaryWriter; the objects were then written a component at a time. It was necessary to write a special identifier after the last reminder of each location to mark the end of that location. 28 Listing 2.15 Writing locations to a file private void saveLocations() { FileStream fs = new FileStream(fn,FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); if (locations.Count>0) { sortLocations(); Loctn current; for (int i = 0; i<locations.Count; i++) { current = (Loctn)locations[i]; bw.Write(current.name); bw.Write(current.lat); bw.Write(current.latDir); bw.Write(current.lon); bw.Write(current.lonDir); for (int j = 0; j<current.reminders.Count; j++) { bw.Write((string)current.reminders[j]); } bw.Write(endOfReminders); } } } In Listing 2.15 a FileStream “fs” is created using a path “fn” which is set to “LocFile.dat” and FileMode.Create which creates a new file or replaces any existing file. The BinaryWriter “bw” is then created using that FileStream, the list of locations is then sorted and written, piece by piece, to the file with a special string “endOfReminders” being used to mark the end of the location. To get the locations back again, the same sort of procedure was followed. A new FileStream was created to be passed to the constructor of a new BinaryReader. Then the locations were read in, one component at a time using the special marker to signal when to start reading in the next location. 29 Listing 2.16 Reading locations from a file private ArrayList openLocationFile() { if (File.Exists(fn)) { FileStream fs = new FileStream(fn,FileMode.Open); return readLocations(fs); } MessageBox.Show(fn+" not found. Creating new."); File.Create(fn); return new ArrayList(); } private ArrayList readLocations(Stream src) { BinaryReader br = new BinaryReader(src); ArrayList newLocations = new ArrayList(); Loctn newLoc; //blue skies - what about when there is no more to read? while(br.PeekChar()!=-1) { try { newLoc = new Loctn( br.ReadString(), br.ReadString(), br.ReadChar(), br.ReadString(), br.ReadChar()); newLoc.reminders = readReminders(br); newLocations.Add(newLoc); } catch(IOException e) { throw e; } } return newLocations; } private ArrayList readReminders(BinaryReader br) { ArrayList newRems = new ArrayList(); string next = ""; while (!(next.Equals(endOfReminders))) { next = br.ReadString(); newRems.Add(next); } newRems.RemoveAt(newRems.Count-1); return newRems; } The code in listing 2.16 would check if a file existed, if no file was found, a new one would be created, but if a file was found: a FileStream would be created to open that file, and the FileStream passed to readLocations(). readLocations() would create a BinaryReader from the FileStream and read in the locations, piece by piece, in the same order as they were written. In order to read in the reminders for each location a separate function was used, which read in the reminders until the special terminator string was read. 30 It was necessary to create a new Loctn for each location read in, otherwise the ArrayList would contain many pointers to the last location read in. 2.3.4 Parsing GPS data The updateTimer (one of the two timers on the main Locrem form) would cause the code in updaTimer_Tick() to be executed every second. This code was responsible for getting data from the GPS receiver (through PDAGPS) and extracting information from this data to update a set of local variables such as the current location, time and speed. Calls to gps.getString() would set gpsData to the most recent data from the GPS receiver (Listing 2.17). The check to see if these data were over 20 characters long was a way of determining if valid GPS data were returned. The 20 character length was chosen so that partial strings would be rejected, while still allowing for the shortest GPS string. If the data passed this test parseGPS() was called. Listing 2.17 updateTimer_Tick() private void updateTimer_Tick(object sender, System.EventArgs e) { gpsData = gps.getString(); if (gpsData.Length<20) { statusLabel.Text = "Bad GPS data. Device not ready."; } else { parseGPS(); } } 31 Listing 2.18 Description of $GPRMC String $GPRMC,201510.540,A,3318.8962,S,02631.1057,E,0.06,,210703,,*0E $GPRMC,POS_UTC,POS_STAT,LAT,LAT_REF,LON,LON_REF,SPD,HDG,DATE,MAG_VAR,MAG_REF*CC <cr><lf> POS_UTC POS_STAT LAT LAT_REF LON LON_REF SPD HDG DATE MAG_VAR MAG_REF CC <cr><lf> - UTC of position. Hours, minutes and seconds. (hhmmss) Position status. (A = Data valid, V = Data invalid) Latitude (llll.ll) Latitude direction. (N = North, S = South) Longitude (yyyyy.yy) Longitude direction (E = East, W = West) Speed over ground. (knots) (x.x) Heading/track made good (degrees True) (x.x) Date (ddmmyy) Magnetic variation (degrees) (x.x) Magnetic variation (E = East, W = West) Checksum (optional) Sentence terminator. Description of $GPRMC string taken from http://www.teletype.com/ All NMEA 0183 compliant strings end with <CR><LF> (“\r\n”) and begin with an identifying tag, and all the GPS ones starting with $GP e.g. $GPRMC (Listing 2.18). The strings were also comma delimited, which helped with parsing the individual strings (Listing 2.18). parseGPS() made a copy of gpsData called currentData and looks for the end of the first NMEA string by getting the index of the first occurrence of “\r\n” in currentData (Listing 2.19). That NMEA string was put into a string called gpsString and removed from currentData by setting currentData to itself minus the first string. The identifying tag of gpsString was then checked to see if was one of the strings containing required information, and if so being dealt with by calling a function to extract the required information from that particular string. This process would be repeated until currentData contained no more NMEA GPS strings (Listing 2.19). 32 Listing 2.19 parseGPS() private void parseGPS() { string gpsString, currentData; currentData = String.Copy(gpsData); int breakPos = currentData.IndexOf("\r\n"); …/*code to set initial values*/ while (breakPos>0) { gpsString = currentData.Substring(0,breakPos); currentData = currentData.Substring(breakPos+2); if (gpsString.StartsWith("$GPRMC")) { gotRMC = parseRMC(gpsString); } if (gpsString.StartsWith("$GPGGA")) { gotGGA = parseGGA(gpsString); } if (gpsString.StartsWith("$GPGSV")) { gotGSV = parseGSV(gpsString); } breakPos = currentData.IndexOf("\r\n"); } …/*code to update Lables*/ The parseGGA() method extracts information from a NMEA compliant GPS string (chosen for its shortness). string.Split() would return an array of strings, one string for each of the comma delimited values, and numSats was set to the value of the 7th string (Listing 2.20). Listing 2.20 parseGGA() private bool parseGGA(string gpgga) { try { numSats = Convert.ToInt16(gpgga.Split(',')[7]); } catch(FormatException e) { numSats = 0; } catch(Exception e) { return false; } return true; } 33 2.3.5 Reminders The second Timer on the main Locrem form was responsible for checking for reminders at nearby locations every 2 seconds, and displaying them in the appropriate listbox. In the reminderTick_Tick() method (Listing 2.21a) the listbox was cleared, and a check was made to ensure that there were valid latitude and longitude coordinates before proceeding. Listing 2.21a reminderTick() part A private void reminderTimer_Tick(object sender, System.EventArgs e) { double closest = 0.0; int selected = locList.SelectedIndex; int numItems = locList.Items.Count; locList.Items.Clear(); if (((curLat!=null)&&curLon!=null)&&(locations.Count>0)) { /**********3.3.5.1b**********/ } } The current latitude and longitude were converted to signed decimal coordinates, and the distance that would be travelled in alertTime seconds calculated (Listing 2.21b). Then for each location Listing 2.21c is executed. 34 Listing 2.21b reminderTick() part B int[] arl = new int[200]; double lat = convertToDecimal(curLat); double lon = convertToDecimal(curLon); double distToLoc; double lLat,lLon; if (latDir == 'S') { lat *= -1; } if (lonDir == 'W') { lon *= -1; } double spd = speed*kmNm/3.6;//current speed in metres per second double dist = spd*alertTime/1000;//distance lacation has to be in for an alert (in km) Loctn current; for (int i = 0; i<locations.Count; i++) { /**********3.3.5.1c**********/ } if (locList.Items.Count>selected) locList.SelectedIndex = selected; if (locList.Items.Count<numItems) Sound.Play(dropSound); if (locList.Items.Count>numItems) Sound.Play(alertSound); If the location had a reminder set, the locations position was converted to decimal coordinates; the distance from the GPS receiver’s current position to the location was calculated; and if the location was closer than either a minimum distance or the distance calculated (Listing 2.21b), the location was added to the listbox Listing 2.21c reminderTick() part C current = (Loctn)locations[i]; if (current.reminders.Count>0) { lLat = convertToDecimal(current.lat); lLon = convertToDecimal(current.lon); if (current.latDir == 'S') { lLat *= -1; } if (current.lonDir == 'W') { lLon *= -1; } distToLoc = distance(lat,lon,lLat,lLon,'K'); if ((i==0)||(distToLoc<closest)) closest = distToLoc; distLabel.Text = "DTCL: " +closest.ToString("####0.0##")+"km\tRange: " +Math.Max(dist,(((double)minDist)/1000)).ToString("##0.0##"+"km"); if((distToLoc<=dist)|| ((distToLoc*1000)<=minDist)) { locList.Items.Add(current.name+" ("+current.reminders.Count+")"); } } convertToDecimal() (Listing 2.22) would convert a coordinate from the form “degrees – minutes – fraction of minutes” to the form “degrees – fraction of degrees.” 35 It is easier to do this if the coordinate is stored as a string because the digits will be in fixed positions, and can be easily isolated. The approach used was to convert the coordinates to decimal degrees was to split the coordinate into 3 numbers: degrees, minutes, and seconds. This separation meant that it was possible to change the minutes without affecting the degrees or seconds. Once the values of the three numbers were appropriately altered all that needed to be done was add them together and return the result. Listing 2.22 ConvertToDecimal() private double convertToDecimal(string coordinate) { //coordinate is in the form ddmm.ssss double temp; //get the seconds double newcod = Double.Parse("0."+coordinate.Substring(coordinate.IndexOf(".")+1)); temp = Double.Parse(coordinate.Substring(coordinate.IndexOf(".")-2,2)); temp *= 100/60; newcod +=temp; temp = Double.Parse(coordinate.Substring(0,coordinate.IndexOf(".")-2) )*100; newcod+=temp; return newcod/100; } Calculating the distance between two points using latitude and longitude coordinates was quite complicated as there is no constant relationship between the latitude – longitude coordinate system and distance. Latitude and longitude are in fact a representation of the angles one needs to move through to get to the specified position from the origin. A fairly complex mathematical equation is used to perform this calculation (source code obtained from ZIPCodeWorld http:www.zipcodeworld.com) (Listing 2.23). 36 Listing 2.23 conversion code from ZIPCodeWorld private double distance(double lat1, double lon1, double lat2, double lon2, char unit) { double theta = lon1 - lon2; double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta)); dist = Math.Acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; if (unit == 'K') { dist = dist * 1.609344; } else if (unit == 'N') { dist = dist * 0.8684; } return (dist); } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //:: This function converts decimal degrees to radians ::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //:: This function converts radians to decimal degrees ::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: private double rad2deg(double rad) { return (rad / Math.PI * 180.0); } The calculation for dist (Listing 2.23) determines the angle between two points on the earth’s surface, in degrees. The next step was to multiply the number of degrees by the average number of statute miles per degree. The two if statements then give the ability to convert this distance to nautical miles, or kilometres. This function accepts coordinates in decimal degrees, which is why it was necessary to convert the coordinates to decimal degrees (Listings 2.21b & 2.21c). 2.3.6 Deployment onto the device In the Microsoft Visual Studio .NET environment, deployment of the application was very easy. The only action necessary for a programmer was, to select Deploy Solution form the Build menu. Visual Studio .NET will then compile and link the necessary files and resources (the same as a build operation in the .NET environment) and make use of a Microsoft 37 ActiveSync connection to copy the appropriate files to the device. Once the application was deployed on the device clicking on the executable would run it. .NET also has a debugging feature that could allow a programmer to debug code running on the mobile device though the ActiveSync connection. The procedure for this was as follows: The environment was instructed to debug A special deployment was performed onto the device The application was automatically launched The interaction with the application happens on the device and all debugging information appears in the development environment 38 Chapter 3 Application Environment and Field Trials This chapter describes the workings of the Locrem application as would be experieced during use; and examines experiments done to verify the accuracy of the application. 3.1 A functional description of the application 3.1.1 Startup When the application was loaded a call was made to the open() method of an instance of the GPSComm class from the PDAGPS namespace (the GPS communication DLL). The open() method would start a thread which opened a port though which it would read GPS data. The GPS data read would be stored in a string which could be accessed through a call to GPSComm.getString(). Locrem would then attempt to populate its list of locations by reading the locations in from a data file. If no file was found a new file would be created, and a message to that effect displayed, as well as a new empty list of locations being created. The final task at start-up was to enable the timers mentioned in chapter 2: one to update the GPS information, the other to check if any reminders needed to be displayed. 39 3.1.2 Front page (info and active reminders) Figure 3.1: A view of the main form in the Locrem system The aim of the first form was to display as much information about the systems status as needed. In the top left corner of the main Locrem form (Figure 3.1) the location of the device was displayed. To the right of that were shown, the speed in kilometres per hour, the number of satellites being used out of the number of satellites in view (both zero due to the screenshot being taken inside a building), and the time taken from the atomic clocks in the satellites (GMT) which was then converted to SAST (South African Standard Time) by adding the time zone attribute, +2. Underneath there was a label showing the status of the GPS receiver, which would be one of the following: Bad GPS data – device not ready. Position not fixed – need 4 satellites. Position fixed. Data valid. 40 The GPS took two seconds to open and transmit data. While this was happening the first form would display “No Data” on most of its labels. If the GPS receiver was completely uncertain of its location it would pass null coordinates causing the location to be displayed as: °`”N and °`”E. The speed, number of satellites being used and the number in view would all be 0. The time would start ticking from 0 GMT which will display as the time zone + the number of seconds; e.g. 02:00:05 for South Africa 5 seconds after the GPS starts. The first bit of information that became available from the GPS was the time, followed by the number of satellites in view and then the position and number of satellites used in determining that position. The last bit of information to be made available was the speed. The list box was used to show any active reminders. An active reminder was actually a location which was in range and had one or more reminders associated wit it A location being in range was defined by on two criteria. One called the minimum distance criterion, the other being the travel time criterion. 41 Figure 3.2 Diagram showing the reminder criteria Minimum distance 50 m 60km/h / 3.6 * 30 =500m Travel time Minimum distance was met if a location was closer than a specified distance to the position of the GPS receiver. Minimum distance was set to 50m for testing purposes (Figure 3.2). Travel time was calculated by taking the speed of the GPS and determining how far the receiver would travel in a specified amount of time. If a location was closer than the calculated distance to the receiver the travel time criterion was met. A travel time setting of 30 seconds means that travelling at 60 km/h or 16.6 m/s the range would be about 500m (Figure 3.2). If a location had a reminder (reminders.Count>0), and was in range, the name of the location would be shown in the list box (Figure 3.3 A). If a reminder was selected and then the reminder button was clicked the reminders for that location would be shown (Figure 3.4). 42 3.1.3 Screen flow Figure 3.3 Screenflow: B A C D A: Locrem form; C: Reminder form; B: Location form; D: Input box 43 Figure 3. 4 Screen samples From the main Locrem Form (Figure 3.3A) it was possible to navigate to both the Location form (Figure 3.3B), for viewing, adding or removing locations, and the Reminder form(Figure 3.3C), for viewing, adding or removing reminders. Getting to the Location form was a matter of clicking the location button, and in order to get to the Reminder form it was necessary to select a location displayed in the listbox (if any) and clicking on the reminders button. The two click process was a bit cumbersome, and a possible enhancement might be to have the necessary action to open the Reminder form from the Locrem form be to merely select the location from the listbox. In the Location form a list of all stored locations was shown. If a location was selected and the reminders button clicked, the reminders form would open, showing all reminders for the selected location. Closing the form would return the Locrem form to view. The Reminder form showed a list of all the reminders for a location. It was possible to navigate through the locations, using two buttons near the top of the Reminder form (Figure 3.3C). Closing the Reminder form would return whichever form opened it to view. 44 Both the Location form and the Reminder form make use of the InputBox to read in values when adding locations and reminders (Figure 3.3D). 3.1.4 Error checking The application was designed to check for errors at the following points: Clicking the Add location button. The application will check if the GPS position is valid before taking a snapshot of the coordinates for the new location. Adding a new location to the list of locations. The application ensures the name of the new location is not already in the list of locations. Getting the data from the GPS. If the GPS data are less than 20 characters ( 20 characters being small enough to allow all GPS strings and big enough to stop most partial reads) the application should dismiss the data as incomplete and not attempt to parse it. 3.2 Field Testing the application 3.2.1 Aim Field tests were conducted to determine the accuracy of the alert mechanism in the Locrem system by matching performance results with configuration settings. The system also needed to be capable of delivering a reminder, with sufficient warning, to allow appropriate action to be taken (e.g. to allow a person to stop the car). 45 Figure 3.5 GPS set up in car 3.2. 2 Method The GPS was set up in a car using an external antenna, which had magnetic base so that it could clip onto the roof of the car. The Locrem programme was started and a GPS fix acquired while driving to a suitable road: the road needed to be straight and flat, with an obvious mark roughly half way along it. This mark was recorded as a location named, and a reminder was added to this location in order to get reminder mechanism to trigger. The car was driven out of range of the marked test location, and then driven towards it at a constant speed. The moment the reminder sounded, the stopwatch was started and the distance from the test point noted. Constant speed was maintained until the test point had been passed. On passing the test point the stopwatch was stopped and the time in seconds was noted. This process was done at speeds of 30, 40 50 and 60 km/h; and was repeated 5 times at each speed. 46 3.2.3 Results Figure 3.6 A Alert Distance vs. Speed (corrected) 600 500 Distance 400 Distance Deviation Deviation(neg) Linear (Distance) Linear (Deviation(neg)) Linear (Deviation) 300 200 100 0 25 30 35 40 45 50 55 60 65 Speed B Time vs. Speed (corrected) 45 40 35 Time 30 Time Deviation Deviation(neg) Linear (Time) Linear (Deviation) Linear (Deviation(neg)) 25 20 15 10 5 0 25 30 35 40 45 50 55 60 65 Speed The results showed the expected trends of distances increasing proportionally to the increase in speed (Figure 3.6 A) while time remained constant (Figure 3.6 B). 47 However the actual values for both distance and time (shown in Appendix A) differed from the expected values: the measured time was about 11 seconds instead of the expected 30, and the distance was 145 instead of 500 (at 60km/h). Upon inspection of the Locrem code an arithmetic error was discovered (a case of dividing a value by a constant in a conversion, when it should have been multiplied). Once the error was corrected the effect of this correction was simulated on the results, and yielded values a lot closer to the expected results (the simulation was done by working back to the point before the error and redoing the calculation correctly). The only discrepancy being that the time values were bigger than they were supposed to be – 37 seconds instead of 30. These inflated time values could be caused by driving slower after the alert appeared than at the moment the alert appeared 3.2.4 Conclusion The alert system worked as expected. It was certainly giving advanced warning of the proximity of a reminder; and the mechanism, though inaccurate at first, works. 48 Chapter 4 4.1 Discussion and conclusion Peculiarities of the system 4.1.1 Off centre problem A moving system would attempt to alert the user to locations within 30 seconds travel time. This was done to allow the user ample time to react to a reminder. This time interval would work ideally if the location was in the direction of travel. But if the location is not in the direct path of the system the reminder would only be likely to pop up for a few seconds as it skirted though the perimeter of the alert system’s range (Figure 4.1). This could cause the user not to have sufficient time to react to the reminder, causing them to pass the desired location. This could be solved by changing the 30 second criterion to one which checks to see if a reminder is within a square with a side length twice that of the radius of circle the current system checks. However so much more computation would be required to include this check that it would outweigh the benefits. Far simpler solutions would be to increase the 30 second time value if this property becomes a problem, or mark locations closer to the road for reminders. Figure 4.1 Off Centre Problem Illustrated Supermarket Locrem system moving in the direction of the arrow Reminder Parking lot entrance 49 4.1.2 Bouncing reminders An interesting effect of the dynamic nature of the 30 second travel time reminder criterion is that it can cause reminders to pop in and out of range. The reminder pops up as it enters range, the user slows down, the range decreases and the reminder disappears. The reminder then comes within the new range and pops up again. This process can repeat causing a potentially annoying bouncing effect. This effect could be countered through a mechanism that prevents a reminder that has recently appeared from disappearing until a certain time period had elapsed. This would be similar to switch denouncing in electronics. 4.1.3 Slow starting GPS Some unexpected behaviour, which appeared to be more of a quirk of the GPS receiver than of the Locrem system, was that the GPS receiver’s first position fix would be inaccurate and then suddenly shift to an accurate fix. After starting up, the GPS receiver would take a little while to get a position fix; this time was found to range anywhere from a few seconds to minutes. The receiver would then transmit data which was tagged as a valid fix. However, this first fix was often inaccurate and could be off by over 100 metres. Waiting for another minute or so would allow one to witness a sudden position shift in the data being delivered by the GPS, resulting in accurate coordinates. Being an inherent property of the GPS there is nothing, within the scope of the system, which can be done about it. 4.2 Problems encountered 4.2.1 Serial Communication The first part of chapter 3 described the development of a class to communicate with a GPS receiver using serial communication on a PDA. However C# and the .NET compact framework did not have any managed code libraries concerning serial communication. This made this part of the project harder than anticipated. 50 The way to do the serial communication was to import system API functions from coredll.dll. (see 2.1.2) 4.2.2 Serialisation Serialisation was not supported by the .NET compact framework. The solution to this was to use IO streams to read and write classes to and from a file, one component at a time. (see 2.3.3) 4.2.3 Threads A serial IO is slow. When performing reads, one does not want to have the read happen in the same thread as the rest of the execution of the programme due to the time wasted waiting for the IO to complete. The solution to this is to put the IO in a separate thread. However, a mistake made at one point in this project was to open the port in one thread and try to read from it in another. When this was done the thread did not have the correct access to the port, and as a result the reads always failed. The solution to this was to ensure that the port, and functions that make use of it, run in the same thread. 4.3 Opinion of the .NET Compact Framework It has been a pleasure working in the Visual Studio .NET 2003 environment. Features of the environment, such as auto-complete and pop-ups which described the parameters needed for functions, together with the Compact Framework class libraries saved many hours of development time. The usefulness of the class libraries was emphasised whenever there was a task that was not specifically by the Compact Framework. The code for these sections always ended up being a lot more complex, and would take a lot longer to develop than sections which were supported by the Compact Framework. Two particularly impressive features of the development environment used during the course of this project were: 51 1. when developing a class that inherits from another, after specifying the inheritance, hitting tab would cause the environment to fill out the required skeleton for that class. 2. the ability of the environment to debug code running on a mobile device from the desktop. Most of the omissions to the .NET Compact Framework encountered in the development of this project were some of the function overloads, and generally obscure ones at that. That being said, there were definitely holes in the supported functionality of the Compact Framework – e.g. no serial communication, no serialisation. However, there was always a way to do the desired task; it just took more work when not directly supported. On the whole working in Visual Studio .NET 2003 with the .NET Compact Framework has been an experience that does not incline one to revert to simple text editors. 4.4 Features to be included in future versions There are a few features which, if they had been included in the .NET Compact Framework, would have made the development of this project far easier. These are: 1. Serial communication support – this would have made the development of the GPS communication side of the project a relatively effortless task 2. Serialisation – this was a surprising feature not to have included in the Compact Framework 3. Multimedia support – this would have helped the playing of simple sound files as alert tones 4.5 Extensions 4.5.1 Enhancements A useful enhancement already mentioned in chapter 3 would be to improve the process to view the reminders of a location displayed on the main Locrem form. Instead of having to select the location and then click the reminders button, one should be able to click on the location and proceed directly to the Reminder form. 52 The introduction of categories of location would be a great enhancement. This would mean that a reminder added to the supermarket category, for example, would pop up if any supermarket is nearby. The system used a time zone setting to convert the time taken from the satellites from GMT to the local time zone. There were also settings for how close a location should be before one is notified of reminders for that location, as well as how many seconds away the location should be if one is moving. But there is no place to set these values outside of the code. Therefore it is necessary to add the functionality to define these settings. Another possible enhancement is the addition of a time factor. This would have two variations: 1. a time factor which will trigger irrespective of location – these are the same as current electronic diary reminders e.g. A doctor’s appointment would need to show regardless of the distance to the doctor’s offices 2. a location time dependency – this is a reminder that will trigger at certain times if one is near a location. This type of reminder would only remind one to get something from a shop at times when the shop is open, for example. 4.5.2 Extensions The system developed in this project was a simple system. The underlying mechanism was the focus of the project. The application of this underlying mechanism was developed as far as to be useful, yet not taken far enough to show the true potential of this type of system. The following paragraphs illustrate what could be developed out of this work. 4.5.2.1 Tour guide This system could be developed into a virtual tour guide. As a tourist nears a location of particular interest – such as a museum or building of historical significance - the system could present both text and audio information on that location. Further enhancements might give the system the ability to direct tourists to locations, and 53 possible even plan a tour route. This is also useful for orientation at a new campus, say for new students, visiting or prospective parents or new faculty staff. 4.5.2.2 Field experiment data capture With field work there are often particular locations that are the focus of research. These can be particular plants, watering holes, or in marine work reefs or canyons. This type of system could be used to alert one to the proximity of such a location, display summaries of previous data collected at that site, and even pop up the relevant form to speed up data capture at that location. A more specific example of a unique use of such a system would be in the current African Coelacanth Ecosystem Programme. As they approach the site of an undersea canyon, such a system could pop up information on previous coelacanth sightings, the exact location of each sighting, the depth, the maximum number of coelacanths sighted at each point as well as the frequency of sightings. 4.5.2.3 Event Guide In a large sporting event or festival there is often a lot of information relating to happenings at various locations. At a festival, a system would act as a programme of events, which could also allow one to book for events on-line, and give instructions on how to get to the venues, as well as being able to recommend attractions in the vicinity. In a sporting event such as a golf championship, where spectators are inclined to wander around, a system could supply spectators with information on which players were playing on nearby holes, and be able to give background information on the players. It would also be useful to provide access to information such as a real-time leader board, and to allow a fan to locate their favourite player on the course as well as show them how to get to them. 54 4.6 Conclusion In terms of the primary objective the project was a success. Through use of the .NET Compact Framework a working system was developed in which reminders popped up well before the location was reached. This shows that it is indeed possible to do this kind of programming using the .NET Compact Framework. A DLL has been created that can read data from a GPS receiver on a PDA which could be used in future programmes. Location based services have wide ranging use and versatility, for example, the animal tracking application that was used to profile criminals [Sunday Times, 2003]. This project should serve as a resource in the department for future work in the area. 55 References: [Ashley, 2003] Ashley, S., Next-Generation GPS, Scientific American, September 2003 issue, http://www.sciam.com/article.cfm?articleID=000B4F14-3F8A-1F45B0B980A841890000&catID=2, 2003 [Brain & Harris, 1998 – 2003] Brain, M., Harris, T., How GPS Receivers Work, http://travel.howstuffworks.com/gps1.htm [Coad, 2002] Coad, N., Serial COM Simply in C#, http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=320 [Deitel et al, 2001] Deitel, H., Deitel, P., Nieto, T., & Steinbuhler, K., Wireless Internet and Mobile Business How to Program, Prentice Hall, NY, 2001 [Digital Angel, 2002] Digital Angel Corporation, http://digitalangel.net/, 2002 [Geodan, 2003] Geodan, AmsterdamToGo, http://www.geodan.nl/uk/project/AmsterdamToGo/AmserdamToGo.htm [Hirschelmann, 2002] Hirschelmann, Klaus H., NMEA 0183, http://www.khgps.de/nmea-faq.htm, 2002 [Leick, 2002]– Leick, A., How do GPS devices work?, Scientific American http://www.sciam.com/askexpert_question.cfm?articleID=000349D4-D6FC-1CFC93F6809EC5880000&catID=3 [O’Brian & Eckel, 2002] O’Brian, & L., Eckel, B. Thinking in C#, Prentice Hall, New Jersy, 2002, pp. 509-531 [Onstar, 2003] OnStar Corp., http://www.onstar.com/us_english/jsp/whatisonstar/idont_whatisonstar.jsp, 2003 [Smithsonian Institution, 1998] Smithsonian Institution, How Does GPS Work?, http://www.nasm.si.edu/galleries/gps/work.html, 1998-2003 56 [Sunday Times, 2003] Lombard, E., Bushman tracking catches muggers, Sunday Times (South Africa), http://www.sundaytimes.co.za/2003/11/02/news/news14.asp, 2003 [Trimble Navigation, 2003] Trimble Navigation Limited, All about GPS, http://www.trimble.com/gps/ [Wigley et al, 2003] Wigley, A., Wheelwright, S., Burbidge, R., MacLeod, R., Sutton, M., Microsoft .NET Compact Framework (core reference), Microsoft Press, 2003 57 Glossary API AOA COO DLL E-OTD GMT GPS GUI ICBM Locrem MSDN Application Programming Interface Angle of arrival Cell of origin Dynamically Linked Library Enhanced observed time difference of arrival Greenwich Mean Time Global Positioning System Graphical User Interface Inter Continental Ballistic Missiles Location Reminder Microsoft Developer Network (can be thought of as a documentation library for using Microsoft development tools) NMEA National Marine Electronics Association National Marine Electronics Association NMEA NMEA-0183 A standard used for presenting GPS data defined by the NMEA Personal Digital Assistant PDA PDAGPS The section of the project developed for communication with a GPS receiver A serial communication protocol RS-232 Time difference of arrival TDOA 58 Appendix A: Test results The original readings were: Speed: Reading 1 2 3 4 5 Average Sdev Speed: Reading 1 2 3 4 5 Average Sdev 30 Distance (metres) 40 50 60 80 77 71 75 76 94 94 93 94 104 124 122 128 128 121 141 128 164 147 140 75.8 3.27 95.8 4.60 124.6 3.29 144 13.13 Time (seconds) 40 50 60 30 13 10 11 10 11 10 11 10 10 11 11 11 12 11 11 11 10 11 12 11 11 1.22 10.4 0.55 11.2 0.45 11 0.71 59 The corrected values were: Speed: Reading 1 2 3 4 5 Average Sdev Speed: Reading 1 2 3 4 5 Average Sdev 30 Distance (metres) 40 50 60 274 264 244 257 261 322 322 319 322 357 425 418 439 439 415 484 439 563 504 480 260 11.22 329 15.79 427 11.27 494 45.05 Time (seconds) 40 50 60 30 45 34 38 34 38 34 38 34 34 38 38 38 41 38 38 38 34 38 41 38 38 4.20 36 1.88 38 1.53 38 2.43