Ambient Networks Mobile phone integration

Carlos Rocha, Rui Botelho

PSTFC FEUP – DEEC 2004

Ambient network - Mobile phone integration

Supervisor professor: Prof. Manuel Alberto Pereira Ricardo

Project supervisor: Prof. Mário Jorge Moreira Leitão

Department: Department of Electrical and Engineering

Institutions:

Faculty of Engineering at University of Oporto

Institute of Engineering and Computer Systems of Oporto

i About the authors

Carlos Rocha

Carlos is a student at FEUP since 1999. Carlos first experience on came with the acknowledgment of the project in the end of 2003. The work on this subject continues at the time of this writing.

Student number: 990503145

E-mail: [email protected]

Telephone: 961818010

Rui Botelho

Rui is also student at FEUP since 1999. As with Carlos, Rui Botelho heard about Symbian in late 2003 as it was a project proposal of Prof. Manuel Ricardo. Since then, this area has been one of his main interests.

Student number: 990503146

E-mail: [email protected]

Telephone: 963379295

ii

We would like to thank Professor Manuel Pereira Ricardo for believing in this work and helping us to overcome the problems that we met along the semester.

We also would like to thank our colleagues, Filipe Abrantes, Ricardo Duarte and António Madureira for all the work done in the integration of our projects.

A special thank you note goes to Filipe Sousa from INESC for all the help and support given.

iii Contents

1. Introduction 1.1 Overview...... 1 1.2 Objectives ...... 2 1.3 Results ...... 3 1.4 Report structure ...... 4 2. Symbian OS 2.1 Introduction to Symbian OS...... 6 2.1.1 Symbian History ...... 6 2.1.2 Symbian OS Structure ...... 7 2.1.3 Networking infrastructure...... 10 2.2 Java programming for Symbian ...... 12 2.2.1 Introduction...... 12 2.2.2 Java and Symbian ...... 12 2.2.3 Programming essentials ...... 14 2.3 Symbian C++ programming...... 16 2.3.1 Getting started...... 16 2.3.2 Development basics ...... 17 2.3.3 Applications structure...... 18 2.3.4 Implementation Details...... 21 2.4 Summary ...... 23 3. PC connectivity 3.1 Introduction ...... 24 3.2 notes ...... 25 3.3 connectivity under Linux ...... 26 3.4 Summary ...... 27 4. Project description 4.1 Overview...... 28 4.2 Fundamentals...... 30 4.3 Application structure ...... 33 4.4 Networking...... 45 4.5 Results...... 50 4.6 Summary ...... 51

iv

5. Project evaluation 5.1 Testing procedure...... 52 5.2 Test validation...... 54 6. Conclusion 6.1 Review of objectives and results...... 55 6.2 Main conclusions...... 55 6.3 Future work...... 56 Appendix A – Symbian’s History...... 57 Appendix B – How to create a Java application ...... 61 Appendix C – First approach to Symbian C++ programming...... 64 Appendix D – How to create a C++ application...... 65 Appendix E – Building an application...... 66 Appendix F – How to create a simple installation file ...... 69 Appendix G – The Communications classes ...... 70 Appendix H – Using active objects ...... 76 Appendix I – Sockets API ...... 79 Appendix J – Using Bluez tools ...... 96 References ...... 101

v Acronym list

ACL – Asynchronous Connectionless packet

AVKON Series 60 extensions and modifications to Symbian’s Uikon and other parts of the Symbian OS Application Framework. CBA - Command Button Area, i.e. toolbar

CDC – Connected Device Configuration Defines a Java runtime environment for “high end” consumer devices with constrained hardware resources such as set top boxes, PDAs and Communicators. Falls under the J2ME umbrella.

CLDC – Connected Limited Device Configuration Defines a Java runtime environment for devices with highly constrained hardware resources.

CommDb Communications database offered by Symbian. It provides access to extensible database which holds information about internet access, GPRS connections, WAP settings, proxy servers

DBMS – Database Management System Defines a general relational database access API, and allows different database implementations to be provided. DUN – Dial-Up Networking profile

FTP – File Transfer Profile

GAP – Generic Access Profile

GOEP – Generic Object Exchange (OBEX) Profile

GPRS – General Packet Radio Service

vi GSM – Global System for Mobile Communications. GSM is the world’s most widely-used digital mobile phone system.

HCI – Host Controller Interface

HTTP – HyperText Transfer Protocol

IDE – Integrated Development Environment

JABWT - Java API for Bluetooth Technology An optional API that allows J2ME applications to access Bluetooth functionality.

JAD – Java Application Descriptor (file)

JAR – Java Archive (file).

Java Industry standard object-oriented language and virtual machine, invented by Sun Microsystems and formally released in 1996. Java is an ideal language for network applications and applets. Sun's Java specifications include many Java APIs and platforms, including the JavaPhone API and PersonalJava platform, which are included in Symbian OS.

J2ME – Java 2 Platform, Micro Edition. The edition of the Java platform that is targeted at small, standalone or connectable consumer, and embedded devices. The J2ME technology consists of a virtual machine and a set of APIs suitable for tailored runtime environments for these devices. The J2ME technology has two primary kinds of components – configurations and profiles.

JavaPhone A Java API specification controlling contacts, power management, call control, and phonebook management, intended specifically for the programmability requirements of mobile phones.

JCP – Java Community Process An open organisation of Java developers and licensees whose charter is to develop and revise Java technology specifications, reference implementations, and technology compatibility kits.

vii JSR – Java Specification Request The process by which new Java specifications are defined. Part of the Java Community Process. JTAPI – Java Telephony API The Java Telephony API is an extensible API that offers an interface to all call control services (from those needed in a consumer device up to those of call centers). JTAPI is part of the JavaPhone API.

JTWI – Java Technology Wireless Initiative An initiative to provide a roadmap of mobile phone related JSRs, indicating their availability in different markets around the world a specification describing the essential client components of an end-to-end wireless environment also to provide a Reference Implementation of the technology and a Technology Compatibility Kit.

JVM – Java Virtual Machine.

Kernel Core of an , a kernel manages the machine’s hardware resources (including the processor and the memory), and provides and controls the way any other component can access these resources. The kernel runs with a higher privilege than other programs (so-called user-mode programs). The power and robustness of an OS's kernel play a major role in shaping overall system design and reliability.

L2CAP – Logical Link Control and Adaptation Protocol

MIDlet An application written for the Mobile Information device profile (MIDP)

MIDP - Mobile Information Device Profile Vertical extension of CLDC. Defines an API set for Mobile information devices such as cell phones.

MMA – Mobile Media API An optional API providing a high level interface to sound and multimedia capabilities.

MMC – MultiMedia Card

viii OBEX – Object Exchange protocol A set of high-level protocols allowing objects such as vCard contact information and vCalendar schedule entries to be exchanged using either IrDA (IrOBEX) or Bluetooth.

OPP – Object Push Profile

OTA – Over-the-Air

Pairing Authentication Procedure for ensuring the identity of a Bluetooth device by using a link key.

PDA – Personal Digital Assistant

PersonalJava A Java platform optimized for the requirements and constraints of mobile devices.

Piconet – Bluetooth network

PC –

PPP – Point-to-Point Protocol

Proxy An intermediary program, which acts as both a server and a client for the purpose of making requests on behalf of other clients.

RFCOMM – Protocol emulating RS-232

Scatternet – Network of multiple piconets

SCO – Synchronous Connection-Oriented packet

SDP – Service Discovery Protocol

SDK – Software Development Kit A collection of tools used to develop applications.

ix SMS – Short Message Service Service available on digital GSM networks allowing text messages of up to 160 characters to be sent and received via the network operator's message centre to a mobile phone, or from the Internet, using a so-called "SMS gateway" website. If the phone is powered off or out of range, messages are stored in the network and are delivered at the next opportunity.

SPP – Profile

Symbian OS Symbian’s advanced open standard operating system for data enabled mobile phones. It includes a multi-tasking multithreaded core, a user interface framework, data services enablers, application engines and integrated PIM functionality and wireless communications.

UEI - Universal Emulator Interface Interface enabling integration of emulators with tools such as the Wireless Toolkit.

UI – User Interface

UID – Unique Identifier

UMTS - Universal Mobile Telecommunications Service A 3G standard supporting a theoretical data throughput of up to 2 Mbps.

WAP – Wireless Application Protocol A set of communication protocol standards to make accessing online services from a mobile phone simple. WAP was conceived by four companies: Ericsson, , , and Unwired Planet (today called Phone.com). The WAP Forum is an industry association with over 200 members.

WINSCW Windows emulation platform for the Symbian OS (Metrowerks CodeWarrior)

WMA – Wireless Messaging API An optional API providing access to wireless messaging resources including SMS.

x Figure List

Figure 1 – Integration of a mobile phone in an AmI scenario ...... 1 Figure 2 – Symbian’s OS structure ...... 7 Figure 3 – Networking architecture in Symbian OS ...... 10 Figure 4 – Multihoming concept...... 11 Figure 5 – Matching functionality to market needs and Symbian OS Java performance...... 12 Figure 6 – Java2 platform...... 13 Figure 7 – MIDP 2.0 in Symbian OS v7.0s...... 13 Figure 8 – KToolbar main window and Sun One Studio 4 ME...... 14 Figure 9 – Series 60 MIDP Concept SDK Beta 0.3.1, Nokia edition and KToolbar settings menu...... 15 Figure 10 – Series 60 emulator running a GUI application and a console application ...... 18 Figure 11 – Application launching sequence and user interface architecture...... 19 Figure 12 – Bluetooth protocol stack ...... 25 Figure 13 – Mobile phone/PC Bluetooth connectivity...... 26 Figure 14 - Mobile phone integration scenario ...... 28 Figure 15 – Service advertisement/request procedure ...... 32 Figure 16 – View 1...... 35 Figure 17 – Options menu 1...... 35 Figure 18 – View 9...... 36 Figure 19 – View 2...... 36 Figure 20 – Options menu 2...... 36 Figure 21 – View 6...... 37 Figure 22 – Options menu 6...... 37 Figure 23 – View 8...... 38 Figure 24 – Options menu 8...... 38 Figure 25 – MODEM_BEARER table information...... 38 Figure 26 – View 5...... 39 Figure 27 – Options menu 5...... 39 Figure 28 – Interface information ...... 39 Figure 29 – View 7...... 40 Figure 30 – Options menu 7...... 40 Figure 31 – Route information ...... 40 Figure 32 – Route introduction ...... 41

xi Figure 33 – Options menu...... 41 Figure 34 – Flow diagram of the SMS sending process...... 43 Figure 35 – Flow diagram of the picture service...... 44 Figure 36 – Ipv6 network configuration...... 49 Figure 37 – Views of a test application on emulator and ...... 52 Figure 38 – Internet connection sharing architecture...... 53 Figure 39 – Architecture used in the SMS service test phase...... 53 Figure 40 – Architecture used in the picture service test phase ...... 54 Figure 41 - Flow diagram showing the life cycle of an active object ...... 77 Figure 42 – Lifecycle for data exchange using datagrams...... 80 Figure 43 – Lifecycle for data exchange using streams ...... 81

Table list

Table 1 – File constitution of a minimum GUI application ...... 20 Table 2 – Main GUI systems...... 64 Table 3 – File types list...... 68

xii

1. Introduction

1.1 Overview

This project was born of the idea of having a simple cell phone, running Symbian OS, integrated in an Intelligent Ambient Network thus communicating, offering or using services of other devices belonging to the same ambient network. This new type of concept is called Ambient Intelligence, it characterises a system where its participants are able to adapt themselves to the medium, sensing, communicating and processing data. As this type of network is populated mainly by mobile devices, the communication between them is made essentially by wireless technologies like Bluetooth and Wireless LAN. A cell phone introduces new resources to the AmI Network like GPRS access offering more connectivity to AmI participants providing new type of services. In this case, the integration of the mobile phone in the AmI Network was made by having the phone offering services. Having a simple phone offering a SMS service, that allows an AmI component to send SMS messages and a picture service that takes advantage of the phone’s digital camera to provide a video stream, to be viewed in another device, are remarkable demonstrations of the AmI concept.

Figure 1 – Integration of a mobile phone in an AmI scenario

1 1.2 Objectives

As this project is focused in a new operating system, it has specific objectives inherent to this fact. The main objectives are:

Study of Symbian Operating System Symbian is an operating system that holds an important place in the mobile phone market, therefore, as a primary objective, stands the need to understand this new OS, to know its capabilities and limitations. The increasing importance of this OS justifies the need to have it as a project subject.

Study of Symbian’s main programming languages potential The Symbian OS implementation has several programming languages. These languages have different characteristics, advantages, and difficulties. In order to assess its potential it is necessary to perform an evaluation of its API’s namely the Java and C++ APIs.

Testing and experimenting Symbian OS communication capabilities One of the main features of this OS is its communication capabilities. This characteristic encourages the development of applications with multi connectivity features namely GPRS, GSM and Bluetooth.

IP connectivity over Bluetooth This is the fundamental communication strategy of the in the Ambient Network. Due to its importance it’s desirable that this aspect is well explored, in order for it to act as the starting point to all kind of new functionalities and services. The use of IPv6 over Bluetooth is preferable.

Integration in ambient networks As Symbian is a powerful operation system, and in order to confirm its excellent characteristics, a decisive test is to use them to allow the integration of a mobile phone in an ambient network that until now is a privilege of more complex devices like PDAs, laptops or personal .

2 1.3 Results

This project achieved extremely motivating results for the consolidation of the Ambient Network concept, as the full integration of a mobile phone was achieved. The main results of this project can be divided in two parts. The first one is concerned with the knowledge gained with the study of Symbian OS and the other one is the practical demonstration of the integration of the mobile phone in a network using the developed application. As Symbian was an unknown OS, the first thing to do was the study of its capabilities and programming languages. The experimental development made with Java programming language and the evaluation of its APIs gave an overall idea of its capabilities, advantages and disadvantages. In the case of the native programming language, all the wok developed, study and implementation allowed a good acknowledgement of Symbian’s C++ programming. Although designed for the specific requirements of mobile phones this OS offers all the tools as others designed for more complex devices. Symbian includes a robust multi-tasking kernel, integrated telephony support, communications protocols, data management, advanced graphics support, a low-level graphical user interface framework and a variety of application engines. Symbian OS provides a rich core of application programming interfaces that crucial for development, particularly when using communication protocols. Symbian’s communication capabilities were extensively tested, except in the case of Infrared technology, as it is of less interest. Multiple GPRS tests were made and total connectivity to a server was accomplished, proving the possibility of using this technology for integration purposes. The basis for communication between the phone and other devices is the IP connectivity over Bluetooth. Using IPv6 over Bluetooth instead of over GPRS or GSM data is the main step for the integration of the mobile phone and therefore it’s one of the most important results. The application developed achieves the full integration of a mobile phone in a network. The integration is done by providing services to other participants in the ambient network, in this case a SMS and a picture services. The SMS service allows other devices with IP connectivity to the phone to send SMS messages by using the GSM/GPRS network through the smartphone. The picture service gives the chance to use the onboard camera of the phone almost as a webcam. Other features were added to the application because of its utility. Using the application, the user can see the interfaces, routes and the internet database setting to check important information very useful when setting up a network.

3 1.4 Report structure

This report is arranged in sections that are composed by individual topics, each of which is arranged in subsections. Each section is dedicated to a topic that was subject of study of this project. The first section is an overview of the project work, the second section gives an introduction to Symbian OS and its programming languages and section three is dedicated to the connectivity between a Linux PC and the phone. The fourth section makes a description of the work developed in this area and the following section is dedicated to the validation of the project results. Finally the last section draws a conclusion of the project work. The structure of this report is as follows: ƒ Section 1 – this section. Introduction to the project work stating the overall idea as well as the main objectives and results. ƒ Section 2 – provides a general introduction to Symbian OS and its main programming languages. o Subsection 1 – in this section are stated important concepts and fundamental information related to Symbian OS architecture and technologies. o Subsection 2 – in this part is made a resumed approach to Java technology and programming for Symbian OS. o Subsection 3 – this section is dedicated to the native Symbian programming language. This is a complete resume of Symbian’s C++ programming. The section starts with an elementary overview of C++ for Symbian then follows a description of the development basics, Symbian’s application structure and networking fundamentals. ƒ Section 3 – offers a guide for establishing PC connectivity with a Symbian mobile phone and a Linux PC using Bluetooth. This section describes the configurations of both Linux PC and mobile phone. ƒ Section 4 – depicts the project description stating the work done over the project’s duration. It starts with an overview of the work, then is presented the project fundamentals and described the structure of the developed application. In the end is described the networking capabilities of the application and presented the project results. ƒ Section 5 – project evaluation. This section describes the testing procedure of the developed application and its validation. ƒ Section 6 – in this last part the project’s work and results are reviewed and future work is suggested. ƒ Appendix A – Symbian’s History ƒ Appendix B – How to create a Java application ƒ Appendix C - First approach to Symbian C++ programming ƒ Appendix D – How to create a C++ application ƒ Appendix E – Building an application ƒ Appendix F – How to create a simple installation file ƒ Appendix G – The Communications Database classes

4 ƒ Appendix H – Using active objects ƒ Appendix I – Sockets API ƒ Appendix J – Using Bluez tools

5 2.1 Introduction to Symbian OS

2.1.1 Symbian History

The desire to be contactable at any place at any time made the cell phone an indispensable gadget for the everyday use. Most of the people already take for granted the ability to make and receive calls from anywhere at any time, but only a few yet take advantage of instantly having access to any data at any time from that very same mobile phone. The growth of wireless computing belongs to the smartphone, a powerful device that extends the voice functionality of a mobile phone into the realm of data communications. The phenomenon of the mobile phones is quite impressive and now a new generation of powerful mobile phones equipped with amazingly sophisticated software rises, offering its users a vast group of services like the exchange of pictures, emails, etc. In just a few years a vast number of people will carry handsets with colour screens, cameras, music players, support for downloadable games, and other features that are now available only in the most advanced models. But these are only the first services because the so called possess advanced computing capabilities and have the ability to handle and host a number of applications, taking mobiles phones to a next level, letting them behave like small computers. The features presented by this devices such as GPRS, IR or Bluetooth controlled by a powerful OS assures that its users are "always best connected", with the phone always jumping in and out of the networks, contacting with other phones and larger computers, acting as organizers, mobile information portals, entertainment devices and clients to all kind of sophisticated data services and other compelling add-on software. All these features facilitates both simple capabilities like easily calling someone by highlighting the phone number in their email signature, to more advanced integrated and interactive messaging capabilities. All of this is possible due to the software that lies in the core of these phones, the Symbian OS. Symbian is an advanced, open operating system licensed by the world's leading mobile phone manufacturers. It is designed for the specific requirements of advanced 2G, 2.5G and 3G mobile phones. The Symbian coalition started out with the goal of developing an open standard operating system for existing and next generation interactive multimedia devices called smartphones. Symbian OS turned out to be a full operating system in terms of functionality and compact enough to fit in the memory of a mobile phone. It includes a robust multi-tasking kernel, integrated telephony support, communications protocols, data management, advanced graphics support, a low-level user interface framework and a variety of application engines. Symbian was established as a private independent company in 1998 with contributing EPOC32, which was used on PDA’s. Initially Symbian was owned by Psion, Ericsson, Motorola, Nokia, Matsushita (Panasonic) but soon other manufacturers like Samsung and Siemens joined the group. The first platform release of Symbian OS was v5.0 which was used in the Psion Series 5mx and PDAs. The was the first device using Symbian OS 6.0 and the imaging phone is built on Symbian OS 6.1. The latest available version of Symbian, at this time, is version 7.0 but its successor, v8.0 is already prepared to equip which will soon be available. The Symbian operating system provides a full C++ API and a Java Virtual Machine. In addition, Symbian OS provides a flexible user interface (UI) framework that enables mobile

6 phone manufacturers to differentiate their products and produce innovative UIs for families of mobile phones such as mobile phones with a numeric keypad, mobile phones with touch screens and mobile phones will full QWERTY keyboards and large colour screens.

2.1.2 Symbian OS Structure

Symbian OS is constituted by a series of elements disposed in layers that combined together produce software that controls the mobile phones. The following picture provides a general overview of the operating system.

Figure 2 – Symbian’s OS structure

Symbian OS provides a rich core of application programming interfaces that are common to all Symbian OS phones. Key elements of Symbian OS in its 7.0 version are:

• Telephony The telephony subsystem provides a multimode API to its clients. This abstract cellular stack makes it easier for handset manufacturers to port Symbian OS from one mobile phone standard to another. The multimode telephony abstraction in Symbian OS is key to providing integration with the rest of the operating system and to enabling the creation of advanced data services. Supported global network standards include: GSM, GPRS, CDMA2000, EDGE (ECSD, EGPRS), WCDMA. • Networking services This contains the key frameworks and system services for wide area network communications. It provides a framework for implementing various communication protocols through a socket interface. The following functionality is: TCP, IPv4, IPv6, IPSec, WAP stack, Multiple PDP contexts, Multihoming.

7 • Messaging The messaging framework provides support for messaging protocols for sending and receiving of text messages (SMS), enhanced messages (EMS), multimedia messages (MMS), email (including POP, SMTP and IMAP functionality) and fax messages.

• Multimedia The Multimedia Framework (MMF) provides a lightweight, multi-threaded framework for handling multimedia data. The framework provides audio recording and playback, audio streaming and image related functionality. Support is provided for video recording, playback and streaming and an onboard camera API providing a consistent interface to basic camera functions. The framework allows developers to write efficient and powerful plug-ins. • Graphics It provides Symbian OS applications with shared access to the screen, keyboard and pointing devices input, bitmap fonts and scalable fonts. It also includes anti-aliasing support, direct screen access and 2D hardware Abstraction layer. • Applications engine Core to any mobile phone is the handling of user data. Symbian OS provides highly optimised engines and API’s for agenda (schedule), to-do, contacts, spreadsheet, alarm and world servers and the help engine. • Applications framework As Symbian OS is oriented to small handheld devices the user interface is extremely important, it has to be simple and easy to use, change and program. In addiction, different mobile phones have different device needs, so the applications framework subsystem provides a powerful environment for licensees and partners to create differentiated user interfaces while enabling applications written in C++ and Java, by Symbian, licensees, partners and third parties to run seamlessly on open Symbian OS phones. Currently, the core GUI components are Uikon (for pen based devices) and Standard Eikon. The UI Toolkit provides generic user interface tools used in development of user interfaces. The objective is to reduce the amount of effort required for UI development. When developing applications the main features of the GUI framework, among others, are: an event-driven GUI and widget architecture, a windowing system for sharing screen, keyboard and pointer between applications and a flexible screen indicator and status bar framework. • PAN connectivity Personal Area Networking connectivity is available through support of Bluetooth, serial, USB, infrared (IrDA) and Ethernet devices. Bluetooth support is provided with a core Bluetooth 1.1 protocol stack along with full Generic Access Profile (GAP), Generic Object Exchange Profile (GOEP) and Serial Port Profile implementations. The Host Controller Interface (HCI) provides a hardware interface via a UART based reference implementation. The OBEX implementation provides an OBEX v1.2 client and server that operate over Bluetooth and IrDA. The OBEX server also provides USB support. USB class support is provided for the WMCDC WHCM and OBEX class, and for the CDC ACM class. All classes are controlled by a USB Manager component.

8 The infrared IrDA stack is contained in a socket server protocol module that implements the following IrDA layers: IrLAP v1.1, IrLMP v1.1 and IrTinyTP v1.1. The supported features are: infrared (SIR) supporting throughputs of 9.6 Kbit/s to 115.2 KBPS, IrOBEX v1.2, IrTRANP v1.0, IrCOMM v1.0. • Base The Base subsystem provides the programming framework for all other components of Symbian OS. Base facilitates the design across multiple platforms and resources, making it easier to port Symbian OS to new types of hardware. The heart of the Symbian OS is the core operating system: a collection of device drivers, data tables, and programs that allows the user to work with computer’s hardware. Symbian OS is based on a small and efficient kernel that ensures robustness, performance and efficient power management – all important in mobile devices. Symbian OS is a 32-bit operating system, which presents an object-oriented design, supports multitasking and multithreading and runs native on ARM cores: ARM V4T, V5T and V5TJ. The main user visible elements are the file system and the common user libraries. The first one provides shared access to the filling systems the second provides the generic libraries and utilities required by Symbian OS components and third party applications. Some examples are: the cryptography , power management framework, database engines, character encoding support, etc. The Base subsystem provides device drivers and/or software controllers for the following devices: DTE serial port, DCE serial port, Infrared (SIR), USB client 1.1, SDIO cards, Keyboard, Digitizer, Ethernet, MMC and LCD. Finally it also provides middleware widely used across Symbian OS like the C standard library and a relational database access API. The can be manipulated either through a subset of SQL or through a Symbian OS proprietary C++ API. • PC connectivity Symbian OS provides a toolkit for creating PC connectivity application (such as Sync and backup services.) Each Symbian OS device manufacturer can create from these tools an appropriate connectivity solution for their device. The toolkit consists of a Connection Manager, to establish and control a link between PC and the device, and a PC toolkit to create application on the PC. • Security The security subsystem enables data confidentiality, integrity and authentication by providing underlying support for secure communications protocols such as TLS/SSL, WTLS and IPSec. It also supports the authentication of installable software using digital signatures. This subsystem contains three elements: the Cryptography module (symmetric and asymmetric ciphers and hash functions), Cryptographic Framework module and the Certificate Management module (for authentication of other entities to the user of the phone, and for authentication of the phone user). • Java Symbian OS provides a Java application execution environment, which is optimized for mobile devices and mobile applications, J2ME. The Java 2 Micro Edition framework is an implementation of the Java Virtual Machine as specified by Sun Microsystems for small handheld devices. This topic will be described later in detail due to its importance and extension.

9 2.1.3 Networking structure

Due to the importance of networking and communications, these topics will be subjected to a more detailed description. Networking Services contain the key frameworks and system services for wide area network communications. It provides a framework for implementing various communication protocols through a socket interface. Networking support in Symbian OS includes: Transmission Control Protocol (TCP), User Datagram Protocol (UDP), IPv4/v6 stack, Internet Control Message Protocol (ICMP), Point to Point Protocol (PPP), Domain Name System (DNS), multihoming, multiple PDP contexts, dial up networking support, security protocols for secure electronic commerce: Transport Layer Security (TLS) and Secure Sockets Layer (SSL), IPSec, Telnet Protocol engine, File Transfer Protocol (FTP) engine and Ethernet support. The picture bellow shows Symbian’s networking architecture.

Figure 3 – Networking architecture in Symbian OS

An important feature implemented by Symbian OS 7.0 is an IPv6/IPv4 hybrid stack. This means that the stack does not contain separate implementations for each version of the protocol (dual stack), but functions internally as the IPv6 stack. It provides both IPv6 and IPv4 functionality and it is therefore called the IPv6/IPv4 hybrid stack. The internals of the stack do not limit or otherwise affect stack usage. When viewed from outside it contains a full implementation of both IPv6 and IPv4 protocol stacks. Another feature is multihoming. Basically, a ‘multi-homed’ mobile device can support several network interfaces simultaneously. Symbian OS 7.0s provides multiple simultaneous OSI Level 2 datalink interfaces, each with its own unique IP address. Multiple IAPs can be active, and applications can specify which ones they will use. It allows connection to multiple GPRS and W-CDMA services simultaneously, like MMS, Internet, WAP; future devices to connect via several different access technologies simultaneously, like WLAN, CSD, W-CDMA,

10 Bluetooth; and provides access to services via Primary PDP contexts. Support also exists to allow applications to specify QoS parameters on GPRS/UMTS networks supporting Secondary PDP Contexts. A PDP context represents a connection between a mobile device and the service on the network. It has an access point name to identify the service and has its own IP address. The following picture illustrates the concept of multihoming.

Figure 4 – Multihoming concept

11 2.2. Java programming for Symbian

2.2.1 Introduction

In this subsection we describe Symbian’s Java technology. It will be shown the evolution of Java on Symbian OS and how the Java platform may evolve in the future. A brief discussion of Symbian OS programming in Java will also be presented.

2.2.2 Java and Symbian

The attractions of Java as a development environment were recognized very soon by Symbian, which made a key decision to provide a Java runtime environment to supplement the native C++ environment. As it would be expected, Java doesn’t offer all the answers but the opening between Java and native performance is closing down and Java functionality is being enhanced. There are two main versions of Java in mobile phones, J2ME CLDC/MIDP and PersonalJava. A third version, JavaPhone, delivers a set of APIs that extend the PersonalJava runtime to access important native functionalities. Symbian OS v7.0s implementation provides MIDP, CLDC with Sun's CLDC Java virtual machine, Bluetooth, and Wireless Messaging. It also includes PersonalJava with the JavaPhone APIs. With PersonalJava and JavaPhone, mobile phones combine the complete power of Java with access to more specialized functionality. Developers, network operators, and service providers benefit from the added value provided by Java on Symbian OS as Symbian’s Java implementation is robust. It is running on the Symbian OS kernel, which is itself designed to operate reliably. User data loss in Symbian OS phones is very rare, and system resets are hardly ever required

Figure 5 – Matching functionality to market needs and Symbian OS Java performance

12 The Java 2 Platform, Micro Edition is the Java platform for devices such as mobile phones, PDAs, TV set-top boxes and a large number of other devices providing a compact Java environment. Like its enterprise counterparts, the J2ME platform is a set of standard Java APIs defined by expert groups that include leading device manufacturers, software vendors and service providers. The J2ME platform delivers the power and benefits of Java technology for consumer and embedded devices, including a flexible user interface, robust security model, broad range of built-in network protocols, and support for networked and disconnected applications. With J2ME, applications are written once for a wide range of devices, are downloaded dynamically, and leverage each device's native capabilities; this by itself is a major advantage of J2ME.

Figure 6 – Java2 platform

The J2ME architecture defines configurations, profiles and optional packages as elements for building complete Java runtime environments consequently increasing the functionality available to MIDlets. Each combination is optimized for the memory, processing power, and I/O capabilities of a specific group of devices. Configurations are composed of a virtual machine and a minimal set of class libraries. They provide the base functionality for a particular range of devices that share similar characteristics, such as network connectivity and memory footprint. At the present, there are two J2ME configurations: the Connected Limited Device Configuration (CLDC), and the Connected Device Configuration (CDC). Mobile phones belong to the first configuration.

Figure 7 – MIDP 2.0 in Symbian OS v7.0s

13 2.2.3 Programming essentials

Most of Java development process for Symbian is exactly the same as for other platforms. Although, if developing extensively for Symbian devices, using Symbian Emulator for development and testing, it's worth getting to know the details of how the environment works. Java 2 Micro Edition Wireless Toolkit offers a complete development environment that complements the Emulator. In this toolkit it can be found KToolbar that is a minimal, easy-to- use development environment for developing MIDlet suites. From KToolbar, it is possible to create a new project or open an existing one; select the target platform and API set for a project; build, run, and debug a MIDlet; tune up (improve the efficiency and speed) a MIDlet by monitoring speed, memory allocation and transmissions; generate a stub connector to access J2ME Web Services; package project files and modify the attributes a MIDlet suite. A KToolbar project can be imported straightforward from an IDE like Sun One Studio 4 ME to be edited, compiled and debugged.

Figure 8 – KToolbar main window and Sun One Studio 4 ME

A KToolbar project is associated with a MIDlet suite. The project contains the suite’s source, resource, and binary files, as well as the JAD and manifest files that contain the suite’s attributes. The J2ME Wireless Toolkit includes emulations of various example devices. They all support the MIDP, MMAPI, WMA, CLDC, J2ME Web Services, and Java Technology for the Wireless Industry specifications. Although KToolbar emulators are good enough for the majority of development, the decisive test before using the real device is to run the application in the Emulator from the SDK of the same platform as the target device.

14

Figure 9 – Series 60 MIDP Concept SDK Beta 0.3.1, Nokia edition and KToolbar settings menu.

In KToolbar settings menu it can be defined the set of APIs that are used for a MIDlet. The target platform may be JTWI – conforms to Java Technology for the Wireless Industry (JSR- 185); MIDP1.0 or 2.0 – includes MIDP 1.0 or 2.0 and CLDC 1.0 or CDLC 1.1; Custom – user defined settings. For a MIDlet suite to operate, it might need to access certain protected APIs. A request for permission to access these APIs is required the MIDlet permissions from the Permissions panel of the Project Settings dialog box. When the code is edited KToolbar compiles and pre verifies source code in one sequence. Once built an application, KToolbar can run it immediately. Debugging is possible from within the KToolbar by connecting to remote debugging facilities, such as an IDE debugger. Once the debugging is complete it’s possible to create a package for project files or create an obfuscated package that reduces the size of the Java byte code, resulting in a smaller JAR file. When MIDlets are packaged OTA can be emulated by choosing Run via OTA command from the KToolbar’s Project menu where it can be simulated the downloading and execution of an application from a web server. See Appendix B for further details on Java programming for Symbian.

15 2.3. Symbian C++ programming

2.3.1 Getting started

C++ is the native programming language of Symbian OS. Symbian uses its own implementation of the C++ language, optimized for small devices with memory limitations. Public C++ APIs allow developers to control the full capabilities of the platform and allow access to a variety of application engines, and to diverse technologies such as Bluetooth connectivity, graphics, Infrared, multimedia, messaging, networking, and telephony. All non- privileged system facilities are directly accessible via C++ APIs available in the C++ Software Development Kit that is freely distributed, providing the full power of the operating system to software developers. C++ offers the greatest access to the Symbian OS APIs, and being the primary language, the best performance in memory use and execution speed. C++ programming is required for certain types of programs like: Servers – background programs that typically manage a system resource, such as communications ports; Plug-ins – which extend a framework provided by Symbian OS, for example, a program that converts HTML files to Symbian OS Word documents, which plugs in to the Symbian OS Converter Architecture; Device drivers – programs that interact with the Kernel. In order to start developing for Symbian platform is necessary to have the following components supplied on the Symbian OS Development Kit: Windows-based emulators – supporting C++ development with industry standard , currently (i.e. for Symbian v7.0) Metrowerks CodeWarrior for Symbian Professional or Microsoft Visual C++ 6.0. Emulators also support Java application development with standard Java tools as well as vendor tools specially targeting Symbian OS; Header files and libraries – to support development for the emulators, and for ARM-based phones and development boards; GCC- based – for building for ARM-based targets; Additional tools – for managing program building and deployment; Symbian OS source code – to help debugging and documentation for the operating system and tools. The following sections point out the development basic concepts that are essential for starting with Symbian C++, the application’s main structure and some implementation details.

16 2.3.2 Development basics

Development for a Symbian OS phone is PC-hosted, based on an emulator which provides a MS Windows-based implementation of Symbian OS. As the emulator-based process accurately impersonates a real phone, the main part of the development cycle is independent of real hardware being available. The development can be based on an IDE like MS Visual C++ 6.0 or Metrowerks CodeWarrior for Symbian Professional development toolset. However, instead of linking and building against Win32, developers link and build against the Symbian OS headers and libraries. The resulting binary is then run on the emulator. Builds can be debug or release but only on debug builds the debugging facilities of an IDE can be used. The tools supplied with the SDK help to ease the development process. The starting point for every program is an environment-neutral mmp project file that can be used to generate specific project files for the chosen IDE and the GCC toolchain that is used to compile for ARM-targets. During development, the project file manages all linking and building details. It also ensures that all outputs from the build, and any required resources, including application resource files, icons, bitmaps, sound files, among others, are built into the appropriate location for debugging on the emulator. Building can be performed from the Windows command line, from the Metrowerks CodeWarrior or from the Microsoft Visual C++ 6.0 IDE. For CodeWarrior the output of this is called a WINSCW build. Binaries built with this compiler are put in the epoc32\release\winscw and epoc32\winscw directory trees. For Microsoft Visual C++ the output of this is called a WINS build and its binaries are put in the epoc32\release\wins and epoc32\wins directory trees. Once installed the SDK and an IDE, applications development can be started using the following model: • edit the code using an IDE or a text editor; • using a supported compiler, compile the code for the emulator target • run the emulator and start the application by selecting it from the application launcher • debug, edit, recompile, and repeat the cycle until the code is thoroughly debugged and runs on the emulator without problems • using the GCC-based compiler supplied with the Development Kit, recompile the code, for the appropriate ARM target • upload the SIS installation file from the PC to a Symbian phone, and launch the application on the device • test exhaustively the application on the device and , edit, recompile and repeat the cycle until no bug is found. Further details how to compile, create the SIS installation file or install the application on the real device are presented in appendix.

17 2.3.3 Applications structure

There are two types of application in Symbian OS, console and GUI applications. Console application consists of a single executable file with a file name extension of .exe. In Symbian OS, such executables are used for two main purposes: as servers with no user interface or as test applications with very simple text based interfaces (as a command line).

Figure 10 – Series 60 emulator running a GUI application (on the left) and a console application (on the right)

Typical sophisticated GUI applications make use of the application framework and user interface libraries. A GUI application on Symbian OS actually consists of four distinct components, each with a corresponding class. It is necessary to implement all this four classes, anything less than this won’t be a Symbian OS GUI application. The classes needed are: 1. The Application ‘shell’ itself. This is derived from CEikApplication and this class is instantiated first by the framework. Once created it has responsibility for initialising the rest of the code. 2. The Document. This is derived from CEikDocument. All applications have a CEikDocument-derived class and by default CEikDocument will create a default document file the first time an application is run. However, not all applications are file based. That is, they may not need to offer the user the ability to create, open, or edit documents. In such applications the instance of the document class is little more than a shell required by the framework to create an instance of the AppUI class and typically a model/engine instance. In file-based applications the document class also manages the saving and restoring of data from persistent storage.

18 3. The AppUI. The AppUI class is derived from the UIKON class CEikAppUi. This is the class, which provides major functionality to all applications such as event handling, control creation, access to several useful system calls, etc. 4. The View. This is what the user actually sees on screen. It can be used to simply display data or to collect data from the user in more complex applications. While all applications have one default view, the most complex ones can offer many views.

A visual representation of this process is as it is shown in the left part of figure 11:

Figure 11 – Application launching sequence and user interface architecture

Although a GUI application can be implemented in only one file with all the necessary classes, a minimum Symbian OS application normally has the constitution presented in the following table.

File Short description MyAppName.cpp The DLL entry point.

MyAppNameApplication.cpp An Application that creates the new blank document MyAppNameApplication.h and defines the application UID. MyAppNameDocument.cpp A Document object that represents the data model and MyAppNameDocument.h is used to construct the App UI.

An Application User Interface (AppUi) object that MyAppNameAppUi.cpp handles the commands generated from menu options. MyAppNameAppUi.h

19 An Application View object that displays data to the MyAppNameAppView.cpp screen. MyAppNameAppView.h

Describes the application's menus and string MyAppNameView.rss resources.

Contains definitions of some UI control enumerated constants that are used in source files and resource MyAppName.hrh files. These constants are Command IDs, Key IDs or View IDs specific to an application. They may be used for key handling or for command handling in dialogs.

Header file that is included in the .rss file containing MyAppName.loc (not mandatory) user interface text strings etc. to make localization easier. The environment-neutral project file can be used to MyAppName.mmp generate specific project files.

The file which contains installation information for MyAppName.pkg applications or files.

A component description file which lists all the projects in a component and gives additional build Bld.inf instructions.

Table 1 – File constitution of a minimum GUI application

Resource files are fundamental to a GUI application they are used to define the way an application looks. Much of the information that defines the appearance, behaviour and functionality of an application is stored in this file. Individual resources are loaded very efficiently as required at runtime to minimise memory requirements. Application resources are compiled and compressed at build time into binary files (with .rsc extension) that are used at run-time. See Appendix D and E for further details on creating these files.

20 2.3.4 Implementation Details

Due to the particular architecture of the Symbian OS there are certain details and patterns in the way the architecture is implemented. Certain techniques are used when implementing applications based in communication and networking. These techniques are shortly described below.

• Client-Server Relationships

Symbian OS uses kernel servers to protect and manage shared resources and services. They form a sort of gateway that processes must go through to access communication functionalities. To use a server, clients need to establish a connection to the desired server. The client-server relationship is facilitated by a socket. Servers listen to socket connections, and according to the resources available, accept or deny a connection. After the request and data exchange are done, the socket is closed. There are several servers in the communication infrastructure like serial communications servers, telephony servers, socket servers, communications database servers and other kinds of servers. This client- server relationship is the way computers interact for example in a TCP/IP network. Our special interest is in communication servers, socket servers and communications database servers. This last server is CommDb, the communications database server. This server is the central repository for information regarding configuration settings for devices and has a very important function. It provides access to an (extensible) database which holds information about internet access, connection preferences, GPRS connections, modems, locations, charge-cards, location information, WAP settings, and proxy servers. The database provides a single repository of communications related information which all communications type software components and applications can access. CommDb allows multiple clients to access concurrently the tables within the communications database. The locking mechanism of the underlying DBMS allows concurrent access by multiple clients while safeguarding the integrity of the database for changes. Later in this section the Communications Database will be detailed. • Asynchronous Events

Communications programming requires some waiting. As a client, an application might wait for a response from a server. As a server, an application would always be waiting for client requests. Because waiting is so obvious and frequent, the programming model will be asynchronous; it will be an event-driven programming. With this kind of implementation method the application will be more optimized and won’t stall while waiting for a connection or a response.

• Active Objects

As stated before, the programming method is asynchronous. In order to accommodate the constant waiting imposed by the asynchronous nature of communications, Symbian OS

21 uses the concept of active objects. Basically an active object is a thread – a parallel object that executes alongside the main code – that makes communications requests and handles the event that is generated when the request gets a response. An active object enables more interaction with applications and a clean interface for handling situations that might arise during communication.

• The Communications Database

The communications database is a standard Symbian OS database, manipulated by the Symbian OS DBMS system. It provides system-wide storage for all information that should need to be referenced about components of the communication infrastructure. This information set includes data pertaining to phones, modems, protocols, and Internet service provision information (network access phone numbers, Internet addresses and physical locations). From a user’s point of view, this database is accessible through the Control Panel in Symbian OS user interface. From an application perspective, it is manipulated via the conventional Symbian OS API for relational databases or through a subset of SQL commands. The communications database is structured as a standard Symbian OS relational database, managed through DBMS procedures. The information is held in several individual data tables in a single database. Each data table is manipulated by constructing a view of the table and working with its records through that view. There is a great number of tables and each of them is composed of several records, so the first thing to do in order to access the communications database is to know which table will be used, how it will accessed and what records will be manipulated. The tables contained in the communications database are listed in Appendix G. The standard way to access this structure is through the following steps:

• Create a new database object; • Use this database object to create a view of a data table; • Select a record – either by creating a new record or finding an existing one; • Manipulate this record – read from or write to it as needed; • Commit any changes made to the record; • When completed, delete the view and database objects.

• Routes and interfaces

In order to communicate with a remote host through a socket, a protocol must establish the IP address and port of the socket, a route to the remote host and a network interface by which to access that route. When a connection is attempted, either by the Connect() function for TCP sockets or using the functions Send(), Write() or SendTo() for UDP sockets, Symbian OS follows this standard steps in order to accomplish what was said before:

22 1. The IP routing table is checked to see if a route to the destination exists. If there is no route (including no default route), then the protocol attempts to invoke its default dial-up interface. 2. If dial-up is successful, PPP is invoked to establish a connection to the remote peer. 3. In its set-up stage, PPP obtains a local IP address from the remote peer (if so configured) and is informed of the peer’s IP address. 4. When TCP/IP is informed that the interface is up, it adds routing entries for the interface. Normally this means that the remote peer becomes the default gateway. 5. If a local address has not been set by Bind(), then the protocol sets the socket’s local address to that obtained in step 3 (which is recorded in the route entry created in step 4), and allocates an ephemeral port number. This process is called automatic binding.

2.4 Summary

In this section it was presented an overall view about Symbian and its programming languages. After presenting some aspects of the history of this operating system, it was explained how Symbian is structured and described the main protocols and technologies available in this OS. Sub-section two illustrated how Java programming language is implemented in Symbian, presented its main advantages and some essential programming concepts. Symbian’s native programming language was also subject of study. This time with more detail, it were described the basic concepts of C++ for Symbian, the application’s structure and implementation aspects. The explanation of the basic structure of a Symbian’s applications (graphical and non-graphical), focused on the fundamental files that compose them and several aspects about the application launching sequence and user interface architecture. The last topic discussed, consisted in a simple overview of how Symbian implements some communication and networking characteristics, exploring aspects like the client-server relationship, active objects, and the communications database.

23 3. PC connectivity

3.1 Introduction

A Symbian OS phone can have a good quality communication aptitude depending of the number of technologies available. It can have Infrared, Bluetooth, GPRS, GSM and USB connectivity. To these may be added a very simple strategy if the phone has a memory card, that is taking it out of the phone and putting it in a USB memory card reader. Wireless PC connectivity can be achieved by Infrared but it’s Bluetooth that offers the best characteristics. Bluetooth is a WLAN technology that is oriented to ad-hoc networks of low cost and short range. Its typical range is 10 metres and has a shared data rate of 1 Mbit/s while Infrared has a limited range of two metres in line-of-sight and limited number of two participants. Bluetooth allows the creation of the so called piconets, a type of small ad-hoc networks. Bluetooth connectivity allows a multiplicity of uses for the mobile phone capabilities from both PC and phone. A common application is the use of GPRS to give internet access to the PC, in this case the phone will act as a modem; this is relatively simple and there's more than enough documentation on this subject. Once established a modem connection between the phone and the Linux box, it’s possible to use PPP to establish the connection to an ISP just as for a real modem. Another application used frequently is file transfer or beaming as it’s also known. This solution is normally used for the purposes of backup/restore and synchronization, but can also be used in a more generic sense. Under MS Windows, the software bundled with the phone or with the Bluetooth dongle is very easy to use, with Linux this is also possible. IP connectivity over Bluetooth to a PC, from a mobile phone, is a subject that is not well documented as it is not of interest for the service providers. Getting an IP address on the phone and other one on the BT interface of the PC allows the phone to get, among other things, internet access; this avoids the use of GPRS/GSM, which can be expensive. Needless to say, this will only work if the phone is within range of a computer with Bluetooth support. The PC connectivity software for Windows, bundled with a Symbian phone creates a TCP/IP connection between the phone and the computer over the Bluetooth serial link but it’s out of question working on MS Windows as it doesn’t have an official and documented Bluetooth stack. Although no dedicated software exists for Linux it’s possible to enable this functionality. Being so, it’s necessary to enable the connectivity by configuring both Linux PC and mobile phone. A common mistake is to think that when the phone is acting as a GPRS modem it has IP connectivity in both GPRS and Bluetooth links. As a matter of fact, when acting as a modem, the phone isn't ‘talking’ PPP itself - the PPP session is between the computer and the ISP, and the phone acts as a simple modem. To have IP on a LAN, the phone itself must ‘talk’ PPP to its host computer. When the PPP channel is established, all it gives is a ‘tunnel’ between phone and the host PC, with an IP number at each end. What gets sent down the tunnel is up to the applications at each end. An interesting thing is that some applications will use the PPP channel for networking, rather than the GPRS or GSM as long as PPP is up. This fact led to think on developing an application that worked on this great feature.

24 3.2 Linux notes

There are several implementations of the Bluetooth stack for Linux kernel like Affix and BlueZ. The tool that seems to be more reliable is BlueZ, the official Linux Bluetooth stack, as it has plenty of documentation and its use is far more common. BlueZ consists of a number of kernel modules that provide basic Bluetooth stack support for the HCI and L2CAP layers of the Bluetooth protocol stack. The user side tools include control programs like hciconfig and dund, system daemons provide RFCOMM and SDP support, and libraries which contain common functions and convenience wrappers. Due to its growing importance and stability, BlueZ was merged into Linux kernel from version 2.4.5 onward. In order to get Bluetooth working, the kernel has to be recompiled and to avoid problems, a recent stable kernel version is the best option. See Appendix J for further details on setting up Bluetooth support on Linux.

Figure 12 – Bluetooth protocol stack

The most important Bluetooth layer used in this project is RFCOMM. RFCOMM basically emulates an RS-232 serial line. To the upper layers of the existing protocols it presents an interface that looks exactly like an RS-232 connection link so it allows an application to treat a Bluetooth link in a way similar to communicating over a serial port. It also interfaces with the L2CAP layer and implements a point-to-point transport method. BlueZ RFCOMM provides serial emulation over Bluetooth that lets serial port protocols like Point-to-Point Protocol (PPP) run unchanged over Bluetooth. Dund is a tool that is used for dial-up connections. In the case of LAN interaction from a Symbian phone, dund is used to accept incoming PPP session requests in a particular RFComm channel. Dund will then use pppd to establish a connection with the smartphone. PPP in the Bluetooth technology is designed to run over RFCOMM to accomplish point-to- point connections. PPP is a packet-oriented protocol and must therefore use its serial mechanisms to convert the packet data stream into a serial data stream. PPP is composed of three parts: a method for encapsulating datagrams over serial links, an extensible Link Control Protocol (LCP), and a family of Network Control Protocols (NCP) for establishing and

25 configuring different network- layer protocols. The encapsulation scheme is provided by driver code in the kernel. pppd provides the basic LCP, authentication support, and an NCP for establishing and configuring the Internet Protocol (IP) (called the IP Control Protocol, IPCP). The first thing pppd does after being called by dund, is to negotiate several link characteristics with the remote end using LCP. Then it will negotiate the IP parameters with its peer using IPCP, the IP control protocol. Both will then announce their addresses to each other. After going through the IPCP setup phase, pppd will prepare the PC’s networking layer to use the PPP link. It first configures the PPP network interface as a point-to-point link, using ppp0 for the first PPP link that is active, ppp1 for the second, and so on. When interacting with a smartphone, it sets up a routing table entry that leads to the phone’s end and then to the attribution of IP addresses in both ends.

3.3 Bluetooth connectivity under Linux

As it was stated previously, in order to get IP connectivity between a Linux PC and a Symbian phone it is necessary to perform some operations in both devices. There are some difficulties with using PPP to get LAN access from a Symbian phone coming from both Linux PC and smartphone. A Symbian phone like Nokia 6600 will not accept incoming requests to initiate a PPP session because it expects to initiate the session itself. If the connection starts from the host computer it attempts to initiate a PPP session on the phone’s virtual serial line. To do this it must bind an RFCOMM device to the right channel and then use it as the port for a pppd call. When the PPP session is established, it is closed immediately by the phone. The phone then does an SDP query to find the channel number of the SP (serial port) profile on the computer. It will only find one if it has been explicitly added to the computer's SDP daemon using, e.g., the Bluez sdptool. Having got the channel number of serial port service, the phone then initiates a PPP session on it and for this to work, it’s necessary to have something listening on the appropriate RFCOMM channel on the host computer. As said previously this can be done with the dund daemon. Once the PPP session is set up, the phone immediately attempts to find the IP number of a router (gateway). This operation must succeed, or the phone will drop the connection. After the PPP session is established, it should then be possible to ‘talk’ TCP/IP between the phone and the Linux box. If, on the other hand, there is an application that starts the connection process by attempting to connect to a host whose address is not in the routing table of the smartphone the phone calls the computer directly and asks it to set up a session.

Figure 13 – Mobile phone/PC Bluetooth connectivity

26 In order to set up the Symbian OS device, it is needed to manipulate the CommDb on the Symbian OS device which holds information relating to phone and modem settings. Specifically it’s necessary to set an empty ISP dial string. This will force a direct PPP connection over the designated virtual serial port which for Bluetooth will correspond to BTCOMM::0 on Symbian OS. It used to be possible to do this manually on the Psion 5 and Revo devices using the Modem control panel applet but this functionality has been obfuscated in Symbian OS 6.0 and beyond. For Symbian OS 6.1 there is an application called Gnubox licensed under GPL that offers some pointers as to how to proceed programmatically. Gnubox turns a 1-box phone into a 2-box that can be used with Linux providing IP connectivity to the phone over Bluetooth (and infrared) through Linux. For Symbian 7.0 there are a few differences. They consist in different record and table names, especially the MODEM table that now has become MODEM_BEARER. After having IP connectivity and explored the rich functionalities of Symbian OS, a great number of applications can be done to demonstrate the concept of ambient networks like the one developed in this project.

3.4 Summary

This section was dedicated to connectivity issues related to Linux PC and Symbian phone. Due to the amount of information presented, it will be showed a re-examination of the most important notions depicted in the section. In the introduction, an overall view of the technologies available to provide connectivity to a PC was presented. It was also made a brief explanation of the different applications of the Bluetooth technology related with PC-phone connectivity. In the Linux notes subsection it was introduced BlueZ and some essential concepts and tools for the Linux Bluetooth communication support. BlueZ provides some of those tools like RFCOMM, dund, and sdptool that combined with the pppd allow the IP connectivity over Bluetooth. The tools interact with each other in this way: sdptool is executed to define a specific channel number for the serial port profile. After that, dund will accept incoming PPP session requests in a particular RFCOMM channel and use pppd to establish the IP connectivity over Bluetooth. Finally, it was presented a short review of the IP connectivity process over Bluetooth between Linux PC and Symbian phone stating both PC and phone configurations needed for establishing a successful IP connection link. Besides the Linux configuration (tools and initialization) referred before, the smartphone needs to update its communications database tables DIAL_OUT_ISP and MODEM_BEARER assigning a Null descriptor into the ISP number and designate BTCOMM::0 to the serial port.

27 4. Project description

4.1 Overview

The mobile phone is itself the best example of mobility while maintaining connectivity. As a result of this, it is only a question of time until this device achieves the communication ability of a Laptop or a PDA that already can use GPRS, Infrared and Bluetooth in its full power. This project represents a new step towards the full connectivity of the mobile phones in a local network as it aims to the IP connectivity of the smartphones. The idea of having IP connectivity to a surrounding environment was, from the first instant, the main step into the integration of the Symbian mobile phone in an ambient network. With IP connectivity the mobile phone can be viewed like any other member of the LAN. The major disadvantage of this device is without doubt the limited processing power and memory to enable more complex applications and also its user interface in the case of the simpler phones with no touchscreen and no QWERTY keyboard. The operating system is not, as stated previously, a limiting issue as it is a powerful OS capable of being used in more complex devices. Having the IP link enabled it is then only a matter of choosing a set of applications for the demonstration of this new concept of mobile phone integration in ambient networks. In our case the integration is made by offering services to the other participants in the local network. The other devices in the network can be PDAs, Laptops or even personal computers in the neighbourhood of the phone. These devices can offer and use services that require resources that a mobile phone can’t have but any service offered by the phone can easily be used by a more powerful device. Although, simple applications can be designed in order to demonstrate the use of ambient services by the phone. The scenario chosen for the demonstration of this concept consists in a network constituted by the mobile phone, PDAs and PCs. The PDAs and PCs create an ambient network in which the smartphone will be integrated. This network is the result of another project that demonstrates the concept of ambient intelligence. The services offered by the phone will be used by these elements that also have services of its own. The architecture the global scenario is shown in the following picture.

Figure 14 - Mobile phone integration scenario

28 Figure 14 shows the mobile phone integrated in the ambient network and offering services to the other participants. On its turn, these participants have a set of services like the recording and display service. The integration stated is supported by predefined protocols that enable the proper communication between elements. This is the only prerequisite needed to the correct articulation of the data exchange. One of the intrinsic characteristics of this type of network is that services may disappear as easily as they can appear. The Bluetooth communication link is limited to ten metres and as a participant steps away of the range of the network it automatically looses the services offered by the network and the network looses the services that the missing participant was offering. This reality brings up two more concepts: service discovery and service advertisement. When offering a service a device must send a message from time to time to the network stating the services offered by it. The other participants can now listen for the advertisement of the arrived participant and build a database with the existing services at the time, hence performing service discovery. Whenever the network looses contact with a device it will stop receiving the advertisement from the missing device and so, after a predefined time equal to the frequency of the advertisement messages, the remaining devices remove from the database the entries corresponding to the lost services. This procedure allows an efficient update of the network constitution. To demonstrate the concept it was developed an application that turns a mobile phone into a fully fledged fully member of a LAN. This application was built upon Symbian C++ programming language and more specifically to the Symbian 7.0 platform that equips the Nokia 6600 smartphone. The application, among other things configures the phone to allow IP connectivity over Bluetooth, advertises the services and runs the servers of the services implemented. Additional features were introduced like routing information views, interface information and CommDb settings. The services offered by the mobile phone are: a SMS service and a picture service. SMS adds another communication capability to the network. The SMS service allows any device with IP connectivity with the phone and running the SMS client program to send this type of messages. The server running inside the application handles the requests and executes them without the phone user being alerted. Needless to say, this service brings out costs to the phone’s owner. Another feature of this service is that it can recognize a SMS message and, without the user knowing, pass the message contents to the network. The message has to be constituted by determined header and content. The server and client programs must be running on both phone and client device respectively. The picture service is a clever usage of the phone’s resources in favour of the network participants. The server program of this service takes pictures on demand of the client program and transfers the resulting JPEG file to the IP address of the client device. This procedure, when repeated results in a type of video streaming with a nice visual impact. The processing limitations of the phone don’t allow the maintaining of a high frequency rate but a minimum of one picture in each second is enough to get a good look of what’s going on. This service enabled the Nokia 6600 used in this project to act like a webcam and like a pre UMTS 3rd generation phone if it used with another phone in the same circumstances (i.e. with IP connectivity to a PC or PDA with internet connection) while maintaining a phone call. As said previously, another feature of the application developed is the ability of see the interfaces and routes present at each moment. This functionality allows the user to have access to information that he normally wouldn’t have. This facility is extremely helpful.

29 4.2 Fundamentals

As it was shown in the previous subsection, the application developed uses mainly GPRS/GSM and Bluetooth interfaces. GSM/GPRS is used to send/receive the SMS messages and Bluetooth maintains the IP connectivity to the ambient network. The usage of these interfaces is independent as the application handles both at the same time The IP connectivity over Bluetooth is the fundamental basis of this work. As it was stated earlier, both phone and Linux PC have to be configured. On the PC side it was necessary to recompile the kernel to support Bluetooth and all the necessary tools had to be correctly configured. Although well documented, the configuration of the PC isn’t straightforward requiring a great deal of patience and some time. The networking subsection describes the process. On the smartphone side, the internet settings database had to be altered to allow the usage of the IP protocol over Bluetooth. These changes are made, if necessary, when the application starts. The alterations on CommDb don’t have secondary effects and once made they remain even after rebooting the phone. The programming details of these changes are explained in the next subsection. In order to accomplish the integration through the use of the services offered by the phone to the other devices it is necessary to create a protocol common to every participant in the network. This protocol will allow the correct articulation and comprehension of the advertisement or request messages exchanged between the devices. For each service there is one server and one client programs, both using the same protocol. A device that wishes to use a particular service must, first of all, comply with the protocol to be able to understand messages received by it and be understood by the other elements. Consequently, this device must already be running a server program that communicates using this protocol. Service advertisement messages are in a XML format which is a structured language particularly good for this purpose. The first step when entering the network is to start sending announcement messages to advertise the presence of the new device. The protocol used defines a message like this: provider name provider ip address

This message is send using UDP to a predefined port number. UDP allows sending these messages without any confirmation as it is desired. If any device is listening in the right port number, it will receive this message and so it will identify a new participant. As a new device can represent new services, the listening device will send a request to the arrived one in order to be informed of the services, if any, provided by it. The request message is sent, now over TCP/IP, to the provider’s IP address in the same port:

The service provider program running on the phone, when recognising the request, immediately sends the XML description of the services it is offering at that moment. With this description, the devices that performed the inquiry can be acquainted with the new services. The XML description has the following structure:

30 name of the service port number name of the client program %i %p localization of the executable

In the specific case of the services presented by the mobile phone, the XML description is:

SMS 6010 smsclient %i %p http://www.fe.up.pt/~ee99145/services/sms.exe PIC 6011 stream %i %p %1 http://www.fe.up.pt/~ee99145/services/pic.exe This description can be altered by the phone’s user by selecting/deselecting the correspondent service on the service offer menu in the application. According to the services selected the XML is changed to describe only the services running at the moment. After receiving and decoding the previous description, the inquiring device adds a new entry to its database, meaning that new services have been found. Right after this the new services are shown to the user in order to allow its use. As it can be viewed in the XML above, the description contains a field with an URL where the executable client is located; with this approach any device with internet access and using the same XML protocol can use a service by downloading the correspondent client program. Notice also that the arguments of the executable are also specified. The SMS service is used by any participant running the client application pointed out by the XML service description. This program allows the user to introduce the message contents and the phone number of the destination. This data is packed into a XML sequence that is sent to the server application running in the mobile phone. The syntax is: SMS nine digit phone number Content of the message When the phone receives the request above it immediately starts the whole process of sending a SMS and meanwhile it echoes back a confirmation message to notify that the request was

31 received correctly. Notice that this does not mean that the SMS was successfully sent or received at the destination phone with the specified number. The message is:

SMS

The picture service is also available to any participant running the client program that has IP connectivity with the mobile phone. In order to take advantage of the Nokia’s 6600 digital camera the server program has to reserve the camera, turn on the camera power, prepare to capture the picture, save the picture after converting it to JPEG format and then send it to the device who requested it. This cycle repeats itself whenever a request is received (refer to the next subsection for further details on the implementation). The request is made trough the following message:

PIC After that, the application sends back the picture in groups of bytes until the end of file is reached. The protocol also specifies that any image should be preceded by a +OK\n\r sequence. On the client side, the image is received and displayed to the user. Repeating this process it can be carried out a type of video streaming with a maximum of one picture each second. The following diagram illustrates the whole service advertisement/request process.

Figure 15 – Service advertisement/request procedure

32 4.3 Application structure

When developing in a new environment it is necessary to start from simple examples. In this case, in order to develop an application that was able to communicate using TCP/IP it was necessary to start from a simple sockets example, provided by the SDK. This example was the first step to achieve IP connectivity, first over GPRS and then over Bluetooth. All connectivity issues where resolved during GPRS communication tests and then, only after having the application thoroughly debugged, the Bluetooth tests started. The final application is relatively complex and, in order to understand it well it is necessary to explain it in some detail showing the main structure. The application can be defined as communications oriented and thus its main features are the socket servers and clients. The environment in which the application is inserted demands it; it’s an ad-hoc network where all constituents announce their presence every 10 seconds over UDP, announce services and communicate with each other over TCP.

Structure details

In section 2.3.3 was given a small overview of the kind of files that a Symbian OS UI application needs and how it’s created. Now, that information will be used as the base to the definition of the application’s structure. The “engine” of the application is the class CAmbientIAppUI. This class gives birth to all the views and main objects that will constitute the program. It creates all the necessary views of the application, a timer object that will control the timing of the presence announcements, the UDP client that is responsible for those announcements, and the three TCP server objects that will listen for connections in ports 6000, 6010, and 6011. The structure of a server object is quite complex, for that it isn’t included here. But a complete overview of its structure as well as its explanation is provided in Appendix I. The AppUI will remain active during the life- time of the application, not like the views, that are destroyed as the user switches from one menu to the other. So, it keeps essential information about the current state of the application, more particularly, the services that the smartphone will provide (or is already providing during the course of the application). The services are kept in a vector that contains the actual state of the service: if it’s active or not. The state of the services is changed when the user explicitly selects or removes a service presented to him in view 2 (more detail below when this view is explained). For that, AppUI contains functions that allow the views that interact directly with the services to read the selection made by the user and then hand them over to the AppUI for storing and processing. The inter-process communication is accomplished through a notifier, the MState notifier. It is essentially composed by four functions that permit the views to set and reset services, get the current active services and to discern if a specific service is active. The functions are SetServices(), ResetServices(), GetServices(), and IsSeti() respectively. The AppUI also contains a function that performs the initialization and configuration of the servers, ProcessRequests(). It analyses the services selected and when the smartphone is ordered to enter the AmI network, the function configures and initializes the necessary servers through the functions: ConnectSMS() for the server that listens to SMS requests, ConnectPIC() for the picture service.

33 All the servers implemented by the application share the same basic structure: there’s a main object called the engine that creates two other objects, a reader and a writer, handles the connections and disconnections, and controls the data exchange between the remote endpoints. The instruction that creates the engine object is: iSocketsEngine = CSocketsEngine::NewL(*this);

This performs the object creation, and initializes it as an active object. When demanded, the AppUI triggers the server object to start the normal steps for listening incoming requests. Next is an example of one of the functions that perform the previous steps: void CAmbientIAppUi::ConnectSMS() { iSocketsEngine->SetServerName(_L("KInetAddrAny")); iSocketsEngine->SetPort(6010); iSocketsEngine->ConnectL(); // Initiate connection }

The function sets the server to listen at port 6010 for incoming connections from any address. At this point the application would be ready to receive service requests and participate in the AmI network. The UDP client used for service announcement also shares the same basic structure: an engine object that performs the initialization and creates a writer object that will deal with the data exchange. In this case, the writer will only send the name which the smartphone will use in the network and it’s IP. The initialization is quite similar to the servers, but in this case it doesn’t depend on the services chosen by the user, as the application starts the presence announcement immediately. iSocketsEngine2 = CStartConnection::NewL();

This is the instruction that creates the object, after this the ConnectS() function is called to start the actual data exchange: void CAmbientIAppUi::ConnectS() { iSocketsEngine2->SetServerName(_L("2020::dead:beff")); iSocketsEngine2->SetPort(6000); iSocketsEngine2->ConnectL(); // Initiate connection

// data to be written iSocketsEngine2->WriteL( _L8("Ami66002020::dead:beff")); }

Associated with this object is a timer that every 10 seconds signals the application and allows it to send another presence announcement. The timer is also an active object, so its creation and initialization is done by these two instructions:

//creation and definition of its priority iTimer = CTimeOutTimer::NewL(EPriorityHigh, *this);

34 // Start of timer iTimer->After(KTimeOut); // KTimeOut = 10000000 => 10 seconds timer

When the loaded variable expires, the TimerExpired() function in the AppUI will be called to transmit the announcement and start the timer again. The code is showed next: void CAmbientIAppUi::TimerExpired() { // Write information necessary for the announcement iSocketsEngine2>WriteL(_L8("Ami66002020::dead:beff"));

//Updates log with the announcement WriteLog();

// Start Timer again iTimer->After(KTimeOut); //KTimeOut = 10000000

}

The function calls WriteL() for the data exchange, updates the log file (using WriteLog() that writes to the file Log.txt all the presence announcements for posterior exhibition to the user) and in the end starts again the timer. These are the objects created by the AppUI, but they act like a daemon, the user isn’t aware of this functionality. The visible part of the application or its interface with the user is the view. Each view has a Control Button Array (CBA) that defines the operation of the soft keys, a Menu bar that is displayed on selecting the Options soft key, operations which are invoked when the view is activated or deactivated, the ability to handle menu commands, and a visual appearance on the display. After the creation of all the views, the first one to be activated and that starts the application is CAmbientIView1. This view creates a container class, which basically defines objects which manage drawing to the screen. CAmbientIContainer1 constitutes the first interface with the user: it presents the initial picture and is also constituted by two buttons named ‘Options’ and ‘Exit’ that allow the user to access the options menu or to leave the application. Next is the aspect of the home view and its possible menu options:

Figure 16 – View 1 Figure 17 – Options menu 1

35 The first picture shows the initial interface presented to the user. The ‘Exit’ button allows the user to leave the application. The ‘Options’ button gives access to a new set of menus; there are three possible choices to select: the ‘Services’ option gives birth to a sub-menu that permits the user to specify the services that he would like to provide (‘Offer’ option), to participate in the AmI network as a user of the services provided by other devices (‘Discover’ option) and the monitoring view is activated choosing the ‘Monitor’ option; the ‘Status’ option allows the user to consult the smartphone’s routing table, network interfaces, and some communications database tables; and to get a better insight about the ambient network the user can select the ‘About’ option and read a help description. Depending on the particular choice the application evolves to a particular view. The last option from the second picture activates the ninth view, CAmbientIView9, which is constituted by a container object, CAmbientIContainer9, and two buttons, one to return to the previous view, ‘Back’, and the other, ‘Options’, opens a menu which permits the user to leave the application. The container basically holds a text that is showed on the screen, containing helpful information about the application and the AmI network. The screenshot of the view is:

Figure 18 – View 9

If the user selects the Services->Offer option, from the menu on figure 17, the application proceeds to the second view, CAmbientIView2. This view creates a container object, from the CAmbientIContainer 2 class, which represents the graphical interface that defines the services that the smartphone will provide to the remaining constituents of the AmI network.

Figure 19 – View 2 Figure 20 – Options menu 2

36 The previous pictures show the list of the possible services (all disabled initially) that this device can offer. As referred before, the services to provide are: a SMS send service (SMS Send option present on the list), a SMS receive service, and a picture service (Picture option present on the list). This view is constituted by two buttons: the ‘Back’ button, that allows the user to return to the previous view, and the ‘Options’ button, which permits the user to select or unselect the service, join the network and leave the application. The correct procedure to join an AmI network should be to select the services present on the list, enable at least one of them (using ‘Enable/Disable’), otherwise the access to the network is denied, and finally enter the network by choosing ‘Start Service(s)’. The current list of the active services to offer is on the AppUI file, which coordinates the entire application. There’s a good reason for that: if the user wishes to take a look at the routing table or to the network interfaces, this view will be destroyed because this information is present in another view (in view 6 which is explained later). So, the current list of services would be lost and the application would not function correctly. As referred before, the communication between this view and AppUI is done by means of the MState notifier. So, when the user activates/deactivates a service, the view uses SetServices()/ResetServices() to inform AppUI of the necessary update. Then the view uses the container to update the list presented to the user, enabling/disabling the selected service. If at least one service is activated, then the user is authorized to enter the AmI network by choosing ‘Start service(s)’ from the ‘Options’ button. After the device is communicating with others, the screen will change and all the events that occur will be saved in the ‘Log.txt’ file (localized in the C:\nokia\images directory) and then presented to the user. For example, when the smartphone announces its presence, the screen will be updated with an ‘Announcement Sent’ phrase. The other options are: ‘Service Request’, ‘SMS sent’, ‘Confirmation sent’, and ‘Picture sent’. Another choice from the menu presented in picture 17 is the ‘Status’ option. If this alternative is selected, the application changes to the sixth view, constituted by the CAmbientIView6 class. This class constructs a container object, implemented by the CAmbientIContainer6 class, which will comprise the list of the information that the user can obtain. The aspect of this view is displayed in the next pictures:

Figure 21 – View 6 Figure 22 – Options menu 6

The purpose of view 6 is to get information from the communications database, smartphone’s routing and interface tables allowing the user to have access to internal information that he normally wouldn’t have. This view has two buttons, the ‘Options’ button which allows the user to select the desired option and jump to another view, and the ‘Back’ button which returns the application to the preceding view. The first picture shows some of the possible

37 choices (there are really four options, in order to see them all the user must scroll down) and the second shows the options menu that will pop if the ‘Options’ button is pressed. After the selection of one of options, the application will step to a different view: view 5 if the ‘Network Information’ option is selected, view 7 if ‘Routing Information’, view 8 if ‘Commdb Information’, and view 12 if the ‘Route Addition’ option is selected. By choosing the ‘CommDb Information’ option the application activates the View8, implemented by class CAmbientIView8. This view, however, is a bit different of all the others presented so far, because it will have two different aspects. For that, it creates two container objects, implemented by CAmbientIContainer8 and CAmbientIContainer8.1. The first form of this view is a list box with the different information that the user can select; the options are:

Figure 23 – View 8 Figure 24 – Options menu 8

There are two buttons in this view, a ‘Back’ and an ‘Options’ button, where this last one allows the user to exit the application and select the option desired by choosing ‘Details’, activating the second container. The second appearance contains the details of the previous choice, thus, this second container, depends on the first one. The selection of the options presented in the list of figure 23 permits the manipulation of the communications database, retrieving a series of records form the desired tables like the DIAL_OUT_ISP and MODEM_BEARER tables. Manipulating the communications database as been already discussed and for that it won’t be showed here how to access it. For that please report to Appendix G and follow the example. The next picture shows the selection of one of the tables presented to the user, the result is a list of some records from that table, in this case the MODEM_BEARER table. Next is presented the information that will be displayed when the ‘Modem’ option is selected.

Figure 25 – MODEM_BEARER table information

38 If the user selects the ‘Network Information’ from figure 21 the application activates the fifth view, CAmbientIView5 class. The purpose is to get information about a specified network interface chosen from a list. This view creates two container objects from CAmbientIContainer5 and CAmbientIContainer5.1 classes. The first container is responsible for drawing a list box with the current existing network interfaces in the smartphone. The procedure is to read the interfaces that currently exist in the smartphone and create a list with all the elements identified before. For this, the container uses the socket API, more particularly the GetOpt() and SetOpt()functions, to retrieve the desired information. This procedure is detailed in Appendix I. The list looks like this:

Figure 26 – View 5 Figure 27 – Options menu 5

Once again this view possesses the same buttons as the previous ones, ‘Back’ and ‘Options’, where the last one permits the user to select an interface, refresh the list to see any new interface, and exit the application. When the user selects one of the options, the view activates the second container. This object will draw in the screen the several details concerning the network interface chosen using the function Infos(). This function also uses the socket API, especially the functions SetOpt() and GetOpt(). Next is a snapshot of the application when the second container has been activated due to the selection of the second element of the list:

Figure 28 – Interface information

The seventh view, CAmbientIView7 class, shows the smartphone’s routing table. Once again this view creates two container objects, CAmbientIContainer7 and CAmbientIContainer7.1 classes, and two buttons, ‘Back’ and ‘Options’. The first container is responsible for drawing a list box with the existing routes present in the routing table. The procedure is to read the existing routes, create a list with all the elements identified before, and, after the selection by

39 the user, present the several details concerning the route chosen. To perform this functionality the container uses the socket API, more particularly the GetOpt() and SetOpt()functions, to retrieve the routes (code details in Appendix I) . The next picture illustrates the list box:

Figure 29 – View 7 Figure 30 – Options menu 7

The ‘Options’ button unveils new options to the user like the selection of the desired route, the actualization of the routing table and allows him to leave the application. To see details of a route the user simply has to select one of them and then the view activates the second container. Once again, this object will draw in the screen the several details concerning the route chosen using the function Infos(). Next is presented the snapshot of the application when the second container is active:

Figure 31 – Route information

The last option from the list box of picture 21 allows the user to add a route to the routing table. View 12, CAmbientIView12 class, creates a container object, CAmbientIContainer12, and two buttons, the ‘Back’ button and the ‘Options’ button that enables the route addition and allows the user to leave the application.

40

Figure 32 – Route introduction Figure 33 – Options menu

This container is a bit more complex then all the others due to the objects that compose it. It is constituted by four labels and four text boxes. Next is an example of the creation of one label and one text box:

TBuf text;

// Creation of the label iCoeEnv->ReadResource(text, R_VIEW5_EDWIN_1_LABEL_1); iLabel1 = new (ELeave) CEikLabel; iLabel1->SetContainerWindowL(*this); iLabel1->SetTextL(text); iLabel1->SetExtent(EDWIN_LABEL_POS1, iLabel1->MinimumSize());

First the R_VIEW5_EDWIN_1_LABEL_1 resource is loaded with the string desired. The instruction ReadResource() passes that string to the TBuf variable, then in the end the text is set and drawn in the screen.

//Creation of the textbox

TResourceReader reader1; iCoeEnv->CreateResourceReaderLC(reader1, R_VIEW5_EDWIN_1); iEdwin1 = new (ELeave) CEikEdwin; iEdwin1->SetContainerWindowL(*this);

To create a textbox the procedure is similar to the previous example. The handling for this view is also more complex than any one existing until now. The OfferKeyEventL() has to be adapted for the interaction with this user interface However, before the introduction of a new route, the user must be sure that the interface in question exists, otherwise the process will fail. The function that performs this action is AddRoute(). As referred in the Appendix H in order to introduce a route, the required route information is loaded into a TPckgBuf object which is used in the process. The fields that compose that object are: iDstAddr, iGateway, iIfAddriNetMask, iState, iType and iMetric. Only the first four elements are displayed for entering, the rest are automatic set to Up, ENormal and 0, respectively.

41 Service details

The service announcement is made right after class CAmbientIAppUi is created. This class creates a CSocketsConnection object and a timer in order to manage the presence announcements. After the IP connection is set, the announce process is started. From time to time, in this case ten seconds, the timer expires calling the TimerExpired() function that sends the request for a write through CSocketsWriter2::WriteL() with the announce message: Ami 6600ip address . This announce is made using UDP. Having its presence announced, the phone must start listening in the ports corresponding to the service discovery, SMS service and picture service. In order to be able to decode the service requests, the application is constantly monitoring the arrival of information, this time using TCP/IP, at ports 6000, 6010 and 6011. The active object in the class CSocketsReader determines from which port the information was received and accordingly to it, calls the respective decoding function. switch(port) { case 6000: Decode(iBuffer); break; case 6010: DecodeSMS(iBuffer); break; case 6011: DecodePIC(iBuffer); break; default: Decode(iBuffer); }

If the data arrives at port 6000 the function Decode() is called to test if the data corresponds to the expected “” string. If the request is recognized it follows a call to class CSocketsWriter that sends the description of the services offered at that moment. To determine the services offered it’s made a request to a notifier function that returns the information stored when the user chooses the services that he would like to offer. In the case of arriving data at port 6010, the port dedicated to the SMS service, the function DecodeSms() is called. This function searches the string received for the phone number to which the SMS will be sent and the message content. If the request is formed according to the protocol, it’s dispatched. In this case, the RequestToSms() function is called and in on its turn schedules the SMS for sending and requests the sending of the confirmation message that is sent from the CSocketsReader class. The called SmsSender() function sets up the message and the phone number that are received by the CSmsSendHandler class. It’s this class that handles the whole sending process. As many other processes, the sending of a SMS is an asynchronous process. This means that the SMS is not sent immediately but only whenever the active scheduler decides. The flow diagram shown on the next page illustrates the process of the SMS service. Notice that the different functions are classes are part of four different classes.

42

Figure 34 – Flow diagram of the SMS sending process

Whenever any information arrives at the port dedicated to the picture service, port 6011, the function DecodePIC() is called. As the other decoding functions, DecodePIC() checks if the data received corresponds to the expected picture request. If that is so, the process of capturing an image using the onboard digital camera is started. This process is rather complicated but it can be resumed. The first function called is PicCapture(), this function tries to reserve the camera, trough CCamera::Reserve(), that is the starting step of the whole process. Once again, the reservation process is a asynchronous event and in order to know when the reserve is complete it’s necessary to implement the ReserveComplete() function. This function is called asynchronously whenever the reserving process completes, the reserve can be successful or not. In the case of successful reserve it is called the PowerOn() method of the CCamera class. This method will try to turn on the camera and the PowerOnComplete() function is called just as ReserveComplete() was. If the camera is turned on it is called PrepareCaptureImage(). This function sets up the bitmap for receiving the image and calls CCamera::CaptureImage() that will call, after the picture is taken, ImageReady(). ImageReady(), on its turn, calls StartConversion() that is the function responsible for the conversion of the mbm image format returned by CCamera::CaptureImage() to a JPEG format. To do this, StartConversion() calls the function SaveImageJpeg() that once more sets up an active object from the CImageEncoder class to wait for the image conversion to complete. After all this, the image is saved in C:\Nokia\Images\ folder. Once the image is saved it is possible to start its transfer. This is done by calling RequestToPic() that sends the name and path of the image file through a notifier to SendPic() function in CSocketsEngine class that calls SendPicture() in the CSocketsWriter class. This function opens the file in binary mode and sends it to the device who requested it, preceding the data with a “+OK\r\n”, as the protocol demands. Picture 35 illustrates the process.

43

Figure 35 – Flow diagram of the picture service

It is necessary to say that the use of the SMS or Camera APIs involve some problems. Although well documented on the SDK help files, both of the APIs existing on the SDK are incomplete. In order to overcome these problems there are some things to do: - To use the camera its is necessary to download a new SDK that supports this feature, in the case of Series 60 v2.0, the Nokia 6600 camera plug-in. - To use the SMS API one needs to put the missing header and .inl files, available for download in the Symbian official website, in the epoc32\include folder. The etelmm.h file is also missing and can be found in the same place.

44 4.4 Networking

Phone configuration

Before starting the Bluetooth communication with the Linux PC, the smartphone has to be configured. For that, as referred before, the communications database has to be manipulated, in particular the DIAL-OUT ISP and MODEM_BEARER tables. For details about the communications database tables and corresponding records please refer to Appendix G.

Inside the first table, the records that are changed are ISP_DESCRIPTION and ISP_DEFAULT_TEL_NUM. Changing the first record is not mandatory, it is changed to better identify the access point used, hence, any string can be introduced. The essential modification in this table is to insert a null value in the ISP default phone number to guarantee that the smartphone doesn’t tries to establish a connection to that number. The descriptor introduced is KNullDesC , which represents a null value in the Symbian OS. An excerpt of the code is showed next: iCommDb=CCommsDatabase::NewL(EDatabaseTypeIAP); iCommDb->ShowHiddenRecords(); CleanupStack::PushL(iCommDb);

CCommsDbTableView* table=iCommDb->OpenTableLC (TPtrC ( DIAL_OUT_ISP)); table->UpdateRecord();

//Insert ISP name table->WriteTextL(TPtrC(ISP_DESCRIPTION),Kdesc);

// Insert NULL ISP telephone number table->WriteTextL(TPtrC(ISP_DEFAULT_TEL_NUM),KNullDesC);

User::LeaveIfError(table->PutRecordChanges()); CleanupStack::PopAndDestroy();

The second table that is changed is the MODEM_BEARER table, more accurately the MODEM_PORT_NAME and MODEM_CSY_NAME records. In the case of establishing a serial connection over Bluetooth, the first record needs to be BTCOMM::0. The second record, once again, is not a priority and can be assign any string desired. The following code produces those alterations in the communications database: table=iCommDb->OpenTableLC(TPtrC(MODEM_BEARER)); User::LeaveIfError(table->UpdateRecord());

//Insertion of BTCOMM::0 in the MODEM_PORT_NAME record table->WriteTextL(TPtrC(MODEM_PORT_NAME),KBtcomm);

//Insertion of a new MODEM_CSY_NAME table->WriteTextL(TPtrC(MODEM_CSY_NAME),KBtcommTxt);

User::LeaveIfError(table->PutRecordChanges()); CleanupStack::PopAndDestroy();

45 The variable KBtcomm needs to contain the string ‘BTCOMM::0’ and KBtcommTxt can have any string, for example, ‘BTCOMM’.

The application is using an access point with the name ‘BT’. When starting, the application will look for it, so in order for all of this to work a GSM data access point has to be created. This may be configured has follows: - Access point name: BT; - Data Bearer: GSM high speed; - Dial-up number: any, e. g., 2222. It doesn't matter as long as it's not empty; - Use password: no; - Password: none; - Authentication: normal; - Webpage: any; - Data type: analogue; - Max. data rate: auto. - Advanced setting: leave the default settings.

The AmI backbone is an IPv6 ad-hoc based network, thus all its participants should communicate over IPv6. Symbian 7.0 version uses a IPv6/IPv4 hybrid stack, meaning that when viewed from outside it contains a full implementation of both IPv6 and IPv4 protocol stacks. Applications based on the IPv4 protocol run in the new hybrid stack environment without recompilation. Depending on the application coding, they may also work without modification for IPv6 connections. In order for the smartphone to integrate perfectly in the network, the phone's interfaces need to be configured to use IPv6. For that, the DIAL_OUT_ISP table from the connections database has to be adapted, more specifically the ISP_IF_NETWORKS record. This record represents a list of network protocols supported by the current ISP entry separated by commas. Normally the interfaces are initialized with the IPv4 protocol, and the string present is the record is ip. To add IPv6 support to the network interface the table entry must be changed to ip,ip6 or the smartphone simply won't accept IPv6 connection requests or router advertisements. The code that performs the communications database modification is presented next.

//Ipv6 enabling data = _L("ip,ip6"); iCommDb=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(iCommDb);

CCommsDbTableView* table=iCommDb->OpenTableLC(TPtrC(DIAL_OUT_ISP)); TInt err = table->GotoFirstRecord(); User::LeaveIfError(table->UpdateRecord()); table->WriteTextL(TPtrC(ISP_IF_NETWORKS),data); err = table->PutRecordChanges();

CleanupStack::PopAndDestroy(); CleanupStack::PopAndDestroy(); iCommDb = NULL;

46 PC configuration

The interaction of the smartphone with the Linux PC requires some explaining as it is relatively complicated. The configuration of the phone has already been discussed and is know time to discuss the PC side configuration. The version of Linux installed was Fedora Core 1 that has kernel 2.4.22. To support Bluetooth it was compiled kernel 2.6.5 with all Bluetooth options enabled. The Bluez tools already are part of this kernel version. Some important tools are hcitool, hciconfig, and sdptool all part of the Bluez package. After installing all the necessary modules rebooting the PC and loading all the modules with modprobe, the Bluetooth device can be inserted in its position and, if all goes right, the PC recognises the new device and puts hci0 up and running. The hciconfig tool can be used to display information about hci0, namely the MAC address of the BT device. With sdptool the MAC address of both phone and PC device can be discovered. The possible usages are: hcitool inq, hcitool scan and hcitool dev. To request further information from the phone use hcitool info . To discover the services available by the phone one can do sdptool browse . The output of this for the Nokia 6600 is shown on Appendix I as well as the outputs of the other commands. After testing the function of the Bluetooth device on the PC and getting important information it’s time to enable basic connectivity. To do that, the following files must be changed: /etc/Bluetooth/hcid.conf – The HCID daemon configuration file. Configuration is as follows:

# HCId options options { # Automatically initialize new devices autoinit yes;

# Security Manager mode security auto; # Pairing mode pairing multi;

# PIN helper, this file must have the same pin as the phone # when pairing devices pin_helper /bin/bluepin; }

# Default settings for HCI devices device {

name "PCName";

# Local device class class 0x100;

# Default packet type #pkt_type DH1,DM1,HV1;

# Inquiry and Page scan iscan enable; pscan enable;

# Default link mode

47 lm accept,master;

# Default link policy lp hold,sniff,park,rswitch;

# Authentication and Encryption #auth enable; #encrypt enable; } /etc/Bluetooth/rfcomm.conf – The RFCOMM configuration file. The settings are: rfcomm0 { # Automatically bind the device at startup bind yes;

# Bluetooth address of the device – use hciconfig to check MAC device 00:10:60:A8:C7:FF;

# RFCOMM channel for the connection – must be the same as the # phone channel 2; } /etc/ppp/peers/options – The PPPD daemon script, where the IPs to be assigned and other connection options are selected. These are the main options: #see manual pages for instructions noauth local modem proxyarp debug ms-dns 194.117.24.1 #the DNS IP address 192.168.0.1:192.168.0.2 #IP of the PC : IP of the phone #ipv6 ::dead:beef,::dead:beff

Once these files are set, the connectivity test can be made, but first the all the daemons must be restarted and the following sequence must be entered on the command line:

[root@kim Desktop]# modprobre rfcomm (if not already loaded) [root@kim Desktop]# hcid [root@kim Desktop]# sdpd [root@kim Desktop]# sdptool add --channel=2 SP [root@kim Desktop]# dund --listen --channel=2

To be able to use the internet access of the PC, from the Opera browser of the phone (the built in browser doesn’t support this) it is necessary to enable NAT and IP forward (see Appendix J). To test the connection it’s possible to use the rfcomm tool: [root@kim Desktop]# rfcomm connect 2 2 And if all goes well the phone can be ‘pinged’ from the PC. To start the connection from the phone it’s possible to use the Opera browser or the application developed. Both will automatically try to connect to the PC if the right access point is selected.

48 In order to use IPv6 protocol it is necessary to install an IPv6 enabling patch for pppd that can be found on the internet at Peter Bieringer’s website. The pppd daemon that comes with Fedora Core 1 does not support Ipv6 and so the use of this patch is essential. To create a ppp interface using IPv6, the script file has to be updated for the new IP version support. On /etc/ppp/peers/options, the pppd daemon script, must be added the following lines: ipv6 ::dead:beef,::dead:beff nomp ipcp-accept-local ipcp-accept-remote ipv6cp-accept-local ipv6cp-use-ipaddr Note that only the IP address's suffixes are discriminated due to the IPv6 auto-configuration nature. The PPP will create a new interface, ppp0, which initially is constituted by a link local IP address. After this, in order to assign a global IP to this interface the radvd daemon is used. The configuration file is /usr/local/etc/radvd.conf and among other options it contains the prefix of the IP to be assigned. The logic behind this procedure is to have the pppd to assign the IP's suffix and then the radvd to assign the prefix. interface ppp0 {

AdvSendAdvert on; MinRtrAdvInterval 3; MaxRtrAdvInterval 10; prefix 2020::/64 { AdvOnLink on; AdvAutonomous on; AdvRouterAddr on; }; }; These settings create two ipcp6::BTCOMM::0 interfaces in the smartphone. The first network interface has a link local IP address assigned by the PPP, which is constituted by a suffix present in the PPP script file, dead:beef, and the fe80 prefix (fe80::dead:beef). Due to the scope of the IP, the PC doesn't know how to reach the smartphone, consequently it can't be ‘pinged’. For this a global scope IP is needed. The second network interface is created after the radvd has been started. The smartphone receives the router advertisement from the first interface and creates the second using the advertised prefix, 2020, and the suffix provided by the PPP. The complete IP address is: 2020::dead:beef. Now, the PC has a direct route to the smartphone which can be successfully ‘pinged’. The configuration used for IPv6 networking was as shown in figure 36:

Figure 36 – Ipv6 network configuration

49 4.5 Results

The results achieved are extremely stimulating for the consolidation of the Ambient Network concept from the mobile phone point of view. Full integration of a mobile phone was achieved, a step than brings us close to the future of mobile devices. Symbian operating system capabilities prove its value when comes to offer tools to develop applications. The main results of this project can be divided in two parts. The first one is concerned with the knowledge gained with the study of Symbian OS and the other one is the practical demonstration of the integration of the mobile phone in a network using the application developed. The study of Symbian allowed recognizing the power of this OS and the similarities to a common OS like MS Windows. Although designed for the specific requirements of mobile phones this OS offers all the tools as other OS designed for more complex devices. Symbian OS includes a robust multi-tasking kernel, integrated telephony support, communications protocols, data management, advanced graphics support, a low-level graphical user interface framework and a variety of application engines. Symbian OS provides a rich core of application programming interfaces that crucial for development, particularly when using communication protocols. The basis for communication between the phone and other devices is the IP connectivity over Bluetooth. Using IPv6 over Bluetooth instead of over GPRS or GSM data is the main step for the integration of the mobile phone and therefore it’s one of the main results. The application developed achieves the full integration of a mobile phone in a network. The integration is done by offering service to other participants in the ambient network, in this case a SMS and a picture services. By developing a SMS service it was possible to offer GPRS/GSM connectivity to allow communication to other devices. This service adds new communication ability to the network participants, being one of the integration factors. The other integration factor is the picture service. By using the onboard camera, the smartphone offers an important resource to the network. The picture service gives the possibility of any participant to have access to a new resource that it doesn’t have and use it in the way it desires. This service is currently used for a video streaming application turning the phone in a video camera. Other features were added to the application because of its utility. Through the application the user can see the interfaces, routes and the internet database setting to check important information that can be useful. New routes can also be added although in this development stage it doesn’t have practical utility.

50 4.6 Summary

This section covered various aspects related with the application and its implementation. First, it was given an overview of the Ambient Network and the prerequisites to participate in it. Other discussed issues were the services and the protocol that allows the correct communication between devices. The protocol messages are constructed in XML and for each service there is a server that listens at a specific port. The smartphone will expect service requests at port 6000, SMS requests at port 6010 and Picture requests at port 6011. Next, the application structure was dissected, separating it in all views and explaining the details about and function of each one. The first view represents the first interface with user, allowing him to access the main features of the application. One of the options (Services- >Offer) leads to the second view which permits the selecting/unselecting the services to offer to the network (but at least one has to be activated to enter an AmI network). Another option (Status) takes the application into view 6 which presents a list that gives the user access to information about the network interfaces (view 5), smartphone’s routing table (view 7), Communications Database (view 8) and allows the user to insert routes (view 12). Finally, view 9 implements a help file displaying some useful information about the AmI network and the application. The last topic involves other configuration issues regarding both the smartphone and the PC. From the smartphone’s side the Communications Database needs to be changed especially the ISP_DIAL_OUT and MODEM_BEARER tables. To enable Ipv6 on the phone it is also necessary to manipulate the first table specially the ISP_IF_NETWORKS record. Regarding the PC, in order for the steps taken in the last section to succeed, the files /etc/Bluetooth/hcid.conf, /etc/Bluetooth/rfcomm.conf, the ppp daemon script present in /etc/ppp/peers/options and the /usr/local/etc/radvd.conf must be correctly configured.

51 5. Project evaluation

5.1 Testing procedure

The first tests with the hardware were made using that runs Symbian OS v. 6.1. For this version of Symbian there is a program called GNUBOX that turns the one-box phone into a two-box phone. The test consisted in applying the necessary changes to the phone’s internet database, as explained in the preceding section, and try to connect to the PC using TCP/IP. To do this the Linux PC had to be configured to support minimum Bluetooth connectivity and the usage of the rfcomm tool. By doing rfcomm connect a TCP/IP session was created with the approximate duration of one minute, after this the phone closed the connection. It was this test that allowed the continuation of the idea of having the phone using IP over Bluetooth. The development started with simple applications for Symbian version 7.0, Series 60 v. 2, based on the examples. These applications allowed learning some important programming skills that were very useful through all the development phase. The first programs, based on console applications proved to be a good way to start from as the console applications are similar to common C++ programs. GUI applications were more difficult to manage but after some time a few tests were successful. The first GUI applications used simple drawing schemes and other GUI elements like lists to show some information about the network, routing tables and CommDb. The figure bellow show some views of a test application on both emulator and real device.

Figure 37 – Views of a test application on emulator (left) and Nokia 6600 (right)

After a first approach to Symbian programming, the real development started. It was developed a simple program that used GPRS connectivity to initiate and terminate an IP connection to a remote host. The next step was to make some data transfer and for this it was established a connection to port 80 of a remote HTTP server and then sent a GET command that retrieved the contents of a webpage. Having dominating the connection process over GPRS it was initiated the transition to Bluetooth. In order to do this, it was necessary to make some changes for the GNUBOX

52 application to run on Symbian 7.0. The configuration of the phone and Linux PC made possible to have access to the PC’s internet connection and use the Opera browser to view some web pages. This type of access didn’t result in any charge as the GPRS counter remained unchanged. The architecture of this experience is shown on the next figure.

Figure 38 – Internet connection sharing architecture The next step was to make a stable connection to the PC and to start it from the phone. For this to happen, an ftp server was installed in the Linux PC and a program that connected to port 21 of the PC was developed. This program sent ftp commands like user and displayed the returned response of the server on the screen like 331 password needed for user . After having the IP over Bluetooth connection stable it was started the development of the final application, i. e., the service implementation. The first to be implemented was the SMS service. In a first approach, it was added the functionality to send a predefined SMS message from a menu in the application. Then, it was used the protocol that defines all the messages exchanged as explained in the previous section. A server program was made to monitor a determined port and seek for a message with the phone number and content of the SMS message to be sent. Using telnet, it was sent to the phone the message that it was waiting for and an SMS was successfully sent. A test with a SMS client program with an user interfsce was also made. The architecture used is shown on figure 38.

Figure 39 – Architecture used in the SMS service test phase.

53 The picture service required more work as it needed the use of camera API functions that are rather complicated. To overcome this difficulty it was used a simple example to start from and from it was added to the application the ability to take a picture and save it in a file. The method used to take pictures and save them, saved the pictures in a format called multi- bitmap, an .mbm file. This type of file is not supported by Linux (for Windows there is a tool called bmconv that converts .mbm to .bmp files) and to be possible to display the image it was necessary to convert .mbm format to .jpg using functions from the phone’s API. After solving this problem, it was made a server application that took pictures whenever prompted by the computer using telnet. Then, it was only necessary to adapt the application code to send the picture back to the device who requested it. The architecture used was just like figure 39 illustrates.

Figure 40 – Architecture used in the picture service test phase

The final test using IPv4 consisted in providing the picture service to a streaming client application. Instead of running this application in a PDA, it was run on the Linux PC where all the tests were made. The result was successful proving that the protocol was well implemented in both applications. To test IPv6 it was necessary to set up the PC using the Ipv6 enabling patch for pppd and the router advertising daemon, radvd. The test was the same has the previous with the difference of the IP addresses that were changed to IPv6.

5.2 Test validation

In this section it was presented a set of test made to validate the work being done through the semester. It was the initial tests that allowed the proceeding of the project as they gave good clues of what to expect in the future. Having made several tests in each important step made possible to continue the development with assured success. The last three tests were made in conditions very close to the scenario to be set up for the presentation. These tests provide evidences that the main objective of this project was accomplished and, since all the final tests made were successful, they are a guarantee that thee application has a minimum of functionalities proven.

54 6. Conclusion

6.1 Review of the objectives and results

This project had the main objective of achieving the integration of a mobile phone, running Symbian operating system, in a local ad-hoc network that is constituted by devices like PDAs and personal computers. As Symbian was an unknown OS, the first part of the project was dedicated to the study of its capabilities and programming languages. The experimental development made with Java programming language and the evaluation of its APIs gave an overall idea of its capabilities, advantages and disadvantages. In the case of the native programming language, all the work developed, study and implementation allowed a good acknowledgement of Symbian’s C++ programming. The testing of Symbian’s communication capabilities was completely achieved, except in the case of Infrared technology, as it is of less interest. Multiple GPRS tests were made and total connectivity to a server was accomplished, proving the possibility of using this technology for integration purposes. Bluetooth connectivity was exhaustively tested and the results achieved prove it. A very important result of this work, as it is the base requisite of the integration is the IPv6 connectivity over Bluetooth instead of GPRS. This constitutes the communication backbone to any service used or provided by the AmI network participants. The objective of the integration in an ambient network was completely fulfilled as the developed application provides services to other devices by using resources that only the phone has, like GPRS/GSM and a camera. The services provided are two: a SMS service and a picture service. The SMS service allows other devices with IP connectivity to the phone to send SMS messages by using the GSM/GPRS network through the smartphone. The picture service gives the chance to use the onboard camera of the phone almost as a webcam. The phone takes pictures, when requested by a client application running on other device, and sends them back to the device that is using the service. These two services give an excellent demonstration of the Ambient Intelligence concept.

6.2 Main conclusions

This project leads to conclude that Symbian OS is the most important tool to allow the integration of a mobile phone in an ambient network and the results achieved demonstrate this statement. The study of Symbian OS allowed to recognize its powerful APIs, the base of all development, and so providing the foundations for the development of applications. This project represents the first work done on Symbian and the results accomplished lead to expect greater achievements from this operating system. The demonstration of the integration concept is a very important result as it allows seeing the mobile phone as a new fully fledged

55 member of a local area network. The ambient network with a mobile phone participant is from this moment a reality. As Symbian is an operating system open for third-party development, now it’s a matter of developing new applications to reach further integration by providing and using new useful services. The development possibilities in this area are almost unlimited and business opportunities seem very good too.

6.3 Future work

As stated previously this project opens a new window of opportunities to develop new applications in this area and also to do enhancements in the present application. The enhancements to do in this application, until the demonstration session, are: ƒ Improve the User Interface of the application; ƒ Add a new view to allow the visualisation of the log created when the phone exchanges messages to other devices. New developments that this work can lead to are: ƒ Add the service discovery functionality to the application; ƒ Integrate a XML parser in the application for a more efficient decoding of services and requests; ƒ Use GPRS to offer services. For example, the picture service can be modified to send the data over GPRS to a reachable host and so offering the possibility of having this service always available; ƒ Provide internet access to other devices by turning the phone into a kind of GPRS gateway. Other ideas for projects: ƒ Develop an application that acts as a Linux shell; ƒ Explore Java networking capabilities; ƒ Multiplayer games using Bluetooth.

56 Appendix A – Symbian’s History

The Psion Years (1980-1998) • 1980 - Psion is founded by David Potter. Psion stands for Potter's Scientific Instruments, and just add an "ON" to it... • 1984 - Psion launches the Psion Organizer, the world's first volume-produced handheld computer, a single line 2 kb model... • 1986 - The Organizer II is released. • 1989 - Psion releases the A4-sized MC 400 - an EPOC laptop. Way ahead of its time, it was a big flop. • 1991 - Psion introduces the EPOC OS (Electronic Piece Of Cheese, according to the legend). • 1991 - The first palmtop appears, a 128k model. • 1993 - The Psion 3a is released. • 1996 - The Psion 3c is released. • 1996 - The Psion Siena is released. • 1997 - Psion Series 5 - the first EPOC32 (32-bit) palmtop. • 1998 - The Psion 3mx is released. • June 1998 - Symbian is established as a private independent company and is owned by Ericsson, Nokia, Motorola and Psion 1999 • January - Symbian expands into Scandinavia with acquisition of Ericsson Mobile Applications Lab • March - Ericsson unveils new mobile companion mc218 with Epoc • May - Matsushita joins as a Symbian partner • June - Psion releases the Psion 5mx. • September - Psion launches the Series7 handheld. • October - Psion releases the Psion Revo. • December - Microsoft, Ericsson announce strategic partnership to drive mobile Internet market. 2000 • January - Motorola and Psion agree joint development alliance for wireless information devices, and start developing the later abandoned Odin smartphone. • February - Ericsson presents its first communicator platform, which was never released. • May - Sony Selects Symbian for Its Next-Generation Wireless Phones. • May - Kenwood licenses Symbian OS, to develop smartphones.

57 • August - Sanyo Licenses Symbian Technology. • September - Symbian ships Version 6 of its software platform to licensees. • September - Psion launches the Revo Plus. • October - Sanyo and Phoenix preview wireless internet Communicator - the first Mobile Communicator device based on the Symbian platform (ESG-EP100). • October - S3 enters PDA market with Diamond Mako - a rebranded Revo plus. • November - The world's first Symbian OS phone, the Ericsson R380 Smartphone, ships. • November - Nokia announces the world's first Symbian™ based Communicator. 2001 • January - Metrowerks to provide development tools for Symbian. • January - Motorola and Psion cancel the Smartphone joint development. Project Odin is cancelled. • February - Siemens signs licensing aAgreement to use Symbian software platform for its future smartphones. • February - The joint Psion and Motorola Quartz design called Odin is cancelled. • June - The world's first open Symbian OS phone became available - the Nokia 9210 Communicator. • June - Nokia announces the 9290 communicator - the first Symbian Smartphone in the US. • October - has announced the availability of the netPad, a rugged Symbian OS handheld tablet. • November - Fujitsu Selects Symbian Operating System for 3G Phones. • November - Nokia introduces the Series 60 - a licensable UI for Symbian. • November - The first 2.5G Symbian OS phone, the Nokia 7650, is announced. The 7650 is the first mass-market Symbian phone and it is based on the Nokia series 60 reference design. 2002 • February - Symbian announces UIQ user interface application for Symbian OS. • March - Symbian OS powered Sony Ericsson P800 Smartphone announced. • April - Siemens joins Symbian as Shareholder. • May - Siemens licenses Series 60 from Nokia. • September - Nokia announces the 3650, a Series 60 smartphone • October - Samsung licenses Symbian OS for smartphones. World’s top five mobile phone manufacturers now Symbian OS licensees. • November - Sendo ditches MS smartphone OS, goes with Symbian (licenses Nokia Series 60) and sues Microsoft accusing the software giant of stealing its technology and customers. • November - Nokia announces the N-Gage, a series 60 based game deck phone.

58 • December - Fujitsu has completed development of a Symbian OS smartphone for NTT DoCoMo's FOMA 3G network - The F2051. 2003 • February - Samsung becomes Symbian shareholder • February - Siemens announces the SX1, a Series 60 smartphone • February - BenQ licenses Symbian OS for smartphones, and also has been demonstrating an OS 7, UIQ-based device • March - Mitsubishi licenses Symbian OS & shows first concept model based on Symbian OS at CeBIT. • March - Samsung announced its first Symbian OS handset, the SGH-D700, a clamshell Series 60 device. • April - Symbian publishes OPL language source code under LGPL. • April - Symbian launches Symbian OS v7.0s at Exposium03. • June - First smartphone based on Symbian OS v7.0s launched by Nokia - The 6600 • July - Fujitsu uses Symbian OS for its latest videophone for NTT DoCoMo’s FOMA 3G service in Japan - the F2102 • August - Motorola finally announces the A920 3G Symbian phone. • September - Motorola announces the long rumoured Microsoft-powered smartphone, the clamshell MPx200. • September - Symbian signs a development agreement with NTT DoCoMo. • October - Motorola leaves the Symbian Camp, selling its stake to Nokia and Psion. • October - The N-Gage, the first Symbian game-deck is now available. • October - Nokia announces two new Symbian phones, the 3660/3620 - updates to the 3650. • October - Sendo X announced the first Symbian (series 60) smartphone from Sendo. • October - Sony Ericsson announces the P900 - an upgrade to the P800. • October - Nokia announces the first "Media" phone, the TV-enabled 7700, based on the new "Series 90". • October - The 6600, a V7.0 based series 60 phone is available. • December - The SX-1, Siemens first Symbian () phone is available. 2004 • January - Nokia announces the 6620 - first EDGE Symbian phone (S60). Basically a 6600 with EDGE. • January - Fujitsu announces the F900i. • February - Psion sells its Symbian stake to Nokia, pending shareholders approval. • February - Legend (Lenovo) is now a Symbian licensee. • February - LG is now a Symbian licensee. • February - Arima is now a Symbian licensee.

59 • February - Symbian OS v8.0 is announced. • February - UIQ v3.0 is announced, with one hand support. • February - Three now phones are announced in 3GSM/Cannes - Nokia 9500, MOT A1000 and Panasonic X700. • March - Psion Shareholders approve the sale of Symbian. • March - Nokia announces the 7610, first MegaPixel camera from Nokia. • March - Samsung announces the SGH-D710, a S60 Megapixel phone. • April - Nokia announces the N-Gage QD. • May - Fujitsu announces a new FOMA phone - the F900iT. • June - Nokia announces two new S60 phones - the 6260 and 6630.

60 Appendix B – How to create a Java application

To write a simple application, bring up a DOS prompt, cd to the erj sub-directory in the place the SDK is installed, and type:

> mkdir Hello > cd Hello > notepad Hello.java

The erj directory contains various Java-related files, such as the classes.zip file, and is a convenient place in which to perform Java development.

Type in the following Java program, a graphical version of Hello World: import java.awt.*; import java.awt.event.*; public class Hello extends Frame implements ActionListener {

public static void main(String[] args) { Hello hi = new Hello(); }

Hello() { Label lab = new Label("Hello world"); Button but = new Button("Dismiss"); but.addActionListener(this); addWindowListener(new Goodbye()); setLayout(new GridLayout(2, 1, 10, 10)); add(lab); add(but); pack(); show(); }

public void actionPerformed(ActionEvent e) { dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }

private class Goodbye extends WindowAdapter { public void windowClosing(WindowEvent e) { System.out.println("Goodbye"); System.exit(0); } } }

61 Save this program in Hello as Hello.java (case sensitive), and compile it into a Java class using the Java compiler present in the JDK. If using the Sun tools, the compiler is called javac:

> javac Hello.java

If the compilation is not successful it may be needed to set (or reset) CLASSPATH by typing: set CLASSPATH= to reset the classpath, or set CLASSPATH=”drive:\” at the DOS prompt before building any Java projects for the SDK.

Successful compilation will generate a pair of Java class files in the current directory named Hello.class and Hello$Goodbye.class. The Hello class contains the application's main() method, the entry point for all Java programs.

Hello World application can now be run, either in the Java Runtime Environment on a PC, or in the Emulator. To run on Windows, just type (from the Hello directory):

> jre -cp . Hello

A Windows application frame containing the text Hello world, and a Dismiss button should appear. To start up a debugging version of the Emulator and run the Hello application, type:

> \epoc32\release\winscw\udeb\pjava_g -cp j:\Hello Hello

Finally, to package both class files together into a Java Archive file, from the Hello directory type:

> jar cf helloapp.jar *.class

This will generate a convenient package of classes in the current directory, named helloapp.jar.

To run Java applications in the same way as other, native C++ applications, it’s necessary to perform a few extra steps to wrap up the Java application appropriately. One needs to create some extra files that together contain the information that the Launcher needs to run a program. This is handled by an application provided with the SDK called AIF Builder, which you can be found in the Windows Start menu. The basic steps are:

1. Go to the directory \epoc32\winscw\c\system\Apps and create a new sub-directory called Hello. This directory will be used to hold the extra files that AIF Builder will create. Copy the jar file to this directory (helloap.jar). 2. Start AIF Builder and do File New to begin a new project. 3. On the Application tab, fill in the details as follows: Application Language: Java; Application Name: Hello; Application UID: 0x01000000; Java Command Line Text: -cp helloapp.jar Hello

62 4. Now switch to the UI variants tab. Under Customise Icon go to the UIQ tab. Set Location to generate files to \epoc32\winscw\c\system\Apps\Hello. Set Output directory for temporary files to any convenient location where temporary files can be put.

There's more to do, such specifying the icon to be used for the application, but this is the minimum required. Press the Generate button and after a short time, AIF Builder should create the following files:

• Hello.app • Hello.txt • Hello.aif and the temporary file Hello.rss.

Now run the Emulator using the Emulator (release) shortcut from SDK program group. On the Launcher screen, among the other standard applications, will be the Hello application.

63 Appendix C - First approach to Symbian C++ programming

In order to start developing on the Symbian OS it is necessary to take a few steps. First of all it is mandatory to: • Identify the target device – will the application run on Nokia 7650, 6600 or N-Gage, SonyEricsson P900 or Siemens SX1? All of these phones, even if all based on Symbian OS, are not completely compatible: Symbian OS is just the name of the low- level operating system and the middleware objects. In top of it comes the GUI system. This system is not licensed directly by Symbian with its OS. It’s up to each phone manufacturer to develop its own GUI or to license a GUI platform that can runs on top of the OS. Currently three main GUI systems: Nokia Series 60, Nokia Series 80 and UIQ. The following table summarizes

GUI Specificities Phones Series 60 v1.x + Resolution=176x208 Phone Nokia 3650, Nokia 7650, Symbian OS 6.1 Keyboard No touch screen Nokia N-Gage, Siemens SX1, Samsung SGH- D700, Sendo X

Series 60 v2.0 + Resolution=176x208 Phone Nokia 6600

Symbian OS 7.0s Keyboard No touch screen

Series 80 + Symbian OS Resolution=640x200 Full Nokia 9210

6.0 Keyboard No touch screen

UIQ v2.0 + Symbian Resolution=208x320 SonyEricsson P900, OS 7.0 Optional Keyboard Touch BenQ P30 screen

Table 2 – Main GUI systems

• Choose the development environment – once selected the platform, there is second step to make: which SDK / IDE shall to use. There are currently three main options: Visual C++ 6.0 (or Visual Studio .NET), Metrowerks CodeWarrior for Symbian OS and Borland C++ Builder, Mobile Edition. Metrowerks CodeWarrior, although, is the only environment that can target all platforms (at least Nokia Series 60 and UIQ).

• Which PC to use – most of today’s PCs are suitable for Symbian development. It is just needed enough memory and Windows NT, 2000 or XP.

Download and install the SDK – there are many sites from where the SDKs can be downloaded.

64 Appendix D – How to create a C++ application

It is traditional to create Hello World application when starting to develop in a new platform. A simple Hello World project can be created as it follows. To start, create a component description file. This file always has the name bld.inf and contains a list of all the project definition files (frequently, there is only one) that make up the component. In more complex cases it will usually contain further build-related information, for a simple application it simply specifies the name of the .mmp project file to be built: PRJ_MMPFILES HelloWorld.mmp

In the HelloWorld.mmp, the project specification file, type: TARGET HelloWorld.app TARGETPATH \system\apps\HelloWorld TARGETTYPE app UID 0x100039CE 0x10004299 SOURCEPATH . SOURCE HelloWorld_Main.cpp SOURCE HelloWorld_Application.cpp SOURCE HelloWorld_Document.cpp SOURCE HelloWorld_AppUi.cpp SOURCE HelloWorld_AppView.cpp RESOURCE HelloWorld.rss USERINCLUDE . SYSTEMINCLUDE \epoc32\include LIBRARY euser.lib apparc.lib cone.lib eikcore.lib Notes:

• TARGET and TARGETPATH specify the name and path respectively of the application; • TARGETTYPE is specified as app, meaning the program is a GUI application • The UID line specifies the unique system identifier for a GUI application (0x100039CE) and the unique identifier for this application (in this case 0x10004299). • SOURCE statements list the project's five .cpp source files. The source files are in the same directory as the project file, so the SOURCEPATH is . (i.e. the current directory). • Sources for application resources, which define all text shown by applications, as well as all menus, dialogs, and other customisable screen furniture, are specified by RESOURCE statements. Resources are compiled by a resource compiler, which is called as part of the build process. • The locations of project-specific and system headers files are specified by the USERINCLUDE and SYSTEMINCLUDE statements respectively • The LIBRARY statement lists the application framework and graphics libraries required for a GUI

After this, use the mmp file to create the project file for the chosen IDE and edit the source and header files with the code given in the SDK help. To build the project see Appendix E.

65 Appendix E – Building an application

Building an application from the command line

Using the command line it is possible to build for any target. The procedure is summarised below.

1. Create a project specification (.mmp) file. 2. Create a component definition file (bld.inf). In many cases this will specify a single project mmp file. 3. Run bldmake from the directory where the bld.inf file is located:

> bldmake bldfiles

This creates an abld.bat batch file, which is used in the next step.

4. Use abld build to build the project.

This builds the project for all valid targets and both release and debug variants. To build for a particular target and variant, use abld build target-name variant, for example

> abld build winscw udeb

to build for the debug variant of WINSCW.

The build is split into six phases:

• The export phase copies exported files to their destinations. This typically includes copying public header files into the \epoc32\include directory. For many applications, as in the current case, this stage will need to do nothing. • The makefile phase creates the necessary makefiles or IDE workspaces. • The library phase creates import libraries. • The resource phase creates the application’s resources files, bitmaps and application information files (aifs). • The target phase essentially creates the application’smain executables. • The final phase is present to perform any final actions that need to be done after the main executables have been created. For most applications, this phase will do nothing.

66 Building from the CodeWarrior IDE

Using the CodeWarrior compiler from the CodeWarrior IDE it possible to build for WINSCW platform and also for ARM targets, this invokes the Cygnus GCC toolchain, rather than CodeWarrior's own compiler.

The simplest way to use CodeWarrior, is, after defining a bld.inf file and a .mmp file, choose the File | Import project from .mmp file command. CodeWarrior then reads the .mmp file selected, and generates and opens a CodeWarrior project. Then, the normal CodeWarrior commands can be used to run, build, and debug the project.

The IDE project files have special build steps which invoke the resource compiler, so for projects that use resources, this does not need to be run separately. The IDE does not currently support building of multi-bitmap files and of AIF files: these will need to be built from the command line.

A slightly longer method is available that creates a CodeWarrior IDE project from the command line. To do this, run bldmake bldfiles as described, and then, to generate a CodeWarrior IDE project, use:

> abld makefile CW_IDE

This creates an importable project file project-name.xml in the directory \epoc32\build\absolute_path_to_mmp_file\mmp_basename\winscw\.

CodeWarrior can now read this file and from it generate a project file of its own native type (an .mcp file). Start CodeWarrior, choose the File | Import Project... command, select the HelloWorld.xml file, and choose a name for the CodeWarrior project (such as HelloWorld again). CodeWarrior will now generate and load the project.

Building from the Microsoft Visual C++ IDE

Applications for a WINS emulator can be buit from the Microsoft Visual C++ 6 IDE.

To do this, define a bld.inf file and a .mmp file, and run bldmake bldfiles as described.

To generate a MS Visual C++ IDE workspace, use:

> abld makefile vc6

The .dsw and .dsp files are created in the directory: epoc32\build\absolute_path_to_mmp_file\mmp_basename\wins\.

The IDE project files have special build steps which invoke the resource compiler, so for projects that use resources, this does not need to be run separately.

67 File types involved in the build process:

.mmp makmake makefile project — specification of a project, input to makmake

.winscw makefile, for use by command-line compilations for WINSCW, output from makmake

.wins makefile, for use by command-line compilations for WINS, output from makmake

.winc makefile, for use by command-line compilations for WINC, output from makmake

.armi makefile, for use by command-line compilations for ARMI, output from makmake

.make build batch makefile, for use by abld for the purposes of building, output from bldmake bldfiles

.cpp C++ source file

.h header file, for inclusion in C++ file

.rss resource source file, for input to rcomp

.rh resource header, for inclusion in resource file

.hrh common C++ or resource header, for inclusion in either type of source file

.rsg generated resource header file, output from rcomp

.rsc generated resource file, output from rcomp

.bmp bitmap file, in format, input to bmconv (can also be output)

.mbm multi-bitmap file, generated by Symbian OS bitmap compiler, output from bmconv (can also be input)

.def linker definition file, for input to link and dlltool, and can be output by deftool

.frz freeze file, really a .def file containing the entry points which must be frozen, for input to deftool

.lib static library containing stubs for DLL linking, output from link or dlltool, input to link or ld

.map map of entities in an executable, output by linker

.exe program — a type of executable, output by link or ld

.dll dynamic link library or DLL — a type of executable, output by link or ld, dynamically loaded at run-time by the .exe loader, or by other executables under program control

.app a GUI application — a DLL which implements the application architecture interface

.aif Application information file, as defined by the application architecture, output by aiftool

Table 3 – File types list

68 Appendix F – How to create a simple installation file

Symbian OS Installation (sis) files can be created manually or using the Sisar tool provided with the SDKs. Sisar packages all the application files into one .sis file for ease of installation onto target hardware. Manually created .pkg files can be imported into Sisar. The simplest installation file is one which simply bundles an application's files and installs them to a specified location on the target phone. The process is:

1. Create a text file with extension .pkg. 2. Specify the package header. In the simplest installation this consists of the application’s name, its UID, and its major, minor and build numbers. 3. Specify the source location of files which should be installed and their destination on the target machine. 4. Invoke the Installation File Generator on the package file. Example The project file for a minimal installation could be: #{"My application"},(0x10004299),1,0,0 ; Only two files to install for the minimal application "MyApp.app"-"!:\system\apps\MyApp\MyApp.app" "MyApp.rsc"-"!:\system\apps\MyApp\MyApp.rsc"

The package header defines the application’s name “My application”, UID (0x10004299), major and minor build numbers (1 , 0) and the build number (0). The second line, preceded by a semi-colon, is a comment. The final two lines specify the location of the files which should be put in the installation file, and their destination on the target machine.

To create the installation file MyApp.sis, invoke the Installation File Generator on the package file: > makesis MyApp.pkg

MyApp.sis can then be installed on the target machine. After installation the application may be run by selecting the MyApp icon on the extras bar.

Important remarks: • The UID is a unique number, used to identify the application. • Relative path names should be used to specify source files. By default .sis files are compressed. If the NOCOMPRESS option is set then the Software Installer uses the filename directly. The .sis file will have a relative path which will result in a "Bad name" error when the .sis file is installed. This will happen with the PC installer and Symbian installer. The full path should be specified as the .pkg file will result in a "Bad name" error when the .sis file is installed. • The application's major and minor version numbers are required for version control (eg. AppName 3.1 specifies a major build 3, and minor build 1.) • The build number is generally incremented whenever the component is rebuilt. • Lines preceded by a semicolon are comments. These are ignored by the Installation File Generator. • The target drive is (probably) selected by the user. This is indicated in the pkg file by specifying ! as the destination drive, rather than, for example, c:. • If directories in the installation path do not exist, they are automatically created by the Symbian Installer.

69 Appendix G – The Communications Database classes

A client must first access the communications database through DBMS. This is done using the services of CCommsDatabase object, which inherits from CComsDatabaseBase.

Basic procedure As already referred, the standard way to access the Communications Database is through the following steps: 1.Create a new database object; 2.Use this database object to create a view of a data table; 3.Select a record – either by creating a new record or finding an existing one; 4.Manipulate this record – read from or write to it as needed; 5.Commit any changes made to the record; 6.When completed, delete the view and database objects.

Creating the database object A client constructs a CCommsDatabase object using the static NewL() function of the CCommsDatabase class. In common with all servers, the first client to attempt to connect to the server causes that server to start. The database is opened with shared access. If the communications database does not exist when NewL() is called, it is created, with empty tables, before trying to connect to the DBMS. Among other NewL() functions this is the main one: static CCommsDatabase* NewL(TCommDbDatabaseType aType);

In this case, like in all servers, the first client to attempt a connection to the server causes it to start. If the communications database does not exist when NewL() is called, it is created, with empty tables, before trying to connect to the DBMS. The type of database that is to be created has to given to the function. The aType parameter indicates the type of database the client is expecting to open. The two types are: ƒ IAP type: the database has an IAP table, which defines sets of ISP, modem, location and chargecards which may be used together. ƒ ISP type: the database is arranged using separate ISP, location, modem and chargecard tables whose records are not associated by using IAPs.

Creating a view of the database Access to an individual table is gained by opening a view on that table. A view is simply a subset of the records (or rows) within a table, selected according to defined criteria. Tables, records, rows, columns, and so on, are DBMS concepts. CommDb uses a

70 CCommsDbTableView object to encapsulate a view on a specific table. A view is constructed using for example this CCommsDatabaseBase member functions:

CCommsDbTableView* OpenTableLC(const TDesC& aTableName); CCommsDbTableView* OpenViewLC(const TDesC& aTableName, const TDesC& aSqlQuery);

The first function opens a view onto a whole table, aTableName - reference to a descriptor containing the name of the table - and returns a pointer to that view. The view excludes hidden records, unless access to them has previously been explicitly requested by calling the ShowHiddenRecords() member function of this object. If the open process is successful, the function constructs and returns a pointer to a CcommsDbTableView object which encapsulates the information on that view. The pointer is also put onto the cleanup stack. The second function opens a view onto a specified table based on an explicitly coded SQL query, and returns a pointer to that view. The view includes all those records which match the SQL query supplied in the descriptor aSqlQuery. It’s the caller's responsibility to code this query correctly.

Acessing and reading records Within a given view, there is always the idea of a cursor which points to a current record. The CCommsDbTableView class offers three functions which allow a client to navigate between records:

GotoFirstRecord() – sets the cursor to point to the first record in the view. GotoNextRecord() – sets the cursor to point to the next record in the view. GotoPreviousRecord() – sets the cursor to point to the previous record in the view.

Should any of these functions find that it cannot navigate as requested, it will return the KErrNotFound error code. The CCommsDbTableView class offers functions which allow a client to read from or write to named columns within the current record. There are specific functions for reading and writing columns of: unsigned integer type, boolean type, short length narrow (ASCII) text, short length wide (Unicode) text and long text (ASCII or Unicode): void ReadUintL(const TDesC& aColumn, TUint32& aValue); void ReadBoolL(const TDesC& aColumn, TBool& aValue); void ReadTextL(const TDesC& aColumn, TDes8& aValue); HBufC* ReadLongTextLC(const TDesC& aColumn);

These functions read integer, Boolean or string data, from the column whose name is given in the first parameter, into the variable given as the second parameter.

71 Creating and Editing Records All changes must start with a call to the CCommsDbTableView member functions InsertRecord() or UpdateRecord(), depending on whether a new record is to be inserted or the current record changed. TInt InsertRecord(TUint32& aId);

This function prepares the database to insert a new record and puts the unique Id associated with this new record in aId.

TInt UpdateRecord();

As referred this function prepares the update to the current record.

To actually modify a record, the functions used are: void WriteUintL(const TDesC& aColumn, const TUint32& aValue); void WriteBoolL(const TDesC& aColumn, const TBool& aValue); void WriteTextL(const TDesC& aColumn, const TDesC8& aValue); void WriteTextL(const TDesC& aColumn, const TDesC16& aValue);

When compared with the read functions, these are quite analogous: the name of the coloumn is given as a string for the first parameter and the value to be written is given as the second. Once again the following kinds of data can be written: integer, Boolean, and string. After these steps and depending if a record has been inserted or just changed, the functions PutRecordChanges() or CancelRecordChanges() need to be called. PutRecordChanges() confirms the changes to the record while CancelRecordChanges() causes the changes to be abandoned. No read type operations can be made while a change to a record is in progress. Any attempt to call a read type function in between, for example, a call to UpdateRecord() and a call to PutRecordChanges(), raises a panic.

TInt PutRecordChanges(TBool aHidden=EFalse, TBool aReadOnly =EFalse);

This function also allows the user to hide records as they are commited to the database or to designate them as read-only. Before closing access to the database, changes to a record can be cancelled by using the following function that works for both InsertRecord() and UpdateRecord() void CancelRecordChanges();

Deleting records

Records are deleted by a call to the CCommsDbTableView member function DeleteRecord().

TInt DeleteRecord();

This function is not normally followed by any write operations; in addition, neither of the functions PutRecordChanges() nor CancelRecordChanges() is called after a record is deleted.

72 Transactions and locking

More than one client can concurrently share information in the database without fear of it being changed while in use. CommDb uses the concept of transactions to implement this, making use of the underlying DBMS mechanism to set the necessary locks. Within a transaction, a client can safely read records without fear that those records may be changed between successive read operations. A client can also, safely, make changes to the database within a transaction. The CcommsDatabaseBase class provides three member functions which provide the necessary support for transactions: BeginTransaction(), CommitTransaction(), and RollbackTransaction(). BeginTransaction() marks the beginning of a transaction: it tries to get a shared read-lock on the database. Other clients can also get a shared read-lock on the database allowing them to read records concurrently. Once a client has a shared read-lock, any subsequent operation by that client which attempts to write to the database will attempt to upgrade the shared read-lock to an exclusive write-lock on the database; this succeeds only if no other client already has a lock on the database. This behaviour is provided by the underlying DBMS. CommitTransaction() marks the end of the transaction committing any changes to the table: it unlocks the database, removing the client's shared read-lock if no write operations were performed, or the exclusive write-lock if write operations were performed. RollbackTransaction() marks the end of the transaction but abandons any changes made since the call to BeginTransaction(): it unlocks the database, removing the client's shared read-lock if no write operations were performed, or the exclusive write-lock if write operations were performed.

Global Settings

There is a special table which holds global settings that govern all connection attempts, they are miscellaneous settings. Global settings can be read, written and cleared using a different set of functions: void GetGlobalSettingL(const TDesC& aSetting, TUint32& aValue); void GetGlobalSettingL(const TDesC& aSetting, TDes& aValue); void SetGlobalSettingL(const TDesC& aSetting, TUint32 aValue); void SetGlobalSettingL(const TDesC& aSetting, const TDesC& aValue); void ClearGlobalSettingL(const TDesC& aSetting);

Each function takes the name of the setting to access as the first parameter and the second parameter represents the value to be read or written according to the desired functionality.Next are detailed the several global settings existing in the Communications Database:

• DIAL_OUT_ISP • WAP_ACCESS_POINT • DATABASE_TYPE • ASK_USER_BEFORE_DIAL • CLIENT_TIMEOUT • ROUTE_TIMEOUT • DIAL_OUT_IAP • REDIAL_ATTEMPTS

73 • MODEM • LOCATION • CHARGECARD • SMS_BEARER • GPRS_ATTACH_MODE • ACCEPT_INCOMING_GPRS • GPRS_CLASS_C_BEARER • CONNECTION_ATTEMPTS • SMS_RECEIVE_MODE • MODEM_DATA_FAX • MODEM_PHONE_SERVICES_SMS • LOCATION_DATA_FAX • LOCATION_PHONE_SERVICES_SMS • MAXMBUF_HEAP

Existing tables

As referred there are a great number of tables and records. The tables are enumerated next but the records aren’t due to its extremely large number.

• Chargecard table • Connection preferences table • Dial-out ISP table • Global table • IAP table: an Internet Access Point (IAP) defines sets of ISP and chargecard that can be used together • Incoming GPRS table • Location table: affects how telephone numbers are dialled • Modems table • Outgoing GPRS table • Proxies table • WAP access point table • WAP IP bearer table • WAP SMS bearer table

To acquire a better insight of the records the user can perform a dump of all the tables from the communications database of the emulator. The program is ceddump.exe, located at \epoc32\release\winscw\udeb and the result is a text file named cedout.cfg that contains important information.

74 Example 1 – Manipulating DIAL_OUT_ISP table

CCommsDatabase* db; db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db);

CCommsDbTableView* view = db->OpenTableLC(TPtrC(DIAL_OUT_ISP));

TInt ret=view->GotoFirstRecord(); if (ret != 0) User::Leave(ret); view->ReadTextL(TPtrC(ISP_DESCRIPTION), IspDesc); view->ReadTextL(TPtrC(ISP_TYPE), IspType); view->ReadTextL(TPtrC(ISP_DEFAULT_TEL_NUM), IspTelNum); view->ReadTextL(TPtrC(ISP_LOGIN_NAME), IspLogin); CleanupStack::PopAndDestroy(); //VIEW CleanupStack::PopAndDestroy(); //db db = NULL;

Example 2 – Manipulating the MODEM_BEARER table

CCommsDatabase* db; db=CCommsDatabase::NewL(EDatabaseTypeIAP); CleanupStack::PushL(db);

CCommsDbTableView* view=db->OpenTableLC(TPtrC(MODEM_BEARER)); TInt ret=view->GotoFirstRecord(); if (ret != 0) User::Leave(ret); view->ReadTextL(TPtrC(MODEM_AGENT), ModemAgent); view->ReadTextL(TPtrC(MODEM_PORT_NAME), ModemName); view->ReadTextL(TPtrC(MODEM_CSY_NAME), ModemCSY); view->ReadTextL(TPtrC(MODEM_TSY_NAME), ModemTSY); view->ReadTextL(TPtrC(MODEM_RATE), ModemRate); CleanupStack::PopAndDestroy(); //VIEW CleanupStack::PopAndDestroy(); //db db = NULL

75 Appendix H – Using active objects

The communications programming is highly asynchronous. The best way to take advantage of that particular characteristic in Symbian OS is to use Active Objects. An active object uses an asynchronous service provider class to provide the service. It hides the asynchronous service provider and offers request and cancel functions for that service provider. An active scheduler encapsulates the wait loop which is at the heart of all programs using multiple asynchronous services. An active scheduler is an instance of a CActiveScheduler class or, in some circumstances, an instance of a CActiveScheduler derived class. Active objects, together with the active scheduler, provide a system of non pre-emptive multi- processing which runs on a single thread. In conventional systems, multi-processing is often done using multiple threads. In Symbian OS, it is easier to write a system of co-operating active objects than a system of co-operating threads. The run-time cost of an active object is also significantly less than that of a thread. Creating and destroying active objects is very much more efficient than creating and destroying threads. The class from which all active objects are derived is CActive. This provides derived objects with data members that allow the user to keep track of the current state of the asynchronous request. The data members are: ƒ The data member iStatus, an object of type TRequestStatus, is passed to the request functions of the asynchronous service provider. The active object’s request functions, therefore, do not include a TRequestStatus among their parameters (except when the active object is itself acting as a secondary provider of asynchronous services). ƒ The flag data member, iActive, is used to indicate that a request has been issued. The active scheduler tests this flag when handling the completion of a wait for any request. This flag is quite useful for the user because it informs the application whether a request is outstanding or not. ƒ The TPriority enumeration, defines the set of priorities which an active object can take. The active object's priority is set during construction of the active object itself.

Classes derived from CActive must implement themselves at least two functions: ƒ Provide a CActive::RunL() function to handle the completion of an asynchronous request, i.e. an event being received. ƒ Provide a CActive::DoCancel() function to implement a cancellation request.

This last function is called as part of the active object’s Cancel(). This function cancels an outstanding request and resets the iActive flag. The diagram on the next page illustrates the life-cycle of an active object. Procedural flow follows the black arrows; control is transferred along the blue links.

76

Figure 41 - Flow diagram showing the life cycle of an active object

Next is presented a simple example to clarify the use of active objects. The following code shows the typical elements required when constructing an active object.

CExample::CExample(CService* aService): CActive(EPriorityStandard), {

iService = aService; CActiveScheduler::Add(this) ; // add to active scheduler }

In this part of the code the active’s object priority was set using one of CActive::TPriority enumeration values. Other possibilities could be EpriorityIdle, EpriorityLow, EpriorityUserInput, and EpriorityHigh. The using the Add() function, the active object was added to the active scheduler, in order to ensure that its requests are handled. Once the active object has been constructed, a request can be issued. In the following code fragment, the active object provides the function IssueRequest() to invoke the encapsulated service function. As stated before, the functions Runl() and DoCancel() need to be implemented.

77 CExample::~CExample() { Cancel();

/* Instructions that the destructor is going to execute*/

} void CSocketsEngine::DoCancel() {

/* Cancel instruction go here*/

}

CExample::RunL() {

/* This function is called when the request is completed. The user once again can do whatever needed at the completion of the request */

}

CExample::IssueRequest() {

iService->RequestService(iStatus); // Request the service SetActive(); // Indicate request has been issued

}

Notice the passing of the TRequestStatus object and the SetActive() instruction. This function sets the active request flag, indicating that the active object is currently active. The flag is reset by the active scheduler before handling a completed request or by the active object base class as part of the cancellation protocol.

78 Appendix I – Sockets API

As already stated Symbian OS features kernel servers. The sockets server is one of them and applications interact with it through published client API which features a number of classes, like for example: • RSocketServ: This class establishes and obtains necessary resources for the connection to the sockets server. As an example of a client-server relationship, this class represents the application’s session with the sockets server. All other client interface classes request a session to the server to be opened via an instance of this class. Each application thread that wishes to use sockets requires an instance of this class to establish a connection (a session) to the sockets server. • RSocket: This class represents a socket. A typical application will have several instances of RSocket operational at any time. Each application thread that wishes to use sockets also requires one or more RSocket objects – these are subsessions. • RHostResolver: This class offers an interface for host name resolution services. • RNetDatabase: This class offers an interface for network database access.

Despite the four classes, the sockets server main classes at its client side API are RSocketServ and RSocket.

Using RSocketServ

This class represents a client application’s session with the sockets server. However, a client application will not use this class to send or receive data or to create a connection with a remote endpoint. The class RSocket is used by client applications for these purposes and is covered shortly. RSocketServ allows client applications to query the sockets server to determinate the number of protocols it knows about, and return information about each of these protocols. A client application wishing to use sockets will need to have one instance of an RSocketServ object which will be used to establish a session with the sockets server. Each individual socket is represented by a separate RSocket instance. An RSocketServ object effectively acts as a container for the RSocket instances. The two main methods offered by RSocketServ are Connect() and StartProtocol().

• Connect(): The connect method is used to create the application’s session with the socket server. It takes one parameter – the number of simultaneous asynchronous operations the application can ask the sockets server to perform. If a value is not included the default number of message slots, KESockDefaultMessageSlots (0x08), is used. • StartProtocol(): This method loads a protocol specified by family, socket type and protocol identifier. The client applications do not normally need to call this function, as loading of a protocol is done automatically by the Sockets Server when a socket of that protocol is opened. Some applications may, however, need to ensure that an open socket call will not take a significant amount of time. This function can be called by such applications to preload the protocol. Although this is an asynchronous service there is no way to cancel this operation once it has been called.

79 Using RSocket

The class represents a single socket used by the application. When compared, is obvious that the application will use the RSocket class much more often than RSocketServ. This is confirmed by the functions that this class performs:

• Connection services, as a client or a server; • Setting or querying its own address, or querying remote address; • Reading data from the socket; • Writing data from the socket;

Before opening any socket, an RSocketServ session must be active. Also, before any of these services indicated above can be used, the socket must be opened. As part of opening a socket, the RSocket subsession object is associated with a sockets server session – that is, an instance of the RSocketServ class.

Establishing communication between endpoints

A socket can either be connected or connectionless. Connection sockets are implemented with streams and connectionless sockets with datagrams, this distinction is made when the sockets are created. The diagram below shows the lifecycle of a typical data exchange using datagrams.

Figure 42 – Lifecycle for data exchange using datagrams

80 The diagram below shows the lifecycle of a typical data exchange using streams.

Figure 43 – Lifecycle for data exchange using streams

Patterns in Socket Usage

Initialization

There are patterns in how applications use sockets. With sockets, initializing means conversing with the socket server. The server has to be started and a connection must be established to it. To do this, has stated before, an RSockServ object has to be created and call its Connect() function:

RSockServ sockserver;

Err = sockserver.Connect(); User::LeaveIfError(err);

If the return code is anything other than KErrNone, something has gone wrong, and the error must be handled. Once the current active object has connected to the socket server, that server can be used in further calls that need to obtain sockets.

81 Opening the Socket

The first thing a socket’s application needs to do is to create a socket before it can be used. The method RSocket::Open() performs that action.

TInt Open (RsocketServ &aServer, TUint addrFamily, TUint sockType, TUint protocol); TInt Open(RSocketServ &aServer, const TDesC &aName); Tint Open(RSocketServ &aServer);

Each of these calls opens a socket for use by an application. The first form is the most specific and allows the user to completely specify the socket. The prototype shown above presents four parameters: a reference to a connected socket server, the address family of the socket, the type of socket to use and finally the protocol family. The first parameter has been already explained. The second specifies the address family which the socket will use. For this, the available protocol families (and their associated identifiers) are:

TCP/IP Î KAIfnet IrDA Î KIrdaAddrFamily Bluetooth Î KBTAddrFamily PLP Î KFamilyPlp SMS Î KSMSAddrFamily WAP Î KWAPSMSAddrFamily

The third parameter, the socket type, can have the following values:

Const TUint KSockStream; Const TUintKSockDatagram; Const TUint KSockSeqPacket; Const TUint KSockRaw;

The first two implement stream-based and datagram-based sockets, respectively. The third option represents a middle ground between streams and datagrams, enforcing sequential packet delivery without all the other trappings of connected sockets. Finally, the last option allows a socket connection with just a raw datastream – a situation where the user would build the packets. Finally, the last parameter specifies which protocol the sockets will use. The protocol module (TCPIP.PRT) implements a number of protocols such as TCP and UDP, which are identified by the values KProtocolInetTcp and KProtocolInetUdp respectively. Another possibility would be KUndefinedProtocol where the selection of the protocol would be done by the sockets server. This option asks the sockets server to create a socket of the specified type using the natural choice of protocol for the selected socket type.

Configuring and connecting sockets

Once a socket is open, then it needs to be connected to another communication endpoint, another socket. This action depends on the type of socket and will be different for connected and connectionless sockets.

82 • Configuring connectionless sockets

Because datagram sockets operate in an unconnected mode, there is no connection for datagrams. All that needs to be done is to create and bind a socket, and then it will be ready to send and receive data. The function Bind():

Tint Bind (TSockAddr &anAddr); will give the socket local information about the address and protocol it is supposed to represent, derived from the anAddr parameter. This information is built into the TSockAddr class and will be different for various kinds of protocols. Once a connectionless socket is bound to a local address, it is ready to send and receive data.

• Connected sockets

Connected sockets are configured with the address of the remote sockets, so that they remain tied together for the duration of the connection. The way this is done will be different whether the socket will be used for a server or client application. A client socket makes a call to one of the functions below: void Connect(TSockAddr &anAddr, TRequestStatus &aStatus); void Connect(TSockAddr &anAddr, const TDesC8 &aConnectDataOut, TDes8 &aConnectDataIn, TrequestStatus &aStatus);

Both calls require an address to connect the socket to and a status variable to monitor the progress of the connection. The second form of the Connect() function sends (through aConnectDataOut) and receives (through aConnectDataIn) some initial data upon connection. Servers require a few additional steps. A server must listen for a connection from a client, accept the connection, and then “shape” a socket to fit the incoming connection so that communication is possible. For that, a server uses blank sockets, moulding them to fit the client’s requirements. To better remember the server’s procedure, return to picture 42. Initially a blank socket is bound to a local address (using the RSocket::Bind() function). This method sets the address of a socket so that data can be routed correctly to the socket as opposed to any other socket. The Bind() method takes only one parameter – a reference to a TSockAddr instance. In case of TCP/IP sockets, a reference to a TInetAddr instance is passed which allows the socket address to be specified in two parts: the address of the networked machine and the logical port number on that networked machine. This parameter comprises wildcards for addresses and port number, for example KInetAddrAny or KInetPortAny. After this, the application must listen for incoming connections that specify the address bound to this socket. Listening is done through the Listen() function:

Tint Listen (TUint qSize); Tint Listen (TUint qSize, const TDesC8 &aConnectData);

The parameter qSize represents the size of the listen queue. If the second notation is used aConnectData represents a descriptor containing data to be sent in connect responses. To use data-in listening, a protocol must have the flag KSIConnectData in its protocol information. Despite the name, this function does not actually listens for incoming connections. Once an incoming connection has been detected, the application must accept it and configure a blank socket to service it. Accepting an incoming connection is done through the Accept()

83 function: void Accept (RSocket &aBlankSocket, TRequestStatus &aStatus); void Accept (RSocket &aBlankSocket, TDes8 &aConnectData, TRequestStatus &aStatus);

After this call completes, the newly configured socket can be used to exchange data with the remote device.

Exchanging data over sockets

Once again according to the socket’s type, specific functions exist for stream based or datagram sockets.

• Connectionless Sockets

Reading and writing data with datagrams is a bit different from the connected sockets, because the address (host and port) of the remote side of the connection must be specified in the I/O request. Reading from a connectionless socket uses the RecvFrom() function: void RecvFrom(TDes8& aDesc, TSockAddr& anAddr, TUint flags, TRequestStatus& aStatus); void RecvFrom(TDes8& aDesc, TSockAddr& anAddr, TUint flags, TRequestStatus& aStatus,TSockXfrLength& aLen);

Both calls need a buffer, aDesc, address and port information of the device to receive the data from, anAddr, some flags that configure the read, flags, and a status variable to monitor the receipt of data, aStatus. The first form will try to fill the entire buffer, while the second form will only read aLen bytes.

Writing to a connectionless socket is done through the SendTo() function: void SendTo(const TDesC8& aDesc, TSockAddr& anAddr, TUint flags, TRequestStatus& aStatus); void SendTo(const TDesC8& aDesc, TSockAddr& anAddr, TUint flags, TRequestStatus& aStatus,TSockXfrLength& aLen);

The methods need the buffer containing the data to send, aDesc, an address to send the datagram, anAddr, some flags to control the transfer, flags, and a status variable for monitoring, aStatus. The first form sends the entire buffer; the second form will only send aLen bytes.

• Connected sockets

Due to the nature of these sockets no address information is needed. The lowest level functions for reading and writing data are the Read () and Write () functions. void Read (TDes8 &aDesc, TRequestStatus &aStatus); void CancelRead (); void Write (const TDesC8 &aDesc, TRequestStatus &aStatus); void CancelWrite ();

84 Each function comes with a respective cancelling function due to the asynchronous nature of the methods. The more flexible way to do socket I/O is to use the Recv() and Send() functions because they include buffer length specifiers and flags that control the I/O, along with the other required parameters: void Recv(TDes8 &aDesc, TUint flags, TRequestStatus &aStatus); void Recv(TDes8& aDesc, TUint flags, TRequestStatus& aStatus, TSockXfrLength& aLen); void CancelRecv(); void Send(const TDesC8& aDesc, TUint someFlags, TRequestStatus& aStatus); void Send(const TDesC8& aDesc, TUint someFlags, TRequestStatus& aStatus, TSockXfrLength& aLen); void CancelWrite();

Once again each function is complemented by its own cancelling function.

There is one more function that can be used to receive data on a connected port. It receives data from a remote host and completes when data is available. The function reads at least one byte of data, but will complete as soon as any data is available. The amount of data received is returned via the TSockXfrLength argument. The function is: void RecvOneOrMore(TDes8& aDesc, TUint flags, TRequestStatus& aStatus, TSockXfrLength& aLen);

Closing sockets

RSocket::Close() should be called on any socket created using RSocket::Connect() to ensure that all resources associated with the socket are released and that it is disconnected from the remote end point. void RSocket::Close(void);

If the RSockServ instance is closed, then all sockets associated with that session will be forced to close. This method is synchronous, if a an asynchronous service is needed, rather than allow the socket to be closed synchronously, the function RSocket::Shutdown() should be called: void Shutdown(TShutdown aHow, TRequestStatus& aStatus);

The first parameter allows the user to specify the mode of disconnection: ENormal, EStopInput, EStopOutput or EImmediate. ENormal allows the disconnection process to run naturally according to the protocol used. EImmediate stops socket input/output and completes (abortive close). EStopInput stops socket input, preventing it to receive incoming data while EStopOutput prevents the socket transmitting data. Even using ENormal with this function the socket is still open, to free resources associated with it the method Close() should also be called.

85 Using active objects in sockets objects

As already stated, networked communication systems are heavily asynchronous. Because of that the use of sockets to channel data between computers implies an asynchronous model. Examples of that asynchronous characteristic are the connection, disconnection and acceptance of incoming connection requests, etc. So, to handle those events more easily, efficient and in a single thread, active objects are used. Later in the text it will be presented an example code of a socket server and client application implemented with active objects.

Implementation details

TCP Servers

All the servers implemented by the application share the same basic structure: there’s a main object called the engine that creates two other objects, a reader and a writer, handles the connections and disconnections, and controls the data exchange between the remote endpoints. The engine is an active object, so the first step in the initialization is the creation and configuration of a typical active object, as discussed in Appendix G. Note that the object that created the engine communicates with it through the notifier, ContainerNotifier, which is also initialized in the constructor. The ConstrucL() function finishes the active object configuration and creates a reader and writer object. Besides the engine, these objects are of most importance. After a connection request accepted by the engine object, it activates the reader, using the Read() function, in order to get the information that a client desires to transmit. The communication between those objects and the engine is done via another notifier, EngineNotifier, which permits the synchronization of the processes. The functions that compose the notifier are: ReportError(), SendAnnounce(), SendPic(), SendSms(), Port(). The reason for the existence of three different objects instead of one that performs all the functionalities, is that this division simplifies the I/O operations because there are now three active objects, and the source of the requests doesn’t need to be carefully controlled, making the application’s code much more simpler. The procedure is: the engine detects a connection request in a particular port and activates the reader for the reception of the data that the client wishes to convey. When all information is correctly read, the reader object now acts like a XML parser discriminating the message and finding out if the service request is correct. All the events regarding the service execution are stored in a file, using the function WriteLog(), and then presented to the user as a log. Then, the application performs the desired actions according to the service received:

• Service announcement

If the reader object detects a service announcement, the function RequestToAnnounce() is used to pass back this information to the engine object, through the function SendAnnounce() of the notifier and store in the file the service announcement request. The engine uses the same function, but on his side, to receive the data and then activates the writer object and tells it to reply to the client information about the current services that the smartphone provides. After that, the connection is terminated and the server is now ready to listen and accept new connection requests. This is done using the Disconnect2() function followed by Connect2() .

86 • SMS service

In this case, the reader detected that someone in the network desires to send a SMS. The result of the parsing process is the destination number and the text message that will be sent. The procedure in this case is a bit different from the case presented earlier. Now, the reader object itself will send the SMS using the function RequestToSms() that also stores in a file the event. After that, if the message is successfully sent, it transmits this information to the engine using the SendSms() function of the notifier. Then the engine activates the writer, using the function WriteL(), for a confirmation message to the delivered to the user that requested the service. After this, once again the connection is terminated and the server waits for new connections.

• Picture service

This alternative is a mixture of the two previous procedures. Here, after the detection of this service request, the reader will take the picture and save it in the Jpeg format (by default Symbian OS saves the pictures with a “multiple bitmap” extension, mbm). After this, the log is updated and the reader reports back to the engine, using SendPic() to inform the engine that a picture has been taken and it’s now ready to be sent to the client. Now, the engine activates the writer object that simply reads in the picture and sends it back to the client, using the function SendPicture(). The termination of the connection and following steps are similar to those announced previously.

Server example

CSocketsEngine*CSocketsEngine::NewL(MContainerNotifier& aContainerNotifier) {

CSocketsEngine* self = CSocketsEngine::NewLC(aContainerNotifier); CleanupStack::Pop(self); return self;

}

CSocketsEngine*CSocketsEngine::NewLC(MContainerNotifier& aContainerNotifier) {

CSocketsEngine*self= new (ELeave) CSocketsEngine(aContainerNotifier); CleanupStack::PushL(self); self->ConstructL(); return self;

}

CSocketsEngine::CSocketsEngine(MContainerNotifier& aContainerNotifier) : CActive(EPriorityStandard), iContainerNotifier(aContainerNotifier), iPort(KDefaultPortNumber), iServerName(KDefaultServerName) {

conta = 0;

}

87 CSocketsEngine::~CSocketsEngine() {

Cancel(); iSocket.Close(); delete iSocketsReader; iSocketsReader = NULL;

delete iSocketsWriter; iSocketsWriter = NULL;

delete iTimer; iTimer = NULL; iSocketServ.Close();

}

void CSocketsEngine::ConstructL() {

ChangeStatus(ENotConnected);

// Start a timer iTimer = CTimeOutTimer::NewL(EPriorityHigh, *this); CActiveScheduler::Add(this);

// Open channel to Socket Server User::LeaveIfError(iSocketServ.Connect(14));

// Create socket read and write active objects iSocketsReader = CSocketsReader::NewL(*this, iSocket2); iSocketsWriter = CSocketsWriter::NewL(*this, iSocket2);

} void CSocketsEngine::ConnectL() { conta++; if(conta>1) ConnectDois(); else {

// Initiate connection process if (iEngineStatus == ENotConnected) { TInetAddr addr; addr.Input(iServerName); ConnectL(addr.Address()); } } } void CSocketsEngine::ConnectL(TUint32 aAddr) // { // Initiate attempt to connect to a socket by IP address if (iEngineStatus == ENotConnected) {

88 // Open the socket that will be in charge of the connection establishment User::LeaveIfError(iSocket.Open(iSocketServ, KAfInet, KSockStream, KProtocolInetTcp));

// Open the socket that will be in charge of the data exchange User::LeaveIfError(iSocket2.Open(iSocketServ));

// Set up address information iAddress.Input(_L("KInetAddrAny")); //iAddress.Input(_L("KInet6AddrNone")); iAddress.SetPort(iPort); //iAddress.SetAddress(aAddr);

// Bind the listening socket for any address and specified port iSocket.Bind(iAddress);

// Set up a listening queue of 2 iSocket.Listen(2);

// Accept the connections from the clients - asynchronous request iSocket.Accept(iSocket2, iStatus);

// Change state ChangeStatus(EConnecting);

// Report Progress to Container iContainerNotifier.ResponseReceived(_L8("Connecting..."));

// Start a timeout for the connection? //iTimer->After(KTimeOut);

//Due to the active objects... SetActive(); } } void CSocketsEngine::Disconnect() { //__ASSERT_ALWAYS(iEngineStatus==EConnected, User::Panic(KPanicSocketsEngine, ESocketsBadState));

// cancel all outstanding operations // since we are connected, the only possibilities are read and write iContainerNotifier.ResponseReceived(_L8("Disconnecting...")); if(iEngineStatus == EConnected) { iSocketsReader->Cancel(); iSocketsWriter->Cancel();

iSocket2.Close(); //iSocket.Close(); ChangeStatus(ENotConnected); } }

// from CActive void CSocketsEngine::DoCancel() {

//iTimer->Cancel();

89 // Cancel appropriate request to socket switch (iEngineStatus) { case EConnecting: iSocket.CancelAccept(); iSocket2.Close(); iSocket.Close();

break; default: //User::Panic(KPanicSocketsEngine, ESocketsBadStatus); break; }

ChangeStatus(ENotConnected);

} void CSocketsEngine::WriteL(const TDesC8& aData) {

// Write data to socket if (iEngineStatus == EConnected) iSocketsWriter->IssueWriteL(aData);

} void CSocketsEngine::Read() {

// Initiate read of data from socket if ((iEngineStatus == EConnected) && (!iSocketsReader->IsActive())) iSocketsReader->Start();

}

// from CActive void CSocketsEngine::RunL() { // Active object request complete handler. // iEngineStatus flags what request was made, so its // completion can be handled appropriately //iTimer->Cancel(); // Cancel TimeOut timer before completion

switch(iEngineStatus) { case EConnecting: // IP connection request if (iStatus == KErrNone) // Connection completed successfully { ChangeStatus(EConnected);

Read(); //Start CSocketsReader Active object }

else { TInt x; TBuf<20> temp; TBuf8<20> temp2;

90 x = iStatus.Int(); temp.Format(_L("Erro no runL%d"), x); temp2.Copy(temp); iSocket2.Close(); iSocket.Close(); //iConsole.ErrorNotify(_L("CSocketsEngine\nConn. failed"), iStatus.Int()); iContainerNotifier.ResponseReceived(temp2); ChangeStatus(ENotConnected); } break; default: //User::Panic(KPanicSocketsEngine, ESocketsBadStatus); iContainerNotifier.ResponseReceived(_L8("Error")); break;

}; }

UDP client

The UDP client implemented is a bit simpler than the servers. The ConstructL() function basically starts the socket session and creates the writer object and ConnectL() function performs all the configuration needed:

User::LeaveIfError(iSocket.Open(iSocketServ, KAfInet, KSockDatagram, KProtocolInetUdp));

// Set up address information iAddress.SetPort(iPort);

// Bind socket to port

User::LeaveIfError(iSocket.Bind(iAddress));

These are the most important instructions performed by the engine. The writer object is also different from the writer objects of the servers presented previously. The function that performs the exchange of data basically performs the following set of instructions:

TInetAddr iSendAddr; TUint iRemotePort = 6000; TBuf<20> iRemoteAddr(_L("2020::dead:beef")); iAddress.Input(iRemoteAddr); iAddress.SetPort(iRemotePort);

// Initiate actual write iSocket.SendTo(iWriteBuffer, iAddress, 0, iStatus);

SetActive();

91 Socket Options

In addition to sockets, the Sockets Client API provides access points to other network facilities such as hostname resolution, service resolution, protocol information, and various byte manipulation utilities. To obtain protocol information (for example information concerning TCP) the API provides the functions SetOpt() and GetOpt(). SetOpt() sets a socket option. The socket server has options which are generic to all sockets and protocols may add specific options. GetOpt() gets a socket option. The socket server has options which are generic to all sockets and protocols may add specific options.

TInt SetOpt(TUint anOptionName,TUint anOptionLevel,const TDesC8& anOption=TPtrC8(NULL,0)); TInt SetOpt(TUint anOptionName,TUint anOptionLevel,TInt anOption);

TInt GetOpt(TUint anOptionName,TUint anOptionLevel,TDes8& anOption); TInt GetOpt(TUint anOptionName,TUint anOptionLevel,TInt& anOption);

The most important options for this work are:

Network interface (anOptionLevel should be KSolInetIfCtrl)

• KsoInetEnumInterfaces

Begin enumeration of network interfaces. This option should be set before enumerating interfaces with KSoInetNextInterface. This option is for use with SetOpt() only.

• KsoInetConfigInterface

Return details of the specified interface. This option is for use with GetOpt() only. For IPv4/IPv6 dual stack, this anOption should be a TPckgBuf; for IPv4, use a TPckgBuf.The interface can be specified by setting the iAddress, iTag, iName, or iHwAddr of the passed object. The complete details are passed back in the same object.

• KsoInetNextInterface

Return details of the next interface in an enumeration started by setting the option KSoInetEnumInterfaces. This option is for use with GetOpt() only. The parameter anOption should be a TPckgBuf.

• KsoInetDeleteInterface

Deletes an interface. The parameter anOption should be a TPckgBuf.

92 • KsoInetChangeInterface

Sets interface details. The parameter anOption should be a TPckgBuf. Unlike KSoInetConfigInterface, this never creates a new interface entry, if one does not already exist. KSoInetConfigInterface never fails with interface not found, as it always finds or creates one.

Analysing the possible options, one reaches the conclusion that the process for obtaining information about the network interfaces is quite similar to a navigation menu: First there has to be a socket server session active, then the socket it self has to be created according to the needs, in this case the address family is KafInet (TCP/IP) and the protocol family is TCP.

//socket server connection

TInt result = socketServer.Connect();

//socket creation result = socket.Open(socketServer, KAfInet, KSockStream, KProtocolInetTcp);

After this phase the process continues by the enumeration of the interfaces: result = socket.SetOpt(KSoInetEnumInterfaces, KSolInetIfCtrl, dummy);

Now that the interfaces are enumerated, the next step is to retrieve details of the specified interface. Notice that the parameter anOption is KSolInetNextInterface and pckt is a variable of type TPckgBuf which is going to contain the respective information about the interface. result = socket.GetOpt(KSoInetNextInterface, KSolInetIfCtrl, pckt);

The next thing to do is to keep proceeding to the following interfaces. The process ends when the GetOpt() function returns anything else than KErrNone.

Routing (anOption should be KsolInetRtCtrl)

• KSoInetEnumRoutes

Begin enumeration of routes. This option can only be used with RSocket::SetOpt().This option should be set before enumerating routes with KSoInetNextRoute.

• KSoInetAddRoute

Adds the specified route to the routing table. The parameter anOption should be a TPckgBuf. The interface concerned must exist as a virtual or real interface. This option can only be used with RSocket::SetOpt().

93 • KSoInetDeleteRoute

Deletes the specified route from the routing table. The parameter anOption should be a TPckgBuf. The interface concerned must exist as a virtual or real interface.This option can only be used with RSocket::SetOpt().

• KSoInetChangeRoute

Modifies the specified route in the routing table. The destination and netmask settings must be the same in the new route as in the old. The parameter anOption should be a TPckgBuf< TSoInetRouteInfo >. This option can only be used with RSocket::SetOpt().

• KSoInetCachedRouteByDest

Find a cached route to a specified destination. This is only supported in the IPv4 stack, not the IPv4/v6 dual stack. The caller should pass a packaged TSoInetCachedRouteInfo with its iDstAddr member set to the required address. The parameter anOption should be a TPckgBuf.This option can only be used with RSocket::SetOpt().

• KSoInetNextRoute

Return the next route in an enumeration started by setting the option KSoInetEnumRoutes. The parameter anOption should be a TPckgBuf. This option can only be used with RSocket::SetOpt().

Once again looking at the options presented, one concludes that the process of retrieval of the smartphone’s routing table is similar to the previous one (network interfaces). First there has to be a socket server session active, then the socket it self has to be created according to the needs, in this case the address family is KafInet (TCP/IP) and the protocol family is TCP.

//socket server connection

TInt result = socketServer.Connect();

//socket creation result = socket.Open(socketServer, KAfInet, KSockStream, KProtocolInetTcp);

After this phase the process continues by the enumeration of the several routes: result = socket.SetOpt(KSoInetEnumRoutes, KSolInetRtCtrl, dummy);

94 Now that the routes are enumerated, the next step is to retrieve details of the specified route. Notice that the parameter anOption is KSoInetNextRoute and pckt is a variable of type TPckgBuf which is going to contain the respective information about the route. result = socket.GetOpt(KSoInetNextRoute, KSolInetRtCtrl, pckt);.

The next thing to do is to keep proceeding to the following routes. The process ends when the GetOpt() function returns anything else than KErrNone.

To add a route to the routing table the procedure is a bit different, but the first two steps are common to all other processes presented. result = socketServer.Connect(); result = socket.Open(socketServer, KAfInet, KSockStream, KProtocolInetTcp);

This time anOption is KSolInetAddRoute and pckt, a variable of type TPckgBuf. To introduce the route, its details need to be loaded in pckt: pckt().iType = ERtNormal; //type of route pckt().iState = ERtReady; //state of route pckt().iMetric = 0; //metric

TInetAddr addr; TBuf<20> iIfAddr(_L("192.168.0.1")); //Interface address addr.Input(iIfAddr); //load addr with the IP pckt().iIfAddr = addr; //insert the interface’s IP in pckt

TBuf<20> iGtwAddr(_L("192.168.0.1")); //Gateway address addr.Input(iGtwAddr); //load addr with the IP pckt().iGateway = addr; //insert the gateway’s IP in pckt

TBuf<20> iDstAddr(_L("192.168.0.2")); //Destination address addr.Input(iDstAddr); //load addr with the IP pckt().i .iDstAddr = addr; //insert the gateway’s IP in pckt

TBuf<20> iNetAddr(_L("255.255.255.255")); //Netmask address addr.Input(iNetAddr); //load addr with the IP pckt().iNetMask = addr; //insert the netmask’s IP in pckt result = socket.SetOpt(KSoInetAddRoute, KSolInetRtCtrl, pckt);

95 Appendix J – Using Bluez tools

This appendix shows how to use the most important Bluetooth tools. The hciconfig tool can be used to display information about hci0, namely the MAC address of the BT device. An example of the output of this tool is:

[root@kim Desktop]# hciconfig hci0: Type: USB BD Address: 00:10:60:A8:C7:FF ACL MTU: 192:8 SCO MTU: 64:8 UP RUNNING PSCAN ISCAN RX bytes:21360 acl:143 sco:0 events:107 errors:0 TX bytes:3749 acl:67 sco:0 commands:25 errors:0

With sdptool the MAC address of both phone and PC device can be discovered. The possible usages are: hcitool inq, hcitool scan and hcitool dev.

[root@kim Desktop]# hcitool inq Inquiring ... 00:60:57:ED:DB:85 clock offset: 0x7f0f class: 0x500204

[root@kim Desktop]# hcitool scan Scanning ... 00:60:57:ED:DB:85 AMI6600phone

[root@kim Desktop]# hcitool dev Devices: hci0 00:10:60:A8:C7:FF

To request further information from the phone use hcitool info .

[root@kim Desktop]# hcitool info 00:60:57:ED:DB:85 Requesting information ... BD Address: 00:60:57:ED:DB:85 Device Name: AMI6600phone LMP Version: 1.1 (0x1) LMP Subversion: 0x248 Manufacturer: Nokia Mobile Phones (1) Features: 0xbf 0x28 0x21 0x00 0x00 0x00 0x00 0x00 <3-slot packets> <5-slot packets>

To discover the services available by the phone, one can do sdptool browse , for Nokia 6600 the output is: [root@kim Desktop]# sdptool browse 00:60:57:ED:DB:85 Browsing 00:60:57:ED:DB:85 ... Service Name: Fax Service RecHandle: 0x10000 Service Class ID List: "Fax" (0x1111)

96 "Generic Telephony" (0x1204) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 1 Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100 Profile Descriptor List: "Fax" (0x1111) Version: 0x0100

Service Name: Dial-up Networking Service RecHandle: 0x10001 Service Class ID List: "Dialup Networking" (0x1103) "Generic Networking" (0x1201) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 1 Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100 Profile Descriptor List: "Dialup Networking" (0x1103) Version: 0x0100

Service Name: Bluetooth Serial Port Service Description: Bluetooth Serial Port Service Provider: Symbian Ltd. Service RecHandle: 0x10002 Service Class ID List: "Serial Port" (0x1101) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 2 Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100

Service Name: OBEX Object Push Service RecHandle: 0x10003 Service Class ID List: "OBEX Object Push" (0x1105) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 9 "OBEX" (0x0008) Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100 Profile Descriptor List: "OBEX Object Push" (0x1105) Version: 0x0100

97

Service Name: OBEX File Transfer Service RecHandle: 0x10004 Service Class ID List: "OBEX File Transfer" (0x1106) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 10 "OBEX" (0x0008) Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100 Profile Descriptor List: "OBEX File Transfer" (0x1106) Version: 0x0100

Service Name: Handsfree Audio Gateway Service RecHandle: 0x10005 Service Class ID List: "" (0x111f) "Generic Audio" (0x1203) Protocol Descriptor List: "L2CAP" (0x0100) "RFCOMM" (0x0003) Channel: 3 Language Base Attr List: code_ISO639: 0x656e encoding: 0x6a base_offset: 0x100 Profile Descriptor List: "" (0x111e) Version: 0x0101

After establishing the connection between PC and phone, it can be used ifconfig and route –n to check the connectivity. Example outputs are:

[root@kim Desktop]# ifconfig eth0 Link encap:Ethernet HWaddr 00:0A:E6:54:D6:86 inet addr:194.117.24.157 Bcast:194.117.24.255 Mask:255.255.255.0 inet6 addr: 2020::2/128 Scope:Global inet6 addr: fe80::20a:e6ff:fe54:d686/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2780 errors:0 dropped:0 overruns:0 frame:0 TX packets:542 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:805374 (786.4 Kb) TX bytes:67322 (65.7 Kb) Interrupt:11 Base address:0xd400 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:121 errors:0 dropped:0 overruns:0 frame:0 TX packets:121 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:7830 (7.6 Kb) TX bytes:7830 (7.6 Kb) ppp0 Link encap:Point-to-Point Protocol

98 inet addr:192.168.0.1 P-t-P:192.168.0.2 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1 RX packets:13 errors:0 dropped:0 overruns:0 frame:0 TX packets:11 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:3 RX bytes:317 (317.0 b) TX bytes:393 (393.0 b) and [root@kim Desktop]# route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.0.2 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0 194.117.24.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo 0.0.0.0 194.117.24.254 0.0.0.0 UG 0 0 0 eth0

(in this case only Ipv4 addresses are used) To forward the requests from the phone through an ISP-Connection it’s necessary to enable IP-Forwarding and NAT. To enable IP-Forwarding it is just needed to type echo 1 > /proc/sys/net/ipv4/ip_forward for Ipv4 and echo 1 > /proc/sys/net/ipv6/conf/all/forwarding for Ipv6 in a shell. This must be done every time the PC reboots because packet forwarding is shutdown on reboot. In order to share the internet via a Linux box by NAT (Network Address Translation) the following steps have to be made: 1. On the Linux box (that is directly connected to the internet, and is supposed to do the internet sharing), start a terminal. Run the command su and then type the root password to become the administrator. 2. Open the file /etc/rc.d/rc.local in a text editor and add /etc/rc.d/rc.ipmasq on a new line at the bottom and save the file. 3. Then, create a new file called rc.ipmasq in the /etc/rc.d/ directory and open this file in a text editor and add these lines: #!/bin/sh IPTABLES=/sbin/iptables

#All The lines below are NAT routing

# flush any old rules $IPTABLES -F -t nat

# turn on NAT (IP masquerading for outgoing packets) $IPTABLES -A POSTROUTING -t nat -o eth0 -j MASQUERADE

# enable IP forwarding (of incoming packets) echo 1 > /proc/sys/net/ipv4/ip_forward

Save this file.

99

Notes: • This script assumes that eth0 is the Ethernet adaptor connected to the internet. If the connection to the internet is not thru an Ethernet device (as in the case of ordinary dialup or USB modem), use ppp0. • The network connections to the internet and intranet should already be up. 4. Make this script file executable by running chmod 755 /etc/rc.d/rc.ipmasq 5. Run the command /etc/rc.d/rc.ipmasq to enable the internet sharing. Now it should be able to browse the internet from the phone or other computer as well.

100 References

Books:

[1] Harrison, Richard; Symbian OS C++ for Mobile Phones, John Wiley, 2003;

[2] Hopkins, Bruce; Java for Bluetooth, Apress, 2003;

[3] Jipping, Michael J.; Symbian OS Communications Programming, Symbian Press,2002.

Documents:

J2ME Wireless Toolkit 2.1 documentation;

SDK 2.0 for Symbian OS documentation;

UIQ SDK for Symbian OS documentation.

Internet sites: http://www.nokia.com http://www.sonyericsson.com http://www.symbian.com http://www.symbianos.org http://www.my-symbian.com http://www.benhui.net http://www.newlc.com http://mobile.linux.pt/p800/symbianlinuxhowto/ http://www.bluez.org http://java.sun.com http://www.uiq.com

101