WAP, Bluetooth, and 3G Programming Cracking the Code

March 27, 2018 | Author: Maher Al-aboodi | Category: Computer Network, Bluetooth, Internet, Mobile Phones, Communications Protocols


Comments



Description

WAP, Bluetooth, and 3G Programming Cracking the Code Dreamtech Software Team Best Selling Books • Digital Downloads • e Books • Answer Networks • e Newsletters • Branded Web Sites • e Learning New York, NY u Cleveland, OH u Indianapolis, IN WAP, Bluetooth, and 3G Programming: Cracking the Code Published by Hungry Minds, Inc. 909 Third Avenue New York, NY 10022 www.hungryminds.com Copyright © 2002 Hungry Minds, Inc. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher. Library of Congress Control Number: 2001095398 ISBN: 0 7645 4905 7 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/RR/RQR/QR/IN Distributed in the United States by Hungry Minds, Inc. Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland. For general information on Hungry Minds’ products and services please contact our Customer Care department within the U.S. at 800 762 2974, outside the U.S. at 317 572 3993 or fax 317 572 4002. For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign language translations, please contact our Customer Care department at 800 434 3422, fax 317 572 4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256. For information on licensing foreign or domestic rights, please contact our Sub Rights Customer Care department at 212 884 5000. For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales department at 800 434 2086 or fax 317 572 4005. For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 317 572 3168 or fax 317 572 4168. For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978 750 4470. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. Trademarks: Hungry Minds and the Hungry Minds logo are trademarks or registered trademarks of Hungry Minds, Inc. Macromedia, Homesite, and ColdFusion are trademarks or registered trademarks of Macromedia, Inc., in the United States and/or other countries. All other trademarks are the property of their respective owners. Hungry Minds, Inc., is not associated with any product or vendor mentioned in this book. is a trademark of Hungry Minds, Inc. Credits Acquisitions Editor Chris Webb Project Coordinator Nancee Reeves Project Editor Neil Romanosky Cover Design Anthony Bunyan Technical Editor N. R. Parsa Proofreader Mary Lagu Copy Editors Jerelind Charles Jeremy Zucker Indexer Johnna VanHoose Dinse Media Development Specialist Angela Denny Permissions Editor Carmen Krikorian Cover Vault door image used courtesy of Brown Safe Manufacturing www.BrownSafe.com Media Development Manager Laura Carpenter VanWinkle Dreamtech Software India, Inc., Team [email protected] www.dreamtechsoftware.com Dreamtech Software India, Inc., is a leading provider of corporate software solutions. Based in New Delhi, India, the company is a successful pioneer of innovative solutions in e-learning technologies. Dreamtech’s developers have over 50 years of combined software engineering experience in areas including Java, wireless applications, XML, voice-based solutions, .NET, COM/COM+ technologies, distributed computing, DirectX, Windows Media technologies, and security solutions. About the Authors Dr. K. V. K. K. Prasad is a renowned software engineer and professor with extensive experience in software engineering, wireless Internet, computer telephony integration, artificial intelligence, data communication, and telecommunications. He is a software consultant. Vikas Gupta is co-founder and president of Dreamtech Software. He is a software engineer and publisher actively engaged in developing and designing new technologies in wireless, e-learning, and other cutting-edge areas. He is also the managing director of IDG Books India (P) Ltd. Avnish Dass, co-founder and CEO of Dreamtech Software, is a talented and seasoned programmer with 15 years of experience in systems and application/database programming. He has developed security systems, anti-virus programs, wireless and communication technologies, and ERP systems. Deepesh Jain is a certified software developer and Microsoft Certified Professional with over three years of experience in VB, .NET, database programming, COM/COM+, Windows programming, and wireless technologies. He is a senior software developer at Dreamtech Software. To our parents and family and our beloved country India, for providing an excellent environment for nurturing and creating world class IT talent. Preface The last three decades of the twentieth century yielded two revolutionary developments in communications technology: the Internet and mobile communication networks. The Internet — the global network that integrates all computer networks — enables us to access data services from our desktops. Mobile communications pave the way for voice communication services for people who are (literally) on the move. The tremendous impact of both these developments is evident from the growth rates of both Internet and the mobile network subscribers throughout the world. Standing at the beginning of the first decade of the twenty-first century, we will now witness the next revolutionary communications development: the integration of the Internet and mobile communications. This will pave the way for wireless Internet access and high-speed services on wireless devices. The ability to access Internet services through mobile devices will lead to anywhere–anytime communication. If wireless networks can support high speeds, users will be able to access data, voice, and video services. As is generally the case, the end user will probably not be concerned about the underlying technologies; he/she will be interested only in the applications that these networks support. Thus, strong application development is essential in order for futuristic wireless networks to achieve wide popularity. This book addresses the subject of developing applications for wireless Internet access. An Overview of the Technology A variety of tools and languages have been developed to create content for wireless systems that support applications with voice and video streaming services. This book describes in detail the tools and languages required to develop outstanding applications over wireless networks using the following three technologies: ♦ WAP ♦ Bluetooth ♦ 3G WAP Wireless Application Protocol (WAP) allows users to access Web content on low-speed wireless networks such as GSM, IS-136, and PDC. WAP was developed as an open standard protocol to bridge the wired Internet and the wireless networks. The WAP Forum was launched in December 1997 by Ericsson, Motorola, Nokia, and Phone.com. WAP specifications define the protocol conversion between the IP and cellular networks, as well as the markup language to create content for wireless Internet access. The wired Internet uses the TCP/IP protocol stack and HTTP to access Web services. The desktop PC is a powerful system with a high-resolution monitor, high processing capability, and an ability to present rich multimedia content to the user through a browser. All this requires huge system resources. To provide Web services to mobile clients is a challenge because mobile networks support low data rates (300 to 14.4 Kbps), and delays are frequent. In addition, mobile devices have small displays (2 to 4 lines with 8 to 12 characters per line), low resolution, no support for color, a limited-function keypad, low battery power, and low processing power. WAP has been developed as a lightweight protocol based on TCP/IP and HTTP. A WAP gateway bridges the WAP protocols and the Internet protocols by carrying out the necessary protocol conversion. To develop content that mobile devices can access, the Wireless Application Environment (WAE) is specified as a part of WAP. The WAE consists of viii Preface ♦ Wireless Markup Language (WML), a page description language that describes the content presentation. WML is similar to HTML and is based on XML. ♦ WML Script, a scripting language similar to JavaScript that can be used to facilitate calculations, validate user input, generate error messages locally, and pass parameters to the server. ♦ Content formats to describe the data, images, and other content. ♦ A micro-browser that runs on the mobile devices. The micro-browser occupies few system resources and provides only limited functionality, as compared with desktop browsers such as Internet Explorer and Netscape. WAP is an open standard that has the support of major equipment manufacturers, service providers, and software developers. WAP 1.1 was released in June 1999, and Version 1.2 was released in November 1999. During the past few years, a number of content providers have developed WAP content for applications — such as obtaining stock quotes, weather information, astrological information, sports news, and so on. Other applications that are now commercially available include mobile commerce, mobile advertising, and mobile banking. WAP has shown us the possibilities of using Internet access to obtain focused information on mobile phones in text format. However, as the capabilities of mobile devices improve and the data rates of the wireless networks increase, we now need to consider using other markup languages for wireless applications. Case in point: WAP has been revised to support XHTML for content creation. The first part of this book addresses content creation for providing wireless Internet access using WAP. We discuss content development using WML, WML Script, Cold Fusion, and Java technologies for creating applications using server-side programming and database access. Bluetooth Today’s business executive uses a large number of devices — desktop PC, laptop, PDA, mobile phone, and the like — in addition to peripherals such as a fax machine, LCD projector, cordless phone, and so on. These devices need to share information and resources, but interconnecting them through cables is cumbersome. Ideally, when two or more devices that need to share data are in close proximity, they should be able to form a network and exchange the data. That is, the devices should be capable of forming an ad-hoc network on their own and sharing data through simple commands given by the user. Bluetooth achieves this through a low-cost, low-power, short-range radio technology. Ad hoc networks can be formed among Bluetooth-enabled devices in the office, home, or car. Almost every electronic device can be Bluetooth enabled, be it a PC, laptop, printer, fax machine, modem, mobile phone, LCD projector, digital camera, cordless phone, music system, television, microwave oven, or Web TV. Bluetooth is a nascent technology that harbors enormous potential. A large number of vendors have developed the hardware and software to make devices Bluetooth enabled. Now the technology is also maturing as a cost-effective solution to replace cable. Developing exciting applications on the Bluetooth protocol stack is the “need of the hour.” This book presents a comprehensive coverage of Bluetooth programming. We also examine the many interesting applications that can be developed through a combination of WAP and Bluetooth. 3G End-users’ desire for increased bandwidth is paving the way for wireless networks that support higher data rates. The 2.5 Generation wireless networks that are evolving from the present 2G networks will support data rates in the range 64–144 Kbps. These 2.5G systems will, in turn, evolve into 3G systems that will support data rates in the range 384–2048 Kbps. Such data rates can support services such as high-resolution graphics and animation, downloading music from the Internet, teleshopping, multiparty audio and video conferencing, audio/video broadcasting over mobile networks, and so forth Preface ix The 2G and 2.5G wireless networks are based on protocols that conform to regional standards. Wireless networks in Europe, North America, and Japan are based on different standards. 3G systems aim to achieve global roaming by providing appropriate gateways for protocol conversion depending on the user’s geographic location. Wireless networks based on 3G networks are yet to be deployed on a large scale. In order for 3G networks to be profitable, they must support quality content and applications. Developing applications that provide low-cost data, voice, and video services is the biggest challenge; software developers and content providers need to concentrate on this aspect in the years to come. A number of alternatives, such as XHTML, XML, Java, and C++, are available for content development. In addition, mobile devices that access the Internet will have different capabilities in terms of memory, processing power, display resolution, size, and so on. To develop content that can cater to all types of devices is a great challenge to content creators. Content creators have to work with a wide variety of tools to create killer applications that the end user can use to carry out his/her business, education, and entertainment activities through mobile devices, all at a very low cost. We study aspects of 3G programming in detail in this book. We use the various tool kits available to test the content in the laboratory environment before deploying it on the network. We focus on creating applications for animation, voice, and video services using XHTML, XML, and Java. We use Qualcomm’s BREW toolkit to do the 3G programming. What This Book Covers This book is based on the unique concept of Cracking the Code and, consequently, mastering the technologies of WAP, Bluetooth, and 3G programming. This book is not meant for beginners: It will teach you only the basics of specific technologies. The Cracking the Code series is meant for software developers/programmers who wish to upgrade their skills and understand the secrets behind professionalquality applications. This book starts where other tutorial books end. It will enhance your skills and take them to the next level as you learn a particular technology. This is the first book to cover both Bluetooth and 3G programming. It contains a unique coverage of using WAP with Bluetooth and 3G content development for multimedia applications. The book is code intensive, with a lesser emphasis on theory. All the applications (and related source code) have been fully tested at Dreamtech Software Research Lab. The source code in this book is based on commercial applications developed by Dreamtech. Each program is explained in a very detailed manner so as to provide insight into the implementation of the technology in a real-world situation. The appendixes provide reference links so that the earnest reader can further explore the new developments that are taking place. Please note that this book does not provide a comprehensive tutorial of specific technologies — it provides only command summaries, as there are plenty of books available to teach you WML, WML Script, Cold Fusion, XHTML, Java Servlets, JSP, and the theoretical aspects of the Bluetooth and 3G protocols. This book’s objective is to put you on the evolutionary pathway of wireless communication and to help you develop exciting software that provides rich content and applications on wireless networks. The book begins with WAP content development using WML, WML Script, JSP, Servlets, Cold Fusion, and other technologies. It then moves on to a discussion of Bluetooth technology and finally to a detailed discussion of 3G. Emphasis is placed on developing applications for Bluetooth and 3G networks. The discussion of 3G content development is targeted to programmers and communication engineers and enables them to use available toolkits in their work. This is the first book that addresses 3G wireless application development and conversion of the WAP applications to 3G applications. This book is also unique in that it provides the programmer with a holistic approach to content development using various markup and programming languages to create high-end multimedia applications. x Preface In the future, every mobile device that is capable of accessing the Internet services through wireless networks will need to be Bluetooth enabled, so that the user can have completely wireless Internet access and data synchronization on various devices. This book gives you the programming ammunition to achieve this objective. Anywhere–anytime communication is the objective of the Global Village, and this book is designed to make you the architect of that village. Who Should Read This Book As it was stated earlier, this book is not for beginners. It is intended for experienced wireless application developers who want to learn the third-generation technologies, 3G and Bluetooth, that serve to integrate hardware peripherals such as refrigerators, televisions, ovens, and mobile phones with a PC. The book mainly targets innovative developers who envision developing their own applications along these lines. This book will also benefit those who aspire to explore the relatively new concept of WAP, as it outlines all of the vital aspects of this technology. Because this book does not provide a comprehensive tutorial of relevant technologies needed for WAP, Bluetooth, and 3G programming, the reader should also have a working knowledge of Java, XML, WML, Visual C++, and JMF. How the Book Is Organized This book contains 14 chapters and five appendixes, which are described as follows: ♦ Chapter 1 provides a brief explanation of the evolution of WAP, Bluetooth, and 3G, as well as the devices used for these applications. ♦ Chapter 2 demonstrates content development using WML and WML Script with the help of two case studies. These case studies illustrate front-end application development for WAP. ♦ Chapter 3 explains the integration of WAP with Cold Fusion. Only the relevant details of the technology are reviewed, but the project helps explain every aspect of a Cold Fusion application. The emphasis here is on using Cold Fusion for server-side programming with MS Access as the database and WML for content presentation. ♦ Chapter 4 contains an introduction to the WTA architecture and programming. It describes the applications of WTA to integrate data and voice applications on mobile devices. ♦ Chapter 5 focuses on the integration of Java with WAP. The two main Java technologies used for Internet applications — JSP and Java Servlets — are also discussed. ♦ Chapter 6 discusses push technology in the WAP framework. We access Internet services using the pull model, whereby the user sends a request to the server and the server responds with content. Another model, the push model, is now being used to provide services such as stock quotes, advertisements, and so on, when the user has not specifically requested that information. ♦ Chapter 7 provides an introduction to Bluetooth technology and protocols. This chapter includes discussions on Bluetooth hardware, software, architecture, and protocols, as well as on Bluetooth applications for creating Personal Area Networks (PANs). ♦ Chapter 8 presents applications that implement WAP with Bluetooth. Using Bluetooth as the bearer, one can develop useful applications: for example, information kiosks that transmit information to mobile devices in public places such as airports and shopping malls. The implementation of this application is also discussed in this chapter. ♦ Chapter 9 focuses on programming aspects of Bluetooth. Using Ericsson’s PC Reference stack, you can see how each layer of the Bluetooth protocol stack can be accessed and also how applications can be developed. ♦ Chapter 10 is an introduction to 3G. The fundamental principles of cellular mobile communication and the Global System for Mobile Communications (GSM) are covered, followed by a discussion Preface xi of the evolution of wireless networks into 2.5G and 3G networks. The various applications of 3G networks, which can support data rates in the range 384–2048 Kbps, are also discussed. This chapter also presents developments in mobile devices and languages for content development. ♦ Chapter 11 covers advanced 3G programming. It illustrates the limitations of WML and focuses on content development using XHTML, XML/XSL, and Java. ♦ Chapter 12 focuses on 3G content development using Qualcomm’s Binary Runtime Environment for Wireless (BREW) toolkit, a powerful tool for creating content for CDMA-based networks. ♦ Chapter 13 deals with using 3G programming to develop multimedia content over IP networks. We discuss the implementation of audio and video streaming applications using Java Media Framework (JMF). These futuristic applications will enable us to access audio and video services from mobile devices that support Mobile IP protocol. ♦ Chapter 14 reviews the exciting developments taking place that will lead to the convergence of networks and services. In this chapter, we peep into the futuristic developments in mobile communications. The integration of mobile networks with broadcasting and fixed networks will lead to low-cost high-speed data, voice, and video services. This chapter discusses the various technologies and standards needed to achieve this convergence. ♦ Appendix A contains a discussion of the contents of this book’s CD-ROM. ♦ Appendix B walks you through Tomcat installation and configuration so that you can install the software and run the code in the book. Tomcat is the toolkit required to work with Java servlets, and JSP. ♦ Appendix C covers the installation of SQL Server 2000 and XML Support Configuration. ♦ Appendixes D and E contain lists of URLs for sites that provide information on Bluetooth and 3G, respectively. All the code provided in this book has been 100% tested and verified. The Nokia toolkit is used for WML and WML Script. Cold Fusion studio is used for working with Cold Fusion, and Jakarta Tomcat is used for working with JSP and Java Servlets. The procedures for installing and configuring all these software packages are also explained in the book. Qualcomm’s BREW is the other tool kit used for 3G programming. All the applications have been developed on a Microsoft platform with Windows NT/ME/98/2000 as the base. Let’s now begin our exciting journey into the realm of content development for wireless networks. Acknowledgments We would like to acknowledge the contributions of the following people for their support in making this book possible: John Kilcullen, for sharing the dream and providing the vision in making this project a reality; Mike Violano and Joe Wikert, for believing in us; and M. V. Shastri, Asim Chowdury, V. K. Rajan, Sanjeev Chatterjee, and Priti for their immense help in coordinating various activities throughout this project. We also thank technical writers Mridula Sharma and Sunil Gupta, who contributed in developing this book’s content. Contents Preface ......................................................................................................... vii Acknowledgments........................................................................................ xi Chapter 1: WAP, Bluetooth, and 3G: A Brief Introduction ......................... 1 Evolution of Wireless Networks .............................................................................................................1 Evolution of Wireless Protocols and Applications.................................................................................1 Languages and Tools for Content Development ....................................................................................2 Wireless Access Devices/Bluetooth........................................................................................................3 Summary ..................................................................................................................................................4 Chapter 2: WML and WML Script Programming: A Case Study................ 5 WML Commands and Syntax .................................................................................................................5 WML Script — Commands and Syntaxes..............................................................................................7 The Information Master Application ......................................................................................................9 The Restaurant Application...................................................................................................................15 Summary ................................................................................................................................................25 Chapter 3: WAP Using Cold Fusion: A Project ......................................... 26 Cold Fusion: An Overview....................................................................................................................26 Application: Question Quiz...................................................................................................................29 Summary ................................................................................................................................................48 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones..................................................................................... 49 Applications of WTA ............................................................................................................................49 Introduction to WTA Architecture........................................................................................................50 Using the Interface Components ...........................................................................................................54 Event and State Management in WTA..................................................................................................59 WTAI Function Call Example ..............................................................................................................60 Summary ................................................................................................................................................62 Chapter 5: Integrating Java with WAP ....................................................... 63 Introduction to Java Technologies ........................................................................................................63 Create Dynamic Content with Servlets and JSPs for WAP Browsers.................................................66 A JSP and Servlets-Based Application for WAP .................................................................................68 Summary ................................................................................................................................................83 Chapter 6: Push Technology in WAP ........................................................ 84 Pull Technology for Accessing Internet Content..................................................................................84 What Is Push Technology?....................................................................................................................84 Push Technology Applications..............................................................................................................85 Push Technology Implementation.........................................................................................................86 Push Framework in WAP ......................................................................................................................89 .................................................................................... 134 Security Issues in Bluetooth............................................................................................................................................................................ 130 Bluetooth versus Other Technologies....................................................... 126 Chapter 7: Bluetooth: A Basic Introduction .................................................... 135 Architecture of a Bluetooth System...... 163 Installing the Bluetooth Module and PC Reference Stack ............................................................................................................. 154 Application: Shopping Mall Kiosk........................... 163 Registering and Discovering Services: SDP Programming............................................................................................................... 158 Summary....................................................... 163 HCI Programming ............................................................................................................................................................................................................................................................................................................ 127 Overview of Bluetooth...........................Contents xiii Push Proxy Gateway ......... 328 Second Generation Wireless Networks .........................................................................................................................5G Wireless Networks .................................................. 127 Bluetooth System Specifications ............. 323 Chapter 10: An Overview of 3G ......................................................................................................................................... 212 Application: Chat ..................... 131 Commercial Bluetooth Solutions.................................................. 148 Implementation of WAP for Bluetooth ................................................................................................................................................ 134 Data and Voice Support ............................................................................................................................ 346 . 96 Application: Shopping Cart with Advertisement Push................................................................................................................................................................................................................................................................ 148 Application of WAP with Bluetooth ............................................................................................................................................................................................................................................................................... 125 Summary.................................................................................................................................................. 325 Multi-Cell Wireless Networks .............................................................................................................................................................................148 Bluetooth as a WAP Bearer ........ 328 2............................ 162 Chapter 9: Bluetooth Programming ............................................. 327 First Generation Wireless Networks........ 94 Develop the Database and Servlet Applications ......................................................................................................................................................................................................... 147 Summary............................................................................................................................................................ 147 Chapter 8: Using WAP with Bluetooth................................................................................................127 Introduction to Personal Area Networks (PANs).............................................................................................................................................................................................................................................. 271 Summary.................................................................................................................................................... 194 File Transfer Application ............................... 153 Application: Airport Kiosk ......................................................................................................................................... 341 Summary....... 135 Bluetooth APIs for Developing Applications ............................................................................... 107 Pros and Cons of Push Framework..................................................................................................................................................................... 153 Addressing in WAP with Bluetooth ..... 95 Application: Pushing the Stock Quotes.................................................................................................................................................................. 326 Cellular System Design Issues.................................... 132 Network of Bluetooth Devices: Piconet and Scatternet..................................... 339 Third Generation Wireless Networks .325 Principles of Cellular Mobile Communications.....................................163 Overview of the Bluetooth Development Kit ........................................................................................................................................................... .....473 Appendix A: What’s on the CD-ROM ................................................420 Protocols Overview.......458 Chapter 14: The Future of Wireless Networks ............................................................................................................................................................................................................................................................................................................. 420 Application of Voice and Video over IP............................................................................................................399 Application: Database............................422 Java Media Framework.............xiv Contents Chapter 11: Advanced 3G Programming........................................................................467 Tools for Content Development ............................................................................................................468 SyncML..............................................................................................424 Application: Voice Messaging ............................................................................................................................................................. 474 System Requirements ................................................................................................................................................................376 Using BREW to Develop a New Application ...........................................472 4G Systems.................................................................................... 477 ...........................................................434 Application: Audio–Video Broadcasting..................................................................................................472 Summary .................................................................................................................................................470 Protocols.............................................................................................................................................................................................................................................409 Summary ................................................................................................ 349 3G Application Development Issues........................................................................474 CD Contents................................................................................................................................................................................................465 Precise Location-Based Services................................................................................460 Emerging Technologies ............................470 Mobile IP..........................................................421 H..........................468 VoiceXML .................................................................................................................................................................................................................... 376 BREW Overview ........................................................................................................................................384 Application: Downloading Music onto a Mobile Device ...............................................................349 Implementation of Real-World 3G Applications ....................................................................................................................................377 Application: Developing Animation ..............................................................................................................................474 Troubleshooting ...........................352 Development of a Mobile Advertising Application Using the Wireless Tool Kit ...............................................................................................................................................................................................................421 Low Bit Rate Coding of Voice and Video.............................................................................................................................................................................................................................................................................................................370 Summary .................375 Chapter 12: 3G Programming Using BREW .............................................467 Mobile Devices ...............................................................................................................................................................465 Unified Messaging...............................419 Chapter 13: Voice and Video Communication over IP and Mobile IP Networks........................................................................476 Appendix B: Tomcat Installation and Configuration .......................................393 Application: Mobile Advertisements .446 Summary ............................................................................................................................................................................................................................................................424 Application: Audio Broadcasting...........................................................................................................................323 Standards..............................................................................423 Application Setup.................................................................................................................................................................... 460 Convergence Technologies........................................................................464 Instant Messaging ................................... ...........................................................................533 ................................................ 478 Deploy Web Applications to Tomcat ................................................... 486 Deploy a Web Application to Tomcat............... 488 Appendix C: SQL Server 2000 Installation and XML Support Configuration ...............512 End User License Agreement .............................0 Community Edition for All Platforms ...... 502 Appendix D: Bluetooth Reference and Resources .............................................................................................490 About MS SQL Server 2000........ Binary Code License Agreement..........................................................................528 Sun Microsystems.....................530 License Agreement: Forte for Java Release 2................................................508 Appendix E: 3G Reference and Resources ....................................................................................................................... 478 Install the Tomcat Web Server .............................................................................................510 Index ........................................................................................................................................................... 490 Complete Installation of SQL Server 2000 (Setup) ............... 501 Using IIS (Internet Information Server) for Accessing SQL Server 2000.............................................................................................. 477 How a Web Server Works: An Overview .................................... 493 XML Support in SQL Server 2000.........................................................Contents xv Introduction to a Web Server............................................................................................................................................................................................................................................................. 477 Introduction to the Tomcat Web Server ............................ Inc.................................................. . 4 Kbps only. Evolution of Wireless Protocols and Applications The 2G systems support data rates up to 14. which are known as the second generation (2G) wireless networks. and small display. came into vogue. and video. Because of industry efforts to support multimedia services.Chapter 1 WAP. The demand for data services by mobile users has increased in recent years. mobile devices are evolving into powerful gadgets. small memory capacity. they will be able to support full-fledged multimedia applications with streaming audio and video. wireless networks that can support innovative applications combining data. however. and low bit rate video services. which will support data rates in the range of 384 to 2048 Kbps. evolve into third generation (3G) networks. which evolve from GSM systems. audio. these networks are characterized by high delay. The mobile devices have limited capability for accessing the Internet — in other words. The standardization efforts of many international bodies resulted in a few proposals for 3G networks. and as a result. We also look at the new languages and tools used to develop content for various applications. Subsequently. Evolution of Wireless Networks The cellular networks developed in the 1960s and 1970s were mostly analog systems that supported voice communication. These networks can support high-speed data services such as high-resolution graphics and animation. applications supported on these networks are capable of handling only text and low-resolution graphics. Asian and African countries adapted the North American and European standards. digital mobile communication networks.5G networks are the IS 95B standard-based networks that evolved from IS95A networks and the GPRS (General Packet Radio Service) networks built over the GSM networks. Two standards that are likely to find wide acceptance are W-CDMA (Wideband Code Division Multiple Access) systems. mainly because the 3G networks have to evolve from the existing networks. graphics. voice communication has been the killer application for many years. As these networks support higher data rates. Moreover. and cdma2000 systems.5G networks will. The 2G networks are now evolving into 2. but on regional standards developed in North America and Europe. North American standards include IS 136 and IS 95A (IS stands for Interim Standard). voice. which can support data rates in the range of 64 to 144 Kbps. The demand for multimedia services is now paving the way for high-speed. a single standard has not evolved. Bluetooth. The 2G networks aren’t based on international standards. and 3G: A Brief Introduction For people on the move.4 Kbps. Hence.5G networks. we review the evolution of wireless networks and the applications supported by these networks. which evolve from IS 95B systems. The browser that can be run on these . Examples of 2. This chapter also contains a brief overview of these developments. in turn. new protocols have emerged for providing wireless Internet access. The 2. and the European systems are based on GSM (Global System for Mobile Communications). These 2G networks support data rates up to a maximum of 14. In this chapter. low processing power. When high-speed networks are available. and betting odds has also gained wide acceptance among WAP users. and news headlines. mobile advertising to display product information on the mobile devices. Because mobile devices didn’t have the capability to run such powerful browsers. which is similar to JavaScript. sports news. in regard to both primary and secondary memories. I-Mode offers the same services as WAP but in packet-switching mode and at a higher speed. and provides very low-resolution graphics. The WAP Forum was launched in December 1997 by Ericsson. . WAP 1. weather information. The drawback with WML is that the content presently available on the Internet needs to be rewritten for mobile access. This is a gigantic task. which supports the WBMP (Wireless Bitmap) format. The content is then interpreted by a browser such as Internet Explorer (IE) or Netscape Navigator (NN). can run on the mobile devices to provide access to all the Internet services for mobile devices.2 uses the Wireless Markup Language (WML). animation. has gained wide popularity in Japan. a number of tool kits are available for testing the complete application in the laboratory environment before deploying the application on the site. The latest version of WAP — WAP 2.2 Chapter 1: WAP. The support for graphics is limited in WAP. To facilitate the development of content using WML and WMLScript. such as highresolution graphics. Content can be developed and tested using any of the popular WAP tool kits. In this book. such as astrological information. Because the TCP (Transmission Control Protocol) is not well suited for real-time audio and video communication. WAP 1. the Wireless Application Protocol (WAP) was developed. called I-Mode. Applications such as mobile banking to access the bank account information. Most of the wireless equipment manufacturers and operators are committed to the WAP standards. The mobile devices and servers that support the RTP and related protocols will provide the users with real-time voice and video transmission over the IP networks. Languages and Tools for Content Development The Internet content that you access from desktops is written mostly by using HTML (HyperText Markup Language). Entertainment content. But the present IP (Internet Protocol) has been designed for fixed terminals.0 — was released in July 2001. WAP enables Internet browsing through a set of protocols. WAP-enabled mobile phones can obtain very focused information such as stock quotes. which is now standardized. but the conversion won’t be very effective because WML supports only a subset of the HTML tags. The WAP gateway interfaces between the mobile network and the Internet to provide the content to the mobile phone. Above the UDP. which is derived from XML (eXtensible Markup Language). WAP protocol has been developed to provide wireless Internet access on low-speed networks. to provide access to Internet services. and so on are also finding wide acceptance. new markup languages were needed to create content that could be presented to the mobile devices. The content that you access through your desktops. can be accessed through mobile devices as well. they can support the TCP/IP protocol stack. To WAP-enable a mobile phone. and 3G: A Brief Introduction devices is also of limited capability.com. which are based on TCP/IP but with low protocol overhead so that the protocols can run on small devices such as mobile phones and pagers. It’s possible to have tools that convert the HTML content to WML content. HTML content is transferred from the Web server to the client machine. Another service. So.1 was released in June 1999 and WAP 1. we will discuss content development for advanced WAP applications. and audio and video clips. The computing power requirements for these browsers are enormous. the WAP protocol stack and a microbrowser need to run on the mobile phone. was developed to provide interactive capability to the content. Nokia.2 in November 1999. the UDP (User Datagram Protocol) is used to carry the voice and video data over the IP networks. WMLScript. The Mobile IP (MIP). and if the mobile devices have higher processing capability. and Phone. Motorola. I-Mode is now making in-roads in other countries as well. the RTP (Real Time Transport Protocol) is used to provide real-time capability. Bluetooth. and 3G: A Brief Introduction 3 To develop content that can be accessed through high-speed. the markup language standardized for applications in WAP 2. provided the mobile device has a Java Virtual Machine (JVM). mobile devices with varying capabilities will be used for wireless Internet access. All these devices have limited processing capability (8 or 16 bit micro-controllers). For effectively managing the input/output operations. Personal Digital Assistants (PDAs). and a fullfledged keyboard. we demonstrate application development using J2ME. In this book. which made them very powerful. Even after wide deployment of 3G networks. new markup languages are required. They now have high processing power. XHTML obviates the need for rewriting the content to be made available to mobile devices if the mobile devices can interpret XHTML. high battery life.0 specifications. which is a meta language. exciting developments have taken place in the world of mobile devices. EPOC. at the higher end are laptop computers that run a full-fledged operating system and a powerful browser. A number of these languages are now being used for content development. Bluetooth. Because the JVM has a high memory requirement. The content. you can develop browsers that don’t need high processing capability. BREW can be effectively used for development of content/applications irrespective of the air interface and the speed of the networks. Using the KVM and a subset of the libraries. larger color display. or a language used to develop other languages. Wireless Access Devices/Bluetooth The wireless devices of 2G support voice and data applications by using Short Messaging Service (SMS). The CDMA-based systems. Another advantage is that in XHTML. The KVM can be ported on devices with limited capabilities such as mobile phones. mobile operating systems such as Win CE. In addition. Another standardized language is XHTML (eXtensible HyperText Markup Language). . which is based on XML with almost the same tags as HTML. Java-enabled mobile devices will run a KVM to download the Java code and present it to the users. wireless networks by more powerful wireless devices. the syntax must be followed strictly. You can exploit the Java programming language’s capability of platform independence and networkcentric programming to develop Internet content using Java. have also found wide acceptance in many Asian countries. and a keypad with limited functionality. a small black and white display that can support 2 to 4 lines of text with 8 to 12 characters per line. which have a large installation base in North America. In recent years. The browsers on the mobile devices have higher capability — the mobile device can download content written in XHTML and present it to the user. and two-way pagers. Sun Microsystems’s Wireless tool kit facilitates development of Java applications using J2ME (Java 2 Micro Edition). This book demonstrates application development using BREW. small memory (generally less than 64 Kbytes). can be downloaded to the mobile device and executed. The WAP protocol and WML have been developed to take care of these limited capabilities of mobile devices. and Palm OS are available. giving them the capability to get connected to a wireless network and download the application. memory. At the lower end of the spectrum are WAP-enabled phones. WAP-enabled phones are used to obtain the WAP content. a virtual machine that requires a few kilobytes (as low as 160K) of memory.Chapter 1: WAP. Sun Microsystems has released the KVM (where K stands for kilobyte). which provides the environment to develop applications for wireless networks. in the form of applets. peripherals such as video cameras are being integrated into mobile devices. As a result. This book covers the content development by using XML and XHTML. We discuss these issues in detail. Qualcomm Corporation — which pioneered the development of CDMA technology — released BREW (Binary Runtime Environment for Wireless). and the various processes that run on the mobile device. you can develop content for wireless devices and the code can move from the server to the mobile device. The content can be written in XML. Developing the content that can cater to all types of mobile devices will be the greatest challenge for the content developers. mobile phone. mobile commerce. Using low-cost.4 Chapter 1: WAP. and then make them communicate with each other. laptop. which can be deployed on present and future wireless networks. the content developers have to create exciting applications that have high visibility. and so on. low-power radio technology. Bluetooth. to use their desktops and fixed peripherals on a daily basis. PDA. Another problem is to ensure that the data in various machines are synchronized: The mail in the mailboxes on the desktop and the laptop need to be the same. for example. Summary In this chapter. and video streaming. we introduced the various aspects of WAP. scanner. Because it’s likely that every 3G mobile device will be Bluetooth enabled in the future. this book aims to equip you to achieve this objective. he or she has to connect the devices through wires. and 3G programming that are explored in this book. Bluetooth solves the problems associated with wires and lack of synchronization of data. mobile audio. we devote two chapters to Bluetooth protocols and programming aspects. For 3G to find wide acceptance by the user community. printer. The focus here is on developing commercial applications in mobile advertising. and 3G: A Brief Introduction Mobile devices don’t make the fixed devices obsolete. Bluetooth. . digital camera. The Personal Area Network (PAN) formed by these devices can exchange data without wires and also synchronize the data among themselves. Bluetooth enables ad hoc networks to be formed among various devices (desktop. If a person wants to transfer a file from the laptop to the desktop or to take a printout of a document that’s on the laptop. and so on). People continue. LCD projector. the address books on the desktop and laptop need to be the same. headset. This synchronization will achieve greater importance when a person downloads mail from different devices at different times but wants to ensure that both devices have the same copies. Consider the following code: <?xml version="1. and show images on the mobile phone. The body of a WML document can consist of one or more of the following: ♦ Deck ♦ Card ♦ Content to be shown ♦ Navigation instructions This is declared as follows: . The second line selects the document type and gives the URL of the document type definition (DTD). The DTD referenced is defined in WAP 1. WML scripting language is used to design applications that are sent over wireless devices such as mobile phones. WML Commands and Syntax WML commands and syntaxes are used to show content and to navigate between the cards. The header must be copied exactly so that the tool kits automatically generate this prolog.1. In order to understand the syntax and commands used in the case studies.0. The body is enclosed within a <wml> </wml> tag pair. This chapter focuses on explaining the application of WML and WML Script.wapforum. Program Structure A WML program is typically divided into two parts: the document prolog and the body.org/DTD/wml12. which consists of WML and WML scripting language.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. format text. you must first understand the commands and their syntax in WML and WML Script. but this header changes with the versions of the WML. WML is an application of XML. We use case studies to explain how to program with WML and WML Script.Chapter 2 WML and WML Script Programming: A Case Study The topmost layer in the WAP (Wireless Application Protocol) architecture is made up of WAE (Wireless Application Environment). WML is based on HDML and is modified so that it can be compared with HTML.2//EN" "http://www. This language takes care of the small screen and the low bandwidth of transmission.dtd"> The first line of this text says that this is an XML document and the version is 1. Developers can use these commands to declare variables. This DTD gives the full XML definition of WML. which is defined in a document-type definition. 6 Chapter 2: WML and WML Script Programming: A Case Study <wml> <card> ….. conversion) Forms <select> <input> Define single or multiple list Input from user Events The various events are as follows: ♦ Do <do> To start a specified action .<a> <go> <prev> Inserting images <img src=”image path/name” alt=”Picture not available”/> Tables <table> <tr> <td> <Thead> Definition of a table Defining a row Defining a column Table header Variable Declared as: <setvar name="x" value="123"/> Used as: $ identifier or $ (identifier) or $ (Identifier. </card> </wml> Commands The commands used in WML are summarized as follows: Formatting <p> <b> <big> <em> <I> <small> <strong> <u> <br> Paragraph Bold Large Emphasized Italicized Small Strongly Emphasized Underlined Line Break Navigation controls Do Go Prev <do> Anchor link . wmls. The functions used are stored in a separate file with the extension .Chapter 2: WML and WML Script Programming: A Case Study 7 ♦ Tasks <go> <prev> <refresh> <noop> To To To No jump to other possible position jump to the prev page reload the page operation WML Script — Commands and Syntaxes WML Script is used to check the part of the program on the client machine.wmls#convert() WML Script is function-based. The functions are called as the filename followed by a hash. followed by the function name: currency. The six main libraries to provide the functionality are: ♦ Lang — for core WML Scripts ♦ Float — for floating-point math functions ♦ String — for String manipulation functions ♦ URL — for specialized String manipulation functions for working with URL ♦ WMLBrowser — for controlling the browser from the program ♦ Dialogs — for controlling dialogs Program Components WML Script program components are summarized as follows: Operators ♦ Assignment operator: equal to (=) ♦ Arithmetic operators: • + Addition • – Subtraction • * Multiplication • / Division • Div Integer division only • % Modulo • ++ Increment • -- Decrement • ?: Ternary operator ♦ Relational and logical operators: • == Equality • < Less than • > Greater than • <= Less than or equal to . max(). minFloat() ♦ String For performing string operations .8 Chapter 2: WML and WML Script Programming: A Case Study • >= Greater than or equal to • != Not equal to ♦ Logical Operators: • && And • || Or • ! Not • Isvalid: checks whether an expression evaluates to invalid ♦ Bitwise operators: • & Bitwise and • | Bitwise or • ^ Bitwise exclusive or • << Left shift • >> Right shift • >>> Right shift with zero fill • ~ Bitwise not Control structures Control structures are used for controlling the sequence and iterations in a program. pow(). maxInt(). parseFloat(). characterSet().abort().float(). floor(). isMax(). parseInt(). ceil().wmls. int(). isInt(). isFloat(). maxFloat(). random(). } The function is called as follows: filename#function name Standard Libraries used in WML Scripts ♦ Lang For WML Script core programming • Examples: abs(). Functions are declared as follows: function name (parameters) { control statements. round(). min(). minInt(). seed() ♦ Float For clients having floating-point capabilities • Examples: sqrt(). return var. ♦ if-else Conditional branching ♦ for Making self-incremented fixed iteration loop ♦ while Making variable iteration loop Functions The user-defined functions are declared in a separate file having the extension . If the user clicks Movie.wml ♦ Movie.wml ♦ Weather. Application Structure The case study discussed here contains the following files: ♦ Information. the Movie. escapeString(). getFragment() ♦ WMLBrowser Used to access WML context by WML Script • Examples: go(). The Information Master Application The Information Master application deals with providing information about movies and the weather to the client.wml file. getHost().wml file. appears. charAt(). removeAt(). sun. getVar(). refresh(). isEmpty(). unescapeString().rand() in the script file and by Weather.wml to display them on-screen. setVar() ♦ Dialogs Contains the user interface functions • Examples: prompt(). format(). The script file has just one function for generating the random numbers for the display of maximum and minimum temperatures on the screen. The functioning and output are shown on the screen of a wireless device/cell phone using a Nokia Toolkit as the emulator. Application Work Flow The application opens a menu with two options: Movie and Weather. compare(). The goal of the applications is to make the user understand the implementation of the WML and WML Script. squeeze(). confirm().ico is an image file used to display the image of sun on the browser screen by the Weather. elements(). It’s made up of three WML files.wml file. elementAt(). trim(). resolve().Chapter 2: WML and WML Script Programming: A Case Study 9 • Examples: length(). getCurrentCard(). isValid(). next(). . appears. The applications are: ♦ The Information Master ♦ The Restaurant These applications are written in WML and the functions are applied to them through WML Scripts. one WMLS file.ico The first three files are the WML application files. getBase(). These temperatures are generated by using Lang.wml ♦ Weather. and one graphic file. loadString(). find(). insertAt().wmls ♦ sun. you saw the structure and syntax of WML and WML Script. which displays the name of movies and show timings. If the user clicks Weather. toString(). getReferer(). Now we willdevelop two applications and explain their functioning. which displays the maximum and minimum temperatures of various cities on the screen.wml code file. replaceAt() ♦ URL For handling absolute and relative URLs • Examples: getPath(). prev(). alert() In the previous sections. the Weather. the fourth is the script file that will be used by Weather. replace(). wapforum.0"?> 2.wml. the system opens the Movie. which shows two options: ♦ Movies Info (Movie.wml // © 2001 Dreamtech Software India Inc.1.Declaration of the WML deck> 4. Application Description Listing 2-1 contains the code for Information. <wml> <!-. On clicking the Weather Info option.1//EN" "http://www. which internally calls the Weather. see Figure 2-1. </head> .wml) ♦ Weather Info (Weather.xml"> <!-.wmls file (Scripting file) that initializes the minimum and the maximum temperatures and returns them to the Weather. the system calls the Weather.10 Chapter 2: WML and WML Script Programming: A Case Study To understand how the files are related. <?xml version="1. // All Rights Reserved 1. <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!-.wml) On clicking the Movies Info option.WML prolog–declaration of file type and version> 3. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.wml. Listing 2-1: Information.meta tag to define the content and cache settings> 6. <head> 5.wml file and shows the listing of the all movies in the selected theatres.org/DTD/wml_1.wml file.wml file. Figure 2-1: Flow diagram of the Information Master application The main file is Information. card end> 14.wml // © 2001 Dreamtech Software India Inc. 13.wml. Movies info. </p> 13.WML prolog–declaration of the file type and version> 3. <card id="MyFirst" newcontext="true"> <!-. <wml> <!-.wml.Chapter 2: WML and WML Script Programming: A Case Study 11 7. and 14 are closing tags for paragraph. 4. 6.wml or Weather.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. </card> <!-.program end> Code description The first two lines are the prolog of a typical WML file.wml">2. Weather Info. respectively. This WML file contains only one card titled MyFirst. Lines 12.org/DTD/wml_1. // All Rights Reserved 1. and WML. This card contains one text line (Line 8) and two links (which are defined in an <a> tag on Lines 10 and 11). Figure 2-2: Output screen of the Information. </wml> <!-. <p align="center"><b>Information Center</b></p> <!--paragraph declaration to display heading> 9. 5.declaration of a card in deck> 8. <a href="Movie.1//EN" "http://www. you can navigate to the file Movie.</a> <!--declaration of links for weather and movies> 12. card. <p> <!--paragraph declaration to display links> 10.wml">1. <a href="Weather.wml. Code output Figure 2-2 shows the output of Information. <?xml version="1. which is defined in Line 7. Listing 2-2: Movie.wapforum.Declaration of the WML deck> <head> <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!--meta tag to define the content and cache settings> </head> .</a> 11. By clicking the links. 2.wml Listing 2-2 contains the code for Movie.1.xml"> <!-. ....declaration of a paragraph to display heading> <p align="center">Cinema 8</p> <p align="center">1040 South</p> <p align="center">Sage Way</p> <p align="center">.. This WML file contains only one card. and Line 37 is the close tag for WML. 32. <p align="center"><b>Movies Information</b></p> <!-......wml.. which is defined in Line 7... 9:15</p> <p align="center">..</p> <p align="center">The Blair Witch Project</p> <p align="center">4:25... 9:30</p> <p align="center">.. Line 36 is the close tag of the card..</p> <p align="center">Runaway Bride</p> <p align="center">7:00.. 31... 21..... 26.</p> <p align="center">Three to Tango</p> <p align="center">7:25.declaration of a card in deck> 8. 29....</p> <p align="center">Super Star</p> <p align="center">7:25.... 11.</p> <p align="center">Inspector Gadget</p> <p align="center">4:40...... 22...... </card> <!--end of card> 37. <card id="First" newcontext="true"> <!-.. 20. 15.</p> <p align="center">Story of Us</p> <p align="center">7:10. 35. 13..</p> <p align="center">Mystery Alaska</p> <p align="center">7:05. 9:20</p> <p align="center">. 9:20</p> <p align="center">... 7:35.. 9:15</p> <p align="center">... 9:25</p> <p align="center">... 16...12 Chapter 2: WML and WML Script Programming: A Case Study 7... 27..... 12. </wml> <!--end of wml code> Code description The first two lines are the prolog of a typical WML file. Lines 8 to 35 are used to store the information about different movies in multiple paragraphs. Figure 2-3: Output screen of Movie. 14.. 18. 30. 7:30.... 28. 33.. 17. you must use the up and down arrows of the wireless device to read the information. named First. 19.declaration of paragraphs to display movie information> 9.wml .. 23.</p> <p align="center">Three Kings</p> <p align="center">7:05. 9:30</p> <p align="center">.... Because the information takes up more than one screen. 9:10</p> <!-.. 34.. 10. Code output Figure 2-3 shows the output of Movie.. 24. 36.. 25.. // All Rights Reserved 1. <wml> <!--declaration of the wml deck > 4. Listing 2-3: Weather. <p align="center"><img localsrc="sun" alt="" src=""/> <!-. 13. 5.declaration of the first row> 17.declaration of paragraph to display sun image> </p> <p> <table align="left" columns="2"> <!-. <td><b>Low</b></td> <!--declaration of two columns in a row to display High & Low> 19.wapforum. 2. <p align="center"><b>Weather Information</b></p> <!-. <tr> <!--declaration of the new row to display content> 21. </onevent> 11. </card> .declaration of the event for navigation> 9. 14. <head> <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!--meta tag to define the content and cache settings> 6. <tr> <!-.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.wmls#Init()" /> <!-. 15. </p> 26.Chapter 2: WML and WML Script Programming: A Case Study 13 Listing 2-3 contains the code for Weather. <card id="MyFirst"> <!-.org/DTD/wml_1. </tr> 24. <td>$var2</td> <!--declaration of the two columns to display the > <!--value of variables var1 and var2> 23. <?xml version="1. </tr> 20.declaration of paragraph to display heading> 12. <onevent type="onenterforward"> <!-.wml. <td>$var1</td> 22.calling of function from the script file > 10. </table> <!--end of table> 25.wml // © 2001 Dreamtech Software India Inc.xml"> <!--WML prolog–declaration of file type and version> 3.1//EN" "http://www.1. <go href="Weather.declaration of the first card> 8. <td><b>High</b></td> 18.declaration of event and > <!-. </head> 7.declaration of the table element> 16. var2 = Lang.end of card> </wml> <!--end of WML code> Code description The table and the scripting language used in this program are a bit complicated. Listing 2-4: Weather.random(100). WMLBrowser. WMLBrowser. <!-. Figure2-4: Output screen of Weather.wml Listing 2-4 shows the code for Weather.14 Chapter 2: WML and WML Script Programming: A Case Study 27.wmls. var1). Let’s look at the execution line by line: ♦ Lines 1–2: WML prolog ♦ Lines 3–6: WML declaration with meta tag ♦ Line 7: Card declaration ♦ Line 8: Event declared (trapping the click event) ♦ Line 9: Specifying the navigation link to the init function of the Weather.seed(-1).random(100).wmls script file ♦ Line 10: Event closed ♦ Lines 11–14: Paragraph declaration to show the text and image on-screen ♦ Line 15: Table declaration having two columns ♦ Line 16: First row declaration ♦ Lines 17–18: Two columns of first row having text as high and low ♦ Lines 21–22: Two columns of second row showing the values of variables defined in init function as of Line 9 ♦ Lines 23–27: Closing tags Code output Figure 2-4 shows the output of Weather.refresh().setVar("var2". WMLBrowser. // All Rights Reserved 1 2 3 4 5 6 7 8 9 10 11 extern function Init() { var var1="10". var2).wml. var var2="15". var1 = Lang. var Dummy = Lang.wmls // © 2001 Dreamtech Software India Inc.setVar("var1". } . so the value of the variable will be stored in these variables and transferred to the calling file. After the user selects the items.wml .wml .wml . which is called from the weather file to display the information on-screen. which is Weather.ico is the image file. You can only call it from other WML files.Chapter 2: WML and WML Script Programming: A Case Study 15 Code description This is a scripting file and has only one function named Init. ♦ Lines 8–9: Stores the values in the variables var1 and var2 defined in Weather. Take a look at the execution line by line: ♦ Line 1: Name of the function ♦ Lines 3–4: Initialization of two variables named var1 and var2 ♦ Lines 6–7: Generation of two random numbers below 100 using the standard WML libraries. and values are stored in the variables var1 and var2. Application Structure The application is made up of five files: ♦ ResScript.Link file to select items of Snacks category . Complete Output Figure 2-5 shows the project flow of the Information Master application. This is called by reference function. sun.The scripting file ♦ Restaurant.wml.Link file to select items of the South Indian dishes category ♦ Soft.ico sun.wml .Link file to select items of Soft Drinks category ♦ Snacks.wml ♦ Line 10: Refreshes the screen Code output You cannot execute the script file directly. Figure 2-5: Output of the complete project The Restaurant Application This application starts with a menu from which the user can select different items to order from a restaurant. the bill is generated accordingly.wmls . so there’s no output for this code.The main menu file to select the category ♦ South. Listing 2-5: Restaurant. the system calls the corresponding WML file and shows the item related to that category. <head> 5. which shows three items: ♦ South Indian (South. </head> 7.wapforum. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1.1//EN" "http://www.0"?> 2. // All Rights Reserved 1.16 Chapter 2: WML and WML Script Programming: A Case Study Application Work Flow The main file is Restaurant.wml) ♦ Snacks (Snacks. The main menu file shows a menu containing three links for three categories.wml.declaration of a new deck> 4. Figure 2-6: Flow diagram of the Restaurant application Application Description Listing 2-5 shows the code for Restaurant. <card id="card1"> <!-.meta tag to define the content and cache settings> 6. Figure 2-6 shows the flow of data in the files. <?xml version="1.wml // © 2001 Dreamtech Software India Inc.declaration of an event for navigation> . <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!-.org/DTD/wml_1.WML prolog–declaration of file type and version> 3.wml) After you click a particular item. <onevent type="onenterbackward"> <!-.wml.wml) ♦ Soft Drink (Soft. <wml> <!-.declaration of a new card> 8.xml"> <!-. <td><a href="Snacks. 16.end of event declaration> 11. 25.end of paragraph> 13.declaration of a new row> 24.wml">Snacks</a></td> </tr> <!-. <go href="ResScript.declaration of a new row> 18.end of row> 23.wml">South Indian</a></td> <!-.declaration of a new row > 21.declaration of a new paragraph to define table> 14.declaration of a new column having link to south. <td><a href="South.Chapter 2: WML and WML Script Programming: A Case Study 17 9. </p> <!-.declaration of a new paragraph to display heading> 12.wml> 22. </wml> <!-. </onevent> <!-. </card> <!-.declaration of an event for navigation and calling of> <!-.wml> 19. <tr> <!-. </p> 28.end of a row> 20. <table align="left" columns="1"> <!-.wmls#Initialize()" /> <!-.wml">Soft Drink</a></td> <!-. 15. <td><a href="Soft. <p align="center"><b> Taj Palace </b> <!-.end of card> 29. </table> <!-.declaration of a new column having link to soft.declaration of a new paragraph to display selection> <!— category> </p> <p align="left" mode="nowrap"> <!-.end of wml> Code description ♦ Lines 1–2: WML Prolog ♦ Lines 3–5: Meta tag on head . </tr> <!-. <p align="left">Select a Category: <!-.end of row> 26. </tr> <!-.function from the script file> 10.end of table> 27.declaration of a table> 17. <tr> <!-. <tr> <!-. navigation takes you to a new file ♦ Lines 27–29: Closing tags Code output Figure 2-7 shows the output of Restaurant.18 Chapter 2: WML and WML Script Programming: A Case Study ♦ Line 7: Defining the first card named card1 ♦ Line 8: Event declared (trapping the click event) ♦ Line 9: Specifying the navigation link to the initialize function of the ResScript.declaration of a variable and initialising it> 11. </refresh> 12.wml.wml Listing 2-6 shows the code for South.wml // © 2001 Dreamtech Software India Inc. </onevent> <!-.declaration of a new event> 9.xml"> <!-. The user can select an item from the list. <card id="card1"> <!-.wmls. <refresh> <!-.0"?> 2. Listing 2-6: South. <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!-.WML prolog–declaration of file type and version> 3. <?xml version="1. // All Rights Reserved 1. This file shows the items belonging to the South Indian category.end of event> . After you select the link.00" /> <!-. Figure 2-7: Output screen of the file Restaurant.refreshing the variable> 10. The price of that item is passed as a parameter to the function Func1 of the script file ResScript.declaration of a new card> 8.org/DTD/wml_1. <onevent type="onenterforward"> <!-.wapforum.declaration of a new deck> 4. <head> 5. <setvar name="var1" value="1.1.wml. each row containing the link to a new category. </head> 7.wmls script file ♦ Line 10: Event closed ♦ Lines11–12: Paragraph declaration to display Taj Palace in center ♦ Lines 13–15: Paragraph to display selection of category ♦ Lines 16–26: Creation of table with one column and three rows.meta tag to define the content and cache settings> 6. <wml> <!-. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www. end of select list> </p> <!-.declaration of navigation to script file to > <!-.00</option> 20. <option value="15. <p> <!-.00</option> 19.00">Mixed stew 30.declaration of a select list> 18.end of paragraph> </card> <!-. 25. </do> <!-. 28. <option value="23.wmls with the value of variable var1 on select option ♦ Line 16: New paragraph ♦ Lines 17–23: Creating the selection list having items belonging to the South Indian category ♦ Lines 24–29: Closing tags Code output Figure 2-8 shows the output of South.00">Onion pancake 23.00">Rice pancake 15. <go href="ResScript. <option value="30. <option value="20. .00</option> 21.declaration a new paragraph> 17.end of event> 16.end of card> </wml> <!-. <option value="10.end of deck> Code description ♦ Lines 1–2: WML Prolog ♦ Lines 3–5: Meta tag on head ♦ Line 6: End of the head tag ♦ Line7: Defining the first card named card1 ♦ Line 8: Event declared (trapping the click event) ♦ Line 9: Specifying the navigation link to initialize the function of the ResScript.00">Rice ball 15. <option value="15.00</option> 23.wmls#Func1($var1)" /> <!-.00</option> <!--options of select list> 24.declaration of an event> 14. </select> <!-.00">Rice doughnut 20. 29.00">Cheese pancake 10.wmls script file ♦ Line 10: Defining a variable var1 and initializing it to 1 ♦ Line 11: End of the refresh tag ♦ Line 12: Event closed ♦ Lines 13–15: Calling the function Func1 from ResScript.call the function funcl with parameter> 15.00</option> 22.wml. <do type="accept"> <!-. 27. 26.Chapter 2: WML and WML Script Programming: A Case Study 19 13. <select name="var1"> <!-. </do> <!-. <onevent type="onenterforward"> <!-. <option value="50.wml.declaration of a new card> 8.00" /> <!-. <option value="10.meta tag to define the content and cache settings > 6.00">Cold Drink 20. <option value="40. <setvar name="var1" value="1.00</option> 19.declaration of a new event> 9. <wml> <!-.end of action tag> 16. <refresh> <!-.00">Cold Coffee with ice-cream 50.options of select list> 23.wml Listing 2-7 shows the code for Soft.00</option> 20.00">Cold Coffee 40.declaration of action to call the function from> <!-. <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!-. </head> 7.0"?> 2.declaration of a new paragraph> 17. <?xml version="1. <go href="ResScript. // All Rights Reserved 1. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. <do type="accept"> <!-.wapforum. <select name="var1"> <!-. <option value="20.org/DTD/wml_1. The price of that item is passed as a parameter to the function func1 of the script file ResScript. This file shows the items belonging to the Soft Drinks category and selects an item from the list.declaration of a select list> 18.wmls#Func1($var1)" /> <!-.WML prolog–declaration of file type and version> 3.00</option> 22. <card id="card1"> <!-.declaration of a new deck> 4.1.declaration of action event> 14.00</option> 21.refreshing the variables> 10.20 Chapter 2: WML and WML Script Programming: A Case Study Figure 2-8: Output screen ofSouth.xml"> <!-. <option value="20.00">Coffee 20. </select> .00">Tea 10.wml // © 2001 Dreamtech Software India Inc. Listing 2-7: Soft. </refresh> <!-.declaring a variable and setting the initial value> 11. <head> 5. <p> <!-.end of event declaration> 13.00</option> <!-. </onevent> <!-.wmls.1//EN" "http://www.end of refresh> 12.script file with a parameter> 15. WML prolog–declaration of file type and version> 3.wmls with the value of variable var1 on select option ♦ Line 16: New paragraph ♦ Lines 17–23: Creating the selection list containing items belonging to the Soft Drinks category ♦ Lines 24–26: Closing tags Figure 2-9 shows the output of Soft.wmls script file ♦ Line 10: Defining a variable var1 and initializing it to 1 ♦ Line 12: Event closed ♦ Lines 13–15: Calling the function func1 from ResScript. 25. // All Rights Reserved 1.0"?> 2.wml. <!-. <onevent type="onenterforward"> .1//EN" "http://www.wapforum. This file shows the items belonging to the Snacks category . <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.end </p> <!-. <?xml version="1.wml. </head> 7.wml // © 2001 Dreamtech Software India Inc.xml"> <!-.wml Listing 2-8 shows the output for Snacks.Chapter 2: WML and WML Script Programming: A Case Study 21 24. The price of that item is passed on as a parameter to the function Func1 of the script file ResScript.1.org/DTD/wml_1. Listing 2-8: Snacks.declaration of a deck> 4.meta tag to define the content and cache settings > 6. <head> 5.end </card> <!-. The user can select an item from the list.declaration of a card> 8. <card id="card1"> <!-. 26.end </wml> <!-.wmls. <meta http-equiv="Cache-Control" content="max-age=time" forua="true"/> <!-. <wml> <!-.end of select list> of paragraph> of card> of deck> Code description ♦ Lines 1–2: WML Prolog ♦ Lines 3–5: Meta tag on head ♦ Line 7: Defining the first card named card1 ♦ Line 8: Event declared (trapping the click event) ♦ Line 9: Specifying the navigation link to initialize function of the ResScript. Figure 2-9: Output screen of Soft. 22. 19.00</option> <option value="25.end of select list> </p> <!-. 25. 26. 24.from script file> 15. <p> <!-.declaration of an action and calling the function > <!-.00">Bread Pakora 20.declaration of a select list> 18. </onevent> <!-.list items> </select> <!-.wmls with the value of variable var1 on select option ♦ Line 16: New paragraph ♦ Lines 17–23: Creating the selection list containing items belonging to the Snacks category ♦ Lines 24–26: Closing tags Code output Figure 2-10 shows the output of Snacks.00">Mix.end of event declaration > 13.select list> 17. 20.end of deck> Code description ♦ Lines 1–2: WML Prolog ♦ Lines 3–5: Meta tag on head ♦ Line 7: Defining the first card named card1 ♦ Line 8: Event declared (trapping the click event) ♦ Line 9: Specifying the navigation link to initialize the function of the ResScript. <option value="40. <do type="accept"> <!-.declaration of a variable and storing initial value> 11.end of card> </wml> <!-. 21.wml . Veg.00" /> <!-. </do> 16.wmls#Func1($var1)" /> <!-.00</option> <option value="30. <refresh> <!-.wmls script file ♦ Line 10: Defining a variable var1 and initializing it to 1 ♦ Line 12: Event closed ♦ Lines 13–15: Calling the function func1 from ResScript.22 Chapter 2: WML and WML Script Programming: A Case Study <!-. <go href="ResScript.00</option> <!-. </refresh> 12. <select name="var1"> <!-. <setvar name="var1" value="1.end of paragraph> </card> <!-.declaration of an action> 14.refereshing the variable> 10.00">Onion Pakora 30. 23. Pakora 25.00">Cutlet 40.00">Cheese Fry 30.declaration of a new paragraph to display > <!-.00</option> <option value="30.declaration of an event> 9.00</option> <option value="20. parseFloat(Price). var Amount = ITEM * Lang.wmls // © 2001 Dreamtech Software India Inc. extern function Initialize() { WMLBrowser.wml#card1 "). // setting the variable TotalAmount to 0 } . // setting the navigation to restaurant’s card1 11.prompt("Enter Quantity".setVar("TotalAmount".refresh().Chapter 2: WML and WML Script Programming: A Case Study 23 Figure 2-10: Output screen of snacks. // refresh the browser 8. Func1 is called from three link files to calculate the amount of the bill.getVar("TotalAmount"). WMLBrowser."0. extern function Func1(Price){ // declaration of function funcl 2. 14. The script file has two functions.wmls.00"). 13. // declaring a dialog to display amount on screen 9. // declaring a new Amount variable and setting it to Price 6. // declaring a new ITEM variable and setting to 0 3.go("Restaurant. var TAmount=WMLBrowser. ITEM = Dialogs. // declaring a dialog to take input from user 5. var ITEM="0". ITEM = Dialogs. WMLBrowser. // adding amount to TAmount 7. WMLBrowser. } // declaration of function initialize 12. // setting the variable TotalAmount to TAmount 10. Listing 2-9: ResScripts.setVar("TotalAmount". and the function Initialize is called from the restaurant file to set the initial value of the browser variable TotalAmount to 0.TAmount).wml Listing 2-9 shows the code for ResScripts. // declaring a new TAmount variable and setting it to // the value of variable TotalAmount 4. TAmount = TAmount + Amount. TAmount). ITEM).prompt("Your Total Bill". // All Rights Reserved 1. the function of which is to calculate the amount and generate the bill accordingly.24 Chapter 2: WML and WML Script Programming: A Case Study Code description This is a script file. . The main calculations are done through this file. The following breakdown shows the functioning of this file in detail: ♦ Line 1: Defining the first function named Func1.wml files’s card1 ♦ Line 11: Function closed ♦ Line 12: Defining of second function named Initialize. This function is called when the application starts functioning Complete output Figure 2-11 shows the complete output of the Restaurant application. which takes price as parameter ♦ Line 2: Defining a variable ITEM and initializing it to 0 ♦ Line 3: Reading the browser variable TotalAmount and storing the result into local variable TAmount ♦ Line 4: Showing a prompt on-screen and accepting the value for quantity and storing it in the variable ITEM ♦ Line 5: Calculating the amount by multiplying the ITEM quantity with price received as parameter ♦ Line 6: Adding the amount calculated to TAmount variable ♦ Line 7: Refreshing the browser ♦ Line 8: Displaying the bill amount on browser ♦ Line 9: Setting the value of browser variable TotalAmount to local variable TAmount ♦ Line 10: Taking navigation control back to main Restaurent. which takes no parameter ♦ Line 13: Sets the browser variable TotalAmount to 0. com ♦ http://www.html . exciting platform on which they can deploy their applications. ♦ http://www. et al. J. L. The WML and WML Scripts syntax and commands are discussed briefly. We studied client-side programming by using WML and WML Script. ♦ Foo. S. John Wiley & Sons. Professional WAP. Our objective was to give the user some insight into WML and WML Script by using real applications.org/ ♦ http://www.aspWMLScript. you found out how WML offers software developers a new. Wrox Press. Links ♦ http://cellphones.com/channels/wap/training/wmlscript. 2000. Inc. ♦ Cook.wirelessdevnet. 2000.zvon. Wrox Press.. The main objective of the study of the two applications (Information Master and Restaurant) was to provide users with an understanding of WML and WML Script implementation in an application. For more information on WML and WML Script programming refer to the following resources: Books ♦ Arehart.wapforum.org/ZvonHTML/Zvon/zvonTutorials_en etc. 2000.).about.com/wap/wml. Beginning WAP: Wireless Markup Language and Wireless Markup Language Script. WAP Servlets: Developing Dynamic Web Content with Java and WML. C.Chapter 2: WML and WML Script Programming: A Case Study 25 Figure 2-11: Execution of The Restaurant application Summary In this chapter.palowireless.com ♦ http://www. (Ed. developed by Allaire. Cold Fusion. In this chapter. You can later embed the Cold Fusion tags between the HTML tags when necessary. Both of these are client-side application development languages used in wireless applications. along with a brief explanation. Structure of Cold Fusion Like HTML. Cold Fusion tags have attributes and a list of the available values for those attributes. Cold Fusion contains the following technologies: ♦ Language: CFML (Cold Fusion Markup Language) — a dynamic language for the Web ♦ Server: Cold Fusion Server — residing on the same server as the Web server ♦ Application: Cold Fusion Studio — a rapid development environment (RAD) A page written in CFML must pass through a Cold Fusion Server in order to be viewed properly. But if the user wants a dynamic and interactive Web page (which can be accessed from any device such as a Palm. Mobile. or Desktop ) Cold Fusion is the solution because Cold Fusion changes the output according to the user’s needs. are provided in it in a very simple way. But Cold Fusion tags start with CF and are processed on the server machine. Category Tag Function Variable manipulation tags CFSET Sets the variable CFPARAM Sets the parameter CFCOOKIE Sets the cookie CFSCHEDULE Sets a schedule CFABORT Stops the processing of the page CFBREAK Breaks out of the CF loop CFEXECUTE Facilitates execution of the process on the server machine Flow control tags . such as CGI and ASP. If a client needs a static Web page. you will learn the fundamentals of Cold Fusion and see its use in wireless applications through a simple project. It’s used to create forms and dynamic pages because all the benefits of languages. runs concurrently with most Windows and Solaris Web servers. HTML is needed.Chapter 3 WAP Using Cold Fusion: A Project The last chapter dealt with WML and WML Script. Also similar to HTML. is provided in the following table. The complete list of Cold Fusion tags. This chapter emphasizes wireless application using Cold Fusion. Cold Fusion is also a tag-based language. Cold Fusion: An Overview Cold Fusion is used to develop Web-based applications. for loop) CFIF CFELSE CFELSEIF Checks a specified condition CFSWITCH Makes a switch construct. alignment. checks cases of an expression CFTRY CFCATCH For exception handling in a Cold Fusion page CFFORM Defines a form in CFML CFSELECT Defines a drop-down list CFTREE Adds tree control in form CFGRID Adds grid control in form CFGRIDROW Specifies individual row data in CFGRID of form CFGRIDCOLUMN Specifies individual column data in CFGRID of form CFTEXTINPUT Enters a single-line text entry box in form CFINSERT Inserts a new record in data source CFQUERY Passes an SQL statement to the data source CFUPDATE Updates the existing record in a database CFPROCPARAM Specifies the information on the parameter CFPROCRESULT Specifies a name to the result set obtained from a query result CFTRANSACTION Groups multiple queries into one CFCOL Defines the table column header. width.Chapter 3: WAP Using Cold Fusion: A Project 27 Cold Fusion form tags Database manipulation tags Data ouput tags File management tags CFLOCATION Opens a specified Cold Fusion or HTML page CFTHROW Throws the exception specified by the users CFLOOP Makes loops (for example. and the text used inside CFTABLE CFCONTENT Defines the mime type of the page CFHEADER Generates custom http response header CFTABLE Builds a table in Cold Fusion CFOUTPUT Displays the result on-screen CFDIRECTORY Sets interactions with directories CFFILE Sets interactions with files . wml and . The specific tag used for this purpose is <CFCONTENT>.wml”> For generating WML Script decks. The output can appear as it’s completed in HTML (such as in paragraphs or a table). This tag should be at the beginning of the Cold Fusion template that contains the normal WML code. you use the Cold Fusion <CFOUTPUT> tag. Specifying content type for WAP <CFCONTENT> is the main tag is used for developing a WAP application with Cold Fusion.28 Chapter 3: WAP Using Cold Fusion: A Project Other tags CFCACHE Speeds up static pages access CFLOCK Sets the locks to database CFSILENT Suppresses the outputs CFREPORT Runs predefined reports CFINCLUDE Includes a CFML page reference in current document CFASSOCIATE Allows the sub tags in the base tag CFSETTING Helps control the page setting aspects CFHTMLHEAD Embeds other HTML tags in CFML Cold Fusion for WAP Cold Fusion pages are configured for the normal Web server with the extension .cfm.wap.<a> <go> <prev> . The tag is written as follows: <CFCONTENT TYPE= “text/vnd. Displaying text in the WAP browser/Commands summary For displaying the text in the WAP browser. The main principle lies in the specification of the content type in a file being worked on in the client browser. You can also define Cold Fusion pages for use by the WAP client.wap. The commands related to the output are summarized as follows: Formatting Tags Used in Cold Fusion <p> <b> <big> <em> <I> <small> <strong> <u> <br> Paragraph Bold Large Emphasized Italicized Small Strongly Emphasized Underlined Line Break Navigation Controls in Cold Fusion Do Go Prev <do> Anchor link .wmls files to access the content from the Web server.wmlscript”> If the page is without any dynamic content. the main tag is used as follows: <CFCONTENT TYPE= “text/vnd. the WAP client uses . Structure of the application The application contains the following files: . Now as the username and password are accepted. For this application. Finally. you see the output as it appears on the WAP browser. a random question is picked up from the database depending on the course ID. and e-mail addresses. After entering the correct answer. the user logs in to play the quiz. then the mobile user picks one from several multiple-choice answers. the users register to play the quiz by their names. This chapter. The following sections discuss the application in detail. Consider a CFML designed for playing a quiz game with the mobile user. provides an overview so that you understand its use and also an application for creating a WAP application. the retry option begins to work. conversion) Forms <select> <input> Define single or multiple list Input from user <do> To start a specified action <go> <prev> <refresh> <noop> To To To No Events Tasks jump to other possible position jump to the prev page reload the page operation Application: Question Quiz The main objective of this chapter is to explain the function of Cold Fusion in a real-life application. ten Cold Fusion files and one database file are created in Microsoft Access. though not meant to teach you Cold Fusion. the user is greeted. we cover the application structure and its function. In the preceding section. In this application. Having registered.Chapter 3: WAP Using Cold Fusion: A Project 29 Putting Images <img src=”image path/name” alt=”Picture not available”/> Tables <table> <tr> <td> <Thead> Definition of a table Defining a row Defining a column Table header Variable Declared as <setvar name="x" value="123"/> Used as $ identifier or $ (identifier) or $ (identifier. Then we look at the code design and description. we discussed the commands and syntax that you use in the application. otherwise. First. street addresses. mdb. Table 3-1: answertable Structure Field Name Datatype Description Qid Number Contains the question ID choice1 Text Contains the Choice Number 1 for the question choice2 Text Contains the Choice Number 2 for the question choice3 Text Contains the Choice Number 3 for the question Answerid Text Contains the Right Option Number for the question Table 3-2: coursetable Structure Field Name Datatype Description Qno Number Contains the total number of questions Table 3-3: questiontable Structure Field Name Datatype Description Qid Number Contains the question ID Question Text Contains the text of the question Table 3-4: userlogininfo Structure Field Name Datatype Description .cfm ♦ tryagain.cfm ♦ action.cfm ♦ submit.cfm ♦ bingo.cfm ♦ login.cfm The Database File Name is prototype.cfm ♦ answer.cfm ♦ checkvalues.30 Chapter 3: WAP Using Cold Fusion: A Project ♦ index. and the tables defined in the Database are as follows: ♦ answertable ♦ coursetable ♦ questiontable ♦ userlogininfo ♦ userpersonalinfo Tables 3-1 to 3-5 describe the structure of each of these tables.cfm ♦ readallvalues.cfm ♦ questiondisplay. which reads the random question. From the file bingo. readallvalues. From tryagain. the file called is bingo.cfm file from which the data is inserted into the table.cfm.cfm reads the total number of questions in the database for the specified course and generates a random number to pick a question from the table. and this particular answer choice is transferred to answer. The correct answer option is also picked up from the user through the next file.cfm.cfm.cfm. which generat automatically Userid Text Contains the user login name Username Text Contains the user name (actual name) Cellno Text Contains the user cell phone number Country Text Contains the name of the country City Text Contains the name of the city Provider Text Contains the name of the service provider of mobile service Stdcode Number Contains the std code of the city in which the user resides Emailid Text Contains the email address of the user Application Function The application begins with the file index. Figure 3-1 shows a diagram of this application.cfm. named submit.cfm. and e-mail address. From here. otherwise. which checks the user password. the execution goes back to index. the control is sent to the file login. it is validated with the correct answer accessed from the database. country.cfm. city. The file index. If it’s incorrect. the file readallvalues. All this information is sent to the action. After entering the information in the database. the user is asked to enter the user ID again. cellno.cfm is utilized to take this Register information for the user.cfm. The information received is userid.cfm. password.cfm is called for the question and answer reading.cfm is called. If the answer is correct. the execution is sent back to login. the file called is tryagain. the file questiondisplay. username.cfm is called. picks an answer from the choices of the question table. If the user ID is already present. For facilitating the login for the quiz. which displays a menu on the mobile screen with two options — Login and Register.cfm again. the file takes the username and password. The new user must click the Register option before Login to execute the quiz application. If the user ID and password are correct. The username and password are passed onto the file checkvalue. and displays it on the mobile screen. the file questiondisplay.cfm. . Here.Chapter 3: WAP Using Cold Fusion: A Project 31 Userid Text Contains the user login name Password Text Contains the user password Table 3-5: userpersonalinfo Structure Field Name Datatype Description Indexno AutoNumber Contains the Unique ID for every row in the database. WML Prolog --> 4.1//EN" “ http://www. </head> 8. <CFSET Session.COM//DTD WML 1.this line is placed for indicating the type of page being sent to the browser -->. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-.render="0"> <!-.<!-.wap.declaration of session variable render --> .begin a new deck --> 5.cfm © 2001 Dreamtech Software India Inc. so that the user can choose between Register and Login. <!DOCTYPE wml PUBLIC "-//PHONE.this line must be added to the top of the Cold Fusion template. the user information is accepted and stored in the session variables. <card id="card1" title="Main Menu" newcontext="true"> <!--defining the first card named as card1.com/dtd/wml11. All Rights Reserved 1.0"?> 3.cfm file’s (Listing 3-1) main function is to create the session variables and display the menu on the mobile screen. If Register is selected.32 Chapter 3: WAP Using Cold Fusion: A Project Figure 3-1: Question Quiz application work flow diagram The following section is a description of each file in the application. --> 2.courseid="0"> <!--declaration of session variable courseid --> 10. The index. <wml> <!-.dtd" > <!-. <CFCONTENT TYPE="text/vnd. <?xml version="1.it defines the meta tag to be used by the browser --> 7.wml"> <!-. The line-by-line description of the code follows. <CFSET Session. --> 9.phone. Listing 3-1: Index. <head> 6. to display the menu --> <!--to define the session variables for the entire application. end of card --> 21. <CFSET Session. <input name="cellno" /> 38.cfm">Login</option> <!-.ID of user <input name="emailid"/> 41. Enter User Name <input name="username" /> 37.declaration of action --> 44. <postfield name="country" value="$(country)" /> 29.declaration of a new paragraph to display heading --> 14. </do> 46. <go href="action. </go> 32. <do type="prev" label="Back"> <!-. Enter User ID <input name="userid" /> 35.declaration of new action --> 24. <select name="url"> <!-.declaration of variables to be posted to new link --> 25. <postfield name="password" value="$(password)" /> 26. </select> <!-.answerid1="0"> 43.declaration of a new paragraph --> 34. <postfield name="emailid" value="$(emailid)" /> <!-.userid="abc"> <!-. <p> <!-. </do> 33.end of paragraph --> 20. </p> 42.end of deck --> . Enter cell No.end of list --> 19. <prev/> 45. <option onpick="login.end of card –-> 47.Chapter 3: WAP Using Cold Fusion: A Project 33 11.list options --> 18. <postfield name="username" value="$(username)" /> 27. Email. <p mode="nowrap"> 15. <option onpick="#entry">Register</option> 17.declaration of session variable userid 12.declaration of a new list for register and login --> 16. <postfield name="city" value="$(city)" /> 30.userpassword="abc"> <!-. </card> <!-. Enter Password <input name="password" type="password" /> 36. <do type="accept" label="ok"> <!-. <postfield name="userid" value="$(userid)" /> <!-. <p align="center"> Main Menu</p> <!-.declaration of new event --> 23.cfm" method="post" > <!-. </wml> <!-. </p> <!-.session variables declaration --> --> 13. Enter country <input name="country" /> 39. <card id="entry" title = "Record Entry" newcontext="true"> <!-. <CFSET Session. Enter city <input name="city" /> 40.declaration of a new card --> 22.declaration of variables to be posted to new link --> 31. <postfield name="cellno" value="$(cellno)" /> 28. </card> <!-. <CFSET Session. From here.34 Chapter 3: WAP Using Cold Fusion: A Project Code description This preceding code shows the menu as a selection list named as a URL on-screen. Code output Figure 3-2 shows the output of index. In this program. Figure 3-2: Output screens of index. Listing 3-2: action.cfm. <CFCONTENT TYPE="text/vnd. we employed the sql query to search for the already existing data and also to add records in the database. password. SELECT 4.cfm The file in Listing 3-2 is used to insert the records in the database.wap. userid.declaration of query --> 3. country. the user is again taken to the file login to work on the application. <cfquery name="abcd" datasource="prototype" dbtype="ODBC"> <!-. city. In that card. All Rights Reserved 1. navigation is transferred to the second card in the same deck named as entry. If the Register option is selected. FROM userid AS abc userlogininfo .cfm © 2001 Dreamtech Software India Inc. After selecting the Login option.wml"> <!-. and mail id are accepted and stored in the table. cellno.cfm. user name. control is carried over to another file named login.declaration of page type to send to the browser --> 2. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-.com/dtd/wml11.0"?> 8.end of paragraph 26.cfm" addtoken="No"> <!-.wml prolog --> 9. password"> <!-. <cflocation url="login.cfm" /> 19. <CFIF abcd.end of if condition 25. username. <!DOCTYPE wml PUBLIC "-//PHONE. </CFIF> <!-.dtd" > <!-.1//EN" "http://www. User ID Already Found Please Choose Again 17.cfm file --> 24.adding record to the userlogininfo for new user login -> 23. <do type="accept" label="Back"> <!-.end of query --> 7.declaration of action event --> 18.end of card 27.checking the condition --> --> 16. <cfinsert datasource="prototype" tablename="userpersonalinfo" dbtype="ODBC" formfields="userid. <CFELSEIF abcd.redirecting to login.adding record to the userpersonalinfo for new user --> 22. </cfquery> <!-. <?xml version="1.beginning of a new deck --> 10. cellno. <head> 11. <card id="checking"> <!-.Chapter 3: WAP Using Cold Fusion: A Project 35 5. </wml> <!-. <cfinsert datasource="prototype" tablename="userlogininfo" dbtype="ODBC" formfields="userid. city. </p> <!-.recordcount NEQ 0 > <!-. emailid"> <!-. <go href="index. WHERE (userid = '#userid#') <!—query --> 6.meta tag declaration --> 12.beginning of a new card to check for the presence of user <!-id --> 14.COM//DTD WML 1. </head> 13.end of wml --> --> --> --> .checking else part of condition --> 20. country.phone. </do> <!-.recordcount IS 0> 21. <wml> <!-. </card> <!-. <p> 15. com/dtd/wml11.phone. <head> 6. <wml> <!-.new deck --> 5. userid. because the user Deepesh was not registered. </head> . if condition is applied to check the number of records passed through the query specified in Line 2. it indicates that the inputted user ID is already present in the table.cfm (Listing 3-4) with the values of variables. ♦ Line 7 defines the WML prolog.36 Chapter 3: WAP Using Cold Fusion: A Project Code description ♦ Line 1 is used for indicating the content type being sent to the browser. Figure 3-3: Output screen of action.cfm © 2001 Dreamtech Software India Inc.cfm.meta tag declaration --> 7.cfm The Login. ♦ Lines 2 – 6 are employed when you need to define and execute a query to search for the record in the database containing the DSN name as prototype for the given userid. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-. <CFCONTENT TYPE="text/vnd.3). <?xml version="1.COM//DTD WML 1.cfm file (Listing 3-3) enables the user to log in after the user is registered. ♦ Line 11 defines the meta tag used by the browser.1//EN" "http://www. If the value is greater than 0.declaration of page type to send to the browser --> 2. All Rights Reserved 1. and password. ♦ Line 15 – In the first card. and consequently the message is displayed to go back to the main menu (as shown in the Figure 3.dtd" > <!-.wap. control is passed to checkvalue.WML Prolog --> 4. Listing 3-3: login. the record is added to the table.0"?> 3.wml"> <!-. If the query returns zero. it means that this particular record does not exist in the database and is now ready to be added to the database. In our example. Code output Figure 3-3 shows the output of action. From here. <!DOCTYPE wml PUBLIC "-//PHONE. </wml> <!--end of deck --> Code output Figure 3-4 shows the output of Login. <postfield name="password" value="$(password)" /> <!-. </card> <!-.declaration of new card --> 9.Chapter 3: WAP Using Cold Fusion: A Project 37 8. <go href="checkvalue.declaration of new paragraph for login --> 16. <do type="accept" label="ok"> <!-. <p> 25.cfm" method="post" > <!-.declaration of action --> 10. Figure3-4: Output Screen of Login. 22. <b>Login Page: </b> 17. 23.end of paragraph --> 24.declaration of new paragraph for password entry --> 26.cfm.declaration of new paragraph for userid 19. 21.cfm --> --> . <postfield name="userid" value="$(userid)" /> 12.declaration of the navigation on event --> 11. </go> 14. </do> 15. </p> 18. <p> <!-.declaration of the fileds to be transferred to the new file 13.end of paragraph 27. <card id="entervalue" newcontext="true" title="Login"> <!-. </p> <!-. Enter password <input name="password" type="password"/> <!-.end of card --> 28. 20. --> User Name <input name="userid"/> </p> <p align="center"> <b>Login Page: </b> </p> <!-. <p align="center"> <!-. <card id="card1" > <!-.userpassword="#match. The query is defined to search for the record in the database containing the DSN name as prototype for the password entered along with the user ID. <cflocation url="login.1//EN" "http://www. <CFSET Session.declaration of a the session variable --> 14.declaration of a query to read password --> 13. If it’s 0.wml"> <!-. <cfquery name="abcd" datasource="prototype" dbtype="ODBC"> 3. <head> 18. <wml> <!-.abc#"> 8.declaration of page type to send to the browser --> 2.declaration of a new card ‡ 21.declaration of a new paragraph --> 22. The <CFIF> condition is used to check the number of records passing through the query specified in Line 2. <!DOCTYPE wml PUBLIC "-//PHONE.cfm © 2001 Dreamtech Software India Inc. then the inputted user ID is not present in the table.phone.declaration of the deck --> 17. </cfquery> <!-. <CFELSEIF match. SELECT userid AS abc 4. SELECT password AS passtemp 10.declaration of if condition --> 23. <cfquery name="match" datasource="prototype" dbtype="ODBC"> 9. Your Record Is not Found Please enter again 24.38 Chapter 3: WAP Using Cold Fusion: A Project The file in Listing 3-4 validates the user ID and the password in the database file.userid="#abcd.declaration of meta tag --> 19. </head> 20.dtd" > <!-. <?xml version="1.wap.com/dtd/wml11. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-. <CFIF abcd.recordcount IS 0> .COM//DTD WML 1.// declaration of a query to read userid --> 7.cfm" addtoken="No"> <!-. WHERE (userid = '#userid#' AND password = '#password#') 12. All Rights Reserved 1. FROM userlogininfo 5.declaration of WML Prolog --> 16. FROM userlogininfo 11. <CFCONTENT TYPE="text/vnd.recordcount IS 0> <!-.declaration ‘to’ navigation to new file --> 25. </cfquery> <!-.0"?> 15. <CFSET Session. and the message appears to enter the user ID again. Listing 3-4: checkvalue. WHERE (userid = '#userid#') 6. <p> <!-.passtemp#"> <!-. <cflocation url="readallvalue.Chapter 3: WAP Using Cold Fusion: A Project 39 <!-. Listing 3-5: readallvalue. <cflocation url="login.end of if condition --> 29.end of card --> 32.checking else part of if condition--> 26. The code then generates a random number between one and the maximum number of questions. Figure 3-5: Output Screen of checkvalue.wml"> .cfm © 2001 Dreamtech Software India Inc.cfm.cfm for displaying the questions on the mobile screen.cfm" addtoken="No"> <!-.end of paragraph --> 31.declaration ‘to’ navigation to new file --> 30. </wml> <!-.cfm The readallvalue. The control is then taken to the new file questiondisplay.cfm" addtoken="No"> <!-. </CFIF> <!-.declaration ‘to’ navigation to new file --> 28.cfm file (Listing 3-5) is used to read the total number of questions from the table. All Rights Reserved 1.wap. Your passwod Is not Found Please enter again 27.end of deck --> Code output Figure 3-5 shows the output of checkvalue. This number is used to display the question on the screen for the quiz. </card> <!-. <CFCONTENT TYPE="text/vnd. </p> <!-. COM//DTD WML 1. 13.0"?> <!DOCTYPE wml PUBLIC "-//PHONE.render# query to find out the question from the questiontable - -> <!-. 18.phone. 7. Listing 3-6: questiondisplay. 11. three options. --> 6.table for display on the screen. 3.render# </cfquery> <!-.dtd" > <wml> <head> <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> </head> <card newcontext="true"> <cflocation url="questiondisplay. 7. 20.40 Chapter 3: WAP Using Cold Fusion: A Project 2. "#quest.cfm. 14. 4. All Rights Reserved 1.com/dtd/wml11. 16. The questiondisplay. <cfquery name="display" datasource="prototype" dbtype="ODBC"> <!-. The whole code listing is doing the background processing.1//EN" "http://www. The particular number of questions to be displayed is generated in the program readallvalues.table for display on the screen. 5.sent to the browser. 3. <cfquery name="choiceid1" datasource="prototype" dbtype="ODBC"> SELECT choice1 AS tempchoice1 FROM answertable WHERE qid = #session. and one correct answer code from the table. 6. 9.query to find out the answer 1 from the questiontable -> <!-. 17. 10. <cfquery name="quest" datasource="prototype" dbtype="ODBC"> SELECT qno AS tempqno FROM coursetable </cfquery> <CFSET tempnumber="1"> <CFSET rendernumber="#RandRange("#tempnumber#". 4.render="#rendernumber#" > <?xml version="1.cfm" addtoken="No"> <p> </p> </card> </wml> Code output No output is generated from this screen. 9. 12.cfm file (Listing 3-6) displays the question read from the table on-screen. Five queries have been defined to read question. --> 2. 8.tempqno#")#"> <CFSET Session. 15. 10. 19. 8. 5. --> - . SELECT FROM WHERE </cfquery> <!-- question AS tempquest questiontable qid = #session.declared for indicating the type of page being --> <!-. The correct answer choice is used to check the answer entered by the user and is stored in the session variable for the future use.cfm © 2001 Dreamtech Software India Inc. </p> 42.COM//DTD WML 1. 13. <wml> <!-.render# </cfquery> <!-.correct#"> <!-. 20.setting up session variable to rightanswer <!-. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-. <CFSET Session. </head> 34.dtd" > <!-.WML deck declaration --> 31.query to find out the answer 3 from the questiontable - -> <!-. 19.table for display on the screen.table for display on the screen. 12.Meta tag declaration --> 33.1//EN" "http://www.com/dtd/wml11. <cfquery name="rightanswer" datasource="prototype" dbtype="ODBC"> SELECT answerid AS correct FROM answertable WHERE qid = #session.wml"> 28. Your Quotation <!-.0"?> 29.render# </cfquery> <!-. 14. <p align="center"> 39. 18.new card declaration to display question & answers --> 35.Chapter 3: WAP Using Cold Fusion: A Project 41 11. 23.new paragraph declaration to display heading --> 40. <go href="submit. <do type="accept" label="Submit"> 36. <p> . --> 21.to check for user input --> --> 27.cfm" method="post" > </go> <!-. 41.query to read the correct answer code from questiontable --> <!-. 15. 17.WML Prolog --> 30. 25. <head> 32. 22. <?xml version="1. <cfquery name="choiceid2" datasource="prototype" dbtype="ODBC"> SELECT choice2 AS tempchoice2 FROM answertable WHERE qid = #session. <!DOCTYPE wml PUBLIC "-//PHONE. 24.query to find out the answer 2 from the questiontable - -> <!-.rightanswer="#rightanswer. </do> 38.action declared to navigate to new file --> 37.render# </cfquery> <!-. <cfquery name="choiceid3" datasource="prototype" dbtype="ODBC"> SELECT choice3 AS tempchoice3 FROM answertable WHERE qid = #session.wap.table for checking with user choice --> 26. --> 16. <card id="questiodisplay" newcontext="true" > <!-.phone. <CFCONTENT TYPE="text/vnd. cfm.</b> </CFOUTPUT> #choiceid3..cfm The submit. </wml> <!-.new paragraph declaration to display question 43. 51. and the navigation is set to answer. 50. 47.tempchoice2# </p> <p> <!-. Figure 3-6: Output Screen of questiondisplay.cfm with the value of the field answer taken as the parameter. </CFOUTPUT> #choiceid2. 59..cfm © 2001 Dreamtech Software India Inc. 49.new paragraph declaration to display third choice --> 58.tempquest# </CFOUTPUT> </p> <p> <!-. The answer choice entered by the user is taken in the variable yanswer. 53. 62. 56. 52. 63. Listing 3-7: Submit.</b> </CFOUTPUT> --> #choiceid1.42 Chapter 3: WAP Using Cold Fusion: A Project <!-. 54.tempchoice3# </p> <!-. --> <CFOUTPUT> #display.new paragraph declaration to display first choice <CFOUTPUT> <b>(a). 44. </card> <CFOUTPUT> <b>(c).tempchoice1# </p> <p> <!-.new paragraph declaration to display second choice --> <CFOUTPUT> <b>(b)</b>.. 60. All Rights Reserved . 46. 55.end of card --> 64. 48.end of deck --> Code output Figure 3-6 shows the output of questiondisplay. 61.cfm file (Listing 3-7) is used to accept the correct answer option from the user. 57. 45. </p> <!-.0"?> 3. <!DOCTYPE wml PUBLIC "-//PHONE. <?xml version="1. <postfield name="yanswer" value="$(yanswer)" /> <!-. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-.1//EN" "http://www.input taken from user in variable ‘yanswer’ --> 16.cfm" method="post" > <!-.WML Prolog --> 4.end of action --> 14.cfm .declaration of variable to be navigated to new file </go> --> </do> <!-.wap. <wml> 5.phone.end of paragraph --> 17. <card newcontext="true"> <!-. 13.com/dtd/wml11.wml"> <!-. <do type="accept" label="ok"> <!-.cfm.content type declaration for browser --> 2. <CFCONTENT TYPE="text/vnd. Your Answer<input name="yanswer"/> <!-.declaration of action event --> 10.declaration of card to take input from user --> 9. Figure 3-7: Output screen of submit. 12. <go href="answer.end of deck --> Code output Figure 3-7 shows the output of submit.end of card --> 18. </card> <!-. <head> 6. <p> 15.declaration of navigation to new file --> 11. </head> 8.dtd" > <!-. </wml> <!-.Chapter 3: WAP Using Cold Fusion: A Project 43 1.meta tag declaration --> 7.COM//DTD WML 1. control is taken to the another file named tryagain. </wml> <!-. . the navigation is sent to two different files. <cflocation url="bingo. All Rights Reserved 1.com/dtd/wml11. control is taken to a new file named bingo.cfm © 2001 Dreamtech Software India Inc.navigation declaration to new location --> 14. Otherwise.1//EN" "http://www. <p> <!-- declaration of a new parafgraph to check userinput --> 10. <CFELSEIF #session.end of deck --> Code output Because this program is checking the answer.declaration of a new card --> 9.navigation declaration to new location --> 12. If the user’s input matches the right answer from the table. <!DOCTYPE wml PUBLIC "-//PHONE.wml"> <!-. Depending upon the value of the condition.end of card --> 17. <head> 6. <card id="card1" > <!-.rightanswer# NEQ #yanswer#> <cflocation url="tryagain.cfm" addtoken="No"> <!-.dtd" > <!-.wap.rightanswer# EQ #yanswer# > <!-.cfm. <wml> <!-. there is no output.Meta tag declaration --> 7.0"?> 3. </p> <!-- end of If condition --> end of paragraph --> 16. A new paragraph is declared to check for the right answer. </head> 8. </CFIF> <!-15.cfm. <CFCONTENT TYPE="text/vnd.cfm" addtoken="No"> <!-.WML Prolog --> 4.new deck declaration --> 5. 13. <?xml version="1.cfm file (Listing 3-8) verifies the answer that the user inputs for the displayed question. Listing 3-8: answer.Checking IF condition for correct answer --> 11.COM//DTD WML 1. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-. </card> <!-.content type declaration for browser --> 2.44 Chapter 3: WAP Using Cold Fusion: A Project The answer.phone. <CFIF #session. declaration of new card --> 9. </card> <!-.COM//DTD WML 1.declaration of new deck --> 5. <p align="center"> <!-. </p> <!-- <b> You choose right answer</b> end of paragraph --> 18. </do> 12. <b>Congratulations</b> 14.cfm" /> <!-.cfm.cfm after the display of the congratulation message.wml"> <!-. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-.phone.meta tag declaration --> 7.declaration of the event --> 10. Listing 3-9: bingo. <go href="index.cfm © 2001 Dreamtech Software India Inc. .0"?> 3. </p> 15.content type declaration for browser --> 2. <?xml version="1. The navigation is sent back to index.cfm file (Listing 3-9) displays the success message on the correct answer. </wml> <!-.wap.end of card --> 19.declaration of navigation link --> 11. 17. <p align="center"> <!-.Chapter 3: WAP Using Cold Fusion: A Project 45 The bingo.1//EN" "http://www. </head> 8.declaration of new paragraph to display congratulation message --> 13. <CFCONTENT TYPE="text/vnd. <do type="accept" label="Home" > <!-.end of deck --> Code output Figure 3-8 shows the output of bingo.com/dtd/wml11. <card> <!-. <head> 6. <!DOCTYPE wml PUBLIC "-//PHONE. All Rights Reserved 1. <wml> <!-.declaration of paragraph to display right answer choice --> 16.dtd" > // WML Prolog 4. <wml> <!-. <?xml version="1. All Rights Reserved 1. The control is sent to questiondisplay.wml"> <!-.0"?> 3. <card> <!-. <p align="center"> <!-.1//EN" "http://www.cfm © 2001 Dreamtech Software India Inc. <head> 6.declaration of new paragraph to display try again message -> . <CFCONTENT TYPE="text/vnd.phone.dtd" > <!-.COM//DTD WML 1. Wrong answer</b> 16.declaration of new paragraph to display wrong answer message --> 15. Listing 3-10: tryagain. 11.WML Prolog --> 4.cfm" /> <!-.declaration of new card --> 9.declaration of new deck --> 5.meta tag declaration --> 7.navigation declaration to new location --> 12. </p> 17.com/dtd/wml11.cfm file (Listing 3-10) displays the “sorry” message when the user inputs an incorrect answer.46 Chapter 3: WAP Using Cold Fusion: A Project Figure 3-8: Output screen of bingo. <!DOCTYPE wml PUBLIC "-//PHONE. </head> 8.. <b>Oops.cfm The tryagain.declaration of new event --> <go href="questiondisplay.wap.content type declaration for browser --> 2. <meta http-equiv="Cache-Control" content="max-age=1" forua="true"/> <!-. 14. </do> 13. <p align="center"> <!-. 10. <do type="accept" label="Back to question" > <!-.cfm after the wrong answer message appears. end of card --> 21. Figure 3-9: Output screen of tryagain.end of paragraph --> 20.cfm Complete Output Figure 3-10 shows the completed output of the application. </card> <!-.end of deck --> Code output Figure 3-9 shows the output of tryagain.Chapter 3: WAP Using Cold Fusion: A Project 47 18.cfm. . </p> <!-. <b>Try again</b> 19. </wml> <!-. This application greatly helps the user understand the functioning.48 Chapter 3: WAP Using Cold Fusion: A Project Figure 3-10: Application output Summary The Question Quiz application demonstrates how you can implement Cold Fusion on a cell phone. and usage of Cold Fusion in developing Web applications. . syntax. is used to integrate voice and data so that both modes of communication can occur simultaneously on a single device. The topmost layer of this architecture is constituted by the WAE (Wireless Application Environment) and the WTA (Wireless Telephony Application). which is implemented by push technology. even if it’s being used for browsing. The list of hotels in a locality. and updating the phonebook entries. This layer is a telephony interface. WTA. .” which you learn more about in later chapters. The main telephony-related functions available on a common wireless device are: ♦ Adding. Applications of WTA The WTA applications provided by phone networks to work on mobile devices could interact with the telephony-related functions available on those same devices. searching. ♦ Sending and receiving the short text messages. ♦ Writing and receiving the text messages on the wireless device. This chapter focuses on the WTA technology architecture and interface. ♦ Administering calls made and calls logged (missed and received calls). The card contains the hotel names and the telephone numbers. ♦ Sending DTMF tones while an active voice call is being made. We briefly discuss the eventmanagement facet and provide details of real-time implementation of WTA. without receiving any request from the client. ♦ Making and receiving the call. WTA bridges voice services and data services by providing a framework to access voice services using WML and WML Script. WTA is instrumental in equipping the conventional WAP architecture with additional telephony functions. which facilitates interaction between the markup language and the wireless client. therefore. can be pushed to the mobile device as a WML card. This concept provides the groundwork for what is called “push technology. It is primarily used to send the data to the mobile client. WTA.Chapter 4 WTA: An Advanced Interaction Technique for Mobile Phones In the preceding chapter. The functions provided by phone network are: ♦ Voicemail. we discussed the layered architecture of WAP. for example. ♦ Working on a keypad when a call is being received. Here we’re explaining how WTA functionality can be used for these applications. enables a wireless device to handle real-time events. a voice call is made to the given telephone number — making the voice call is the WTA function call. When a particular hotel is selected. The infrastructure required is the WTA server as indicated in Figure 4-1. the service provider must have the necessary infrastructure to support WTA applications. The main beneficiaries of this technology are online packet networks such as GPRS. WTA extends the WAP application environment by providing these services. hold. ♦ Intelligent Network Services. ♦ Conferencing. but also other external devices. The telephony services in WTA communication are managed by the WAP gateway. and forward. Figure 4-1 depicts the logical architecture of WTA. Figure 4-1: WTA architecture The major components of the WTA architecture are: ♦ WTA user agent ♦ WTA server ♦ WTA interface libraries . such as upon the arrival of a message in the user’s voice mailbox when the user is using the mobile device for some other application (such as browsing). which delivers the WTA applications. ♦ Automatically recalling a number until the call goes through. ♦ Getting the status of the reservation done on the wireless device. ♦ Score/regular political updates. Not only does the wireless device handle events. ♦ Getting regular weather forecasts at the specified intervals. ♦ Sending an alert to the user. Although network carriers primarily control the functionality of the WTA. Introduction to WTA Architecture In push technology. Applications of the WTA in a common scenario are: ♦ Making a table reservation in a restaurant from a list of restaurants in the wireless device.50 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ♦ Call transfer.visual interfaces to voice-mail systems. In fact. the WTA enables trusted application servers to initiate transmission of information to WAP devices. ♦ Automatically calling a number found in a yellow pages search. ordinary users can also program the WTA by using the WTA libraries and functions. For supporting the real-time needs of telephony applications. ♦ A secure WTP port is used on the WAP gateway for the WSP sessions by the WTA user agent. a secure link is established between the WAP gateway and the WTA server. and making illegal or unauthorized calls through a WML and WML Script code. ♦ User-permission criteria are specified and configured over the mobile device for the execution of different WTAI library functions. The user agent is similar to that in the WTA environment. Therefore.Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 51 ♦ Storage (also called Repository) We discuss each of these in the following sections. It’s also responsible for the security of the network — the services are always under the direct or indirect control of the network operators who have the administrative rights to these services. rendering WML. WTA Security Considerations Security is an important consideration for a telephony architecture like WTA. Otherwise. it executes and presents the WML and the WML Script content to a server. The WTA user agent has strong real-time context management components. the following features are incorporated in the WTA architecture: ♦ With the help of a private network. The WTA user agent architecture is shown in Figure 4-2. They are the following: . ♦ Strong authentication mechanisms have been defined for establishing a secure link between the WAP gateway and the WTA server. and executing WML Scripts. You can configure three types of user permissions on a mobile device. you run the risk of a third party changing the content. a content provider cannot provide the complete set of WTA services. You have to ensure the security of the original content of the WTA server. To avert this situation. these are called trusted services. The main functions required of the user agent are supporting WTAI libraries. The operators can transfer these rights to the third-party WTA providers that have to work according to the specifications of the network operators. Figure 4-2: WTA user agent WTA Server The WTA server is basically a Web server that contains the WTA content and services. WTA User Agent The WAE in the WAP is composed of decks and cards. Only authorized persons should be able to write or amend the content of the WTA and execute it on a client device. such as address-book data. It doesn’t have the stack through which decks are stored in the history and retrieved by using the Back button. 52 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ♦ Blanket permission: Granted to the executable for the specified WTAI library function. The functions of these libraries are discussed later in the chapter. it’s a single permission. The syntax of the URI schemes is: wtai://<library>/<function>.<parameter>![<result>]. The WTA security model is shown in Figure 4-3.0.zero or more return values delimited by . An example is: WTAvoiceCall. Voice call is vc <function> . These sessions are authenticated and encrypted by using WTLS.identifier of the specific function in the library <parameter> . An example is: wtai://vc/rc. followed by the function name. These libraries can be called in two ways: ♦ URI Schemes: It begins with wtai://. A special security model is employed for maintaining the security of the WTA architecture. ♦ Network specific WTAI–depends on network.[<result>] <library> . different for different networks. ♦ Public WTAI–for the user to adjust the properties of the device by using WAP architecture. the WTA user agent sends the request for the WTA application from a mobile device to the WAP gateway through the WTP code by establishing a special WSP session. The WTP ports (port 2805 for connectionless session and port 2923 for connection-oriented sessions) are used by WAP gateways to send the information to trusted WTA servers. Figure 4-3: WTA security model WTA Interface Libraries The WTA libraries help in defining the WTA interface. ♦ Single action permission: Granted to the executable for the specified WTAI library function. The syntax is: Library type.retval ♦ WML Script: In this method.the parameter of the function <result> . independent of network.name of the library. There are three types of libraries: ♦ Network common WTAI–handles the incoming calls. . In this model. the type of function is specified first. If an application or content is not received through the trusted port. it is not admitted for the process network event.release("0"). ♦ Context permission: Granted to the executable for the specified WTAI library function during a specific run-time context.function name ([parameters]). The other WSP ports are not trusted. and information passed through those ports is confined to certain specified WTAI function libraries on the mobile client only after user authorization. At the time of unloading the channel. Thus. voice. receiving. Stored contents fall under the following two categories: ♦ Resources: This data resource includes decks. With this model. Multiple channels are used to share resources to conserve memory of the mobile client. dialed. ♦ Logical indicator model: To access the logical indicators of the devices. ♦ Channels: This refers to special resources that contain a set of links to other resources and special control information. and received calls. which include information about missed. and getting the information regarding network messages. Figure 4-4: WTA repository ♦ Call log model: Used to maintain the logs of the calls. It is downloaded to the mobile devices using WSP and is stored with meta-data. WML Script. the time taken to pull the content over the WTA network before executing it is saved. only those resources that are not shared by any other channel are removed from the repository. To load the resources and channels into the repository. or e-mail messages . ♦ The application is installed into the repository at the time of manufacturing or during the subscription process. The channel is unloaded if it becomes stale or if space is required for any other application. implementation of one or many simultaneous voice calls is possible. The WTA repository model is shown in Figure 4-4. making for instant responses as with wireless communication. This is programmed using Channel Content Format. A framework of storage is provided on repository. ♦ The WTA user agent can install the application by pulling it from the WTA server. receiving. This prevents having to access the network for loading and executing these services. the following methods are used: ♦ A channel is pushed directly into the repository from the WTA server. The various models of WTA and their areas of application are as follows: ♦ Voice call model: This model helps in placing. and wireless bitmap images.Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 53 Storage or Repository The common WTA services are stored within the mobile device as a separate storage module. ♦ Network message model: This model helps in sending. which are: • Fax. ♦ Phone-book model: Used to access and modify the phone-book available on the mobile devices. and terminating voice calls. or data calls • Call waiting • Voice call messages WTA services can be initiated by selecting the URL. such as details of the transaction ID and the party called. The processing occurs as follows: When the user makes a call. thereby triggering the Call Cleared (wtac-cc/cl) event. Using the Interface Components The WTA application-programming interface has two components: ♦ The event model: Allows the application to take action depending on the events. by using push technology over a secure WTA session or by using an event handler. There are two models. and the call transitions to the Digits Dialed state. When the call is answered. This model is outlined in Figure 4-5. whose content is hosted on the WTA server. This state is maintained until either the user or the calling party disconnects. depending on the calls received or calls made by the user. The Call Connecting (wtac-cc/cl) event is received by the WTA user agent. The Event Model This model generates a sequence of events. which employs the appropriate event handlers to handle these events. the WTA application receives the outgoing call (wtae-cc/cl) event. The Call Connected (wtaev-cc/co) event is received by the WTA user agent when the user receives the call and the call moves from the Ringing state to the Answer state. the Call Connected (wtaev-cc/co) event is received by the WTAI user agent. The mobile client detects ringing from the network in this state only. The phone returns to the Idle state when the call has been answered. Figure 4-5: Originating Call model ♦ Terminating Call model: This model handles the events generated when the device receives a call. The processing occurs as follows: An Incoming Call (wtaev-cc/ic) event causes the call to move from the Idle state to the Ringing state. The information regarding an event.54 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones • Incoming voice. and the call proceeds to the Ringing state. ♦ A scripting interface: Allows the application to initiate and control telephony operations. and the call enters the Answer state. Because the values of the variables change while navigating through the cards. are stored in the variables in WML. These events are accepted by the WTA user agents and transferred to the WTA application. these are stored in card-specific variables. Then the . fax. which are used to trap telephony events from the voice network: ♦ Originating Call model: This model handles the events generated when a call is made from the device. This state is maintained until the user or the called party disconnects. Figure 4-6: Terminating Call model So far. nt/it Wteav-nt/it Network text/Incoming text event that indicates the receipt of network text message. Table 4-1: WTAI Events Event name Event id Description cc/ic Wtaev-cc/ic Call control/incoming call indicator event that is picked up by the calling WTAI function. It’s then ready for new incoming or outgoing calls. Table 4-1 contains the complete list of WTAI events and their meanings. cc/cc Wtaev-cc/cc Call control/Outgoing call alert event that indicates bell ringing at the destination. The phone gets back to the Idle state after the call is cleared. cc/co Wtaev-cc/co Call control/Call connected event indicates that the call is connected. cc/oc Wtaev-cc/oc Call control/Outgoing call event that indicates that outgoing call is being placed. . cc/cl Wtaev-cc/cl Call control/Call cleared event indicates that the connected call is disconnected. This model is outlined in Figure 4-6. nt/st Wteav-nt/st Network text /Network text sent event that indicates sending of the network text message. accept call. we have discussed some predefined WTAI network events.Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 55 WTA user agent receives the Call Cleared (wtaev-cc/cl) event. cc/dtmf Wteav-cc/dtmf Call control/dtmf sequence sent event. WTAVoiceCall. These steps may initiate an interaction between the network and the mobile device.org/DTD/channel.wml" > <resource href="first. independent of the network. The function type dictates the library specification. WTAVoiceCall.wml" failure="wtaFailure. Any result delivered by this function call will not reflect the outcome of this procedure.wmls"/> </channel> WTAI Scripting Interface and Function Libraries The WTAI scripting interface is made possible through the various WTAI function libraries.accept Accepts an incoming voice call.56 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ms/ns Wteav-ms/ns Miscellaneous/network status indicator event generated on the change in certain network parameter. as explained in Table 4-1. These libraries can be accessed by using the WML Script. WTAVoiceCall.operator. Event Binding The events. This is a nonblocking function. . WTAVoiceCall. or through URIs.sendDTMF Sends a DTMF sequence through a voice call. Network common WTAI The Network common WTAI is used to control the handling of incoming calls. The related functions are shown in Table 4-2.wapforum. waiting to be attended.dtd"> <channel maxspace="2048" base ="http://wta. The function then terminates independently from the started network procedure.wml"/> <resource href="first.release Releases a voice call. There are three main function libraries.callStatus Retrieves information about a voice call. Table 4-2: Network Common WTAI Functions Function Explanation WTAVoiceCall.setup Initiates a mobile-generated call.com" eventid="wtae-cc/ic" channelid="Incoming Call Distributor" success="wtaSuccess. which itself may result in events.0"?> <!DOCTYPE channel PUBLIC " -//WAPFORUM//DTD CHANNEL 1. WTAVoiceCall. The channel and resources use the events as follows: <?xml version="1.send Sends a network message. through the scripting function libraries.2//EN" "http://www. are generally used in the WML Script file.list Returns the call handle that can be controlled within the WTA context that involved the function. WTANetText. remove Permanently removes incoming or outgoing network message from the device. WTANetText. For example: ♦ location() — One important GSM specific function used for providing location information (mobile country code. Network specific WTAI Network-specific WTAI functions and events are applicable to only one specific network and will differ from network to network. WTAPhoneBook. WTAMisc.search Returns the index of phone book entry that matches the search condition.write Writes a phone-book entry. WTAPhoneBook.getFieldValue Retrieves a field value from the specified log entry.setIndicator Modifies the status of the logical indicator.change Stores the given value in the specified field in the phone-book entry. This information can be further used to provide area specific information to the subscriber. IS136.missed Returns the call log handler of an entry from the missed call log. WTAMisc.getFieldValue Retrieves a field value for a specific phone entry. To date it has only been developed for GSM.setProtection Sets the protection mode of the WTA context. ♦ reject() — Used for rejecting the incoming call. WTAMisc. overwriting the existing one. .Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 57 WTANetText.markAsRead Marks a message as read.getProtection Returns the protection mode of the WTA context.endContext Terminates the current WTA user agent context.remove Removes an entry from the phone-book making the entry vacant. area code. network code. WTAPhoneBook. WTACallLog. ♦ sendUSSD()— The additional function of GSM library to handle USSD (Unstructured Supplementary Service Data). WTANetText. WTACallLog.received Returns the call log handler of an entry from the received call log.dialed Returns the call log handler of an entry from the dialed call log. WTAMisc. ♦ hold() — For call held. WTACallLog. ♦ transfer() — For call transfer.list Returns the message handle of the existing message. WTAPhoneBook. WTAPhoneBook. and the cell identifier). WTACallLog.getListValue Retrieves a field value from a specific value. and PDC (JAPAN) based networks. WTANetText. The network-specific libraries also define additional events in order to support extra capability by the new network. Public WTAI Public WTAI is used to adjust the properties of the device by using the WAP architecture. To make a phone call programmatically.sendDTMF("123*4567") The preceding code would send the touch-tone sequence associated with that string.sendDTMF Send a DMTF sequence through the voice call most recently created using the WTAPublic. For example: WTAPublic. This is the most basic function used for making a call. The return code from this function can be used for application development.makeCall function. ♦ Send DTMF tones. ♦ Add a phone book-entry. use the following code: Var a= WTAPublic. WTAPublic.sendDTMF (dual-tone multifrequency) is better known as touch-tone dialing. A public library has the following three functions: ♦ Make a call. This function gives the added benefit of adding a # and * in the dialing string. The error return values are: ♦ empty string — all occurred as planned ♦ 108 — no active voice connection ♦ 1 — an unspecified error . Table 4-3: Public WTAI Functions Function Explanation WTAPublic.makeCall("1234567") This makes a phone call from the phone to the number specified as the argument. (multiparty().58 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ♦ The WTAGSM library provides the functions for multiparty operations. and so on) through which a subscriber can be added to an ongoing call or be disconnected from the multiparty call. WTAPublic. Functions used in the script file The following sections describe some functions commonly used in the WML Script file. just as if the user had entered it on the keypad manually. retrieve(). The functions are outlined in Table 4-3. The return codes are as follows: ♦ Empty string — successful code ♦ 105 — busy party ♦ 106 — network not available ♦ 107 — no answer from called party ♦ 1 — an unspecified error The WTAPublic. rather than manually.addPBLibrary Used to write a new phone-book entry.makeCall To initiate a mobile-generated voice call. while ( (ide = WTAVoiceCall. one can use the phone-book facility of mobile phones. The user-defined function. you can perform various actions on WTA events. } return ide.addPBEntry. By virtue of this function. This command has two parameters. in which the WTA library function is used. 0)) <0) { if (ide > -4 && ide < -7 ) break. The phone subsequently dials the bank and transfers the information directly. "WTAI") The functions we just discussed are generally used in the WML Script file. you can automate to glean an account number from a database (granted. This provides almost instantaneous access to the bank account.addPBEntry("18001234567".Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 59 Using the DTMF function. They are: .wml) as: <do type="accept"> <go href="appl. you want to ensure some level of security here) and store it temporarily in the phone's memory. only the following line of code is added: WTAPublic. which is shown in Listing 4-1. which enables a phone to read the bank's automated system. Through this facility. is called by the WML application file. cell phones can store numbers. which.setup(no.wmls function kc(no) { var ide.. Listing 4-1: appl. There are two types of bindings by which events are bound to event handlers. in turn. The company can add a link in its WAP page that automatically stores its toll-free number in the user's phone to make sure it's always readily available in future. The function that adds entries to the phone-book is WTAPublic. For the action of a key. dial out. and enter the information by pressing a single button (or key on the keypad). which are the number and the associated name. All the network events are processed by the WTA user agent. Event and State Management in WTA Through WTA programming. directs the network event to the appropriate handlers within the applications.wmls#kc($no)"/> </do> . } The function is called from the WML application file (kca. The return codes are: ♦ Empty string — operation completed successfully ♦ 100 — name parameter is too long or unacceptable ♦ 101 — number parameter is not a valid phone number ♦ 102 — number parameter is too long ♦ 103 — the phone-book entry could not be written ♦ 104 — the phone book is full ♦ 1 — an unspecified error Suppose that a business provides customer service over the phone. In this case. The mobile user obtains a list of services (in text form) on the display. WAI function is executing Wait for completion of the function and then the WTA context is interrupted to process the event. When a network event is received. the event is passed to the phone to be handled by a process of callback handling done in the default fashion. Local Navigation in progress Navigation is completed. it’s the function of the user agent to check for the bindings. WTAI Function Call Example In this example. Note that the code can be tested on devices that support only WTAI functionality. ♦ Temporary binding: This type of binding occurs when the event handler is present in the content currently being executed by the WTA user agent. we make use of a WTAI function call to dial the telephone number. WSP method request in progress Abort all request of WSP and event is executed. These are called every time the event occurs. Here. the event is handled in the following way: ♦ Callback handling: The event is not allowed to interrupt the currently executing WTA context. Table 4-4: WTA User Agent Actions State Action Stable Current WTA context is interrupted to process WTA event. . the temporary binding exists. they are bound globally. current context is interrupted. so there isn’t any binding. the WML cards provide only text services. Otherwise. and the WTA is processed. the user agent searches for the event handler in the repository. Listing 4-2 provides the WML code to achieve this functionality. a call is made to the corresponding telephone number. Unless a temporary binding is not defined with the current deck and the context is not protected. The user agent tries to locate local binding by dispatching the event to the locally executing program. we illustrate how you can access some of the emergency services. This is executing when the WTA service is running in the WTA user’s agent. When the desired service is selected through the keypad. If the event handler is not found in the repository. the temporary binding also exists. depending on the state of the WTA user agent.protected(1) Table 4-4 shows the different actions taken by the WTA user agent. If there is no binding. and the event is executed. WML Script is processed WML Script is interrupted. a matching global binding also exists. Note that in absence of WTA. the current context is interrupted. when the WTA context is interrupted. It’s possible to control the WTA event to interrupt the execution of content in a WTA context by using the library function: WTAMisc. If there’s a matching event handler.60 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ♦ Global binding: When the event handler for a particular event is present in the repository. <b>Check Services</b> 12. Choose Service : 20. Car Service.1//EN" "http://www. ♦ Lines 18–25: This code displays the message Choose Service and provides the options of Pharmacy. <option value="5551234">Car Service</option> 23. ♦ Line 3: Beginning of WML deck. <br/> 10. </do> 8. <wml> 4. <card id="ers" title="eServices"> 15. <p> 9. ♦ Lines 15–17: <do> tag with the task of calling the telephone number that is obtained based on the option selected. the control is transferred to the card which has the ID as ‘ers’.Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones 61 Listing 4-2: WML Code for Accessing Emergency Services through WTAI © 2001 Dreamtech Software India Inc. <option value="5553344">Hospital</option> 24. ♦ Line 13: End tag for the first card. <do type="accept" label="GetIt"> 16. </do> 18. Corresponding to each service. ♦ Line 14: Beginning of second card. When the user presses the accept button. a telephone number is allocated in the option tag with attribute value. The card ID is ers and the title is eServices.0"?> 2. </card> 27. </p> 26. ♦ Lines 8–12: Display the text Check Services. . In line 16.$emergencies"/> 17. The selected telephone number is stored in the variable emergencies. <go href="#ers"/> 7. the corresponding value will be stored in the variable emergencies and WTA will dial that telephone number.1. and Hospital. <p> 19. <card id="service" title="EMERGENCY SERVICES "> 5. 1. </wml> Code Description ♦ Lines 1–2: XML version and Document Type Definition. </p> 13. When a particular option is selected by the user. <br/> 11.xml"> 3. <do type="accept" label="EServices"> 6.wapforum. All Rights Reserved. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. </select> 25. </card> 14. we made use of the WTAI function to make a call.org/DTD/wml_1. <go href="wtai://wp/mc. This card has two attributes: ID and title. ♦ Lines 5–7: <do> tag with type as accept and title as eServices. ♦ Line 4: Beginning of the first card with ID as service and Title as emergency services. <?xml version="1. <select name="ServiceNum"> 21. <option value="5556789">Pharmacy</option> 22. its common uses. We discussed the architecture and implementation of the WTA.62 Chapter 4: WTA: An Advanced Interaction Technique for Mobile Phones ♦ Line 26: End tag for second card. We also described building the WTA application environment on the standard WAP application by using the WML and the WML Script. The WTA application’s ability to give the user interaction control over the incoming and outgoing calls. which is the topmost layer of the WAP architecture. has made it both popular and necessary. The WTA also maintains the call log. and calls made. and its ability to turn the complex calling operations into easy tasks. such as manipulation of phone-book entries. and sending and receiving short text messages. Figure 4-7: Service options displayed on the WAP phone emulator Summary This chapter focused on the WTAI as a part of the WAE interface. The event management and the state management of the device were also discussed. provides standard telephony services apart from Web browsing and searching. Code Output The output on the phone emulator is shown in Figure 4-7. which includes the calls received. making use of the push technology. ♦ Line 27: End tag for WML. . This interface. missed calls. a quick review of the popular Java technologies — with special emphasis on JSPs and servlets — is necessary.” Since then. Table 5-1 lists some of the main technology groups and products. are vital aspects of a Web application. v 1. Java Pet Store JDBC API 3. which could be used to create software for consumer electronic devices.3 (SDK) Used by developers for writing applications and applets. as well as placing the data on the client. It was developed as a platform-independent. By 1993. Table 5-1: Java Technology Groups Group Product Description Java 2 Platform. Because this chapter focuses on explaining the application of JSP and servlets for the wireless client. Standard Edition. Micro Edition (J2ME) Used for handling micro devices such as pagers. consumer . we will be working with and explaining the application. Sun Microsystems has developed several editions of Java and related software. ASP.0 Java 2 Platform.Chapter 5 Integrating Java with WAP Storing and accessing the data from the database server. In order to understand the syntax and commands used in the application.0 Java Servlet 2.3 Java Server Pages 1. Enterprise Edition (J2EE) ECperf Version 1.2 Used for building serverside applications as it uses various technologies. PHP. object-oriented language. Standard Edition. v 1. Java offers itself for partial client-side and server-side development. PDAs. programmers were using it frequently in Internet programming. Java 2 Runtime Environment. This chapter is devoted to the features of Java that make it suitable for WAP. Technologies such as Cold Fusion. Standard Edition (J2SE) Java 2 SDK. and Java servlets can be useful in server-side processing. and it became famous as the “Internet version of C++. We have already considered the suitability of Cold Fusion technology for server-side scripting.3 (JRE) Java Plug-in Java Web Start Java HotSpot Server Virtual Machine Java 2 Platform. Introduction to Java Technologies Programmers at Sun Microsystems founded Java in 1991. Extensions to core Java products. Consumer and Embedded Technologies Java 2 Platform. and embedded devices. . Micro Edition Connected Device Configuration (CDC) For small devices. Wireless Toolkit Personal Java Application Environment Personal Java Technology. Source Edition Java Card JavaPhone API Java TV API Consumer and Embedded Products Java Dynamic Management Kit Optional Packages Java Media Framework (JMF) Java Embedded Server Software Java Communications API JavaBeans Activation Framework (JAF) Java Naming and Directory Interface (JNDI) JavaMail InfoBus Java 3D Java Advanced Imaging Java Servlet Java Cryptography (JCE) JavaHelp RMI-IIOP Used for wireless. home gateway. having short resources. digital interactive TV. and automotive.64 Chapter 5: Integrating Java with WAP electronics. Source Edition Embedded Java Application Environment Embedded Java Technology. Connected Limited Device Configuration (CLDC) C Virtual Machine (CVM) K Virtual Machine (KVM) Mobile Information Device Profile (MIDP) Java 2 Platform. Micro Edition. Done through the service() method. The packages required to work with Java are javax. A Java servlet must undergo three stages of development: ♦ Initialization: Done by init(). Run it by typing the following command in the browser: http://localhost/examples/servlet/HelloWorld Figure 5-1 shows the output of the servlet. and doDelete.io.java and then compile the code by entering: c:\>javac HelloWorld. . which are used for handling Get. doPost. import javax. public class HelloWorld extends HttpServlet { public void service (HttpServletRequest req. out.class is created. This method is finished before any other method is called in a program. An example of creating a servlet follows: import java. Put.servlet.java The class file named HelloWorld. import javax. copy the class file in TOMCATHOME/examples/web-inf/classes.servlet.*. Java Servlets Servlets are used to make dynamic pages by getting data from the database server and giving it to the client. These are modules of Java that run on the Java server.Chapter 5: Integrating Java with WAP 65 Java Authentication and Authorization Service Java Secure Socket Extension Early Access Optional Packages Java Management Used for designing system management solutions for heterogeneous systems. Post. HttpServletResponse res) throws ServletException. ServletRequest and ServletResponse objects are used to manipulate the user requests and responses. a servlet can be destroyed from the memory. Other objects in the service method are doGet. ♦ Destruction: By using the destroy() method.*. The HTML or WML codes can be generated from a servlet to display dynamic content on the client screen.getWriter(). A servlet can generate the output in a pure-text format or even generate the client application code. respectively. doPut. } } Save the file as HelloWorld.http. which is called just once in the life span of a servlet. and Delete requests of the user. ♦ Service: Receives the request and sends the response to the user.servlet. In order to run Java servlets.http.servlet and javax.*. IOException { PrintWriter out= response. This is also done just once in the life cycle of a servlet. Next. you need either a Web server that understands Java servlets or a self -standing Java servlets engine.println(“Hello World”). the MIME type has to be set.setContentType("text/vnd. and the Web server.wap.jsp in Tomcat_HOME\examples\jsp. or XML code. servlets. http://localhost:8080/examples/jsp/Hello. thereby generating a dynamic Web page for the client. and the servlets execute to get the response for the user.wml"). The JSP talks to Java classes. To run the WML document. The JSP technology is an extension of the servlets. A JSP is compiled to a servlet by a JSP engine. . The response is inserted in the HTML code. The prerequisite is that the user must be familiar with JSPs. enter the following URL in the browser. Create Dynamic Content with Servlets and JSPs for WAP Browsers You can conveniently use Java servlets and JSPs for developing dynamic WML documents for mobile devices. JSP tags are integrated between the code. %> Now create the following JSP code: <%=”Hello World”%> Save this file as Hello. You can do this with a servlet in the following way: Response.jsp. To execute the above JSP. JSPs and servlets are related in a complementary way to make data communication possible over the Internet. and WML (wireless markup language).jsp Figure 5-2 shows the output of Hello. WML. servlets. A JSP is a simple text file having HTML.66 Chapter 5: Integrating Java with WAP Figure 5-1: Execution of servlet The Java Server Page A Java Server Page (JSP) is the implementation of Java code into HTML or WML so that the page becomes dynamic. applets.println(“hello”). JSP codes are short forms of Java codes. The following is an example: <%=”hello”%> Here’s another example: <% out. 2.println(" <p align=\"center\">").java //© 2001 Dreamtech Software India Inc. 3. } 1.wap. IOException { Setting the mime as wml document 6.Chapter 5: Integrating Java with WAP 67 Figure 5-2: Output of Hello.wml"). } 20. out. out. //Response. PrintWriter out = response.println(" A trial servlet <br/>"). //class declaration of the name TrialServlet 4.1//EN\""). response.println("</p>"). and servlet handling operation.http. 9. 12.xml\">").getwriter gives a stream to write the response to the client 7. public void service (HttpServletRequest req.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.jsp Code Listing 5-1 demonstrates the development of WML from a servlet.io. These packages include packages for the Input/Output operations.println(" Prints the welcome message”).servlet.println("</wml>"). 14.getWriter().println("<card title=\"MobileDemo\">").println("<?xml version=\"1.*. public class TrialServlet extends HttpServlet { 5.println(" \"http://www. 15.wapforum.println("</card>"). // Writing to the stream 8.org/DTD/wml_1. //Response send to the wap browser or client.setContentType("text/vnd. out. // WML Prolog 11.0\"?>"). out. out. 10.*.println("<wml>").1. import javax. 16. out. Code Description ♦ Lines 1–3: Importing various packages used for the servlets to run.*. out. HttpServletResponse res) throws ServletException. //end of paragraph 17. //end of card 18. Listing 5-1: TrialServlet. out. out.servlet. //declaration of new card 13. The content type is the WML 19. import javax. out. . out. //All Rights Reserved //importing various packages used by the servlets import java. org/DTD/wml_1. A greeting will appear if the answer selected is correct. ♦ Line 7: Obtaining an object of the class PrintWriter.println("<wml>").wap.println("</wml>").println("</p>"). The content type is the WML 13. out. which is the response sent to the WAP browser on the client device . On selecting Weather Report. out. out. From this list. out. the user will receive the message “wrong answer. 5. <?xml version="1.println("</card>").println("The demo JSP Page <br/>").println("<card title=\"MobileDemo\">"). This application generates a WAP page with a menu that contains two options: Weather Report and Question of the Day. let’s look at an application that demonstrates the implementation of the same technologies to create WAP-based pages. out.println is the response send to the wap browser or //client.68 Chapter 5: Integrating Java with WAP ♦ Lines 4–5: A class is declared. This is used to send the response to the client program. //above lines starting from out. 7. out. ♦ Lines 8–18: These lines throws WML.println(" <p align=\"center\">").1//EN" "http://www.java . <% //Setting up mime Type as wml document 4. Listing 5-2 also demonstrates the development of WML.wml .JSP © 2001 Dreamtech Software India Inc All Rights Reserved 1. This class is inherited from the base class HttpServlet and a method — doGet — is called. and to store and retrieve the data in the MS Access database.wml"). but using JSP. the user has the chance to answer a multiple-choice question from a given list of answers.” Application Structure Five files are used in this application: ♦ TestWML. The weather details of that city then appear on the screen. otherwise.xml"> 3.java ♦ Report.wap. 9.setContentType("text/vnd. Listing 5-2: TrialJsp.println("Prints the welcome message”).0"?> 2.1. On selecting the Question of the Day option. the user selects a city. 12.java ♦ Call. 8. %> Both Listings 5-1 and 5-2 print the welcome message on the mobile device. ♦ Line 6: Setting the response type of the response to be sent to the client as text/vnd. which is responsible for sending the data back to the calling client program. A JSP and Servlets-Based Application for WAP Now that we have discussed JSP and servlets in brief.wapforum. a list of cities appears. out. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. response. 6. out. 10. 11. in which the user’s choice is passed as a parameter.Java (Listing 5-3) creates a menu on a wireless device. out. 16.*.java ♦ Question&report. // Event handling tags are written on to the stream 19. Description of the Application This section examines the Java files in detail.Java //© 2001 Dreamtech Software India Inc.println("<wml>"). //All Rights Reserved 1. Listing 5-3: TestWML. // meta tag declaration 17.println("</head>"). { 8. out = res.java is called. try //Begin of the block for exception checking 9. // A method by the name doGet is called which is responsible for sending the // response back to the client program 6.1//EN\" " + "\"http://www. Call. out.println("<?xml version=\"1. four are Java codes and one (Question&report.http. TestWML. //WML Prolog declaration in the servlet 14. From this file.servlet. { 10. //Setting MIME type as WAP Document //Obtaining the stream to the program 11.wapforum. import java. public class TestWML extends HttpServlet // declaration of the main servlet class which extends httpservlet class 4.setContentType("text/vnd. PrintWriter out. { 5. The menu has two options: Weather Report and Question of the Day. Application Work Flow Figure 5-3 outlines the function of the Weather application. import javax. out.mdb) is the database in MS Access in which questions are stored. 13.println("<card id=\"MyFirst\" newcontext=\"true\">"). // Writing the various parameters on to the stream 12. res.wap.println("<onevent type=\"onenterforward\">"). //importing java standard packages used by Servelets 3.1.io.mdb Of the five files.println("<head>"). public void doGet(HttpServletRequest req.println("<meta http-equiv=\"Cache-Control\" content=\"max-age=time\" forua=\"true\"/>"). 15. HttpServletResponse res) // declaration of the service method 7.*. out.0\"?>"). out.org/DTD/wml_1.getWriter().println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1.wml").xml\">"). out. 18.Chapter 5: Integrating Java with WAP 69 ♦ Solution. out. out. 2. // declaration of the event . java is made after taking the input from the user in the variable name choice.println("<go href=\"http://localhost:8080/examples/servlet/Call?choice=$choice\"/>"). } } //End of the java servlet code Code Description ♦ Lines 1–2: Importing various packages used for the servlets to run. // end of event 24. // displaying message to input a choice 30.println("</onevent>"). // declaration of the variable to set initial value to 1 22. //command to call. These include packages for the Input/Output operations. Question of the Day</b></p>"). 27. . ♦ Lines 3–6: A class.println("<setvar name=\"choice\" value=\"1\"/>"). out.println("</do>"). catch(Exception ex) // to catch the exception. // end of refresh 23. out. out. is declared and a method doGet is called. // refreshing the memory 21. ♦ Line 10: Setting the response type of the response to be sent to the client as text/WAP.println("<input name=\"choice\" format=\"1N\"/>"). which enables it to run on a mobile device. and servlet handling operation. out. 28. ♦ Lines 26–31: Declaring all the commands in WML.println("<p><b> 2. //Declaring all the commands. // taking user name as input 31. } 36. ♦ Line 19: Event handling tag in WML is written on to the stream. ♦ Line 11: Obtaining an object of the class PrintWriter.class file with the user’s choice as input //is taken in the variable choice 26. ♦ Lines 12–37: Writing the response on the client program in the form of various WML tags. out.println("<p><b> Please enter a choice(1 or 2)</b>"). out. out. This is used to send the response to the client program.println("<refresh>"). Weather Report</b></p>").println("</refresh>"). but nothing is done in the exception 34.70 Chapter 5: Integrating Java with WAP 20. out.println("<do type=\"accept\" label=\"Ok\">"). which will generate a WML code to //display menu on screen 32. out. out. ♦ Line 25: A call to the class Call. // displaying two choices on screen 29. which is inherited from the base class HttpServlet. { 35. } 33. out. // declaration of the action 25.println("</p></card></wml>"). out. which is responsible for sending the data back to the calling client program.println("<p align=\"left\"><b> 1. which result in a WML menu. .Chapter 5: Integrating Java with WAP 71 Figure 5-3: Flow diagram of the Weather application Code Output Figure 5-4 shows the output of TestWML.java. *. 26. // Setting MIME type as WAP Document. 4) 5) 6. import java.wap. con = DriverManager. 9) 10. 7) 8.*. import java. 3.java //© 2001 Dreamtech Software India Inc. out = res. Statement s.*. HttpServletResponse res) // start of the action class { try // declaration of a block to catch exception { Class. Listing 5-4: Call. 27. } catch(Exception se) // catching the exception { System. 2. 21. 19. or if the choice entered is “2” the user is asked a question with multiple-choice answers. //All Rights Reserved 1. 25. s = con."").getWriter().out.forName("sun.http. Connection con. import java. Further output depends on the choice entered by the user. String value.util.setContentType("text/vnd. 23.JdbcOdbcDriver").jdbc. import javax.println(se). 14. If the choice entered is “1” it displays the list of cities for Weather Forecast. 28. // Start of the servlet request public void doGet(HttpServletRequest req.java (Listing 5-4) is called from TestWML."".wml"). ResultSet rs. 11.*. 17.getConnection ("jdbc:odbc:testservlet". 22.servlet. 13. .java Call.io.createStatement(). Vector name = new Vector(). } try // definition of a new block for catching another exception { res. 24. 15.odbc. 12. 18. public class Call extends HttpServlet // declaration of the main class which extends the httpservlet { PrintWriter out. 20.sql.java.72 Chapter 5: Integrating Java with WAP Figure 5-4: Output screen of Test WML. 16. rs = s._out. // Defining pull down list to show options for the city names stored in table 55. out. value = req.println("<go href=\"http://localhost:8080/examples/servlet/report?WChoice=$WChoice\"/>"). out. 60. if (value.println("</head>"). 57. out. 44. // for Choice 1 i. int h = 1. // WML deck declaration 33.nextElement() + "</option>").println("<?xml version=\"1.println("<onevent type=\"onenterforward\">"). 40. // WML meta tag declaration 35. 36.1//EN\" " + "\"http://www. out.hasMoreElements()) 58. { 42. Enumeration e = name. Weather Report 37.println("<meta http-equiv=\"Cache-Control\" content=\"max-age=time\" forua=\"true\"/>").getParameter("choice"). 31. while(rs. out. out.org/DTD/wml_1. 34. 51.Chapter 5: Integrating Java with WAP 73 29. out. 54.println("<wml>").println("</do>").1. out. { 59. // Defining the event type for the action to take place on submit button 47.println("<select name=\"WChoice\">"). out.println("<refresh>").xml\">"). 56. // WML Prolog defination 32. h++. out.println("</refresh>"). // variable declaration 49.e.println("</onevent>"). . // refreshing the client memory 48. 62. out. i++. int i = 0.println("<option value = \""+h+"\">" + (String)e. name. rs.println("</select>"). // Filling the pull down list options with the values taken from recordset 61.println("<card id=\"CardA\" newcontext=\"true\">"). // WML event declaration 52.executeQuery("Select * from Weather").println("<setvar name=\"WChoice\" value=\"1\"/>").equals("1")) //checking the value of variable passed from TestWML. // Calling the file report with the choice accepted by the user 53. out. out. //Querying from the weather table 39. while(e. out. 50.next()) 41. out.println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1. 43.getString(2)).println("<head>"). out.add(i.println("<do type=\"accept\" label=\"Ok\">").println("</p>"). // getting the value entered by the user in the field of the name // choice and storing the result in a string variable of the type value 30. out.wapforum. } 45. { 38. out. // WML card declaration 46. out.println("<p> The Choices of cities are").elements().0\"?>"). question = rs. if (ij == 0) 82. { 94. i++.next()) // browsing through the recordset 90. int rem = (int)time/i.next()) // browsing through the recordset 71.next()) // searching the question in the recordset on the // index value of Question ID 102. out. int ij = 0. 88. 81. // Store the id of the question 95. 79. 89.executeQuery("Select * from Question"). java.while(rs. // getting the result 99. { 83. rs = s. qid = rs. } 97. { 68. if (ai == ij) 93. 69. } 98. ij = 5.if (((String)rs.{ 105.executeQuery("Select * from Question"). 92.74 Chapter 5: Integrating Java with WAP // end of paragraph 63.add(index.equals(qid)) 104. // Stores the question 96. String qid = "".println("</wml>"). } 85. ij = (int)time-rem*i. while(rs. rs = s. . else // The else part is to check If Choice entered in TestWML is // Question of the Day 67. // Adding data to recordset with the result obtained from query 86.util.getString(3)). // End of WML Deck 65. String question = "". } 66. ai++. 70.executeQuery("Select * from Answer"). int i = 0. long time = date.{ 103. out.getTime().getString(1). } 74. 75. 84. rs = s. int ai = 0.util.getString(1)). 100. Vector choices = new Vector(). 101. 87.rs.Date().choices.println("</card>"). // End of WML card 64.getString(2) .Date date = new java. { 72. { 91. // For random number generation 80. 73. while(rs. // defining date and time variables 78.int index = 0. } 137. // setting the variable Qchoice and initialising it to 1.elements(). 112. out. catch(Exception ex) // catching the exception & displaying it on screen 134. System. . 108.println("</refresh>"). 115.println("<card id=\"CardC\" newcontext=\"true\">"). 109. // End of WML card 130.println("<p>"+question). out. 114.out.println("<onevent type=\"onenterforward\">").println("</wml>").println("<go href=\"http://localhost:8080/examples/servlet/solution?QChoice=$QChoice*Qid="+q id+" \"/>"). out. // Displaying the question on screen 119. } 127. 122. } 132.nextElement() + "</option>"). h++. { 124. 121. } } out. // Adding options into pull down list from the values in the recordset // and displaying it on screen 125. out. int h = 1. // End of WML Deck 131. { 135. 116.println("<do type=\"accept\" label=\"Ok\">"). out.println("<select name=\"QChoice\">"). out.Chapter 5: Integrating Java with WAP 75 // to store the choices in the recordset on the basis of the id index++. out.hasMoreElements()) 123. // A Call to the solution servlet with the Qchoice as a parameter // which will contain the option entered by the user. 129.println("</do>"). 107.println("<setvar name=\"QChoice\" value=\"1\"/>"). } //End of java code 106.println("<option value = \""+h+"\">" + (String)e. // Creating pull down list by taking options from the recordset and // Displaying it on screen 120. out. 126._} 138.println("</p>"). Enumeration e = choices. while(e. to check //whether the answer provided by the user is correct or not 117. 118. 136.println("<refresh>"). // End of pull down list in WML 128. out. } 133. out. out. out. 113.println("</select>"). // Defining event type in WML 111.println("</card>").println( "Exception "+ex ). out. out.println("</onevent>"). out. 110. This class is inherited from the base class HttpServlet and a method doGet is called which is responsible for sending the data back to the calling client program. ♦ Lines 27–28: Setting the content type as a text/WML document. ♦ Line 46: Event-handling routine for the event generated by the user for determining the weather of a particular city. These include packages for the Input/Output operations. ♦ Line 30: Writing the response on the client program in the form of various WML tags. the Question of the Day class is generated. Figure 5-6 shows what happens when choice 2 in Call. ♦ Line 79: A random question is generated. ♦ Lines 17–19: Initializing the database driver — make a connection with the database and initialize the record set. ♦ Lines 117–138:Exception handling and closing of the database connection is complete. ♦ Line 116: Call to the solution servlet is made.java. ♦ Lines 54–63: Defining the pull-down menu to show the cities available after querying the database. If it is 1. If the choice entered is 2. This is used to send the response to the client program. which allows execution on a WAP-enabled device. ♦ Line 66: Question of the Day option is selected. Figure 5-5: List of cities . ♦ Lines 5–13: A class is declared. Code Output Figure 5-5 shows what happens if choice 1 in Call.76 Chapter 5: Integrating Java with WAP Code Description ♦ Lines 1–4: Importing various packages used for the servlets to run.java is selected. Obtaining an object of the class PrintWriter. ♦ Lines 80–114: Showing the question on-screen in a proper format. which takes as a parameter the value entered by the user and matches it with results from the database. and servlet handling operation. ♦ Lines 36-38: First the program checks whether the choice entered is 1 or 2.java is selected. ♦ Line 29: Getting the choice entered by the user in TestWML. the Weather Report is generated and the database is queried for the names of all the cities for which information is available. String temp_min = "".jdbc. } try { res.java program (Listing 5-5) displays the maximum and the minimum temperature of the cities by accessing the data from the MS Access database.createStatement().""). 14.setContentType("text/vnd. 7.out. 22. 18. 16. 13. 8. //setting up MIME type as WML page. String temp_max = "".*. } catch(Exception se) // catching the exception.wap. Statement s. 25.sql. connection and resultsets etc. import java. 2. 5.wml"). con = DriverManager. import java.*. 3. //All Rights Reserved 1.io. // importing the various java packages used by servlets import javax. If any while creating the database connection { System. String value.java //© 2001 Dreamtech Software India Inc. 15. public void doGet(HttpServletRequest req.*. . 4. Connection con.servlet. Listing 5-5: Report. ResultSet rs. 9. 11.forName("sun. 12. import java.getConnection("jdbc:odbc:testservlet".http.util.Chapter 5: Integrating Java with WAP 77 Figure 5-6: Question of the day The Report.odbc."".println(se). 17. // Declaration block for declaring string. 6. 26. 10. 27. 23. HttpServletResponse res) { try // Begin of the try block for the exception checking { Class. 21.*. // Setting up of the database connection s = con. 24. 28. 29.JdbcOdbcDriver"). 20. 19. public class Report extends HttpServlet { // Declaration block defining variables and recordset PrintWriter out. Vector name = new Vector(). 34. } 54.out. 57. } 44. } // end of the program. 59.next()) 36. // End of card 52. { 39. catch(Exception e) // catching the exception and displayimg it on the screen 55. These packages include packages for the Input/Output operations and servlet handling operation.getString(4). // To store the value of variable wchoice passed from the calling program 32. city = rs. out. // Executing query to read all the records from table and store in recordset 35. out. out. String city = "".println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1. out.parseInt(rs. out. 49. if (Integer.executeQuery("Select * from Weather"). ♦ Lines 5–15: A class is declared. out.getString(1)) == val ) 38.getString(3). 40. int val = Integer. temp <b> "+temp_min+"</b></p>"). .println("<p align=\"left\">Max. temp_min = rs.getString(2).println("<?xml version=\"1.parseInt(value). // End of WML 53.getParameter("WChoice").1. 41.println("<wml>"). out. 45.println("<card id=\"cardB\">"). } End of java code Code Description ♦ Lines 1–4: Importing various packages used for the servlets to run.println("</wml>"). temp_max = rs. } 58. ♦ Lines 19–21: Initializing the database driver — make a connection with the database and initialize the record set.println( e ).println("<p align=\"center\">The temperatures at <b> "+city+" </b> are as follows </p>"). This class is inherited from the base class HttpServlet and a method doGet is called.0\"?>"). out. // Displaying maximum and minimum temperature of various cities 51.78 Chapter 5: Integrating Java with WAP 30. 31.1//EN\" " + "\"http://www.println("<p align=\"left\">Min. 50. { 37.xml\">"). temp <b> "+temp_max+"</b></p>"). out. // Declaration of card 48. minimum and maximum temp in local variables taken from //recordset having result passed through query from database 42.println("</card>"). value = req. while(rs.getWriter(). // Storing the city. which is responsible for sending the data back to the calling client program. out = res. 47.org/DTD/wml_1. { 56. 46. } 43.wapforum. 33. rs = s. System. Listing 5-6: Solution. 15. import java. ♦ Line 34: When the user indicates the choice as 1. 7. which allows execution on a WAP-enabled device. Statement s. import java. import java.java //© 2001 Dreamtech Software India Inc. Obtaining an object of the class PrintWriter. Connection con. ♦ Line 50: Displaying the temperature along with the city name in a proper format to the user. //All Rights Reserved 1. import javax. Figure 5-7: Display of max and min temperature Solution. 16. This is used to send the response to the client program. // variable declarations public void doGet(HttpServletRequest req. 8. It then displays a message indicating whether the user’s answer is correct or incorrect. the list of all the cities for which the weather information is available is retrieved from the database and displayed. 14. 6. HttpServletResponse res) . 10. String id.java (Listing 5-6) compares the user’s answer to the question of the day with data from the Access database. 11. ♦ Lines 51–59: Exception handling and closing the WML tags Output.java. 5. // Importing the various java packages used by the servlets public class solution extends HttpServlet { // Defining a servlet class based on HttpServlet. // Variable declarations block PrintWriter out.*. String temp_min = "". ResultSet rs.servlet. String value.*. String temp_max = "". ♦ Line 35: Writing the response on the client program in the form of various WML tags. 4. Code output Figure 5-7 shows the output of Report.java. 3.io.util. 2.http.*. 9.*. 12.Chapter 5: Integrating Java with WAP 79 ♦ Lines 29–30: Setting the content type as a text/WML document. This class checks the //solution on the basis of the choices entered by the user. 13.sql. Vector name = new Vector(). ♦ Line 31: Setting the choice entered by the user in Call. } 50. if (rs.JdbcOdbcDriver"). } // Checking for the displayed question in the recordset and on finding the //question.substring(value. value = req. { 30.next()) 39. 32. } // End of the try block for the exception checking and displaying the name //of the exception 28. out. // Breaking the variable value into id and value where the delimiters are ‘=’ & ‘*’ 36. // Setting up the data base connection to access the data from the database 21. { 46. { 44.0\"?>").value. // if the answer matches. try // Begin of the try block for exception checking 19. System.executeQuery("Select * from Answer"). if (rs.jdbc.indexOf("=")+1). boolean right = false.1//EN\" " + "\"http://www. catch(Exception se) 25. Class. .wml"). // Setting up variable value with the data of the variable Qchoice.equals(value)) 43.1. } 24.println(se). 27.forName("sun. 22.println("<!DOCTYPE wml PUBLIC\"" + "-//WAPFORUM//DTD WML 1.substring(0. // Setting up content MIME type as WML Page 31.odbc. con = DriverManager.equals(id)) 41.getParameter("QChoice").println("<?xml version=\"1. rs = s. } 51."". res. System.""). 52.equals("r")) 45. 34.createStatement(). { 42. 47. // Matches the choices on the basis of question_id and answer supplied by //the user 38. out = res. value = value.out. if (rs.org/DTD/wml_1. { 26.wap. 35. out.getWriter().xml\">").getString(4). then the variable right is set to true else false.indexOf("*")). } 49. right = true. 23. while(rs. received //from the calling program 33. 37.println( value +" "+ id ).getString(1). { 40. { 20. // the result entered by user is matched with the answer in the recordset. // which is later used for condition checking 48. { 18.out.80 Chapter 5: Integrating Java with WAP // The doGet() method of the servlet having request and response objects 17. id = value.setContentType("text/vnd.wapforum. s = con. try // Begin of the try block for the exception checking 29.getConnection("jdbc:odbc:testservlet".getString(2). the answer entered by the user is matched with the answer in the recordset.println("</wml>").println("<p align=\"left\">Your answer is wrong</p>"). out. ♦ Lines 5–15: A class is declared. This class is inherited from the base class HttpServlet and a method doGet is called. // Definition of meta tag in WML 56.java. // end of WML Deck 66.println("<card id=\"cardB\">"). ♦ Lines 51–60: Displaying to the user whether the answer is right or wrong. This is used to send the response to the client program. ♦ Lines 20–22: Initializing the database driver — make a connection with the database and initialize the record set. 55. out. } // End of the try block for the exception checking and displaying the name of //exception executed 71. } Code Description ♦ Lines 1–4: Importing various packages used for the servlets to run. .println("<wml>"). which allows the execution on a WAP-enabled device. ♦ Line 32: Getting the choice entered by the user in Call. out. and on finding the question.println("<meta http-equiv=\"Cache-Control\" content=\"max-age=time\" forua=\"true\"/>"). out. ♦ Lines 30–31: Setting the content type as a text/WML document. ♦ Lines 38–47: Checking for the displayed question in the recordset. // Displaying wrong answer in wml 64. } 67. if (right) // Checking for Right or wrong answer in wml 59.Chapter 5: Integrating Java with WAP 81 // WML Prolog 53. 70. 58. { 69. // end of WML card 65. ♦ Lines 63–72: Exception handling and closing the WML tags. //Generates a Card to show option entered by the users is correct or not 57. and servlet handling operation.println( e ).println("</card>"). System. which is responsible for sending the data back to the calling client program. else 63. out.out.println("<head>").println("<p align=\"left\">Your answer is right</p>"). out. catch(Exception e) 68. } 62. Obtaining an object of the class PrintWriter. 54. out. ♦ Line 35: Writing the response on the client program in the form of various WML tags. then the variable ‘right’ is set to true. out. // Displaying Right answer in wml 61. These packages include packages for the Input/Output operations.println("</head>"). out. If the answer matches. } 72. { 60. Figure 5-8: Display of the correct option Complete Execution of the Application Figure 5-9 shows the complete output of the Weather application. Figure 5-9: Complete Output of the Application .java.82 Chapter 5: Integrating Java with WAP Output Figure 5-8 shows the output of Solution. . please refer to the following books and links: Books ♦ Burd. The data for the application is taken from the MS Access database.html ♦ http://www.html ♦ http://java. 2001. 2001. Summary Java and Java-related technologies occupy a remarkable position in the area of Internet and intranet application development. The main objective of this chapter is to provide insight into some of the popular Java technologies that work with WAP. Hungry Minds. This chapter only skimmed the surface of the concepts of JSP and servlets.com/docs/books/tutorial/servlets/index.edu/~hall/java/Servlet-Tutorial/ ♦ http://www.jhu.webdevelopersjournal.apl. ♦ Whitehead. Inc.com/taglibtut/ . JSP: JavaServer Pages.orionserver.Chapter 5: Integrating Java with WAP 83 The Weather application has demonstrated the integration of WAP with servlets. and Morasn. Inc...com/articles/intro_to_servlets. which is used for mobile communication. Recent research has shown that most of the development in wireless is done on the Java technology platform. To learn more about these technologies. Links ♦ http://www. This can be attributed to the cross-platform and multiple-device support of Java. Hungry Minds.. R. B. Java Server Pages: Your Visual Blue Print to Designing Dynamic Content with JSP.sun. P. which we developed in the earlier chapters. the pull model facilitates information on demand. The WML content is interpreted by the micro-browser in the handset. which is interpreted by the browser on the desktop. as shown in Figure 6-1. The origin server sends the information in the form of an HTML document. All the programs. This mode of accessing the content is known as the pull model. Pull Technology for Accessing Internet Content While accessing the Internet. Figure 6-1: The pull model The server uses a Domain Name Server (DNS) to find out where the information corresponding to the URL is located (called the origin server). we invoke the Web browser and give a request in the form of a URL (http://www. and the content is presented to the user. . The complete code listings for practical push applications are also presented. So.com) to the server of the Internet Service Provider (ISP). use the same methodology for obtaining the Internet content from the handsets. the push model facilitates content to be sent by a server without the need for explicitly requesting information by the user. The same methodology is followed while accessing the Internet through the mobile terminals (the handsets).iseeyes. which is sent to the WAP gateway. and the gateway forwards it to the origin server to obtain the WML content. In this chapter. we will discuss push technology in detail: the protocols.Chapter 6 Push Technology in WAP One of the most attractive features of WAP is its support for push technology. we generally use the pull model. The user gives a request in the form of a URL. as we “pull” the information from the server by giving an explicit request. the network elements required to carry out push functions. these can be tested with a tool kit that supports the push model. From the desktop. and a connection is established with the origin server. Special protocols are defined in the WAP framework to support such applications. What Is Push Technology? In contrast to the pull model. and how to develop applications using the push model. Push technology allows information to be sent to handsets without an explicit request from the user. Push technology is of immense use in applications such as m-commerce (mobile commerce) and m-advertising (mobile advertising). ♦ Service organizations can keep their customers updated with the latest information and new services to be offered. The service indication is just a prompt to the user to find out whether the user would like to view it. every day when the NASDAQ closes at 1 p. The server keeps sending the information with the given periodicity. For example. she can log on to the stock exchange portal and make a request for obtaining information on the stock quotes of four companies in which she has interest).. and so on). Figure 6-2: The push model Push Technology Applications Push technology is now being used for providing a number of value-added services to the users. the user can respond with a “no. In the push model. If the user does not want to see the information at that point in time. she will also give the mobile number and the periodicity with which she would like to receive the information (daily.” The user can see the information later. . weekly. Some of these applications are ♦ Users can be sent daily information on stock quotes. the server first sends a “service indication” — a small message to the effect that some information from the stock exchange is to be sent along with the URL that has the actual information. the following procedure takes place: 1. While registering the preferences. ♦ Sales/customer support staff who are on the move can be informed of the arrival of new mail in their mailboxes or about a service call that needs immediate attention. ♦ When used in intranet and extranet environments. the stock prices can be sent immediately to the interested users. 2. The user logs into a server and registers her preferences for obtaining the push information (for example. ♦ Users can obtain sports information such as soccer/cricket scores periodically when the match is in progress — there’s no need to send a request every time.Chapter 6: Push Technology in WAP 85 As shown in Figure 6-2. The user can respond with a “yes. ♦ Users can register with an astrology portal and obtain a daily horoscope.m. While sending the push information. by retrieving the service indication message stored in the handset and invoking the URL present in the message. push technology helps in providing effective customer-relations management. a user can register with a server for obtaining information (say.” after which the actual information will be sent by the server. stock quotes) and the server sends the information automatically without the user making explicit requests. 3. If the user is not within the service area. transportation. Known as m-advertising. But many handsets support predictive input — software capable of predicting and completing the word being typed. which are as follows: 1. To use an old cliché. SMS Architecture To provide SMS. The message sent is stored at the SMS Center and then forwarded to the recipient — SMS uses the store-and-forward mechanism. Push Technology Implementation The push model can be implemented in two ways: ♦ Using the Short Messaging Service (SMS) Server ♦ Using Push Proxy Gateway (PPG) We briefly discuss the Short Messaging Service and then go into the details of the Push Proxy Gateway. The operation of the SMS involves two steps: ♦ Mobile-originated SMS (from handset to the SMS-C) ♦ Mobile-terminated SMS (from SMS-C to the handset) Mobile-Originated SMS As shown in Figure 6-3.86 Chapter 6: Push Technology in WAP ♦ Business houses can use the push framework for advertising. education. The only problem in using SMS is that the text messages are difficult to input. If the authentication is successful. this is expected to be a great revenue earner for the mobile operators. SMS-C then forwards the message to the destination. . and many value-added services can be provided to the subscribers. If the recipient’s handset is turned off when the SMS Center has a message to forward. You can gauge the popularity of SMS by the fact that nearly one billion messages are exchanged in Europe every month using it. SMS messages can be exchanged between two handsets or between a handset and a PC (through the Internet). SMS has become popular because it doesn’t require a heavy infrastructure for the mobile operator. the handset sends a short message to the SMS-C via the MSC. just as it does for a normal voice call. 2. the message will be delivered as soon as he comes within the service area. entertainment. which is connected to the Mobile Switching Center (MSC) of the GSM network. mobile-originated SMS is handled in two steps. The handset establishes a connection to the network. imagination is the limit for effectively using push technology in every business sector — service. The destination can be another handset or a terminal in the fixed network. manufacturing. Short Messaging Service Short Messaging Service (SMS) allows text messages to be sent and received on mobile handsets. the mobile operator has to install an SMS Server (known commonly as SMS Center). and so on. the SMS Center will forward the message as soon as the handset is turned on. The maximum size of the message is limited to 160 characters. hospitality. E-commerce proponents feel that push technology would be the right mechanism to encourage impulse buying. Whenever the network can access the handset. one of the MSCs will be designated as Gateway MSC (GMSC). GMSC routes the message to the corresponding MSC. 8. which forwards the calls/messages to the correct MSC. A user sends a short message to the SMS-C (using the procedure just described). If the delivery is successful. 4. a delivery report is sent by the MSC to the SMS-C. 6. GMSC queries the Home Location Register (HLR) and obtains the routing information. Mobile-Terminated SMS As shown in Figure 6-4. The handset is paged and a connection is set up like a normal call setup. MSC delivers the message if the authentication is successful. the information that the delivery was not successful is stored in the HLR. HLR sends the routing information to the GMSC. the short message from a mobile or a fixed terminal is sent to the SMS-C. If the delivery is not successful. which in turn is sent to the destination. SMS-C sends the message to the Gateway MSC (GMSC). Note that when a service area has more than one MSC. 3. 5. The procedure is as follows: 1. 7. 2.Chapter 6: Push Technology in WAP 87 Figure 6-3: Handset-originated short message transfer to SMS Center. Figure 6-4: Handset-originated short message transfer to SMS Center . the HLR informs the SMS-C to resend the message. you must type the message in one of the following ways: ♦ PQR BAL — to obtain the balance in the bank account ♦ PQR CHKBKREQ — to request a checkbook Special services: You can configure the SMS Center to provide special services such as renting a car. You will hear a beep when a new message arrives in your handset . Type the e-mail ID of the person to whom a message is being sent. The SMS Center then forwards the message to the destination number. as specified by the operator). enter a space. Press OK and enter the mobile number to which the message will be delivered. The message is first sent to the SMS Center. For sending e-mail from handset to PC: Go to the messages menu and select Write Messages. stock quotes.88 Chapter 6: Push Technology in WAP Configure the Handset for SMS To use the SMS. For this service. Type the message. the only requirement is to configure the WAP server to use the SMS bearer. To access the news service. and select Read Messages. . 3. 6. compose the message. The procedure is as follows: 1. In addition.com. The message will go to the SMS Center. To make use of the SMS bearer for WAP services by using the push model. ordering a bouquet. This message has to be sent to the special number allocated by the operator (for example. This is a one-time process. You can effectively use SMS to send and receive e-mail from normal PCs as well. Send the message to the given number (such as 500 or 600. you must configure the handset just as you do with SMS. The SMS Center will forward the news headlines within a few seconds. 5. Go to the Messages option in your handset. Similarly. Under Message Service Center number. The mobile operator can assign short codes such as NEWS for the news service. weather information. a number of value-added services can be provided. To use this option. 2. The SMS Center can be configured by the mobile operator to send information services such as news. which will forward the mail to the handset. and local information. You must configure this number in the handset as described earlier. To access the services of the bank PQR. and so on. with the given Message Service Center number given by the operator. the operator will again assign a special SMS Center number. You can also do mobile banking by using the SMS. 500). For sending e-mail from PC to mobile: The handset’s e-mail ID will be in the form yourmobilenumber@operator. a user can obtain information about net losers and net gainers in the day’s stock trading by using a simple code such as STOCK. you must complete bearer adapter configuration settings to indicate that the bearer is SMS. The handset is now ready for SMS. Enter this e-mail ID in the To field. enter the number (a mobile number given by the operator). go to the Text Messages menu and select Write Message. In the WAP server manager. To send a message. The procedure explained in the preceding section will be used for these two operations. and send it (as you have done before). and then type the message. Applications Using SMS The most widely used application of SMS is exchanging short text messages. you must configure the handset to register with the SMS Center. 4. the user has to type this short code (NEWS) under the Write Messages option. Go to the menu options. as in m-commerce. Note that the PPG is a logical entity and physically can be combined with the WAP server. To carry out transactions. Because the SMS Server has to cater to the normal text messages in addition to the WAP services. As the Push Initiator (PI) and the Push Proxy Gateway (PPG) are connected to the Internet. or a WAP server. and the fifth step is optional. the Push Access Protocol uses the HTTP for exchanging the information between the PI and PPG. the Push Over The Air Protocol uses the Wireless Session Protocol (WSP) for exchanging information between the PPG and handset. The four steps indicated in Figure 6-5 and described below are compulsory. A Push Proxy Gateway (PPG) interfaces between the Internet domain and the wireless network domain. Push Framework in WAP The push framework is shown in Figure 6-5. Figure 6-5: Push framework A Push Initiator (PI) in the Internet domain initiates the push messages. Another limitation of SMS is that there’s no effective interaction between the server and the user — SMS is based on a store-and-forward mechanism. providing only WML content. To send a message longer than 160 characters. Push Message Processing The push messages are delivered to the handset by using a five-step procedure. Another protocol is required to transmit the push message to the handset. the maximum size of the message is limited to only 160 characters. One protocol is required between the Push Initiator and the Push Proxy Gateway to exchange control information and the content to be sent to the handset. interactivity is a must. To avoid overloading. The PPG obtains the push messages from the Push Initiator and sends it to the designated handset over the mobile network. SMS can work as the bearer for the WAP push services. Another problem in using SMS for WAP services is overloading. as shown in Figure 6-6. You need two special protocols for pushing the messages. 1. SMS is not an attractive bearer. WAP service providers can use a separate frontend server and not connect directly to the SMS Server. the SMS server can get overloaded due to heavy traffic and may even crash. The Push Initiator sends a Push initiation message to the PPG. The Push Initiator can be a Web server. this protocol is known as Push Access Protocol (PAP). This is not a user-friendly mechanism. this protocol is the Push Over The Air (OTA) protocol. you must split the message. If the push messages are limited to 160 characters. If the messages are longer or when interactivity is required. which also provides the WAP services. .Chapter 6: Push Technology in WAP 89 Limitations of SMS Although SMS can be used to provide many value-added services. This message consists of control information such as delivery instructions and the actual content in WML format. As the PPG communicates with the handsets in the WAP domain. The messages are exchanged in the form of XML entities. The WML content is encoded into compact binary format for a faster transfer on the mobile network. and the PPG will cancel the delivery of the push message. The PI may send a message to the PPG in the form of a status query to find out the status of a particular push message.90 Chapter 6: Push Technology in WAP 2. . the PPG may encode the WML content. The PPG must send an acceptance or rejection. The message can be rejected if it does not meet the Document Type Definition (DTD). This is to indicate whether the push message has been successfully delivered. Table 6-1 gives the various PAP attributes and the status codes to be sent by the PPG. The PAP carries out five operations: ♦ Push Submission (from PI to PPG) ♦ Result Notification (from PPG to PI) ♦ Push Cancellation (from PI to PPG) ♦ Status Query (from PI to PPG) ♦ Client Capability Negotiation (from PI to PPG) Push submission The push submission message contains the control information in the form of an XML entity containing the delivery instructions and the content in WML format. The PPG sends the push message to the handset using the Push Over The Air Protocol. Some PPGs support cancellation of the push messages. This is an optional step. or is undeliverable. The PPG sends a result notification to the PI. The PPG implementation may include tests to be carried out on the push messages. is pending. Result notification The result notification is in XML format from PPG to PI to indicate whether content is delivered to the handset. Figure 6-6: Protocols for push model Push Access Protocol The Push Access Protocol (PAP) is used to exchange information between the PI and PPG. whether the push message has been cancelled. The PPG has to respond with the message status on receipt of the status query message from the PI. The PPG sends a push submission acceptance or rejection message to the Push Initiator. Before sending the message to the handset. and so on. 3. the PI can send a cancellation message to the PPG. 4. 5. In this case. such as whether the message has crossed the expiration time. The PPG sends a request to the SIA in the client to create a push session. the WAP content may not appear uniformly on all handsets. Connectionless push is carried out on a Wireless Datagram Protocol (WDP) port. a small program called Service Initiation Application (SIA) will be running.Chapter 6: Push Technology in WAP 91 Table 6-1: PAP Attributes and Status Codes PAP Attribute Status Message-state undeliverable | pending | expired | delivered | aborted | canceled Code transformation failed Desc implementation dependent value (description of problem) event-time time of failure | time of delivery delivery method unconfirmed | confirmed Push cancellation The push cancellation message is sent from PI to PPG. When a client receives pushed content. or a scheduler. The PPG will send a request to the client to establish a session. PI and PPG exchange messages by using the HTTP/1. The client then establishes a session with the PPG to receive the push message. Only a client can create a session — the PPG cannot create a session to push the message. The server receives an acknowledgement after successful push operation. and so on. Because the Push Access Protocol is in the Internet domain. or is undeliverable. More work needs to be done in the specifications arena to take care of handsets with different capabilities. for example. The PI sends this message if a push message is already submitted but should not be dispatched. Client capability negotiation The PI can send a message indicating the assumed capabilities of the client (the handset). Push Over The Air Protocol Push Over The Air (OTA) Protocol runs above the Wireless Session Protocol (WSP). the server pushes the data without establishing a session. Three types of push functionality are supported: ♦ Confirmed data push during a session: An existing Wireless Session Protocol (WSP) session is used to push the data. the clients can have different capabilities in terms of memory. Another piece of software that has to run on the client is the Application Dispatcher. In the client. but there is no acknowledgement after the push operation. is pending. the despatcher looks at the push message header to find out to which application the message must be sent — the message. an e-mail reader. . Status query The PI can send a status query in XML format to the PPG to find out the status of a specific push message. ♦ Non-confirmed data push during a session: An existing WSP session is used to push the data.1 protocol over the TCP/IP protocol suite. ♦ Non-confirmed data push without an existing session: In this case. This message is also in XML format. Note that in a wireless network. which the PPG uses to make a request to the client (the handset) to establish a connection. display size. The PPG will respond with a message indicating whether the message has been delivered. can be sent to a microbrowser. Because of this. The PI sends the SI to the PPG in XML format. to remind about the credit card payment to be made. The PPG forwards the SI to the handset after necessary encoding. The URL associated with the alert message is sent to the PPG by using the WSP GET method. The operation involves the following steps: 1. The PPG sends the request to the server by using the HTTP GET method. 3.si.92 Chapter 6: Push Technology in WAP Push Messages Two types of push messages exist: ♦ Service Indication (SI) ♦ Service Loading (SL) Service Indication (SI) messages are to send an alert to the handset. the actual message will be obtained from the server and displayed on the user’s handset. The PPG encodes the WML content and transmits to the handset. The message will contain a small alert such as “Would you like to view the stock quotes?” and the URL. Service Indication (SI) A typical Service Indication message is as follows: 1. to indicate that news headlines are waiting to be displayed. The server sends back the content (in WML content) to the PPG. SI messages are used to avoid intruding into the present activity. <si> 2. The user may respond with a Yes to receive the actual message. to send advertisements. this means the actual service will not be loaded (the actual information will not be displayed). 4. The content is interpreted by the micro-browser and presented to the user. 5. The SI consists of a small message to the user about the event and a Uniform Resource Locator (URL) from which the service can be loaded. The mechanism of the Service Indication and Service Loading are shown in Figure 6-7. This is known as Service Loading.wap. 2. The message can be used to inform a user that a new mail message has arrived in a mailbox. or to inform that the latest stock quotes are to be displayed. 6. The content type format of this message is text/vnd. If the user gives her consent to load the message.wml si-id=customerno1020” created=’2001-07-01T13:00:00Z” si-expires=”2001-07-02-2001T23:59:05” action=”signal-medium” . <indication href=http://stockquote.com/wel. Figure 6-7: Service Indication and Service Loading. The Service Indication is just that — only an indication. The Service Indication is sent to the handset based on the preferences the user has registered earlier for obtaining the push content. Expired messages need not be presented to the user. and suddenly the push message is delivered. where YYYY represent four digits for the year. with default as the signal-medium. signal-high. MM represent two digits for the month. Levels of intrusion To ensure that the push messages do not disturb the user. signal-low. all actions are client-implementation dependent. </indication> 4. the Service Indication must be presented in a non-intrusive manner. The letters T and Z should appear literally. for additional information to be provided. signalmedium. When the action is signal-medium. When action is signal-high. When the action is signal-low. DD represent two digits for the day. The action can be any of the following: signal-none. hh represent two digits for the hours. delete. this URL is sent to the handset. The time has to be represented in the 24-hour time keeping format. (See the next section). si-id Unique IS assigned to each message created Date and time of creation of content specified by the URI. the message can be deleted. Table 6-2: Service Indication Attributes Attribute Explanation Href URL to a service application designed to provide the content. Suppose that the user is composing a short message. Based on the implementation. </info> 8. the SI can be postponed and presented later. When the action is delete. <info> 5. Generally. </si> The Service Indication attributes are shown in Table 6-2. mm represent two digits for the minutes. levels of intrusion have been defined in the WAP framework. Class Subelement of info element. there may be intrusion — even if the user is busy with something else. . the action attribute may not provide the desired result. si-expires Service indication expiration date and time Action Level of intrusiveness. Along with the alert message. The action attribute in the Service Indication is used to indicate to the user what type of action needs to be taken based on the present activity of the user. The default action is signal-medium.Chapter 6: Push Technology in WAP 93 Would you like to view stock quotes now?” 3. the SI can be stored in the handset and presented later. This will be in the format YYYY-MMDDThh:mm:ssZ. But this is only indicative because of the varying capabilities of the handsets. to the dismay of the user. the message will be displayed. <item class=”moreinfo”> Your last update was on 05-01-2001 6. and if the user decides to obtain the actual information. ss represent two digits for the seconds. this URL is invoked. </item> 7. ” . When the user responds to the alert message indicating his interest in seeing the content.wap. you can use the tool kit. the Service Indication gives an alert to the user. If the user responds negatively to the alert message. the developer needs to write the code as illustrated in the section “Service Indication.sl. This alert also contains the URL from which the actual content will be obtained. the job includes ensuring that the messages are delivered to the handset. the content will be obtained from the URL and presented to the user. It also has to ensure that the messages are being received from a genuine PI using the authentication mechanisms generally used in the Internet environment. and if not. Note that the Service Indication is automatically generated in the tool kit.wml” action=”execute-low” </sl> The action can be: ♦ Execute-low — without intrusion ♦ Execute-high — may result in intrusion ♦ Cache — placed in cache. But in practical applications. it has to do the protocol conversion (like the WAP server).com/abc. Again. ♦ Content transmission: The PPG has to use the Push OTA protocol to transmit the content to the handsets. this functionality is the same as that of the WAP server. Invoke the tool kit and select the Device Settings.94 Chapter 6: Push Technology in WAP Service Loading (SL) As mentioned earlier. then check the following items: ♦ Listen to push messages ♦ Auto-activate push messages when received ♦ Set the push settings ♦ Connectionless mode ♦ Connection-oriented mode In the push message simulator. The following is a Service Loading example: <sl> href http://www. ♦ Protocol conversion: Because the PPG has to talk to the PI in the Internet domain and the handset in the wireless domain. So the PPG can be integrated with a WAP server as well. the WML code is converted into binary format by the PPG. ♦ Binary encoding: For transmitting the WML content on the wireless network efficiently. As a part of this functionality. specify the URL for service indication. The content type format for SL message is text/vnd. Push Proxy Gateway Based on the discussion on the push protocols. the Service Indication will be stored in the local memory of the device for later retrieval by the user. we can summarize the functions of the PPG: ♦ Push initiation identification and authentication: The PPG has to get the push initiation messages from the PI.stockquote. to inform the PI using the Push Access Protocol. To test the applications in a laboratory environment. 0. we must write servlet applications. you must edit the mime. Start the server by typing startserver in the base directory of the jswdk directory.2 or above ♦ JSWDK 1.wap. 6. Set the mime types on the server. Develop the Database and Servlet Applications Here’s a brief review of how to build servlets for WML content.properties file and add the following lines: wml=text/vnd. 2. 3.1 (Java servlets development kit) ♦ Nokia tool kit 1. Enter the URL of the servlet in the location box.wmlscript wmls=text/vnd. 4.1 Create a directory in the jswdk installation directory to keep all class files in that directory. Push Application Development For push application development. Perform the following to test the servlet application: 1. The content appears.xml as follows to group your servlets into separate services and locations: <webapplication id=”myprogram” mapping=”/myfile” docBase=”myprogram”/> Test the Application To test the application. Configure the servlet engine To configure the servlet engine. 2. Use the Nokia tool kit to test the application. Start the Nokia emulator and click the load location item on the Go menu.wmlscript wmlsc=application/vnd.wmlscript Edit webserver. follow these steps: . follow these steps: 1. 7. Create a subclass of HTTP Servlet.2 or 1. Set content type to WML. Add the servlet entry to the servlet property file.2.wap.wml wbmp=image/vnd/wap/wbmp wmlc=application/vnd. 3. 8. 4. Start the servlet server.Chapter 6: Push Technology in WAP 95 We will now build two applications by using push technology — one for pushing stock quotes and one for pushing advertisements with a mobile cart. The requirements for building servlets are the following: ♦ JDK1.3 or 2.wap. Add an entry to the Web server XML file to map the URL to your servlet directory. To develop these applications. 5. write WML content to the output stream. Compile the servlet and move the servlet class to the JSWDK servlet directory.wap. 14. 4. 17.96 Chapter 6: Push Technology in WAP 1. the periodicity with which she would like to receive the stock quotes (daily. Listing 6-1 shows the HTML code for creating the registration form. Application: Pushing the Stock Quotes The objective of this project is to push stock quotes to a handset periodically. 23. 20. 2. A user has to register with a server. 3. //All Rights Reserved 1. <html> <head> <title>STOCK REGISTRATION</title> </head> <body bgcolor="#FFFFFF"> <div align="center"> <table width="640" border="0" height="350" bordercolordark="#FFFFFF"> <tr align="left" valign="top"> <td> <form method="post" action="http://localhost:8080/RegStock" name="reg"> <h3 align="center"><font face="Arial. 4. 5. Design an HTML page that takes the personal preferences for the given application. The information is then stored in a database. and the names of the companies for which she would like to get the stock quotes. 21. 3. Register personal preferences by registering with a Web server. 10. 19. sans-serif"> <!--Code For User Input --> NAME : <input type="text" name="name"> MOBILE PHONE NO : <input type="text" name="cellno"> ADDRESS : <input type="text" name="add1"> <input type="text" name="add2"> <input type="text" name="add3"> CITY : <input type="text" name="city"> E-MAIL ID : <input type="text" name="mail"> PREFERENCES : <input type="checkbox" name="satyam" value="Yes">Satyam <input type="checkbox" name="infosys" value="Yes">Infosys <input type="checkbox" name="wipro" value="Yes">Wipro . 11. sans-serif">STOCK REGISTRATION FORM</font></h3> <pre><font size="2" face="Verdana. the mobile number. 7. Store the information in a database. which she can fill up and submit. 2. 9. 6. When the user logs on to the server. a registration form (Figure 6-8) must appear. 8. Helvetica. and the periodicity with which the information needs to be pushed. providing her mobile number. A servlet will be running on the server that keeps track of the information to be pushed to the handsets and pushes the information with the required periodicity. Arial. Create a servlet that checks periodically for when the information must be pushed. 16. Helvetica. Use the push simulator in the tool kit to simulate the push application. 13. weekly). 22. 18. Listing 6-1: HTML Code for Registration //© 2001 Dreamtech Software India Inc. 15. 12. </div> 34. </table> 39. </body> 40. <font size="2" face="Verdana. <input type="checkbox" name="reliance" value="Yes">Reliance SEND DETAILS: 26. <input type="radio" name="send" value="twiceaday">Twice A Day 29. “localhost:8080” indicates where the page needs to be submitted. <input type="checkbox" name="IBM" value="Yes">IBM 25. ♦ Line 10: This line is for creating a form for registration and to post the data in to the database when the form is submitted. sans-serif"> 31. </center> 36. <center> 30. </html> Code Description ♦ Lines 1–9: These lines contain the basic header tags for creating the HTML page and setting the color and alignment. . Arial. Helvetica. <input type="submit" name="Submit" value="Submit"><input type="reset" name="Reset" value="Reset"></font> 33. </form> 35. <input type="radio" name="send" value="onceaday">Once A Day 28.Chapter 6: Push Technology in WAP 97 Figure 6-8: Registration form 24. < !-Code For Submitting User form --> 32. </tr> 38. </td> 37. <input type="radio" name="send" value="hourly" checked>Hourly During Stock Hours 27. Fill the tables in with data corresponding to the names of the companies and their stock quotes today. Hourly. body. ♦ Lines 14–19: This code is for obtaining the user input using the input tags. ♦ Lines 33–40: This code corresponds to the end tags. Check boxes are provided and the user has to check the box to obtain the stock quotes corresponding to that company. and e-mail ID are obtained from the user. mobile phone number. ♦ Lines 27–28: This code is to obtain the periodicity with which the push messages have to be sent. Create two tables like the following two examples (in an application such as Access). As a good programming practice. address. once a day. The name of the user. HTML). CustomerDetails Field Name Data Type CustomerID Number (generated automatically) CustomerName Text MobileNo Number (Primary key) Address1 Text Address2 Text Address3 Text City Text Mail Text Satyam Text Infosys Text Wipro Text IBM Text Reliance Text Forward Text (to indicate the periodicity) StockPrice Field Name Data Type Company Text Price Number . ♦ Lines 29–30: Centers the input and defines fonts. city. You must create a database before creating the application.98 Chapter 6: Push Technology in WAP ♦ Lines 11–12: The code is for centering the text “STOCK REGISTRATION FORM” and for font definitions. ♦ Lines 21–25: This code obtains the preferences — names of companies for which stock quotes are to be obtained. ♦ Line 32: This code is for submitting the form. and twice a day are the options provided. close all tags (table. println(e).Chapter 6: Push Technology in WAP 99 Listing 6-2 provides the Java program for storing the preferences in the database. int c1=0. 28. String ccellno="".http. public void init(ServletConfig sc) throws ServletException{ /* CONNECTING TO THE DATABASE */ try{ Class. 26.cwipro="No". 39. 45.stmt1.s7.ino1.stmt8.stmt5. 25.rs3. 50. String cmail="".next()) { /* Retrieve the Record from the Database */ ino1 =rs.cfx. 43.ccity="".ccount.temp="".max=0. import javax.createStatement(). stmt1= con.servlet.s5. 13.cl1.odbc.*.sql.s4.*. import javax. 19. Statement stmt. ino2 =ino + 1. 30. 27.getConnection("jdbc:odbc:stock"). import java. 12.cadd3="". try{ /* Count No of Customers in the Database */ rs=stmt1. String url.servlet.forName("sun.rs1. 23. 8.ii2.*.phno.getParameter("name").cinfosys="No". stmt = con. 7. 31. import java. 46. con = DriverManager. 20.*.ino=0.} } public void doGet(HttpServletRequest request.max1. 16. 18.s2. 36. 38. }catch(Exception e){System.rs7. while(rs.ii.cadd2="". 48.parseInt(ino1). 4.stmt3. 51. 10.*. String cname="".jdbc.getString(1). /* Get Info of the Customer */ cname=request. String s1.executeQuery("select count(*) from CustomerDetails").JdbcOdbcDriver"). String cadd1="". 40.out. 14. 29. 44. 33. //All Rights Reserved 1. 32. Listing 6-2: Java Program for Storing the Preferences in the Database //© 2001 Dreamtech Software India Inc. String csend="". Connection con.rs4. 41. 9. cadd1=request. 34. 3. 24. 47.stmt6.util. 11. ccellno=request.s3. . 37.rs6.IOException { /* DESIGN A FORM FOR DISPLAYING DATA */ PrintWriter out = response. 21. //Push Application import java. 15. 35.cuno1. 17.getParameter("cellno"). 2. public class RegStock extends HttpServlet { String[] cuno.c11.ino2.mg="".io.stmt4.close().getParameter("add1"). } rs. 5. /* Parse and Increment the Customer Id */ ino =Integer.createStatement().cno1.s6.rs2.creliance="No". 6. 42.stmt2. 49.rs5.getWriter(). ResultSet rs. String csatyam="No". HttpServletResponse response) throws ServletException. 22.cibm="No". } 86. 82.println("<head>").toString()). temp=request. . 77. { 66. if(!(temp == null)) 70. 56. out.100 Chapter 6: Push Technology in WAP 52. } 73.getParameter("satyam"). } 83. 85.println("<p>"). cinfosys= temp.'"+ cadd3 +"'. temp=request. out. out. 90. 98. out. } 63.'"+ cibm +"'. 67. 74.response). 84. /* Write the response to the User */ 88. { 81. /* Insert Details of the User into the Database */ boolean x=stmt. out. if(!(temp == null)) 75. 59.getParameter("add3"). } 78. creliance = temp. cibm = temp. { doGet(request.println("</head>"). */ 58.println("<body>").</title>").println("Your CustomerID is : "+ino2). { 71. if(!(temp == null)) 65. public void doPost(HttpServletRequest request. 55. out. cadd3=request. 97. temp=request. out. 96.'"+ ccellno +"'. csend=request.execute("insert into CustomerDetails values("+ ino2 +".'"+ cwipro +"'.'"+ csatyam +"'. out.'"+ cadd1 +"'. if(!(temp == null)) 80.'"+ csend +"')"). HttpServletResponse response) throws ServletException. 72. 69. 99. /* Get Info of the Company. 93. 79. } 68. temp=request. 62. out.getParameter("send").out.. Assign it to a temp Variable and Check for !NULL 57. 89.getParameter("add2").getParameter("reliance"). catch(Exception e1){System. ccity=request. csatyam= temp.println("</p>").IOException 101. 64. 54. 53. 92.'"+ ccity +"'. { 76.println("<html>"). cwipro= temp. out.println("</html>").. out.'"+ cinfosys +"'.'"+ cmail +"'.getParameter("city"). 95.getParameter("IBM").'"+ creliance +"'.} 87.println("</body>"). } 100.getParameter("wipro").'"+ cname +"'. temp=request.getParameter("infosys"). 91. cmail=request. if(!(temp == null)) 60.println("<title>Thank You.'"+ cadd2 +"'. { 61. 94.println("<h3>Thank You For Registering</h3>"). cadd2=request.println(e1.getParameter("mail"). the user has the option to select any or all of the four companies for which he/she would like to obtain the stock quotes. mobile phone number. These will be used subsequently. city. } Code Description ♦ Lines 2–6: The code is for importing the necessary class libraries: viz. 7. city. 6.http. util. ♦ Lines 88–103: A response is sent to the user with the message “Thank You For Registering. a new customer ID is generated.*. ♦ Lines 49–55: The information input by the user in the registration form (name. import java. 10. mobile phone or cell number. This number is incremented by one and assigned to the new customer. servlet. The name. ♦ Line 7: Class declaration. and mail ID obtained in the registration form are taken as the variables for storing in the database. Lines 63–67 for the second company. Connection con. a message to that effect will be sent.*. To achieve this. String url. This code is to increment the customer ID based on the previous records stored in the database. Listing 6-3: Servlet to Push the Stock Quote Information //© 2001 Dreamtech Software India Inc. io. This code is to check whether the user has selected each of the four companies.mg="". address. public class StockPrice extends HttpServlet { String[] cuno. Listing 6-3 shows the servlet code used to push the stock quote information. mail ID) is obtained through this code. } 103. ♦ Lines 35–47: For every customer who registers.*. import javax. are caught through a try block. and sql. import java. Exceptions.Chapter 6: Push Technology in WAP 101 102. 9.io. A number of temporary variables are declared. the already-existing last customer ID in the database has to be obtained. The job of this servlet code is to check the user preferences in the database and push the stock quote information to the user.util.*. and so on.http. ♦ Lines 24–30: The code is for connecting to the database using JDBC-ODBC connectivity.servlet. 5. String cname="". import javax. 4. 2. //All Rights Reserved 1. ♦ Line 22: Function declaration.sql. ♦ Lines 58–62 Used to check for the first company.servlet. ♦ Lines 9–21: The code declares the variables used in the program and the necessary initializations. ♦ Lines 83–86: Whatever information the user has input in the registration form is inserted in the database. 12. . //Push Application import java. ♦ Lines 31–33: Function declaration. 11. address fields. 8. If the customer ID is not valid. if any.” A customer ID is also given. ♦ Lines 58–82: In the registration form. 3. servlet.*. 22. 49.stmt8. 14.s3. } 31.ino1. */ .rs9.rs1. 45. 32.cadd3="". 55.cl1. 36.forName("sun.ii.setContentType("text/vnd.rs2.c11.println("</do>"). 60.getConnection("jdbc:odbc:stock").out.createStatement(). CustomerDetails where CustomerID="+custidint). custidint = Integer.wapforum. /* Write the Response */ 42.custidint=0. rs1 = stmt.stmt2. ResultSet rs.temp="". try{ 25.ccity="".executeQuery("select Satyam. 20.getWriter().ino2.println("<wml>"). PrintWriter out = response. String ccellno="".s5.println("<prev/>"). \"http://www. 48. 29. 46. Statement stmt.close().println(e). 65.rs3. Class.s4.s7.rs8. stmt = con. 38.0\"?>").executeQuery("select CustomerID from CustomerDetails where 54. if(rs1.s6. HttpServletResponse response) throws ServletException. s2 = rs1. { 67. out. 41.ino=0. 21. 28. String s1.rs4. public void doGet(HttpServletRequest request. } 59.102 Chapter 6: Push Technology in WAP 13.wap. String csend="".getParameter("CustId"). ino =rs.println("</template>"). }catch(Exception e){System.Reliance from 64. 18.Infosys.} 30.IOException 33. custidstr = request. String custidstr="".stmt6. 43.println("<do type='prev' label='Back'>"). 47. 27.JdbcOdbcDriver").stmt4. 26.s8. /* Information on the Customer From the Database 53. rs. response. stmt1= con. out.println("<?xml version=\"1. /* Set Content-type Header */ 40.createStatement(). out. 19.getString(2).jdbc.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.next()) 56. { 34. String cmail="". con = DriverManager.norows=0.getInt(1).getString(1).parseInt(custidstr).wml"). /* DESIGIN A FORM FOR DISPLAYING DATA */ 35. s1 = rs1.max1.IBM. { 57. rs=stmt1.rs6. 58.rs7.xml\">"). out.odbc. int c1=0. 50. out. CustomerID="+custidint).1//EN\" 44.stmt5. 39. try{ 63. out. /* Get the Identity of the Customer */ 37. public void init(ServletConfig sc) throws ServletException{ 23. 17. while(rs. 16.s2. try{ 52.1.println("<template>"). /* CONNECTING TO THE DATABASE */ 24. String cadd1="".stmt3. if(custidint == ino) 61.Wipro. 51.rs5. { 62. out.next()) 66. 68. out.cadd2="".org/DTD/wml_1.stmt1. 15. 95.println(e2.} out. 101. s7 = rs2. s5 = rs1.next()) { s6 = rs4. out. s7 = rs4. 88. s3 = rs1. 114. if(s1.println(e3. 103. out.println("<tr><td><strong>Company</strong></td>").getString(5). 81.} /* Print out info of Customer in a Row */ out. 86. 111. out.equals("Yes")) { try{ /* Information on Stock Quotes Customer has Selected(ie. 102.getString(2). 100. 105. 75. 104. 107. 119. 96. if(s2.println("<td><strong>Price</strong></td></tr>"). out.executeQuery("select * from StockPrice where Company='Wipro'"). 112.close(). 78.while(rs3.equals("Yes")) { try{ rs4 = stmt. 71.getString(2).executeQuery("select * from StockPrice where Company='Satyam'"). 91.getString(3). } catch(Exception e2){System. out. } catch(Exception e3){System. 97.equals("Yes")) { try{ rs3 = stmt. 87. 82. 85. } rs1.println("<card id='card1' title='Stock Quotes'>").getString(2). 79. } rs3.println("<tr><td>"+s6+"</td>").out. 99.println("<table columns='2' align='LL'>"). } vrs4. 121. 118.close().toString()).next()) { s6 = rs3.println("<tr><td>"+s6+"</td>"). 117.println(e1.out.println("<td>"+s7+"</td></tr>").getString(1). 89.close(). .out.println("<td>"+s7+"</td></tr>"). 80. 113. } if(s3. 93.toString()). } catch(Exception e1){System. 92.toString()).next()) { s6 = rs2. 110. 76.getString(1). while(rs4. out. System. while(rs2. 115.executeQuery("select * from StockPrice where Company='Infosys'"). 116. 109.Company & Price from the Database)*/ rs2 = stmt. 77.println("<p>"). s4 = rs1. 70. 73. 72. 120.close(). 74. } rs2.} /* Print out info on Customer in a Table in 2 Columns */ out.out.getString(1). 83. 98.Chapter 6: Push Technology in WAP 103 69. 84. 94. s7 = rs3. 108.getString(4). 90.println("S1 :"+s1+" s2 :"+s2+" S3 :"+s3+" S4:"+s4). 106. 173. 140.println("</card>").println("Your ID Is Not Valid. out. 135. 143.out.println(e6. 147. 152. 169.println("</table>").out.getString(2). 168. 171. out.out. 152.} out. out. } catch(Exception e5){System.println("<tr><td>"+s6+"</td>"). out.getString(1). } rs6.println("</wml>"). 154. HttpServletResponse response) throws ServletException.println("<card id='card1' title='Sorry'>"). } if(s4. 153."). 167.toString()).getString(2). out.println("<td>"+s7+"</td></tr>").while(rs6. out. } }catch(Exception e1){System. 146. 165.getString(1).println("</p>"). 166.println("<td>"+s7+"</td></tr>").println("</wml>").println("<tr><td>"+s6+"</td>").equals("Yes")) { try{ rs5 = stmt. 150. s7 = rs6.} out. 129. 142. 155.executeQuery("select * from StockPrice where Company='Reliance'"). out.IOException . } if(s5.toString()). 145. 158.println("</p>"). } rs5. } out.println("<tr><td>"+s6+"</td>"). 136. out.} out. 139. 123.println("<p>"). 137. 141. 132.equals("Yes")) { try{ rs6 = stmt.println(e1. 149. 151. s7 = rs5. 161. 126.close(). 134.toString()). 164.next()) { s6 = rs5. while(rs5. 148. } catch(Exception e6){System. } catch(Exception e4){System.toString()). 133.println("</card>"). 144. 131. out. out. 174. 159. 130.executeQuery("select * from StockPrice where Company='IBM'"). 156. 170. } } public void doPost(HttpServletRequest request.println(e5.close(). 128.println("<td>"+s7+"</td></tr>").104 Chapter 6: Push Technology in WAP 122. 138.println(e4. } //if ends else { out. 127. 163.next()) { s6 = rs6. 157. 162. out. 160. 125. 172.out. 124. place the class files in the servlets folder and the stock. again the stock quote is obtained from the database and the company name and the price are kept in the table columns. and the WML page. you need to create the Service Indication messages.println statements with WML tags as arguments. ♦ Lines 161–176: If the customer ID is not valid (the user sends a wrong ID from the handset).html) and enter the data. ♦ Lines 78–82: This code generates a WML card containing a table with two columns — company name and price with the card title as “Stock Quotes. ♦ Lines 127–140: Again. The same variables used in the earlier program are also used here. The company name and the price are kept in the two columns of the first row in the table generated in the code in Lines 74–80. ♦ Lines 7–21: This code is for declaration of the class and initialization of variables. ♦ Lines 24–30: This code is to connect to the database (named stock). ♦ Lines 97–112: When the user selects the second company. ♦ Lines 155–159: These lines generate the WML code for closing the table.java and StockPrice.” This code is again a set of out. The code consists of a series of out. ♦ Lines 60–76: The names of companies selected by the customer in the registration form are obtained from the database.response). the message “Sorry. A customer ID will appear to the user. ♦ Lines 31–50: This code generates a WML card to obtain the customer ID from the user. } 176. for the fourth company. ♦ Lines 141–154: This code completes the process for the fifth company. Figure 6-9 shows the push message simulator. This code is kept in a try-catch block to catch the exceptions. ♦ Lines 113–126: The above process is repeated for the third company. the corresponding stock quote is obtained from the database using a select query. But in commercial WAP servers that support push. it is automatically generated in the format described earlier. ♦ Line 22: Function declaration.html file in the public HTML folder. the card.println statements with WML tags to generate the WML code. If you are using JSWDK. In the push simulator. invoke the HTML registration form (stock.html in the Web pages folder.Chapter 6: Push Technology in WAP 105 175. you don’t need to create the service indication. Test the Application Compile the Java files RegStock. Through a browser. If you are using a Java Web server. } Code Description ♦ Lines 2–6: This code imports the necessary Java class libraries. ♦ Lines 83–95: If the user selects the first company. The code is kept in a trycatch block to catch any exceptions. The code in these lines generates a WML card to pass this message to the handset. place the class files in the Web-inf folder and stock.java. Your ID Is Not Valid” appears. { doGet(request. This process is repeated for the third and fourth company as well in the following lines. the above process is repeated. ♦ Lines 51–59: This code checks whether the customer ID is valid. . 106 Chapter 6: Push Technology in WAP Figure 6-9: Push message simulator. It also shows the stock information displayed on the WAP phone through push framework. Select the tool kit and the phone emulator (for example. In the push view. Figure 6-10 shows the pushed content on the WAP phone emulator. you no longer need to browse the newspaper to search for the stock prices of your favorite companies! . Also select the push view in the tool kit. In the HREF. the Blueprint device in the Nokia tool kit). select Create Message. The company names and the stock prices are displayed with the card title Stock Quotes. type the URL http://localhost:8080/Stock/servlet/StockPrice?CustId=1 if you are using the JSWDK and http://localhost:8080/servlet/StockPrice?CustId=1 if you are using a Java Web server. Figure 6-11 shows the shopping cart registration form. You can certainly appreciate the power of push technology now. We will integrate a shopping cart — the user can order an item from the handset. we will not worry about the payment details (one possibility is to obtain the credit card information. A user can register his preferences for selected items (groceries. In this example. clothes) and also request information whenever new products are launched into the market (a very polished way of pushing advertisements!). accessories. . we will develop a virtual mall.Chapter 6: Push Technology in WAP 107 Figure 6-10: Push information displayed on the WAP phone Application: Shopping Cart with Advertisement Push In this example. or the bill can arrive with the mobile phone bill if the cellular operator has an agreement with our virtual shopping mall). create a database as per the following examples: CustomerDetails Field Name Data Type CustomerID Number CustomerName Text MobileNo Number (Primary key) Address1 Text Address2 Text Address3 Text City Text Mail Text .108 Chapter 6: Push Technology in WAP Figure 6-11: Shopping cart registration form As in the previous example. The registration form is shown in Figure 6-11. NewProduct Field Name Data Type Category Text ItemCode Text ItemCode Text Itemname Text ItemPrice Number OrderInfo Field Name Data Type OrderNo AutoNumber CustomerId Text OrderItemsAndQty Text Now we need to create an HTML page for the registration form. .Chapter 6: Push Technology in WAP 109 Groceries Text Accessories Text Cosmetics Text Fasionwear Text NewProduct Text Forward Text Groceries Field Name Data Type ItemCode Text Itemname Text ItemPrice Number Accessories Field Name Data Type ItemCode Text Itemname Text ItemPrice Number Cosmetics Same field names and data types as Accessories. Fashionwear Same field names and datatypes as Accessories. The corresponding HTML code is shown in Listing 6-4. 29.Code For Submitting the form --> <input type="submit" name="Submit" value="Submit"><input type="reset" name="Reset" value="Reset"></font> </div> </form> </center></td> </tr> </table> </body> </html> Code Description ♦ Lines 1–9: The basic header tags of the HTML page. Arial. 10. 17. 30. sans-serif"> <!. 26. 2. along with the necessary attributes. sans-serif"> /* Code For User Input */ NAME : <input type="text" name="name"> MOBILE PHONE NO : <input type="text" name="cellno"> ADDRESS : <input type="text" name="add1"> <input type="text" name="add2"> <input type="text" name="add3"> CITY : <input type="text" name="city"> E-MAIL ID : <input type="text" name="mail"> PREFERENCES : <input type="checkbox" name="groceries" value="Yes">GROCERIES <input type="checkbox" name="accessories" value="Yes">ACCESSORIES <input type="checkbox" name="cosmetics" value="Yes">COSMETICS <input type="checkbox" name="fashion" value="Yes">FASHION WEAR <input type="checkbox" name="newproduct" value="Yes">Inform whenever new Products arrive SEND DETAILS: <input type="radio" name="send" value="weekly" checked>Weekly <input type="radio" name="send" value="fortnight">Fortnightly <input type="radio" name="send" value="monthly">Monthly <input type="radio" name="send" value="bimonthly">Bi-Monthly</font></pre> <center> <font size="2" face="Verdana. 6. Helvetica. 24. 15. 25. 20. 27. 39. 18. 16. <html> <head> <title>SHOPPING CART REGISTRATION</title> </head> <body bgcolor="#FFFFFF"> <div align="center"> <table width="640" border="0" height="350" bordercolordark="#FFFFFF"> <tr align="left" valign="top"> <td> <form method="post" action="http://localhost:8080/RegShopping" name="reg"> <h3 align="center"><font face="Arial. 41. 7. sans-serif">SHOPPING CART REGISTRATION FORM</font></h3> <pre><font size="2" face="Verdana. 14. 34. 12. 19. 40. 38. 28. Helvetica. Helvetica. 35. 37. 21. 3. 23. Arial. //All Rights Reserved 1. 9. 42. 31. 13. 8. 33.110 Chapter 6: Push Technology in WAP Listing 6-4: HTML Code for Registration //© 2001 Dreamtech Software India Inc. . 4. This is followed by table tag. 5. 32. 36. 11. 22. rs3.*.max1. import javax. that posts the information of the form in a database located in the local host. 23.cnew="No". 30.servlet. ♦ Lines 34–42: To create Submit and Reset buttons for obtaining the registration form (filled in) from the user.ii. public class RegServlet extends HttpServlet { String[] cuno. or bimonthly. 3. 19. city. String ccellno="". cosmetics. String url. import java. ♦ Lines 27–31: The periodicity with which the information has to be pushed — weekly.mg="". public void init(ServletConfig sc) throws ServletException{ /* CONNECTING TO THE DATABASE */ try{ Class.stmt5. Listing 6-5 provides this Java code. stmt1= con.ii2.util. import java.c11. String s1. String csend="".rs6.temp="". ♦ Lines 21–26: Code to obtain the user preferences for different items such as groceries. monthly. 8. new products. 25.jdbc.rs4.rs2.ino=0. ResultSet rs.s6. address. con = DriverManager. Statement stmt.*. stmt = con.stmt8.s7. 14.s3.s4. The attribute method is “post”.createStatement().stmt4.stmt6. import javax. mobile number. Listing 6-5: Java Program for Storing the Preferences in a Database //© 2001 Dreamtech Software India Inc.cno1. 26.stmt1. //All Rights Reserved 1.Chapter 6: Push Technology in WAP 111 ♦ Line 10: Form tag along with the necessary attributes. 10. fortnightly.max=0. ♦ Lines 14–20: Code for user-input details such as name.s2.out.*. String cname="". 12.stmt3. 16.cuno1. 15.http. String cmail="". 7. String cadd1="". The type of input is a check box.rs7. Connection con.} } public void doGet(HttpServletRequest request.cadd2="".rs1.odbc.ino2.cadd3="". .ino1.ccity="".caccessories="No".forName("sun. accessories. 20.*.stmt2. 28. 21.servlet. and e-mail ID. int c1=0.cfx.createStatement(). 27. 18.sql. ♦ Lines 32–33: Tags to center the Submit and Reset buttons and set the font. 17.*.println(e).JdbcOdbcDriver"). 9. 22. 11.rs5. import java.cfashion="No". ♦ Line 12: Defines the font for the registration form input fields. 24. 4. ♦ Line 11: The title of the registration form is generated with the necessary font and alignment at center.ccosmetics="No". 29.cl1. String cgroceries="No". 6.getConnection("jdbc:odbc:shop").io. Lines 38–43 are the closing tags for the HTML page. Now we need to write the Java code that will take the inputs from the registration form and store the information in the database. }catch(Exception e){System.s5. 2.ccount. fashion. 13. 5.phno. ccity=request. 46.getParameter("name"). 41.IOException { /* DESIGN A FORM FOR DISPLAYING DATA */ PrintWriter out = response. if(!(temp == null)) { cgroceries= temp. 74. 81. 76.getParameter("cellno"). 60. 44. 39. 73.getParameter("cosmetics"). } temp=request. 64. 49. 70. cadd3=request. /* Get Info of the Customer */ cname=request. 50. if(!(temp == null)) { ccosmetics= temp. 58. 65. if(!(temp == null)) { caccessories= temp.getParameter("city"). /* Count No of Customers in the Database */ try{ rs=stmt1.executeQuery("select count(*) from CustomerDetails"). 34.getParameter("add1"). 45. 53. 59. /* Parse and Increment the Customer Id */ ino =Integer. 55.getWriter().next()) { /* Retrieve the Record from the Database */ ino1 =rs. 72. ccellno=request. Assign it to a temp Variable and Check for !NULL */ temp=request. 35. 66.close(). 79. 80. cadd2=request. 67.getParameter("newproduct").parseInt(ino1). 51.getParameter("mail"). /* Get Info of the Company.execute("insert into CustomerDetails values("+ ino2 +". 43. HttpServletResponse response) throws ServletException. 48. 57. 56.getParameter("groceries").getString(1). '"+ cname . 68. 78. 83. 63. 82. 71. 52. cadd1=request. ino2 =ino + 1. } temp=request. 40.getParameter("add2"). 69. 38. 62. if(!(temp == null)) { cnew = temp.112 Chapter 6: Push Technology in WAP 31. } rs. 47. 77. 84. 33. 61. } temp=request. while(rs. 32. 36. 75. /* Insert Details of the User into the Database */ boolean x=stmt. 54. cmail=request. 42.getParameter("fashion"). 37. } csend=request.getParameter("accessories").getParameter("add3"). } temp=request. if(!(temp == null)) { cfashion= temp.getParameter("send"). '"+ cadd2 +"'. The code is kept in a try-catch block. out.'"+ cadd1 +"'. 102..println("</body>"). Now comes the actual push application. 92.</title>").IOException { doGet(request.. out. out. 98. +"'.println("<p>"). cell number. 103. 89. out. which is generated automatically. city. This code checks for the present customer ID. 95.response).println("<title>THANK YOU. out. 87. HttpServletResponse response) throws ServletException. } public void doPost(HttpServletRequest request. 101.'"+ csend +"')").println("<html>").'"+ caccessories +"'.'"+ ccosmetics +"'. } catch(Exception e1){System.'"+ cfashion +"'. out. 97.'"+ cadd3 +"'.'"+ cmail +"'. 96. and some temporary variables are defined here. ♦ Lines 84–103: This code generates an HTML page with the message “Thank You For Registering” and gives the customer ID (or security ID because we’re dealing with online shopping). 100. ♦ Lines 30–46: As in the previous example (stock quotes). 91.println("<head>").out. } } Code Description ♦ Lines 1–5: This is the familiar code to import class libraries.println("<h3>Thank You For Registering</h3>"). just to ensure that if something goes wrong. out. increments by one. out. 88. This is a repetitive code for each of the items in the registration form. ♦ Lines 57–82: This code gets the preferences selected by the user.println("<body>"). 99. 90. 93.'"+ ccity +"'. the exception is caught.'"+cnew+"'. Listing 6-6 gives the Java program for validating the user based on the customer ID and displaying the information on the browser of the handset. .'"+ cgroceries +"'.'"+ ccellno +"'. This response is given to the user on completion of successful registration.} /* Write the response to the User */ out.toString()). 94. It discovers whether the check box has been checked and assigned to a temporary variable temp. ♦ Lines 6–20: Code for declaration of the class RegServlet and initialization of variables. out. ♦ Lines 21–29: This code is to connect to the database using JDBC-ODBC connectivity.println("</p>").Chapter 6: Push Technology in WAP 113 85.println("Your CustomerID is : "+ino2).println("</html>"). We need to write the code that will check the database for each user’s registered preferences and push the content to the user based on the periodicity indicated in the registration form.println(e1. ♦ Lines 48–54: This code gets the information of the customer (name. 86. address fields. out. and mail ID).println("</head>"). and assigns an ID to the new user. each customer is given a unique ID. All the fields in the registration form are given variable names. 1//EN\" \"http://www.rs8. 25.ino2. 46.util.rs1.servlet. import javax. //All Rights Reserved 1.JdbcOdbcDriver"). 35.114 Chapter 6: Push Technology in WAP Listing 6-6: Java Program for Validating and Displaying on the Browser //© 2001 Dreamtech Software India Inc. 27.stmt8. out. 12.wap. 50. public void init(ServletConfig sc) throws ServletException{ /* CONNECTING TO THE DATABASE */ try{ Class.stmt6.rs7. 10. 48. 2. out.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1. 20. 14.max1.rs11. /* Write the Response */ out. 28.getWriter().out. String csend="". 7. 49. String s1.org/DTD/wml_1.*. String url. import java.setContentType("text/vnd.xml\">"). con = DriverManager.cadd3="".wml").jdbc.stmt2.println("</do>"). ResultSet rs. import javax.rs10. 21. String cnew="". 3.io. stmt1= con. String cadd1="".createStatement(). /* Set Content-type Header */ response. Connection con.0\"?>").stmt1.println("</template>").rs5. 32. 43.stmt3. 9. out. 40. import java.println("<wml>").s6.rs3.http. String ccellno="". 30. int c1=0. 33.s3. 6. 34.rs4. 15.forName("sun.s4. 11.s5. out. 45.*.s2. 16. String cmail="". 5.s9. 23.IOException { /* DESIGN A FORM FOR DISPLAYING DATA */ PrintWriter out = response.servlet.rs2.println("<template>"). 51. try{ .custidint=0.ii.parseInt(custidstr).HttpServletResponse response) throws ServletException.wapforum.s7. import java.cl1.stmt4.*. /* Get Identity of the Customer and Parse it */ custidstr = request.mg="". 42. 19.ccity="". }catch(Exception e){System.println(e).getConnection("jdbc:odbc:shop").cadd2="". 44. 17. 38.println("<prev/>"). Statement stmt. String custidstr="". 47.} } public void doGet(HttpServletRequest request.getParameter("CustId").rs6. 39. 41.ino=0.println("<do type='prev' label='Back'>"). public class ShopingCart extends HttpServlet { String[] cuno. 22. 24. custidint = Integer.*. 36.ino1. 26. out. 31.s8. 4. 13. 8.createStatement().1.stmt5. 18.sql.rs9. out.temp="".c11. String cname="".*.odbc. 29. 37. stmt = con. out.println("<?xml version=\"1. 80. } rs1.next()) { s1 = rs1. 62. } if(s9. 105. 76. out. 70. 94. 89. /* Anchor for Navigation to Accessories Card */ out. 87.equals("Yes")) { System. 75.getString(1).out.} /* Print out Shopping Cart info for the User to Order */ out. 95.println("S1 :"+s1+" s2 :"+s2+" S3 :"+s3+" S4:"+s4+"S9 :"+s9). 77. 55. } if(s2. 88.println("S2").executeQuery("select Groceries. 60.println("<p>"). 82.out.println(e1. s3 = rs1.Acessories.out. } if(s3.out.getString(5).out. 97.println("S4"). 99. 72. 54. /* Anchor for Navigation to Groceries Card */ out. 92.getString(3). 85.executeQuery("select CustomerID from CustomerDetails here CustomerID="+custidint).NewProduct from CustomerDetails where CustomerId="+custidint). s4 = rs1. 100. 65. 98. 104.equals("Yes")) { System.next()) { ino =rs. 64. 56. 73.equals("Yes")) { System. 69.println("<card id='card1' title='ShoppingCart'>"). 84. } catch(Exception e1){System. out. 81. 66. 58. 67. 96. 71. 106. 74. 103.println("<a href='#fash'>FashionWear</a><br/>"). } if(s4.getString(2).getString(4). 90. 68.println("<a href='#groc'>Groceries</a><br/>"). if(rs1. 61. 93.println("S3").println("<a href='#cosm'>Cosmetics</a><br/>").getInt(1). 101. s9 = rs1. out.toString()). } rs.println("<a href='#aces'>Accessories</a><br/>"). 79. 91. 83. while(rs. 57.close(). s2 = rs1.Cosmetics. if(custidint == ino) { try{ /* Based on the CustId Retrieve the Details from Database */ rs1 = stmt.equals("Yes")) { System. 63. /* Information on the Customer From the Database */ rs=stmt1. 59. 86. System.FashionWear. 53.out.println("S1 "). //if starts if(s1. 102. 78.Chapter 6: Push Technology in WAP 115 52.close().equals("Yes")) { . println("<a href='#new'>New Products</a><br/>").println("<go href='http://localhost:8080/Shopping/servlet/Order' method='get' >"). 117.next()) { s8 = rs8. 137.executeQuery("select * from Groceries").println(e11.} } if(s2. out. } catch(Exception e13){System. 122. 112. 134. 125. 151. 116. 140.next()) { /*Retrieving First Column From the Database */ s8 = rs6.equals("Yes")) { try { rs8 = stmt.getString(1). 118. 109.close(). 156. 126. 110. 124.println("S5"). while(rs6.equals("Yes")) { try { rs7 = stmt.out. 141. 115. 158.getString(1). out. } rs8. } out. 154. /* Check If User has selected the Item in the Registration Form */ if(s1. } rs7. 161. 127. 145. 128. 131. } rs6. 113.116 Chapter 6: Push Technology in WAP 107. 148. 108. /* Posting Parameters to Order Servlet */ out. /* Link for Navigation to Order Servlet */ out. 123. while(rs8.close(). 111.toString()).} } if(s4.println("<postfield name='"+s8+"' value='$("+s8+")'/>"). 159. 155. 157.} } if(s3.println("<postfield name='"+s8+"' value='$("+s8+")'/>").println(e12. } catch(Exception e11){System.toString()).equals("Yes")) . while(rs7. 150. } catch(Exception e12){System. 143.println(e13. 147.executeQuery("select * from Acessories").getString(1). 138.println("<anchor title='Link'>Order"). 120.next()) { s8 = rs7. 132. 152. 121. 136. 119.equals("Yes")) { try { rs6 = stmt. out. 135. 129. 142.out. 139. /* Set the Parameter Name and Value */ out. 114.executeQuery("select * from Cosmetics").out. 144. 160. 146. 153.close(). 130.println("<postfield name='CustId' value='"+custidint+"' />").println("<postfield name='"+s8+"' value='$("+s8+")'/>").out. 149. System.toString()). 133. println(e14.} out. 176.println("<input name='"+s7+"' type='text' value='0' />"). 201.getString(2).print(s5+" "+s6). 179.equals("Yes")) { try { rs11 = stmt.close(). out.toString()). 174. 213.println("</card>").toString()). 191. 211. 181. 189. 188. //out. 195. 214. 196.close(). out.executeQuery("select * from newproduct"). 177. } rs2. out. 163.equals("Yes")) { out. { try { rs9 = stmt. try { rs2 = stmt. 199. 202. 212.println(e14.getString(2). 186. 209. 208. 198. 164. 194. } catch(Exception e14){System.} } if(s9. 207. 205.next()) { s8 = rs11. while(rs9. 192.close(). 187.executeQuery("select * from Groceries").executeQuery("select * from FashionWear"). 165.out.next()) { s7 = rs2. 167. out. out.toString()). } catch(Exception e3){System. } rs9. 204. 184. 182. s6 = rs2. while(rs2.println("<br/>").println(e3. 215. s5 = rs2. out.println("</p>"). 193.println("Item Name Rate Qty"). 210.getString(3). 180.out. 175.println("<card id='groc' title='Groceries'>"). 190. 173. 185.println("<p>"). 200. 216.} } out. while(rs11. 178. 183.println("<postfield name='"+s8+"' value='$("+s8+")'/>"). out. /* Write the Response to the Groceries Card if User Registers for item */ if(s1. out.println("<postfield name='"+s8+"' value='$("+s8+")'/>").println("</p>"). 203. out. } . 170. out. 206. 169.out.getString(1).next()) { s8 = rs9.getString(1). 197.println("</card>").Chapter 6: Push Technology in WAP 117 162. 166. 168.println("Groceries Here").println("</go></anchor>"). } rs11. 172. } catch(Exception e14){System. 171. 259.toString()). 226. rs3.println("Cosmetics Here").println("</card>"). } 238. s5 = rs4.next()) 253. 237. 233. /* Write the Response to the Cosmetics Card if User Registers for item */ 243.getString(3).close(). 241.println("<card id='fash' title='FashionWear'>"). 247. . out.println("<br/>"). s7 = rs3. try 224. 257. out. { 225. catch(Exception e4){System. 231.executeQuery("select * from Acessories"). if(s2. s5 = rs3.println("</card>").out.println("<card id='aces' title='Accessories'>").equals("Yes")) 268. 222. out. { 269.next()) 228. out. 223. /* Write the Response to the Accessories Card if User Registers for item */ 218. 258. out.print(s5+" "+s6). { 245.println("<input name='"+s7+"' type='text' value='0' />"). out. s7 = rs4. { 250. try 249. rs3 = stmt. 252.getString(3). out. out.executeQuery("select * from Cosmetics"). //out. out.println("Item Name Rate Qty"). 230. { 229. { 254. out.println("<br/>"). out.getString(1). /* Write the Response to the FashionWear Card if User Registers for item */ if(s4.} 239. 256. } 236. 221. 251.println("Item Name Rate Qty").println(e5. out. s6 = rs4. 240.out.equals("Yes")) 219. rs4. out. 232.118 Chapter 6: Push Technology in WAP 217.print(s5+" "+s6). rs4 = stmt. s6 = rs3. } 263. 266. 255. if(s3. } 267. while(rs4.} 264. 246.close().getString(1). { 220. 262. } 242.println("<p>").println("<input name='"+s7+"' type='text' value='0' />"). 248. 235. catch(Exception e5){System. out.equals("Yes")) 244. out.println("</p>").toString()).getString(2). out. 234. 227.println("Acessories Here"). 260.println("<card id='cosm' title='Cosmetics'>").println("<p>"). while(rs3. } 261.getString(2). //out.println(e4.println("</p>"). 265. out. equals(temp1)) { i=0. 301.executeQuery("select * from newproduct order by category"). 276. i++. 312. 296. 280.println("<input name='"+s7+"' type='text' value='0' />").println(temp).println("Item Name Rate Qty"). 277.println("</card>"). out.getString(3). while(rs10. 310. 295. 273. 294. 293. 309. 313. } } if(i == 0) { temp1=temp. 290.println("<br/>"). } s7 = rs10. } catch(Exception e6){System.println("<br/>"). 286. 320.println("FashionWear Here"). out. 297. out. 272. 281. 283. s5 = rs5.getString(3). //out. int i=0. 289.println(e6.println("<br/>"). } rs5. 314.print(s5+" "+s6). out.println("</p>").println("<p>"). //out. out. 285. 287. } /* Write the Response to the New Products Card if User Registers for item */ if(s9. out.out.temp="". 274.next()) { s7 = rs5. 278. s6 = rs5. 308. 317. 325. //out.equals("Yes")) { out. if(flag) { if(!temp.println("Item Name Rate Qty").getString(1). 316.println("<card id='new' title='New Products'>"). while(rs5. out. 322. 271.toString()). out. 291.Chapter 6: Push Technology in WAP 119 270. 323. 324. 275. 299.println("<p>"). 307. 282.close().getString(1). 284.println("FashionWear Here"). try { rs5 = stmt. 279.println("Item Name Rate Qty").getString(2). 321. String temp1 = "".next()) { temp = rs10. out. 304. try { rs10 = stmt. 288. 318.} out. boolean flag=false. 311. 315. out. . 305. s5 = rs10.executeQuery("select * from FashionWear"). out. 298. 306.getString(2). 319. 292. 302 303. Lines 91–95 are for fashion wear. 347.println("<card id='card1' title='Sorry'>"). When the user inputs the data. out. 349. we import the necessary class libraries. 328. a WML card containing the shopping cart will be generated.response). and also some temporary variables are declared. } //if ends else { out.println("</wml>"). 344. only the following code is executed. For exception handling.println(e6. the content type is set to WML. this code retrieves the details (items selected) from the database. the shopping cart has to display the item name.println(e1.} out. out. 350. } rs10. ♦ Lines 6–21: This code is for declaration the class and initialization of variables. 340.toString()). 327.toString()). 345.println("</card>"). the code is kept in a try-catch block. it has to be stored in the database through another servlet . ♦ Lines 105–115: If the user selects groceries when the code given in Lines 80-104 is executed in the handset. ♦ Lines 31–40: A WML card is created in this code to get the customer ID from the handset. 352. Lines 74–79 generated the code for groceries only if groceries are selected by the user.print(s5+" "+s6). } } Code Description ♦ Lines 1–5: As usual. Lines 86–90 are for cosmetics. } }catch(Exception e1){System. 332.println("<p>"). out. Line 71 generates the card title. 333. HttpServletResponse response) throws ServletException. 346.println("Your ID Is Not Valid. out.println("</card>"). 351.getString(4). } out. ♦ Lines 42–50: The customer ID obtained from the user is verified in the database. 348. out. If the customer ID is valid. } catch(Exception e6){System. ♦ Lines 80–104: Based on the items selected.IOException { doGet(request. 330.println("</p>"). ♦ Lines 22–30: This code connects to the database using JDBC-ODBC connectivity. a message saying that the ID is not valid is sent to the handset as in the code in Lines 321–329. Lines 96–100 are for new products.out. 334.println("</p>"). 337. out.120 Chapter 6: Push Technology in WAP 326.} } public void doPost(HttpServletRequest request. 331.println("<input name='"+s7+"' type='text' value='0' />"). 341. 342. 339. Lines 80–85 are for accessories. 354. 343."). 329. 355. rate. 338.close(). out. and quantity fields that can be input by the user.println("<br/>"). All the fields in the registration form are given variable names. 335. s6 = rs10. flag = true. out.println("</wml>"). out. 353. At line 40. Otherwise. ♦ Lines 51–78: Based on customer ID. 336.out. The above program obtains the information from the user — the information is the items of interest and the quantity the user would like to procure. HttpServletResponse response) . //All Rights Reserved 1.Chapter 6: Push Technology in WAP 121 called Order. 3. Connection con. ♦ Lines 268–290: The card generation process is repeated for fashionwear.util.*. import java. Statement stmt. import javax. rate.out.odbc.rs2. 16.getConnection("jdbc:odbc:shop").stmt1. and quantity. ♦ Lines 161–174: This code corresponds to the above process for fashionwear.JdbcOdbcDriver"). ♦ Lines 133–146: The above process (displaying the item name. stmt1 = con.createStatement(). and quantity. ResultSet rs. 22. This has to be posted in the database for later processing of the order. rate. ♦ Lines 352–355: All the inputs will be posted in the database.jdbc. ♦ Lines 193–216: If user selects groceries. 12.} } public void doGet(HttpServletRequest request. ♦ Lines 175–191: This code corresponds to the same process for new products.*. the WML card is generated along with fields for item name. public void init(ServletConfig sc) throws ServletException { //Connecting To the Data Base try{ Class. this card is generated with fields for item name. and quantity fields that can be input by the user is performed for groceries.*. 10. public class Order extends HttpServlet { String orderstr. 14. 20. 21. Listing 6-7 gives the Java program for saving the customer order in the database. 8.rs1.createStatement(). The items selected in the shopping cart selected by the user will be posted in the database using this code. } catch(Exception e){System.toString()). 2.io.custidstr. 17. ♦ Lines 147–160: The above process is repeated for cosmetics.servlet. 13. 7. rate and quantity fields) is repeated for accessories.http. con = DriverManager. 18. 9. ♦ Lines 341–351: If the customer ID is not valid. Listing 6-7: Java Program for Saving the Customer Order in the Database //© 2001 Dreamtech Software India Inc. import java. the process of displaying the item name. 15.sql. and the recordset will be closed. ♦ Lines 243–266: The process of card generation is repeated for cosmetics. 6. 5. import javax. 11. the message “Sorry.forName("sun. 4. Your ID Is Not Valid” is generated using this code. 23.*. ♦ Lines 218–241: If the user selects accessories in the shopping cart.*. rate. stmt = con. ♦ Lines 292–339: The card generation process is repeated for new products. 19. import java.servlet.println(e. ♦ Lines 117–132: Here. 40.wap. out. 25. and quantity for each item.println("</card>"). template. out. 30.println("</p>"). 26. 36. 41.getQueryString().println("</template>"). 48. out.xml\">").execute("insert into OrderInfo (CustomerId. OrderItemsAndQty) values ('"+custidstr+"'. out. 32.println("</wml>"). 62. . 27. 61.out. 50. 39.println("<wml>"). 55.println("</card>"). 38. out. custidstr = request. Lines 32–37 generate the necessary WML template by using the wml.out. 44.wapforum.println("</do>"). out. 37.IOException { /* Order Information is Being Saved in the DataBase */ orderstr = request. PrintWriter out = response.println("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1. 45. out.println("</wml>").122 Chapter 6: Push Technology in WAP 24.println("<prev/>").setContentType("text/vnd. /* Print Info of Order being Saved */ out.println("<card id='card1' title='Error'>"). }catch(Exception e){ System. out. 51.println("<p>"). 31. 33. } } } Code Description ♦ Lines 1–5: To import the necessary class libraries. try{ /* Insert Details of the User into the Database */ boolean b = stmt1.getWriter().toString()). ♦ Lines 15–22: This code is to connect to the database using JDBC-ODBC connectivity.getParameter("CustId"). 59.0\"?>"). 54. out.println("<?xml version=\"1.println(e.println(e. 47. out. out. out.println("<p>"). out.toString()). ♦ Lines 23–42: The order placed by the user is saved in the database through the Servlet. 49. 34. System. 46. ordered items. 60. 35. 53. 58.1. /* Set Content-type Header */ response.1//EN\" \"http://www. out.println("Your Order Is Saved<br/>"). 42. 57. 56. /* Write the response to the User */ out. out. ♦ Lines 12–13: Function declaration.println("<template>"). 29.wml").println(" Order Information :"+orderstr). 63 64 throws ServletException.org/DTD/wml_1.println("<do type='prev' label='Back'>"). 28. out. ♦ Lines 43–46: The order is saved with details of customer ID.'"+orderstr+"')"). 52. ♦ Lines 6–11: This code is for declaration of the class and initialization of the variables.println("</p>"). out. and do tags.println("<card id='card1' title='OrderSaved'>"). 43. out. which calls this shopping cart. </anchor> 16. a WML card is generated containing the exception (Error) message. <go href="http://localhost:8080/Shopping/servlet/ShopingCart" method="get"> 13. ♦ Line 11: To obtain the customer ID through an input tag. <!-Link to Shopping Cart Servlet When you Click Order -. <card id="card1" title="Virtual Mall"> 5. Hello Customer 7. card. <postfield name="CustId" value="$(CId)"/> 14. ♦ Lines 5–8: To welcome the customer with a Hello Customer message. the ID must be obtained by the card. and wml.1. ♦ Line 15: To take the customer ID and assign it to a variable CId. </p> 17. ♦ Line 9: To prompt the customer to enter the security number. “Hello customer. having a welcome message that says. <?xml version="1. The shopping cart and order placement is done through a servlet. ♦ Lines 3–4: The familiar WML and card tags with the card titled Virtual Mall. . <p> 6. enter your security ID to order items. <input name="CId" type="text"/> Then Select Order Option 10. and the customer ID has to be posted on the server. <wml> 4.org/DTD/wml_1. <anchor title="Orders">Order 12. </card> 18.” When the user enters the ID. ♦ Lines 16–18: Closing tags for p. Now we need a small WML code. </go> 15. the servlet ShoppingCart has to be invoked. ♦ Lines12–14: To invoke the servlet by using the anchor tag.” ♦ Lines 54–64: This code is to take care of any exceptions.wapforum.0"?> 2.> 11. Listing 6-8: WML Code for Calling the Shopping Cart Servlet and Placing the Order //© 2001 Dreamtech Software India Inc. This is a simple program with just one card with the title Virtual Mall.xml"> 3. which is used to confirm to the user that his order is saved with the message: “Your Order Is Saved.Chapter 6: Push Technology in WAP 123 ♦ Lines 48–53: A WML card is generated. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. Listing 6-8 provides the WML code for calling the shopping cart servlet and placing the order. Cid is a variable that contains the customer ID. <br/> 9. <br/> Enter Your Security ID To Purchase Order 8. //All Rights Reserved 1. </wml> Code Description ♦ Lines 1–2: The header for the WML card giving the Document Type Definition.1//EN" "http://www. The Item name and Price are displayed. This invokes the servlet for the shopping cart. Figure 6-13: Shopping cart displayed on the WAP Phone . You can enhance the application shown here to take care of payment — it can be done through a credit card or by transferring money from a bank account. The WML code shown in Listing 6-8 executes first and appears on the handset. and a field for entering quantity is available for the user. Figure 6-12: Virtual mall entry screen for user to input the security ID The user has to enter the security ID (or the customer ID) and select an order. as shown in Figure 6-15. This example shows the power of mobile commerce and mobile advertisements. The operators and content providers can use the WAP push technology to create simple but useful applications for mcommerce. which causes the display to appear as shown in Figure 6-14. the shopping cart appears on the handset in Figure 6-13. The user can input the quantity and go back to the previous menu and select the Order option. The user can select a category. The entry screen for the virtual mall is shown in Figure 6-12. The order is saved in the database and the user sees the Order Saved screen.124 Chapter 6: Push Technology in WAP The procedure for executing this program is exactly same as that of the preceding example. To periodically obtain content from the Internet without making a request every time is a very attractive option to users. we still need to download items by connecting to the Internet. Think of a situation where you walk into a music store with your handset. Push technology is still in a nascent stage. This sort of thing is a possibility with the help of WAP technology. the commercial WAP servers that support push applications are just being released. . pushing the newsletters that you subscribe to). On the other hand. the push framework is more attractive for the mobile devices because they are always on. Imagine that a server in the store can display the latest titles and specials on your handset. and the advertisements can be pushed without the user explicitly getting connected to the Net. But proponents of push technology say that it is the market pull rather than technology push that is driving the WAP push framework. The impact of push technology on users and whether users will really utilize the technology is yet to be seen.2.Chapter 6: Push Technology in WAP 125 Figure 6-14: Selection of Item and Quantity Figure 6-15: Order saving confirmation Pros and Cons of Push Framework Push framework has been defined in WAP version 1. Although the Internet supports push in a limited way (for example. Push technology in WAP holds great promise both for the user and the operator. we studied push technology in the WAP environment. is used for communication between the Push Proxy Gateway and the Push Initiator. and code for two applications — pushing stock quotes and mobile cart integrated with m-advertising — have been presented. betting odds. The Push Proxy Gateway bridges the wireless network domain and the Internet domain to push the content from the Push Initiator to the handset. by using the special protocols defined for the push services (Push Access Protocol and Push Over The Air Protocol). The user is freed from the burden of making requests every time she wants to get the information — whether it’s stock quotes. Development of push applications has been discussed in detail. The WAP push services can be provided through the SMS bearer. is used for communication between the Push Proxy Gateway and the handset. Push Over The Air Protocol. The operator has a great potential for revenue. as m-advertising promises to be very lucrative. cricket scores. Alternatively. which puts a limitation of 160 characters for each message.126 Chapter 6: Push Technology in WAP Summary In this chapter. or astrological predictions for the day. Push Access Protocol. . innovative services can be provided to the user. which uses the HTTP protocol. which runs above the Wireless Session Protocol. consequently. reliable radio. Bluetooth will replace cable connections because it’s as cheap. HomeRF. every office and every home will have Bluetooth-enabled devices. Many Bluetooth-enabled devices operate through a battery. if not cheaper. headset. and appliances. such as a PC. and Nokia. A Bluetooth-enabled device can exchange information or transfer data with another Bluetooth- . All the headaches associated with administering such networks can be avoided if these devices are made to communicate through radio links and if one device can discover the presence and capabilities of other devices. but the current cost of making a Bluetooth-enabled device is high. Introduction to Personal Area Networks (PANs) A typical office is equipped with a number of electronic gadgets. interoperate. Bluetooth is likely to be one of the most popular technologies for wireless personal area networking. more reliability. and every electronic device can become Bluetoothenabled. and better appearance. These devices are interconnected through wires for the purpose of using a service (a print service) or for sharing information (transferring a file from a desktop to a laptop) — they form a Personal Area Network (PAN). we study the Bluetooth technology with an emphasis on protocols that enable you to develop Bluetooth applications. therefore. a $5 Bluetooth solution is expected. In the coming years. It uses radio as the transmission medium to avoid wire connections. Bluetooth Special Interest Group (SIG) was founded in February 1998 by Ericsson. Of these technology standards. Intel. and IEEE 802. Interconnecting these devices without wires through radio offers tremendous advantages in terms of less maintenance. Bluetooth is considered the most attractive choice. peripherals. at homes. IBM.11. Bluetooth devices made by different manufacturers can. or cordless phone can become Bluetooth-enabled by means of an attached module that contains the hardware and software for running the Bluetooth protocols. Many manufacturers have come out with Bluetooth hardware and software. laptop. the power consumption to make the device communicate over radio is very low — hence. digital camera. Overview of Bluetooth Bluetooth technology is a low-cost. Bluetooth specification version 1. the range is very short.0 was released in July 1999 and version 1. Because of all these features. and so on. they change dynamically. modem. however. In this chapter. than the cable. A PAN is an ad hoc network because the topology and the number of nodes at any time are not fixed.Chapter 7 Bluetooth: A Basic Introduction Due to the widespread use of computers and other electronic gadgets. and in cars. every office and home is now a labyrinth of wires that connect computers.1 in February 2001. notably Bluetooth. the radio should emanate low power. radio technology open standard for development of personal area networks (PANs). fax machine. Over the next few years. Toshiba. A number of technologies have been proposed for PANs. Bluetooth provides a solution by interconnecting devices through low-cost. short-range. IrDA. The need for PANs is everywhere — in offices. low-power. printer. typically about 10 meters. It is based on open standards — standards framed by an industry consortium. Because Bluetooth helps in creating a small network of devices that are close to one another. thereby paving the way for competition and lowered costs. A device such as a PC. This situation can create a lot of maintenance problems. 128 Chapter 7: Bluetooth: A Basic Introduction enabled device over a radio. It’s estimated that by 2002. the microwave oven will flash a message on the TV indicating that it’s time to eat. and send the fax. and cars. Just as with the PAN in the office. When dinner is done. The headset doesn’t need to be connected to the mobile phone through a wire to answer a call received on the phone. The user can synchronize the appointments stored in the laptop and mobile phone and ensure that both contain the same set of appointments for the next day. the laptop will discover the presence of the fax machine. The user can bring his digital camera and download the picture on to the desktop and create a printout without connecting any cable. . Bluetooth in the Office As shown in Figure 7-1. the laptop will know that fax service is not available. and refrigerators ♦ Set top boxes and Web TVs ♦ Point of sale terminals and ATMs Because Bluetooth is a nascent technology. (Despite all the conveniences that Bluetooth affords. more and more devices will be Bluetoothenabled. As the technology matures and demand picks up. tired after a hard day’s work. nearly 100 million mobile phones will be Bluetooth-enabled. This is a typical Bluetooth office scenario. Bluetooth in the Home Consider the PAN in the home shown in Figure 7-2. offices. the cost of making a device Bluetooth-enabled is currently quite high. but this is just one example of the advantages of wireless networking in the home. you still need to eat dinner with your own hands!) Perhaps this Bluetooth scenario has the potential of making you a couch potato. Consider the following example. establish a connection. If the user wants to send a fax. all the devices in an office can form an ad hoc network whenever they come together. various devices can communicate with one another by using Bluetooth radio. Any electronic device that needs to communicate with another electronic device can be Bluetoothenabled. which illustrates the potential of this technology: When you go home. Bluetooth-enabled devices will be common in homes. Such devices include ♦ Desktop PCs ♦ Laptops and Personal Digital Assistants ♦ Keyboard and mouse ♦ Mobile phones and two-way pagers ♦ Cordless phones ♦ Fax machines and scanners ♦ Overhead and LCD projectors ♦ Headsets and loud speakers ♦ Televisions and music systems ♦ LAN access points ♦ Domestic appliances such as microwave ovens. washing machines. you can put dinner in the microwave oven and relax in your living room while watching the TV. If the fax machine isn’t working. such as a sound system. and headset. If the car has a navigation system with a GPS (Global Positioning System) receiver. can be made to communicate with each other through Bluetooth. A person can hear the music emanating from the music system through the headphones.Chapter 7: Bluetooth: A Basic Introduction 129 Figure 7-1: PAN in an office Figure 7-2: PAN at home Bluetooth in the Car The various gadgets in a car. . mobile phone. Someone sitting in the back seat can compose e-mail on the laptop and send the mail through the mobile phone without physically connecting the two. the devices in the car will form a PAN or a personal operating space. again without a wired connection. it can send the instructions to the driver on the headset without wires. laptop. As shown in Figure 7-3. Class 2 devices transmit 10 mW and the range is 50 meters. In normal radio communication systems. Services Supported Bluetooth supports both voice and data services. and the receiving device has to automatically tune to the changed frequency to receive the data. the second packet in another frequency. but the advantage of frequency hopping is that the communication link is secure — unless the receiver knows the hopping sequence. every Bluetooth device transmits in this frequency band. In Bluetooth specifications. The link established between devices for voice communication is an Synchronous Connection Oriented (SCO) link. The range is dependent on the power of the radio transmitter — the higher the power. both types of connections are supported in Bluetooth. using the 79 frequencies that are available in the band. the transmitting device sends the data using only one frequency. you’re going to take a look at the broad specifications of a Bluetooth system. . the higher the range. Bluetooth System Specifications The specifications of the Bluetooth system are discussed in the following sections. In frequency hopping.5 MHz. So. three classes of devices are defined. the Bluetooth radio transmits the first packet by using one frequency. and they can have a range of 100 meters. Operating Range The normal operating range of Bluetooth is 10 meters (the devices that form the network should be within a radius of 10 meters). Bluetooth radio uses frequency hopping — the frequency of transmission changes for every packet. Operating Frequency The Bluetooth operating frequency is 2400 – 2483. The band consists of 79 channels. there is a hop sequence where the transmitting device changes the frequency. Class 3 devices transmit 1mW and have a range of 10 meters. and so on. Class 1 devices transmit a maximum of 100 mW. This certainly creates complexity in the design of the radio. each of 1-MHz bandwidth. and the link established for data communication is an Asynchronous Connection Less (ACL) link. Most of the commercially available devices have a transmitting power of 1 mW and a range of 10 meters.130 Chapter 7: Bluetooth: A Basic Introduction Figure 7-3: PAN in a car Now that you’ve seen some of the typical applications of the Bluetooth technology. it cannot receive the data. Because voice communication is done in circuitswitching mode and data communication in packet-switching mode. which the receiving device is tuned to. and mobile phones. IrDA-based products. can be a master or a slave to a desktop. two types of channels are possible. 64 Kbps data rate is supported in both directions. The master decides the hop-frequency sequence. though data rates are higher.6 Kbps in the other direction.2 Kbps in one direction and 57. the data rates are different in the two directions — 723. A cellular phone. bank ATMs. ♦ To activate home appliances through cordless telephones. In a symmetric channel. and IEEE 802. For voice communication. which all other devices (called slaves) tune to. Bluetooth versus HomeRF HomeRF is another radio technology for home-networking of computers and peripherals and is Bluetooth’s strongest competitor. the communication is point-to-multipoint. and so on. The main disadvantage of IrDA is that infrared rays cannot penetrate walls. The IR communication can be implemented in PDAs. The directed IR systems allow one-to-one communication in point-to-point mode and are not subject to regulations. for communication with other devices within a range of 1 meter. with one acting as master and one as slave.irda. Serial IR (SIR) supports data rates up to 115 Kbps and Fast IR (FIR) supports data rates upto 4 Mbps. Bluetooth versus Other Technologies You can choose from a number of technologies to develop a small network. for example. the communication is called point-to-point communication. 433. Another drawback of IrDA is that it supports only data services. You study the detailed architecture of a Bluetooth system later in the chapter. Network Topology In a PAN. a set of devices forms a piconet (a small network). with one acting as master and others as slaves.11 Wireless Local Area Network (LAN) standards formulated by Institute of Electrical and Electronics Engineers (IEEE). Users having high-tech homes with multiple PCs and peripherals would like having a low-cost solution to network the PCs and peripherals for applications such as the following: ♦ To transfer a file from a laptop to a desktop without connecting the two with wires. For asynchronous links. Bluetooth versus IrDA The Infrared Data Association (http://www. Bluetooth is better than IrDA in this regard. HomeRF formulated by HomeRF group. because radio frequencies can do so. If more than two devices communicate with one another. a maximum of seven slaves can actively communicate with the master. keyboards. In a piconet.Chapter 7: Bluetooth: A Basic Introduction 131 Data Rates The Bluetooth device can support one asynchronous channel and up to three synchronous voice channels. are now commercially available. . If two devices in a piconet communicate with each other. fax machines. cameras. Any device can become a master — the master/slave terminology is only to define the protocols. and the slaves synchronize with the master to establish links. ♦ To allow multiple PCs to share the same modem and telephone line for high-speed Internet connectivity. In an asymmetric channel. there is one master.9 Kbps data rate is supported in both directions. These include IrDA standards formulated by InfraRed Data Association. In each piconet. IrDA systems support only point-to-point communication.org) was founded in 1993 to develop standards for low-cost solutions for point-to-point infrared (IR) communication. which include laptops. printers. overhead projectors. These are the broad specifications of the Bluetooth system. which ensure that all vendors interpret and implement the same set of features in their devices. The 802. Shared Wireless Access Protocol (SWAP). backyard. Its main attractions are higher data rate support than Bluetooth and support for a higher number of devices. sponsored by HomeRF working group www. Both HomeRF and Bluetooth operate in the same frequency band and use frequency-hopping technique. The two standards that have been proposed for wireless home networks are 802. HomeRF is a definite competitor to Bluetooth in home networking space.11b standard is sponsored by the Wireless Ethernet Compatibility Association (WECA) for the wireless networking of home devices. The network ID.11 Wireless LAN IEEE developed the wireless LAN standards through the 802. it’s cost that decides the large deployment of the technologies. and easier maintenance.homerf. 1. provides low-cost solutions to home-networking needs. Though wired networks based on standards (such as IEEE 1394) are available.11 committee. It uses Direct Sequence Spread Spectrum (DSSS) for medium access.8 Mbps (data rates are likely to be increased up to 20 Mbps in the future versions of the standard) ♦ Access: Frequency-Hopping Spread Spectrum with 50 hops per second Each network is given a 48-bit ID. The broad specifications of this standard are: ♦ Range: Up to 150 feet (covering a home. To ensure that the devices supplied by different vendors can work together (interoperability). Bluetooth SIG released the Bluetooth profiles. and the 128-bit data encryption provide the necessary security for the network and the data. These profiles are . no need for cables. Another drawback of the systems based on this standard is that its support for voice over IP (Internet Protocol) is limited. This standard supports 10 to 100 access points with a data rate of 11 Mbps. and all these technologies may coexist. The wireless LANs based on the IEEE 802. Ultimately. wireless home networks are certainly more attractive because of fast installation. A number of technologies are available to meet the needs of personal and home-networking by using radio. The current networks based on this standard are costlier than HomeRF and Bluetooth. frequency hopping. Each technology meets the needs of a specific segment of the user community. ♦ To forward calls to different cordless handsets.132 Chapter 7: Bluetooth: A Basic Introduction ♦ To download music from the Internet on to the PC and listen to the music through a headset. but without connecting the PC to the headset through wires. Installing multiple networks in multi-storied apartments causes interference — unless the radio base stations are installed at carefully chosen places. and garage. whereas HomeRF can provide better voice over IP support. Home networks are now gaining popularity to support such services. as compared to the number of active devices in the piconet of Bluetooth. 0. Bluetooth versus 802.11 standard have become popular and have a large installation base. Commercial Bluetooth Solutions Because of the great business potential in Bluetooth technology. so concurrent operation of multiple coallocated networks is possible.6 Mbps.4 GHz (ISM band) ♦ Transmit power: 100 mW ♦ Speed: 10 Mbps peak data rate with fall back mode to 5 Mbps.org/. many equipment manufacturers are introducing a variety of Bluetooth-enabled devices.11b (covered in the next section) and SWAP by HomeRF. if the home is not a mansion) ♦ Number of devices: Up to 127 per network ♦ Frequency band: 2. HomeRF certainly meets the requirements of home networking. The Bluetooth-enabled base station acts as a gateway to the telephone network so that the handset can be used to make telephone calls through a normal telephone network. ♦ Bluetooth desktop/note book PCs: A desktop PC can be Bluetooth-enabled by connecting the Bluetooth module to the USB port and running the software module in the desktop.1. thereby allowing for presentations without wires. PDA. such as headphones.1. ♦ Bluetooth LAN access point: The LAN access point integrates Bluetooth-enabled computing and communication devices into a wireless network. cordless phones. ♦ Dial-up networking profile: To access the cellular network from a PC through a mobile phone. . A Bluetooth-enabled desktop/note book PC can receive dial-up connectivity through the base station. ♦ Headset profile: For devices such as a mobile phone and a desktop PC to connect to a headset. ♦ Service discovery application profile: Procedures for a device to discover the services available on other devices. ♦ File transfer profile: To transfer files from one device to another. ♦ Serial communication profile: For two devices (two laptops) to communicate with each other through serial communication. These phone solutions are compliant with Bluetooth cordless telephony/intercom profile version 1. ♦ Bluetooth LCD projector: An LCD projector can obtain the data from a notebook PC over the Bluetooth radio link. and LAN access points. Other designs include a compact flash card with an adapter module that can be plugged into the notebook PC or other handheld devices and a PCMCIA card with Bluetooth hardware integrated into it.1: ♦ Generic access profile: Generic procedures to discover Bluetooth devices and establishing connections with other devices and security aspects. or to access a fixed network from a PC through a line modem. ♦ Bluetooth speakers: Home stereo systems can be connected to speakers over the radio link by making the speakers Bluetooth-enabled. This solution is compliant to LAN access profile version 1. These headsets are compliant with headset profile version 1. Bluetooth SIG released the Bluetooth profiles. These devices should have low power consumption and be lightweight.1. and the associated software can be loaded in the system. or desktop/notebook PC. ♦ Synchronization profile: To synchronize objects (such as appointments) in different systems such as a notebook PC and cellular phone. It can also provide connectivity between existing LANs and Bluetooth-enabled wireless networks. The following are some of the commercial Bluetooth solutions available: ♦ Bluetooth headset: The headset provides a wireless connectivity to the cellular phone. The following profiles are presently defined in version 1. ♦ LAN access profile: To access a LAN from a Bluetooth-enabled device (such as PC). ♦ Cordless telephony profile: To make use of a cellular phone to access a fixed telephone network. To ensure that different vendors implement the same set of features so that devices are compatible. an add-on card can be plugged into the PC. ♦ Intercom profile: For cordless phones. desktop phone.Chapter 7: Bluetooth: A Basic Introduction 133 defined for a variety of devices. Alternatively. ♦ Object push profile: To push an object (such as an electronic business card) from a cellular phone to another cellular phone. Two handsets can communicate with each other over the Bluetooth link. ♦ Fax profile: To send a fax message from a PC through a cellular phone. ♦ Bluetooth cordless phone: This consists of a Bluetooth cordless handset and a base station. . Network of Bluetooth Devices: Piconet and Scatternet The network formed by a set of Bluetooth devices is called a piconet. a piconet is a small network with two or more devices sharing the same channel. as shown in Figure 7-4. The slaves in the parked mode are locked to the master: They cannot be active on the channel. Formally defined.134 Chapter 7: Bluetooth: A Basic Introduction Note that these profiles specify the features that have to be implemented in various devices to make them Bluetooth-enabled. The master controls the channel access. there’s no acknowledgement or indication that the packet is received with errors. however. but a master of one piconet can be a slave in another piconet. as shown in Figure 7-5. and many more can be in the parked state. In the part of the figure marked a). A piconet can support two types of communication. In broadcast mode. Each piconet has its own frequency-hopping sequence. Each piconet will have a master. the master’s and slave’s frequency and time must be synchronized. Figure 7-4: Bluetooth piconet To communicate. a piconet has one master and one slave. If a packet is received with errors. but they are synchronized to the master. The data is divided into packets and sent over the radio channel. The slave should know in which frequency the master is transmitting and tune to that frequency. wherein two devices can exchange data by using packet transmission. the master can communicate with all the slaves. The profiles help the developers in ensuring that the same sets of features are implemented. In a point-to-multipoint configuration. there’s a device called a master. In a piconet. The receiving device acknowledges the packet or reports that the packet is received in error. several Bluetooth devices share a channel. The slave should also know the time of the packet transmission. so that there’s no interference between two piconets. In this case. Data and Voice Support Bluetooth supports data services such as file transfer. The master must then indicate to the slaves how many times a broadcast packet will be transmitted so that every slave will receive the packet without errors at least once. up to seven slaves can be active. It’s also possible to broadcast packets to all the slaves. so it’s a point-to-multipoint communication. the packet is retransmitted. In a piconet. a piconet has one master and a number of slaves. A master and slave can switch roles — the slave can become a master and the master can become a slave. In this case. In b). so it’s a point-to-point communication. only these two devices are involved in communication. and a number of other devices called slaves. Multiple piconets with overlapping coverage form a scatternet. and a Link Manager. which can be a laptop. ♦ Every Bluetooth device has a random number generator. and Continuously Variable Slope Delta Modulation (CVSD) technique. ♦ Data on the channel is encrypted so that only the intended recipients can receive it. Figure 7-5: Bluetooth scatternet Security Issues in Bluetooth A radio system is generally considered to be prone to attacks because anyone can have a radio receiver tuned to the transmitter frequency and receive the data. Every Bluetooth device on earth will have a unique address.711 standards. which is a coding technique to convert analog voice signal into 64-Kbps format based on G. ♦ A frequency-hopping scheme provides built-in security — only those devices that know the hopping sequence can decode the data sent by the master. the second device is authenticated. these numbers are used for authentication. and so on.Chapter 7: Bluetooth: A Basic Introduction 135 In the case of voice. The following sections describe each of these modules. Voice packets are not retransmitted. Architecture of a Bluetooth System Figure 7-6 shows a Bluetooth module consisting of a Radio. a mobile device. the first requirement is to convert the voice (which is an analog signal) into digital format. The module consisting of these three blocks is interfaced to the host. Two types of voice coding techniques are used: Pulse Code Modulation (PCM). Bluetooth is a highly secure system for the following reasons: ♦ Every Bluetooth device is given a 48-bit address that uniquely identifies the device. a Link Controller. which also converts the voice into 64Kbps data rate. ♦ When one device wants to communicate with another device. . The radio operates in frequency-hopping mode — each packet is transmitted in a different frequency. and 10 meters. The minimum distance between two Bluetooth devices should be 10 centimeters.25 mW 3 1 mW -- Based on the power radiated. Information is exchanged between Bluetooth devices in the form of packets.5 mW 0.5 MHz. only one frequency is used for communication in both directions. .4 GHz ISM (Industrial. which is received by the other device.5 MHz. In TDD. If a packet extends more than one slot. Nominal frequency-hop rate is 1600 hops per second. During one time slot. the slave sends the packets in odd numbered slots. a lower-guard band of 2 MHz. Normally. Table 7-1: Power Classes Power Class Maximum Output Power Minimum Output Power 1 100 mW 1 mW 2 2. in the next time slot. There are 79 RF channels with a channel spacing of 1 MHz. one device will send the data. Time slot Each time slot has a duration of 625 microseconds. but can extend to up to five slots. Three power classes are defined based on the power radiated by the Bluetooth radio. Each piconet has a different frequency-hop sequence. and each slave synchronizes with the master in a piconet. The frequency spectrum allocated is in the range 2000 to 2483. This is known as Frequency Division Duplex (FDD).136 Chapter 7: Bluetooth: A Basic Introduction Figure 7-6: Functional block diagram of a Bluetooth module Radio Hardware Bluetooth radio operates in the 2. respectively. The master starts the transmission in even slots by sending a packet addressed to a slave. In other words. the other device will send the data. The master decides the hop sequence. the range of the Bluetooth device can be 100 meters. and each packet is transmitted in a different frequency. Each packet is normally transmitted in a slot of 625 microseconds. two frequencies are used — one frequency in each direction. The radio receive must be designed so that the Bit Error Rate (BER) of minimum 0. A packet generally occupies one time slot. Gaussian Frequency Shift Keying (GFSK) is used as the modulation technique. though some packets can extend upto five slots. the radio should provide a link that ensures that there won’t be more than one error for every 1000 bits sent. Table 7-1 shows the various power classes and the radiated power. To achieve full-duplex communication between the master and slaves. A positive frequency deviation represents 1 and a negative frequency deviation represents 0. and thus security is built-in. in the radio communication systems. 50 meters. the hop frequency will be the same for the entire packet. The guard bands ensure that there will be no interference with radio equipment operating in the adjacent frequency bands.1% is ensured. These slots are numbered from 0 to (227)–1. Link Controller A link controller carries out baseband protocols and other low-level link routines. Scientific and Medical) band. a Time Division Duplex (TDD) scheme is used. and an upper-guard band of 3. To respond to an inquiry. the device will start listening to traffic again. Figure 7-7: Communication between master and slave States of a Bluetooth device A Bluetooth device can be in one of the two major states: connection state and standby state. In hold mode. After paging of devices is complete. master response.” The device doesn’t need to listen to all the packets. the device enters the inquiry response state. the master transmits in slot to the slave using frequency f1. the master and slave establish a connection in active state. When a device wants to get connected to another device. After the expiration of the specific time. sniff. a slave will be given an instruction such as “listen starting with slot number S every T slots for a period of N slots. The connection can be in park mode. In connection state. the master transmits in slot 2 using frequency f3. When the inquiry is successfully completed. When the device pages for the device. In sniff mode. the devices should periodically enter into inquiry scan state. and the master enters the master response state. inquiry. it enters the page state to page for another device. The connection can also be put in one of the three modes: hold. it enters the slave response state. A typical procedure for setting up a Bluetooth link is as follows: . or park. the slave transmits to the master in slot 1 using frequency f2. the device will stop receiving the data traffic for a specific amount of time so that other devices in the piconet can use the bandwidth. There can be seven substates: page. and inquiry response. page scan. In standby state. an application program in a Bluetooth device can enter the inquiry state to find out about other devices in the vicinity. the other device may respond.Chapter 7: Bluetooth: A Basic Introduction 137 The single packet transmission is shown in Figure 7-7. the device is communicating with another device by exchanging packets. The command for this paging has to come from an application program running on this Bluetooth device. inquiry scan. the device would become the master and page for other devices. To start. which are the sniff parameters. In this figure. slave response. and so on. After the device receives the page-scan packet. but only as specified through the preceding parameters. wherein the device only listens to a beacon signal from the master occasionally. In this state. Devices should enter the page scan state periodically to check whether other devices are paging for it. the device is not communicating with another device and will be in low-power mode to save battery power. This is the default state. during which the packet transmission takes place. it synchronizes with the master but has no data transmission. The selected device. All packets in a piconet will have the same access code. a header (54 bits).9 Kbps symmetric data rate. ACL links provide point-to-multipoint communication between the master and all the slaves that participate in the piconet environment. Figure 7-8: Bluetooth packet format An access code is used for synchronization and identification of devices in a piconet. or an access code. Packets not addressed to any slave are broadcast packets.6 Kbps in the reverse link) or 433. This packet contains the information needed to connect to it. the voice packets need to be exchanged between the master and the slave continuously. For voice communication. 4. an access code and header.138 Chapter 7: Bluetooth: A Basic Introduction 1. The device sends an inquiry using a special inquiry-hopping sequence. An access code is used for paging and inquiry procedures. Only one ACL link can exist between master and the slaves. The inquiring device requests a connection to the device that responded to the inquiry. Inquiry scanning devices respond to the inquiry by sending a packet. SCO packets are never retransmitted. An asynchronous channel can support a maximum of 723. ACL is a packet-switched connection between the master and all the slaves for data communication. If the responding device accesses the connection. Packet retransmission is done in ACL links in case of packet loss. The packet consists of an access code (68 or 72 bits). ♦ Device Access Code (DAC): This code is used for paging and response to paging. which has entered the page scan state. . 5. responds to the page. Paging is used to initiate the connection with the selected device. After voice connection is established. A master can support up to three SCO links. Packets can contain only an access code (a shortened access code with 68 bits only). it uses a combination of circuit switching and packet switching. and a payload (0 to 2745 bits). Voice channels support 64 Kbps in each direction. If a master sends a packet addressed to a slave. such as voice —packet delays are unacceptable (they can cause breaks in the voice). 3. Bluetooth can support an asynchronous channel and up to three synchronous voice channels. which are received by all the slaves. Note that SCO links are mainly for applications that are time-critical. it synchronizes with the master’s timing and frequency hopping sequence. The packet format is shown in Figure 7-8. 2.2 Kbps asymmetric (and upto 57. SCO links are for point-topoint communication between master and slave. no header or payload is required because only signaling information is carried. Synchronous Connection Oriented (SCO) channel is used. header. all packets in a piconet contain this code. and a slave can support three SCO links from one master or two SCO links if the links are from different masters in a scatternet environment. Voice and data connections Because Bluetooth supports both voice and data. and for data communication Asynchronous Connection Less (ACL) channel is used. in such cases. There are three types of access codes: ♦ Channel Access Code (CAC): Identifies a piconet. 6. the slave can send its packet to the master in the next slot. SCO links are like circuit-switched connections for voice communication. Slots then can be reserved for synchronous packets. and payload. and to take care of the device’s different states. To summarize. Out of these. and Non-Significant Address Part with 16 bits. if required. . ♦ 8 bits for Header Error Control for error checking. rate 1/3 FEC is used to make it 54 bits by repeating each bit three times. ♦ 4 bits for type code (SCO link. the link controller does a lot of work — to establish the link based on the type of service required (voice or data). This field contains the user information. Upper Address Part (UAP) with 8 bits. ♦ 1 bit for sequence number (for each packet. so only seven active devices can be in a piconet. this address is referred to as BT ADDR. each bit is repeated three times to help in error correction at the receiving end if there are transmission errors. In literature dealing with Bluetooth. the master can make them active for exchange of packets. Bluetooth addressing Each Bluetooth module (the radio transceiver) is given a 48-bit address containing three fields: LAP (Lower Address Part) with 24 bits. or ACL link. Parked member address is either the BT ADDR of 48 bits or an 8 bit parked member address denoted by PM ADDR. which limits the number of addresses in a piconet to eight. 1 bit for acknowledgement indication (1 indicates that packet is okay. In 1/3 FEC. The addressing format is shown in Figure 7-9. This address is unique to each Bluetooth device. In addition to the maximum of seven active members.Chapter 7: Bluetooth: A Basic Introduction 139 ♦ Inquiry Access Code (IAC): General IAC is used to discover which Bluetooth devices are in range. 0 for stop and 1 to go). A packet header is 54 bits long and breaks down as follows: 3 bits for active member address (all zeros for broadcast) ♦ 3 bits for active member addresses. 0 indicates packet in error). The parked members also need to have addresses so that. 1 bit for flow control (if buffer is full. You’re then left with seven addresses. Only those devices can be discovered. These bits total 18 bits. which can be either data or voice. many more devices can be in parked mode. Figure 7-9: Format of Bluetooth address Each active member in a piconet will have a 3-bit address. Note that three bits are allocated for active member address. this bit is reversed). Dedicated IAC is common for devices with a common characteristic. how many slots packet will occupy). to take care of addressing. This address is assigned by the Bluetooth module manufacturer and consists of company ID and company-assigned number. one address (all zeros) is for broadcasting the packets in a piconet. These parameters include the number of repetitions for broadcast packets. the master can ask the slaves for timing accuracy information. ♦ Switching master/slave role: The master and slave in a piconet can switch roles by using the LMP messages. The Link Manager on one device exchanges messages with the Link Manager on the other device as indicated in the figure. will be on the Bluetooth module attached to the device. The switching operation can be initiated by the master or slave. This layered architecture is shown in Figure 7-10. a packet containing a random number. ♦ Request SCO link: This is used after ACL link is established. which is a function of challenge. The various functions of the LMP are as follows: ♦ Authentication: Of the two devices that need to communicate. The claimant calculates the response. ♦ Encryption: The master sends a key to all the slaves with which the data is encrypted through an LMP message. delay. ♦ Link supervision: This is used to monitor a link when the device goes out of range (through a time-out mechanism) ♦ Connection establishment: When a device responds to the paging message. connection establishment is done through the LMP messages. control information is sent using the LMP messages. ♦ Power control: This requests the transmission of less power. one is a verifier and the other is a claimant. ♦ Clock offset request: To synchronize the clocks between the master and slave is a must for proper data exchange. The three layers. mainly to save power. This is useful particularly for Class 1 devices. ♦ LMP version: A version of the LMP protocol is exchanged to ensure that both devices use the same set of protocols and understand each other’s messages. and sends the response along with its Bluetooth address (48-bit address) and secret key. which is called a challenge. . and a Link Manager. ♦ Quality of Service (QoS) parameters exchange: In applications that require a good quality transmission link. quality of service parameters can be specified. ♦ Timing accuracy information request: To ensure synchronization. a Link Controller. and bandwidth allocation. ♦ Multi-slot packet control: When data has to be sent in more than one slot. ♦ Name request: Each device can be given a user-friendly name having a maximum of 248 bits in ASCII format. are not propagated to higher layers. LMP messages are sent as single-slot packets with a header of one byte. to make a request SCO link. This is known as a challenge response scheme — you throw a challenge and check whether the other device can correctly respond to that challenge. These messages. ♦ Detach: Messages exchanged to close a connection. The verifier sends a message. ♦ Hold mode: This is used to place an ACL link in hold for a specified time when there is no data to send. RF. If the clock has to be offset. Link messages have higher priority to data. A device can request the name through an LMP message and obtain the response. the LMP exchanges messages to ensure clock synchronization. ♦ Park mode: This is used to be in synchronization with the master but not participate in data exchange.140 Chapter 7: Bluetooth: A Basic Introduction Link Manager Protocol The Link Manager Protocol (LMP) is used to set up and control links. ♦ Request and response features of LMP: Request and response packets are used to obtain the LMP features supported by the Bluetooth devices. known as LMP messages. which are capable of transmitting 100 mW power. you need other protocols. The complete Bluetooth protocol architecture is shown in Figure 7-11. For voice connection. Therefore. When one PC wants to initiate the chat session. The signaling information is exchanged through ACL links and the voice through SCO links. We study these protocols in detail in the following sections. . and then transfer the data. the Bluetooth protocol stack has to discover the other Bluetooth PC. But to ensure that the whole application runs as per user requirements. establish an ACL connection.Chapter 7: Bluetooth: A Basic Introduction 141 Figure 7-10: Layered architecture for Bluetooth module As mentioned earlier. you need quite a few protocols to handle the voice and data applications. the Bluetooth device will implement these three layers in a hardware/firmware combination. there should be a chat application program running on each of these PCs. first the signaling information has to be transmitted and then the voice information. These layers ensure establishment of a connection and management of the connection for transfer of voice or data. Consider the case of establishing a voice connection between two devices. To start. Figure 7-11: Bluetooth protocol architecture Consider a scenario where two Bluetooth-enabled PCs want to enter a chat session. Large L2CAP packets are segmented into small baseband packets and sent to the baseband. ♦ The details of services such as classes of services and the attributes of services. L2CAP layer sends connection request and QoS request messages from the application programs through the higher layers. connect confirmation pending. time out indication. the application software running on the client machine initiates the request and the SDP client sends an SDP request to the server (the device that can provide the required service). Service Discovery Protocol The Service Discovery Protocol (SDP) provides the Bluetooth environment with the capability to develop ad hoc networks. The operation of SDP is depicted in Figure 7-12. The functions of L2CAP layer are the following: ♦ Protocol multiplexing: In the protocol stack shown in Figure 7-11. it’s assumed that an ACL link is already established between two devices. above L2CAP. Note that the server and the client can be either of the two devices — the server is the device that can provide the service being requested by the client. ♦ Services to be discovered based on class of services (such as a print service). This is protocol multiplexing. . This protocol is used for location of services provided by or available through a Bluetooth device. cellular phones. and quality of service violation indication. The responses can be the following: connection indication. disconnect confirmation. ♦ The discovery of new services when devices enter RF proximity of other devices. The SDP client and server then exchange SDP messages. L2CAP data packets can be up to 64 Kilobytes long. the small packets received from the baseband are reassembled and sent to higher layers. Similarly. It’s also assumed that ordered delivery of packets is ensured and L2CAP doesn’t do any checksum calculation. disconnection indication (from remote). The SDP facilitates the following: ♦ The client’s ability to search for the services needed by it in the piconet. connection confirmation. The L2CAP layer is only for ACL links. ♦ Quality of Service: To ensure Quality of Service (QoS). and other wireless devices. ♦ The capability to discover services on another device without consulting the third device. constraints are honored. ♦ Segmentation and reassembly: Baseband packets are limited in size. L2CAP protocol runs on hosts such as laptops. Note that L2CAP does not support SCO links for voice communication and multicasting. A packet received by L2CAP indicates which protocol is to be identified so that it’s passed to the correct higher layer. as you have seen in the packet format. When L2CAP messages are exchanged between two devices. ♦ The mechanism to find out when a service becomes unavailable because the device goes out of RF range (when there is no RF proximity). ♦ The capability to browse services. It receives the responses for these requests from the lower layers. a number of other protocols can be running. When a device wants to discover a service. connect confirmation negative.142 Chapter 7: Bluetooth: A Basic Introduction Logical Link Control and Adaptation Protocol (L2CAP) L2CAP runs above the baseband and carries out the data link layer functionality. requires a print service. 4. asking for the details of the service. Each attribute has two components — an attribute ID and an attribute value. Client sends a service attribute request. a service ID. Two devices can communicate through RFCOMM by using serial communication protocols over Bluetooth radio (see Figure 7-13). It provides the capability to discover availability and details of different services. and a service description. an icon URL (an iconic representation of the service). To achieve this. Server sends a service search response to the client indicating that two print services are provided. such as protocols to access the service. protocol descriptor list to the server. The laptop is a client looking for a print service in a Bluetooth environment. 2. a protocol description list (protocol used for using the service). A 32-bit number identifies each record for unique identification. such as a laptop. a service name. Client sends a service search request specifying the print service class ID to the Server. a provider name. The process would execute as follows: 1. These signals are: ♦ 102 for signal common ♦ 103 Transmit Data (TD) ♦ 104 Received Data (RD) ♦ 105 Request to Send (RTS) ♦ 106 Clear to Send (CTS) ♦ 107 Data Set Ready (DSR) ♦ 108 Data Terminal Ready (DTR) ♦ 109 Data Carrier Detect (DTR) ♦ 125 Ring Indicator (RI) . along with other pertinent service information. The SDP is the heart of the Bluetooth system. RFCOMM emulates the nine connections of RS 232. RFCOMM RFCOMM is a transport protocol to emulate serial communication (RS232 serial ports) over L2CAP. Suppose that a device.Chapter 7: Bluetooth: A Basic Introduction 143 Figure 7-12: Service discovery protocol The server maintains a list of service records. 3. A service record has a number of attributes. The attributes can be a service class ID list (type of service). Server sends the response to the client indicating that PostScript print service is provided. 931. Type 2 devices are part of a communication segment such as a modem. which is the standard for ISDN. you need SCO links. Type 1 devices are communication end points such as computers and printers. TCS messages are exchanged between devices in the format specified in the protocol to carry out the following functions: . SCO links are not handled by the L2CAP protocol. Figure 7-14: Type 1 and Type 2 RFCOMM devices This protocol is based on the International Telecommunications Union (ITU) standard Q.144 Chapter 7: Bluetooth: A Basic Introduction Figure 7-13: Serial port emulation through RFCOMM RFCOMM is derived from GSM specification TS 07. But L2CAP handles the signaling required for establishing voice connections through Telephony Control Protocol Specification (TCS). TCS defines call control signaling for establishing speech and data calls between Bluetooth devices and mobility management procedures. It supports two types of devices. Note that it’s not abbreviated as TCP — this stands for Transmission Control Protocol used in the Internet protocol architecture.10 for serial emulation. as shown in Figure 7-14. Telephony Control Protocol Specification (TCS) ♦ To establish voice communication between two Bluetooth devices. which is implemented in a host. as well as access to hardware status and control registers. which are sent from the module to the host ♦ Data packets. hardware status registers. Figure 7-15: Bluetooth protocol stack on a laptop HCI provides a command interface to the baseband controller and link manager. In the Bluetooth module firmware. HCI commands are implemented so that the host can access baseband commands. A Bluetooth device can have two parts: a module implementing the lower layers (LMP and below) and a software module implementing the higher layers stack (L2CAP and above). You can connect a small Bluetooth module to the USB port of the laptop and run the protocol stack on the laptop (called the host). Figure 7-15 depicts the protocol stacks that need to run on the Bluetooth module and host. and event registers. which are exchanged between the host and the module The functions of HCI are: ♦ Setting up. The Host Controller Interface (HCI) provides a uniform interface so that the two modules can be from different vendors. which are sent from the host to the module ♦ Events. control registers. HCI uses three types of packets: ♦ Commands. and configuring the links ♦ Control of baseband features such as timeouts ♦ Retrieving the module’s status information ♦ Facilitating local testing of the module by issuing a set of commands from the host. .Chapter 7: Bluetooth: A Basic Introduction 145 ♦ Call control signaling to establish and release calls ♦ Signaling information not related to a call Providing supplementary services such as calling line identification Host Control Interface (HCI) Suppose that you have a laptop computer that’s going to be Bluetooth-enabled. HCI has to reside in the Bluetooth module connected to the laptop as well as the host. Qualification testing of Bluetooth devices is also done using HCI commands. disconnecting. link manager commands. the bus driver is implemented as software. voice coding. In the host. In this figure. of the laptop). This firmware is responsible for link management to set up and manage links.146 Chapter 7: Bluetooth: A Basic Introduction Figure 7-16 shows how the Bluetooth protocol stack is implemented. the baseband controller is a hardware implementation. and UART (Universal Asynchronous Receive Transmit). and encryption. physical layer protocols such as error correction and flow control. The Bluetooth module is connected to the USB port (say. above which the HCI driver software and other higher layer protocol software are implemented. Three transport layers are defined to get HCI packets from host to the Bluetooth module: USB. The hardware consists of a Central Processing Unit (CPU) and associated firmware in which the link manager and HCI are implemented. RS 232. The functions of this module are baseband processing. The physical bus is the USB port. The HCI commands can be categorized as: ♦ Link control commands to establish piconents and scatternets ♦ Link policy commands to put devices in hold mode/sniff mode ♦ Commands to get information about the local hardware ♦ Commands to get the status parameters ♦ Commands to test the local Bluetooth module Figure 7-16: Hardware/firmware/software implementation of a Bluetooth system . a serial interface without error correction. We will study the details of the development kit and show how to develop applications later in the book. and secure communication between mobile and fixed devices. A number of devices sharing the same frequency channel form a piconet. One of these — the Bluetooth development system — is shown in Figure 7-17. and software that is run on the host computer. The APIs are in the form of function calls. Breathtaking developments are taking place in Bluetooth technology and Bluetooth will become ubiquitous in the near future. and IEEE 802.11 are available. Link Manager. low-power radio technology based on open standards. SDP. SDP. This layered architecture of Bluetooth helps in interoperable Bluetooth devices. Overlapping piconets form a scatternet.Chapter 7: Bluetooth: A Basic Introduction 147 Bluetooth APIs for Developing Applications To facilitate development of Bluetooth applications. L2CAP layer. a rich set of monitoring and debugging tools are also provided to make the development easy and fast. reliable. Though competing technologies such as HomeRF. IrDA. The development kit consists of a Bluetooth module (a printed circuit board). and ACL links for data communication. For each of the layers — HCI layer. The Host Controller Interface provides a uniform interface between a Bluetooth module and the host by defining the interface commands. L2CAP. The communication between the master and the slaves can be point-to-point communication or point-to-multipoint communication. its capability to form ad hoc Personal Area Networks. a number of vendors supply Bluetooth application development kits. which contain the Application Programming Interface (API) calls for different layers. Link Controller.4 GHz ISM band using frequency hopping. and its support for voice and data services using low-cost. SCO links are established for voice communication. RFCOMM. Voice and data services are supported. Figure 7-17: Bluetooth development system Summary This chapter laid the foundation for Bluetooth technology — the technology that enables devices to be interconnected through the radio transmission medium — which provides a low-cost. which can be connected to the USB port of the desktop or laptop. Every piconet has a master and up to seven active slaves. The Bluetooth protocol stack consists of baseband. Bluetooth operates in the 2. and TCS. Generally. Bluetooth is preferred because of its industry support. and RFCOMM — APIs are provided so that the developer can access any layer functionality to develop applications. written in ANSI C language. . Bluetooth as a WAP Bearer The WAP protocol stack runs on a “bearer” — the bearer carries the data using the necessary protocols over the physical medium to establish and maintain links for communication. To achieve this. The protocol stacks that must run on the devices to make them both WAP.Chapter 8 Using WAP with Bluetooth WAP enables mobile devices to access Internet content through a WAP server. and if the phone is on. This scenario is called the “hidden computing scenario. we can develop interesting applications. The WAP protocol stack has been developed in such a way that it can support different bearers — GSM-.and Bluetooth-enabled are described.” Forbidden message Another case of hidden computing is the “forbidden message. but you can’t send them because you aren’t allowed to use mobile phones in the aircraft. we assume that the devices are Bluetooth-enabled and also WAP-enabled. the mobile phone can obtain WAP content and present this content to the user. which is in your mailbox on the laptop. a Bluetooth link is established between the mobile phone and the laptop. This aspect is discussed in this chapter. So. After the plane lands. Bluetooth enables mobile devices to communicate with other mobile/fixed devices over a short range. we need to see what kind of applications we can implement by using WAP with Bluetooth. Bluetooth provides the physical medium and the link control for communication between a WAP server and a WAP client. however.” If you are traveling in an aircraft. We also discuss the implementation of typical applications using push technology. Application of WAP with Bluetooth Here are some typical applications of WAP with Bluetooth. if a WAP server (or a WAP proxy server) is Bluetooth-enabled and a WAP-enabled mobile phone is also Bluetooth-enabled. Before that. TDMA-. The email messages are then sent over the wireless network through te mobile phone. Briefcase trick Assume that you are waiting at the airport with your laptop tucked into your briefcase. and so forth. Bluetooth also can be one of the bearers for WAP. the laptop automatically checks for the mobile phone. We study the services provided to users by a mobile device that is both WAPenabled and Bluetooth-enabled. If both your laptop and your mobile phone are Bluetooth-enabled. . These applications demonstrate how location-dependent services can be provided to the users. or CDMAbased systems. These applications are described in the Bluetooth specifications. If devices are enabled to handle both WAP and Bluetooth protocols. we need to define the necessary protocols. you can compose e-mail messages on your laptop. In these examples. You don’t have to open the briefcase and take out your laptop. you can establish a communication between the phone and the laptop and browse through the mailbox using your mobile phone. You would like to browse through your e-mail. WAP in Bluetooth Piconet Consider a piconet in which a Bluetooth-enabled WAP server is located. When a Bluetooth-enabled WAP phone comes into the vicinity of the kiosk. connect to the WAP server. . the kiosk can push the information to the mobile phone. Mobile phone entering and leaving the Piconet. or alternatively. For example. In other words. Figure 8-1: Piconet with a WAP server. obtain content. it discovers the WAP server. the mobile phone can request information from the kiosk. For communication between the server and the mobile phone. The kiosk can be a WAP server in which the WML content resides. such as Airport Information Server). or it can be just a WAP proxy server that obtains information from an Origin server on the Internet. This is a typical example of an ad-hoc network where the mobile devices get into and out of the piconet. a kiosk at an airport can keep sending gate information to the mobile phones in its vicinity.Chapter 8: Using WAP with Bluetooth 149 WAP Smart Kiosk WAP. The SDP provides the mobile device the following information: ♦ Name of the server (a descriptive name.and Bluetooth-enabled kiosks (servers that provide information) might be located in airports to provide arrival and departure information to travelers. When the device enters the RF range of the Bluetooth-enabled WAP server by using Service Discovery Protocol (SDP). there are two possibilities: ♦ Initiation by the client ♦ Initiation by the server Initiation by the client A Bluetooth-enabled mobile device can actively listen for the availability of other Bluetooth devices in the vicinity. and so forth. A mobile device can enter the piconet. and leave the piconet. the mobile device detects the presence of the WAP server. such as in Figure 8-1. a kiosk in a shopping mall can give information about the location of different shops or new product arrivals. Because the mobile device can be a high-end device. For push applications. it fetches the content from the Origin server and sends it over the Bluetooth link to the mobile device. the content is obtained from the server by a mobile device using the pull model. the client and the server have to run the protocol stack. These devices exchange SDP messages to discover the services of each other. However. This is a small descriptive message regarding the content to be pushed (for example. if the initiation is by the server. The user can invoke the URL and access the content later through the normal mobile network. ♦ Service Discovery Protocol (SDP) locates the services provided by other Bluetooth devices. . One of the devices sends an SDP request and the other sends an SDP response. it connects to the client and pushes the message. If the server discovers a WAP-enabled device in the piconet environment. by using the information in the preceding list. and the messages exchanged between the Bluetooth modules are not passed to the higher layers. the WAP server sends the SDP request to the mobile device and obtains the response. ♦ Server capabilities (whether the server provides the content or it is just a proxy server that obtains information from some other server). because the user is likely to move away from the server. In such a case. as shown in Figure 8-2.150 Chapter 8: Using WAP with Bluetooth ♦ URL of the server’s home page. Protocol Stack for Using WAP with Bluetooth To support WAP services with Bluetooth in the Client/Server environment. As the mobile device moves in the piconet. SDP or RFCOMM) In other words. such as a cellular phone. the mobile device sends the SDP request and obtains the response. it obtains the following information: ♦ Client name (in a friendly format) ♦ Client capabilities (the Bluetooth capabilities of the mobile device) So. Either the WAP server or the mobile device can send the request and obtain the response. The following is a brief description of each of the layers: ♦ Baseband/Link Manager Protocol (LMP) takes care of link management over the radio. the client and the server) and identifies the higher layer to which the messages have to be passed on (for example. the information obtained through the SDP can be stored in the cache memory of the mobile device. Note that the actual content is not sent to the client and only a service indication is sent. the user can get the content from the server by invoking the URL provided. ♦ Logical Link Control and Adaptation Protocol (L2CAP) assumes that a Bluetooth link is already established between two devices (in this case. this layer carries out protocol multiplexing. So. the communication link may be lost as the device goes out of range of the piconet. such as a laptop. the stack shown in Figure 8-2 is very generic in order to accommodate a variety of mobile devices. the WAP server checks periodically for the availability of clients using the SDP. The responses are in the form of service records. This layer establishes the Bluetooth link. If the WAP server is only a proxy. the mobile device obtains the content from the server using the push model. “Would you like to see the flight departure information?” at an airport) and the URL corresponding to the content. or a low-end device. When the server discovers the clients using the SDP. The client can discard the message or invoke the URL in the service indication to see the actual content. For pull applications. Initiation by the server In this scenario. which contain the details of the service. if the initiation is by the client. Every device connected to the Internet is given an IP address. this protocol is required. The advantage of UDP is its low protocol overhead as compared to TCP. Every packet contains the source IP address and the destination IP address. Because we are emulating the serial communication dial up through RFCOMM. ♦ Internet Protocol (IP) is the protocol that takes care of the addressing and routing on the Internet. ♦ Wireless Datagram Protocol (WDP) is the transport layer equivalent of UDP. ♦ Wireless Transport Layer Security (WTLS) is the optional security layer of the WAP stack. Unlike Transmission Control Protocol (TCP) that uses connection-oriented service. . ♦ User Datagram Protocol (UDP) is the transport layer protocol. ♦ Point to Point Protocol (PPP) is the protocol used for dial-up lines to transport packet data from higher layers across the Bluetooth RFCOMM serial port emulator. which is the transport layer protocol in the WAP stack. the service is unreliable as packets may be lost. The destination IP address is used to route the packets to the correct destination.Chapter 8: Using WAP with Bluetooth 151 Figure 8-2: Protocol stack on Client and Server for WAP with Bluetooth ♦ RFCOMM is the transport protocol that emulates the RS 232 serial port. UDP uses connectionless service. This layer provides the optional functionality of authentication and encryption for applications that require secure communication. However. meaning we can assume that the communication between the mobile device and the server is in the form of serial communication without the cable. note that the WAP services can also be provided through Short Messaging Service (SMS). If the request corresponds to the content that is available locally on the WAP server. The Wireless Datagram Protocol (WDP) can run on the SMS bearer. Above WTLS. If the content is not available locally. encode it in binary format. In such a case. These protocols establish a session and communicate with the WAP server/gateway for obtaining the information. it will fetch the WML content. They then present the information to the user through the Wireless Application Environment (WAE). The Bluetooth-enabled WAP gateway receives the request. and sends it to the client. Wireless Transaction Protocol (WTP) and Wireless Session Protocol (WSP) may be run. the Wireless Transaction Layer Security (WTLS) layer is run (note that this is only an optional layer). the WAP server has to do the necessary protocol . If security above WDP is required. which has a micro-browser to interpret the WML content. Because the Origin server has the TCP/IP protocol stack. there is no need to run the IP and UDP protocols.152 Chapter 8: Using WAP with Bluetooth ♦ Wireless Transaction Protocol (WTP) and Wireless Session Protocol (WSP) together provide the HTTP functionality in the WAP environment. Figure 8-3: Protocol Stack on WAP Gateway and Origin server for WAP services with Bluetooth The WAP client sends a request in the form of a URL through the Bluetooth bearer (over the radio link) to the WAP gateway. the WAP server contacts the Origin server through HTTP protocol. obtains the content. Figure 8-3 shows the complete protocol stacks that run on the WAP server/gateway and the Origin server to provide WAP services with Bluetooth. and send it to the client. ♦ However. will be transparent to the user to obtain the content. ♦ When a device enters the RF proximity of another device. The Bluetooth specifications include interoperability requirements for WAP and Bluetooth. Addressing in WAP with Bluetooth Bluetooth. this is known as asynchronous notification. the gateway should be capable of using the DNS to obtain the network address. ♦ Name of the client and the client capabilities should be sent to the client through the SDP. the URL has to be mapped to the IP address. the information is sent to the mobile device. ♦ Detecting that the server node signal is lost: The mobile device should be capable of detecting the loss of an RF signal. which is done by a Domain Name Server (DNS). The user uses the normal URL to access the content using pull model. Implementation of WAP for Bluetooth In the WAP protocol stack. For implementing WAP with Bluetooth. However. the WAP gateway has to convert the content into WML format. do the encoding of the content. If the URL corresponds to the content present in that WAP gateway itself. and leave the piconet environment. So. it comes within the proximity of Bluetooth enabled servers. The same procedure as for Service Indication and Service Loading is followed in the case of push messages. The following are the important interoperability requirements to provide full-fledged services: ♦ Name of the server and the server capabilities should be sent to the client through the SDP. the Bluetooth Host Control Interface derives all information except the server push detection. as the bearer. the implementation of WAP services with Bluetooth will happen gradually. In the Bluetooth protocol stack. We will assume that the WAP server that provides the WML content and the . the network is highly dynamic meaning new clients get connected and disconnected. and send it to the mobile device over the Bluetooth bearer. Thus. the management entity should be capable of: ♦ Detecting new clients: Because mobile devices come within the proximity of the WAP server. ♦ Detecting new servers: As the mobile device keeps moving. ♦ Detection of server push messages: In the case of a push model being used for WAP over Bluetooth. ♦ Detecting that the client node signal is lost: The server should be able to detect when the mobile device goes out of its RF range and immediately frees the resources allocated to it.Chapter 8: Using WAP with Bluetooth 153 conversion. and the management entity in the mobile devices should be capable of detecting new servers en route. the WDP management entity is responsible for managing the services provided by WDP. If the Origin server sends the content in HTML instead of the WML format. which is a requirement stated in the Bluetooth specifications. we will study two applications that demonstrate the capability of WAP in a Bluetooth environment. Interoperability requirements WAP’s interoperability with Bluetooth is considered one of the “killer applications” of Bluetooth. one of the requirements for the WAP gateway is to have the capability of the DNS address mapping. the mobile device should be able to detect the server push messages. one device should automatically be notified about the presence of the other. For the WAP gateway to send the URL request to the right Origin server. detection of new clients is an important function of the management entity of the WDP. If the content is not present in the gateway but has to be fetched by the gateway. make connections. In the following sections. ContentType = "text/vnd. These are text fields in which the flight number. the WAP server discovers the mobile device and pushes the content. You can create the database in MS Access that contains a table named flight.Connection") 7.1.1.wml" %> 2. Figure 8-4: Database for flight information Now we need to write a program that generates a WML card that pushes the information stored in the database to the mobile device.open("dsn=flight") 8.wap.CreateObject("ADODB.xml"> 4. <card id="home" title="FLIGHT TIMINGS"> 11. The program written in ASP is shown in Listing 8. the server can discover a mobile device in its vicinity to push the information onto the mobile device.wapforum. We need to create a database that stores the flight information in the following format: flight number.0"?> 3. <% . dbConn. Listing 8-1: ASP code (flight. and time.asp) for Airport Kiosk © 2001 Dreamtech Software India Inc All Rights Reserved 1. destination of the flight. <?xml version="1. gate. and time of departure are stored. The applications are: ♦ A kiosk in an airport. set dbConn = Server. destination. gate.execute("SELECT * from flight") 9. <% Response.1//EN" "http://www. %> 10. set flight1 = dbConn. <% 6. and time of departure. The fields in the table are flightno. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.org/DTD/wml_1. Figure 8-4 shows a sample database. When the mobile device enters the RF region of a Bluetoothenabled WAP server.154 Chapter 8: Using WAP with Bluetooth mobile device are Bluetooth-enabled and through SDP. respectively. gate number. <wml> 5. destination. which provides information on the location of different shops and information about new shops Application: Airport Kiosk This application illustrates the push model usage for sending information on flights to mobile devices that come in the vicinity of a WAP server. <p align="center"> 12. which provides gate information to the users ♦ A shopping mall kiosk. 19. 21.Chapter 8: Using WAP with Bluetooth 155 13. 20. The DSN used is flight. 16. The While loop ends at line 26.eof %> FLIGHT NO: <%=flight1("flightno")%><br/> DESTINATION: <%=flight1("destination")%><br/> GATE: <%=flight1("gate")%><br/> TIME <%=flight1("time")%><br/> <br/> <% flight1. 29. 18. card and wml deck tags . ♦ Line 15: This is text to be displayed on the WML card: FLIGHT NO ♦ Line 16: The script to display the field “flightno” retrieved from the database ♦ Line 17: Simple text to display DESTINATION ♦ Line 18: The script to display the field “destination” retrieved from the database ♦ Line 19: Simple text to display GATE ♦ Line 20: The script to display the field “gate” retrieved from the database ♦ Line 21: Simple text to display TIME ♦ Line 22: The script to display the field “time” retrieved from the database ♦ Line 23: Break tag ♦ Lines 24–27: The script used for moving to the next record in the database and also for closing the While loop ♦ Lines 28–30: Closing tags for para. 30. After opening the database. 27. 15.MoveNext Wend %> </p> </card> </wml> Code Description ♦ Line 1: This line is to set the content type to WML. 24.wml” ♦ Line 2: Indicates the XML version being used ♦ Line 3: Indicates document type definition ♦ Line 4: Indicates the start of the WML deck ♦ Lines 5–9: This code creates the database object and opens the database using the DSN (Data Source Name). ♦ Line 10: Card tag with card id “home” and title of the card “FLIGHT TIMINGS” ♦ Line 11: Para tag with attribute to align the text at center ♦ Lines 12–14: This code is to create a loop to read all the records from the database until the end of the file. it executes a select statement to extract the details from the database and assigns the result to a variable flight1. 14. 22. 25. While not flight1.wap. 17. 26. 23. 28. we set the content type of the response to “text/vnd. As per the MIME setting requirement. Call the Program Create a folder named wap under inetpub/wwwroot. The information in the URL (http://localhost/wap/flight. . Now look for ODBC Data Sources and double-click the icon. go to the TOOLKITSHOWPUSHVIEW menu and click the menu item. for example. The push message simulator is shown in Figure 85. Because the server machine is the same as the client on which we are testing this application. The 32-bit data sources administration window is opened.asp) is pushed to the browser.156 Chapter 8: Using WAP with Bluetooth Create the DSN To create the DSN. Otherwise. The DSN is created. we must use the name of the server. select the database. Pass the URL in the href text box and click the OK button. http://MyServer/wap/flight. Click the Createmsg button. In the Nokia tool kit.asp. Select the appropriate driver (in this case. on the Windows desktop go to StartSettingsControl Panel. It asks you to select the driver. Place the flight.asp file in this folder. The ODBC Microsoft Access Setup window displays: there you have to give the data source name. in user DSN. MS Access) and click the Finish button. we used localhost as the server name. click the activate msg button. The Push Message window appears. and click the OK button. The SI code is shown in Listing 8-2. Figure 8-5: Push message simulator for Airport Kiosk In the push message menu window. The Push Message Simulator window opens. click the Add button. The tool kit automatically creates a Service Indication (SI). </indication> </si> The si tag has action attribute as “signal-high”.0" encoding="ISO-8859-1"?> <!DOCTYPE si PUBLIC "-//WAPFORUM//DTD SI 1.dtd"> <si> <indication action="signal-high" href="http://localhost/wap/flight. Figure 8-6: Flight information displayed on the mobile phone . and si-expires indicates the expiry time of the service indication. si-id.0//EN" "http://www. The href is the URL. Code Output The output displayed on the phone emulator is shown in Figure 8-6.org/DTD/si. si-id is the unique ID assigned to the service indication message.asp" created="1999-01-01T01:48:40Z" si-expires="1999-01-02T01:48:40Z" > This is displayed text.asp" si-id="http://localhost/wap/flight. created and siexpires attributes.wapforum. created specifies the date and time of creation of the message. followed by href.Chapter 8: Using WAP with Bluetooth 157 Listing 8-2: Service Indication generated by the Tool Kit for Airport Kiosk Push Message © 2001 Dreamtech Software India Inc All Rights Reserved <?xml version="1. wapforum.Connection") 7. <% 6. Figure 8-7: Database for Shopping Mall Kiosk The fields in the table are item. <do type="accept" label="New"> . This kiosk pushes information about shop locations and new products to the mobile devices. and status.org/DTD/wml12. we will provide an option to the user.wap. shopno.CreateObject("ADODB. Shop. create a database in MS Access called shop. set shop = dbConn.ContentType = "text/vnd. in which case only those records with “new” in the status field are displayed. In regard to the ASP code for this application.1//EN" "http://www.158 Chapter 8: Using WAP with Bluetooth Application: Shopping Mall Kiosk In this example. a small display appears that has a soft key called New. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.open("dsn=shop") 8. Thus we will write two ASP programs.dtd"> 4.wml" %> 2. As soon as the user enters the RF proximity of the WAP server. we will create a kiosk that can be placed in a large shopping mall. dbConn. The soft key is a software-generated key — one of the buttons on the keypad can be programmed to do a specific task. <p align="center"> 12. set dbConn = Server. All the fields are text fields. the field can be blank in the records.asp) for Shopping Mall Kiosk © 2001 Dreamtech Software India Inc All Rights Reserved 1. floor.asp code is shown in Listing 8-3. The item field gives the name of the item. Listing 8-3: ASP code (shop. and the status field gives whether the shop has any new products in stock. %> 10 <card id="home" title="SUPERMARKET"> 11. which contains one table with the name “item. The user can go through the shops’ details in order or only press the New button.0"?> 3. As in the previous example. we need to create a database and an ASP program. <% Response. floor indicates the floor number on which the shop is located. shop number gives the number of the shop. <wml> 5. If there are no new arrivals.execute("SELECT * from item") 9.” See Figure 8-7. <?xml version="1. First. it executes a select statement to extract the details from the database and assigns the results to a variable shop.asp). we are creating a softkey “New”and after the user presses this key on the mobile device. 24. we referred to shopnew. 26. label is “New”. After opening the database. The task is to navigate to a new link given by href (shopnew. This code is invoked after the “New” soft key is pressed. 19.asp (through href attribute in the go tag in Line 13). 15.asp. card. Listing 8-4 shows the code for shopnew. ♦ Line 10: Card tag with card id “home” and title of the card “SUPERMARKET” ♦ Line 11: Para tag with attribute to align the text at center ♦ Lines 12–14: Do tag which is used to assign a task. .Chapter 8: Using WAP with Bluetooth 159 13. and wml deck tags In the above code. 25. 14. 23. 20. <go href="shopnew. shopnew. 29. 17. The task type is “accept”. 21.MoveNext Wend %> </p> </card> </wml> Code Description ♦ Line 1: Sets the content type that is being used in the file ♦ Line 2: Indicates the XML version being used ♦ Line 3: Document type definition that is being used ♦ Line 4: wml deck starting ♦ Lines 5–9: Code to create the database object and open the database using the DSN. So. 27. 16.asp" /> </do> <% While not shop. 22.asp is invoked. 28.eof %> ITEM: <%=shop("item")%><br/> SHOPNO: <%=shop("shopno")%><br/> FLOOR: <%=shop("floor")%><br/> <% shop. till the end of the file ♦ Line 18: Simple text to display ITEM ♦ Line 19: Script to display the field “item” retrieved from the database ♦ Line 20: Simple text to display SHOPNO ♦ Line 21: Script to display the field “shopno” retrieved from the database ♦ Line 22: Simple text to display FLOOR ♦ Line 23: Script to display the field “floor” retrieved from the database ♦ Lines 24–27: Script to move to the next record in the database and end of the while loop on reaching the end of file ♦ Lines 28–30: Closing of para. ♦ Lines 15–17: The script to create a While loop to read the records in the database one by one. 30. 18. <% 25.wap. <wml> 5. set dbConn = Server.asp" /> 14.1//EN" "http://www.wapforum. This statement retrieves only those records for which the status is ‘new’. The result is assigned to a variable shop. </wml> Code Description This code is the same as the shop.MoveNext 26. %> 28. set shop = dbConn. go to the TOOLKITSHOWPUSHVIEW menu and click the menu item. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.0"?> 3. Note the where clause in the select statement.ContentType = "text/vnd.wml" %> 2.open("dsn=shop") 8. <%=shop("floor")%><br/> 24. . <%=shop("shopno")%><br/> 22.org/DTD/wml12. Create the DSN To create the DSN. While not shop. %> 10.eof 17. The push menu window opens. <card id="home" title="SUPERMARKET"> 11. shop. Call the Program Place the asp file in the inetpub wwwroot by creating a folder wap. FLOOR: 23.asp except in retrieving the data from the database. Instead of retrieving all the records. <% 6. </p> 29. dbConn. <%=shop("item")%><br/> 20. follow the same procedure as given for the Airport Kiosk application.asp) for Shopping Mall Kiosk © 2001 Dreamtech Software India Inc All Rights Reserved 1. <% 16. After opening the database. <?xml version="1. it executes a select statement to extract details from the database. %> 18.execute("SELECT * from item where status = 'new' ") 9. <p align="center"> 12.Connection") 7.CreateObject("ADODB. Lines 5-9: This code creates a database object and opens the database using the DSN. <do type="accept" label="Home"> 13. In the Nokia tool kit. </do> 15.dtd"> 4. </card> 30. <go href="shop. ITEM: 19. <% Response.160 Chapter 8: Using WAP with Bluetooth Listing 8-4: ASP code (shopnew. Wend 27. this code retrieves only those records with category as new. SHOPNO: 21. Click the Createmsg button. as shown in Figure 8-8. The information in the URL (http://www.asp" si-id="http://localhost/wap/shop. click the activate msg button. In the push menu window.asp" created="1999-01-01T01:48:40Z" si-expires="1999-01-02T01:48:40Z" > .localhost/wap/shop. The push simulator automatically generates a Service Indication. as shown in Listing 8-5.dtd"> <si> <indication action="signal-high" href="http://localhost/wap/shop.asp) is pushed on to the browser.org/DTD/si.0//EN" "http://www.Chapter 8: Using WAP with Bluetooth 161 The push message simulator window displays. Figure 8-8: Push Message Simulator for Shopping Mall Pass the URL in the href box and click OK.0" encoding="ISO-8859-1"?> <!DOCTYPE si PUBLIC "-//WAPFORUM//DTD SI 1. Listing 8-5: Service Indication generated by Tool Kit for Shopping Mall Push Message © 2001 Dreamtech Software India Inc All Rights Reserved<?xml version="1.wapforum. A WAP server can communicate with a WAP client over a Bluetooth radio link. and through either a pull model or a push model. Implementing WAP with Bluetooth can provide hidden computing services. </indication> </si> Code Output The display on the WAP phone emulator is shown in Figure 8-9. the entire list is displayed. discover the services available through the Service Discovery Protocol. we studied how WAP services can be provided on Bluetooth-enabled devices. as shown in Figure 8-9(a). the WAP content can be presented on the mobile device. Figure 8-9(b) shows the display when the New soft key is pressed. which can be scrolled.” Kiosks that are Bluetooth-enabled WAP servers/gateways can provide location specific information to the users in various places. where only those records with status of new are displayed. Bluetooth acts as a bearer for WAP stack.162 Chapter 8: Using WAP with Bluetooth This is displayed text. By default. . wherein the mobile devices enter the server’s RF range. such as airports and malls. such as the “briefcase trick” and “forbidden message. We also studied the implementation of kiosks using the push framework. A kiosk is an interesting example of ad-hoc networks. (a) (b) Figure 8-9: Push Message from WAP Server displayed on the mobile phone: (a) display of records one by one and (b) display of records having status of new Summary In this chapter. and get out of the range in a random fashion. sending an inquiry to a remote Bluetooth device. The PC reference stack software has to be loaded on the system. The development kit consists of a Bluetooth module (a small Printed Circuit Board) containing the hardware and firmware and a software module that runs on the Windows NT/98/2000 environment. When the Bluetooth module is connected to the PC.Chapter 9 Bluetooth Programming In this chapter. We see how to access the different layers of the Bluetooth protocol stack and also develop applications in the Windows environment by using Ericsson’s Bluetooth PC Reference stack. Because the software uses the Windows COM model. and doing loopback testing. familiarity with COM is assumed. The PC reference stack and the driver software need to be installed on the systems (the Bluetooth hosts).teleca. we focus on the programming aspects of Bluetooth. The development is done in VC++ environment. RFCOMM. In this chapter. Overview of the Bluetooth Development Kit The Bluetooth development kit used for illustrating Bluetooth programming is Ericsson’s PC reference stack distributed and supported by Teleca Comtec (http://www. you can start working on the following examples. The Bluetooth module works on either a USB interface or a serial interface. After you have the previous requirements (consisting of two Bluetooth-enabled desktop PCs) set up. For carrying out development work. obtaining its address. The sample chat application given with the PC reference stack can be executed and tested to ensure that the Bluetooth modules are working in a proper manner.comtec. SDP. So. the first step is to establish communication between the protocol stack running on the PC and the Bluetooth module. we start . you must install the Bluetooth module and software on at least two systems. The stack provides the API calls for HCI driver. and OBEX (Object Exchange) protocol layers. we need at least two such modules. The programming aspects give better insight into the protocols and functioning of Bluetooth. The explanation covers the description of the API calls.se). These include configuring the port on which the Bluetooth module is placed. The complete source code listings for accessing the Host Controller Interface (HCI). we discuss how the services provided by different layers are accessed through the API calls. L2CAP. HCI Programming The HCI (Host Controller Interface) driver that runs on the host (the PC) is used to carry out a number of functions. obtaining the local Bluetooth module address. Installing the Bluetooth Module and PC Reference Stack Before trying the following applications. obtaining the packet sizes supported for ACL (Asynchronous Connection Less) and SCO (Synchronous Connection Oriented) links. Service Discovery Protocol (SDP). The Bluetooth module can be connected to the USB interface or serial interface of the PC. obtaining the version number of the Bluetooth device. The complete source code is given along with a detailed explanation. and RFCOMM using the Application Programming Interface (API) calls provided with the PC reference stack are presented. All Rights Reserved 1. This example illustrates the HCI commands and responses.WM_BLUETOOTH_EVENT. 22. 14. The variables used in this class are declared in HCI Information CommandsDlg. (AFX_PMSG)(AFX_PMSGW)(void(AFX_MSG_CALL CWnd::*)(void**))& memberFxn }.164 Chapter 9: Bluetooth Programming Bluetooth programming with HCI programming.cpp.h. #pragma once 10. { 19. Note that HCI programming is fundamental to Bluetooth programming because the first step for establishing a connection between two Bluetooth devices is for the stack on the host to communicate with the Bluetooth module.h> 9. #define AFX_HCIINFORMATIONCOMMANDSDLG_H__30FC7B07_A10F_11D2_B756_ 0080C805A679__INCLUDED_ 5. CListBox m_DeviceList. enum { IDD = IDD_HCIINFORMATIONCOMMANDS_DIALOG }. //Macro to send a Bluetooth Event to the windows message map 15. uiBtEventID.0. It is implemented with CRemoteDevice class in a file named RemoteDevice. 25.h" 7. \ 13. #if _MSC_VER > 1000 6.cpp.h.pMsg) \ 16. public: 21. CEdit m_ScoCount. Listing 9-1: HCI Information CommandsDlg. #include "Events. // HCI Information CommandsDlg. #include <afxtempl. #include "RemoteDevice. The user can identify whether the issued command is a success by getting the fired HCI Event information in the message boxes. It is implemented with Events class in Events. 26. #define WM_BLUETOOTH_EVENT (WM_USER + 100) 12.(WPARAM) uiBtEventID. memberFxn) \ { WM_BLUETOOTH_EVENT. The variables used in this class are declared in RemoteDevice.h (Listing 9-1). ♦ REMOTE DEVICE: This module is to present the Remote BLUETOOTH device address to the user.1. CHCIInformationCommandsDlg(CWnd* pParent = NULL). ♦ EVENTS: This module connects to the BT COMServer (COM Server supplied by Ericsson along with the BLUETOOTH PC reference stack) and receives all outgoing events from the BT COM Server. // 3. CEdit m_add. For each HCI command generated by the user.h © 2001 Dreamtech Software India Inc. 24. This module is implemented with CHCIInformationCommandsDlg class in a file named HCI Information CommandsDlg. #define SEND_BT_EVENT(uiBtEventID.(LPARAM)&pMsg) 17. SendMessage((HWND)this->m_hWnd.cpp file. class CHCIInformationCommandsDlg : public CDialog 18. 23. the Bluetooth module fires a HCI event. #if !defined(AFX_HCIINFORMATIONCOMMANDSDLG_H__30FC7B07_A10F_ } 11D2_ B756_0080C805A679__INCLUDED_) 4.h : header file 2.0. #define ON_BLUETOOTH_EVENT(uiBtEventID. // Construction 20. This application contains the following three modules: ♦ GUI: This module provides a good user interface to generate HCI commands. . #endif // _MSC_VER > 1000 11. The variables used in this class are declared in Events.h" 8. Chapter 9: Bluetooth Programming 165 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. CEdit m_ScoSize; CEdit m_AclCount; CEdit m_AclSize; CEdit m_ver; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CHCIInformationCommandsDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL public: void AddDevice(CRemoteDevice device); void ShowAllDevicesFound(); // Implementation protected: HICON m_hIcon; CArray <CRemoteDevice,CRemoteDevice&> m_DevicesFound; Events *m_pServerEvents; int m_RemoteNameCounter; int m_ServiceCounter; // Generated message map functions //{{AFX_MSG(CHCIInformationCommandsDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnInquiry(); afx_msg void OnConnect(); afx_msg void OnDestroy(); afx_msg void OnCloseapplication(); afx_msg void OnComStartCnf(void **ppMsg); afx_msg void OnComStartCnfNeg(void **ppMsg); afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg afx_msg void void void void void void void void void void void void void void void void void void void void OnHciConfigurePortConfirm(void **ppMsg); OnHciConfigurePortConfirmNegative(void **ppMsg); OnHciInquiryCnf(void **ppMsg); OnHciInquiryEvt(void **ppMsg); OnHciLocalAddressCnf(void **ppMsg); OnHciLocalAddressCnfNeg(void **ppMsg); OnHciRemoteNameCnf(void **ppMsg); OnHciRemoteNameCnfNeg(void **ppMsg); OnHciStartCnf(void **ppMsg); OnHciReadLocalVersionCnf(void **ppMsg); OnHciReadLocalVersionCnfNeg(void **ppMsg); OnHciWriteLoopbackModeCnf(void **ppMsg); OnHciWriteLoopbackModeCnfNeg(void **ppMsg); OnHciDataInfoCnf(void **ppMsg); OnSilSetDeviceCnf(void **ppMsg); OnSilSetDeviceCnfNeg(void **ppMsg); OnButton1(); OnButton2(); OnButton3(); OnButton5(); 166 Chapter 9: Bluetooth Programming 82. 83. 84. 85. 86. 87. 88. 89. 90. afx_msg void OnButton7(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: BOOL OnBluetoothEvent(UINT message,WPARAM wParam,LPARAM lParam); }; //{{AFX_INSERT_LOCATION}} #endif Code Description Listing 9-1 is a header file for declaration of the necessary constants and declaration of the class and its methods. Note that the MFC application wizard automatically generates lines 1–5, 9, and 10. Lines 6 to 8 are the include files required for our program. Events.h and Remotedevice.h are the header files, which are created for our application and afxtemp1.h is a library file. Lines 11–13 and lines 15 and 16 are constant definitions as required by the Bluetooth PC reference stack. Lines 17–90 are for the declaration of the class CHCIInformationCommandsDialog for creation of buttons, edit boxes, and message boxes for displaying various messages when events are thrown by the Bluetooth module for various HCI commands issues by the host. The HCI commands and messages are explained in Listing 92. Listing 9-2: HCI Information CommandsDlg.cpp © 2001 Dreamtech Software India Inc. All Rights Reserved 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. // HCI Information CommandsDlg.cpp : implementation file #include "stdafx.h" #include "HCI Information Commands.h" #include "HCI Information CommandsDlg.h" #include <exp\msg.h> #include <exp\vos2com.h> #include <exp\hci.h> #include <exp\hci_drv.h> #include <exp\sil.h> #include <exp\com.h> #include <exp\sd.h> uint16 SeqNr; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif union MessageMapFunctions { AFX_PMSG pfn; // generic member function pointer void (AFX_MSG_CALL CWnd::*pfn_btf)(void **); }; #define PORTSETTINGS (uint8 *)("COM1:Baud=57600 parity=N data=8 stop=1 ") class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) Chapter 9: Bluetooth Programming 167 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // CHCIInformationCommandsDlg dialog CHCIInformationCommandsDlg::CHCIInformationCommandsDlg(CWnd* pParent) : CDialog(CHCIInformationCommandsDlg::IDD, pParent) { //{{AFX_DATA_INIT(CHCIInformationCommandsDlg) //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_pServerEvents = new Events(); } void CHCIInformationCommandsDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CHCIInformationCommandsDlg) DDX_Control(pDX, IDC_EDIT1, m_add); DDX_Control(pDX, IDC_LIST1, m_DeviceList); DDX_Control(pDX, IDC_EDIT8, m_ScoCount); DDX_Control(pDX, IDC_EDIT7, m_ScoSize); DDX_Control(pDX, IDC_EDIT6, m_AclCount); DDX_Control(pDX, IDC_EDIT5, m_AclSize); 168 Chapter 9: Bluetooth Programming 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. DDX_Control(pDX, IDC_EDIT2, m_ver); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CHCIInformationCommandsDlg, CDialog) //{{AFX_MSG_MAP(CHCIInformationCommandsDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BLUETOOTH_EVENT(COM_START_CNF,OnComStartCnf) ON_BLUETOOTH_EVENT(COM_START_CNF_NEG,OnComStartCnfNeg) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF,OnHciConfigurePortConfirm) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF_NEG, OnHciConfigurePortConfirmNegative) ON_BLUETOOTH_EVENT(HCI_INQUIRY_CNF,OnHciInquiryCnf) ON_BLUETOOTH_EVENT(HCI_INQUIRY_EVT,OnHciInquiryEvt) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF, OnHciLocalAddressCnf) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF_NEG, OnHciLocalAddressCnfNeg) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF,OnHciRemoteNameCnf) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF_NEG,OnHciRemoteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_START_CNF,OnHciStartCnf) ON_BLUETOOTH_EVENT(HCI_READ_LOCAL_VERSION_CNF, OnHciReadLocalVersionCnf) ON_BLUETOOTH_EVENT(HCI_READ_LOCAL_VERSION_CNF_NEG, OnHciReadLocalVersionCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_LOOPBACK_MODE_CNF, OnHciWriteLoopbackModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_LOOPBACK_MODE_CNF_NEG, OnHciWriteLoopbackModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_DATA_INFO_CNF,OnHciDataInfoCnf) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF, OnSilSetDeviceCnf) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF_NEG, OnSilSetDeviceCnfNeg) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3) ON_BN_CLICKED(IDC_BUTTON5, OnButton5) ON_BN_CLICKED(IDC_BUTTON7, OnButton7) //}}AFX_MSG_MAP END_MESSAGE_MAP() // CHCIInformationCommandsDlg message handlers BOOL CHCIInformationCommandsDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { Chapter 9: Bluetooth Programming 169 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX , strAboutMenu ); } } SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_pServerEvents->m_pParentDialog = this; return TRUE; // return TRUE unless you set the focus to a control } void CHCIInformationCommandsDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } void CHCIInformationCommandsDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } HCURSOR CHCIInformationCommandsDlg::OnQueryDragIcon() { return (HCURSOR) m _hIcon; } LRESULT CHCIInformationCommandsDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class MSG_TMsg **ptMsg; 170 Chapter 9: Bluetooth Programming 191. 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218. 219. 220. 221. 222. 223. 224. 225. 226. 227. 228. 229. 230. 231. 232. 233. 234. 235. 236. 237. 238. 239. 240. 241. 242. 243. 244. 245. if (message == WM_BLUETOOTH_EVENT) { // It is a Bluetooth event, so call the corresponding handlefunction OnBluetoothEvent( message, wParam, lParam); ptMsg = (MSG_TMsg**)lParam; /* free the message received from the bluetooth server */ if (*ptMsg != NULL) VOS_Free((void **)lParam); } return CDialog::WindowProc(message, wParam, lParam); } BOOL CHCIInformationCommandsDlg::OnBluetoothEvent(UINT message, WPARAM wParam, LPARAM lParam) { const AFX_MSGMAP* pMessageMap; const AFX_MSGMAP_ENTRY* lpEntry; // look through message map to see if it applies to us #ifdef _AFXDLL for (pMessageMap = GetMessageMap(); pMessageMap != NULL; pMessageMap = (*pMessageMap->pfnGetBaseMap)()) #else for (pMessageMap = GetMessageMap(); pMessageMap != NULL; pMessageMap = pMessageMap->pBaseMap) #endif { #ifdef _AFXDLL ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()); #else ASSERT(pMessageMap != pMessageMap->pBaseMap); #endif lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]); while (lpEntry->nSig != AfxSig_end) { if((lpEntry->nMessage==message)&&(lpEntry->nCode== wParam)) { union MessageMapFunctions mmf; mmf.pfn = lpEntry->pfn; //lets call the function to handle the message (((CWnd *)this)->*mmf.pfn_btf)((void **)lParam); return TRUE; } lpEntry++; } /* unable to find a handler function for this Bluetooth event */ return FALSE; } return FALSE; } void CHCIInformationCommandsDlg::OnInquiry() { HCI_TLap tLap = {0x9E,0x8B,0x33}; HCI_TInquiryLength tInquiryLength = 2; HCI_TNrOfResponses tNrOfResponses = 0; Chapter 9: Bluetooth Programming 171 246. 247. 248. 249. 250. 251. 252. 253. 254. 255. 256. 257. 258. 259. 260. 261. 262. 263. 264. 265. 266. 267. 268. 268. 269. 270. 271. 272. 273. 274. 275. 276. 277. 278. 279. 280. 281. 282. 283. 284. 285. 286. 287. 288. 289. 290. 291. AfxMessageBox("Request to send INQUIRY \nCommand:HCI_ReqInquiry(1,tLap,tInquiryLength,tNrOfResponses)"); HCI_ReqInquiry(1,tLap,tInquiryLength,tNrOfResponses); } void CHCIInformationCommandsDlg::OnDestroy() { CDialog::OnDestroy(); } void CHCIInformationCommandsDlg::AddDevice(CRemoteDevice device) { m_DevicesFound.Add(device); } void CHCIInformationCommandsDlg::ShowAllDevicesFound() { CRemoteDevice device; int iFound,i; CString str; iFound = m_DevicesFound.GetSize(); for (i=0; i < iFound; i++) { device = m_DevicesFound.GetAt(i); str.Format("Address:0x%s Name: %s", device.GetAddress(),device.GetName()); m_DeviceList.AddString(str); } } void CHCIInformationCommandsDlg::OnSilSetDeviceCnf(void **ppMsg) { ppMsg = ppMsg; AfxMessageBox("UART INTERFACE was selected \nEvent:SIL_SET_DEVICE_CNF"); AfxMessageBox("Request to Configure Port \nCommand:HCI_ReqConfigurePort(0,PORTSETTINGS)"); HCI_ReqConfigurePort(0,PORTSETTINGS); } void CHCIInformationCommandsDlg::OnSilSetDeviceCnfNeg(void **ppMsg) { AfxMessageBox("INTERFACE was not selected\nEvent:SIL_SET_DEVICE_CNF_NEG"); } void CHCIInformationCommandsDlg::OnHciConfigurePortConfirm(void **ppMsg) { //HCI_TConfigurePortCnf *tConfigurePort =(HCI_TConfigurePortCnf*) *ppMsg tConfigurePort = tConfigurePort; AfxMessageBox("Serial Port was Configured\nEvent:HCI_CONFIGURE_PORT_CNF"); AfxMessageBox("Request to start RFCOMM \nCommand:COM_ReqStart(0)"); COM_ReqStart(0); } void HCIInformationCommandsDlg::OnHciConfigurePortConfirmNegative(void **ppMsg) { // HCI_TConfigurePortCnfNeg *tConfigurePort = (HCI_TConfigurePortCnfNeg *)*ppMsg; tConfigurePort = tConfigurePort; 172 Chapter 9: Bluetooth Programming 292. MessageBox(_T("Could not open port")); 293. } 294. void CHCIInformationCommandsDlg::OnComStartCnf(void **ppMsg) 295. { 296. // COM_TStartCnf *tStartCnf = (COM_TStartCnf *)*ppMsg; 297. tStartCnf = tStartCnf; 298. AfxMessageBox("RFCOMM was started \nEvent:COM_START_CNF "); 299. AfxMessageBox("Request to get Local BD_ADDRESS\nCommand:HCI_ReqLocalAddress(0)"); 300. HCI_ReqLocalAddress(0); 301. } 302. void CHCIInformationCommandsDlg::OnComStartCnfNeg(void **ppMsg) 303. { 304. // COM_TStartCnfNeg *tStartCnfNeg = (COM_TStartCnfNeg *)*ppMsg; 305. tStartCnfNeg = tStartCnfNeg; 306. MessageBox(_T("Could not start RFCOMM")); 307. } 308. void CHCIInformationCommandsDlg::OnHciLocalAddressCnf(void **ppMsg) 309. { 310. HCI_TLocalAddressCnf *tLocalAddress = (HCI_TLocalAddressCnf *)*ppMsg; 311. char add[59]; 312. wsprintf(&add[0], "0x%02X%02X%02X%02X%02X%02X\0", 313. tLocalAddress->tAddress.ucByte0, 314. tLocalAddress->tAddress.ucByte1, 315. tLocalAddress->tAddress.ucByte2, 316. tLocalAddress->tAddress.ucByte3, 317. tLocalAddress->tAddress.ucByte4, 318. tLocalAddress->tAddress.ucByte5); 319. AfxMessageBox("Returned Localadress\nEvent:HCI_LOCAL_ADDRESS_CNF"); 320. m_add.SetWindowText(_T(add)); 321. 322. } 323. void CHCIInformationCommandsDlg::OnHciLocalAddressCnfNeg(void **ppMsg) 324. { 325. ppMsg = ppMsg; 326. m_add.SetWindowText(_T("UNABLE TO CONNECT TO DEVICE")); 327. } 328. void CHCIInformationCommandsDlg::OnHciInquiryCnf(void **ppMsg) 329. { 330. HCI_TInquiryCnf *ptInquiryCnf; 331. int count; 332. CRemoteDevice device; 333. AfxMessageBox("INQUIRY was sent\nEvent:HCI_INQUIRY_CNF"); 334. ptInquiryCnf =(HCI_TInquiryCnf *) *ppMsg; 335. count = m_DevicesFound.GetSize(); 336. m_RemoteNameCounter = 0; 337. if (count > 0) 338. { 339. device = (CRemoteDevice) _DevicesFound.GetAt(m_RemoteNameCounter); 340. AfxMessageBox("Request to get remoteName \nCommand:HCI_ReqRemoteName (10,device.tAddress,device.tPageScanPeriodMode, device.tPageScanMode,device.tClockOffset )"); 341. HCI_ReqRemoteName(10, 342. device.tAddress, Chapter 9: Bluetooth Programming 173 343. device.tPageScanPeriodMode, 344. device.tPageScanMode, 345. device.tClockOffset ); 346. } 347. else 348. { 349. m_DeviceList.AddString(_T("No Devices found")); 350. } 351. } 352. void CHCIInformationCommandsDlg::OnHciRemoteNameCnf(void **ppMsg) 353. { 354. HCI_TRemoteNameCnf *ptRemoteNameCnf; 355. CRemoteDevice device; 356. char sName[248]; 357. int count; 358. AfxMessageBox("Returned RemoteDevice BD_ADDRESS\nEvent:HCI_REMOTE_NAME_CNF"); 359. ptRemoteNameCnf =(HCI_TRemoteNameCnf *) *ppMsg; 360. sprintf(sName,"%s",&ptRemoteNameCnf->tName); 361. m_DevicesFound[m_RemoteNameCounter].SetName((CString)sName); 362. m_RemoteNameCounter++; 363. count = m_DevicesFound.GetSize(); 364. if (count > m_RemoteNameCounter) 365. { 366. device = (CRemoteDevice) m_DevicesFound.GetAt(m_RemoteNameCounter); 367. HCI_ReqRemoteName(0, 368. device.tAddress, 369. device.tPageScanPeriodMode, 370. device.tPageScanMode, 371. device.tClockOffset ); 372. } 373. else 374. { 375. ShowAllDevicesFound(); 376. } 377. } 378. void CHCIInformationCommandsDlg::OnHciRemoteNameCnfNeg(void **ppMsg) 379. { 380. HCI_TRemoteNameCnfNeg *ptRemoteNameCnfNeg; 381. CRemoteDevice device; 382. int count; 383. ptRemoteNameCnfNeg =(HCI_TRemoteNameCnfNeg *) *ppMsg; 384. m_DevicesFound[m_RemoteNameCounter].SetName((CString)_T("UNKNOWN")); 385. m_RemoteNameCounter++; 386. count = m_DevicesFound.GetSize(); 387. if (count > m_RemoteNameCounter) 388. { 389. device = (CRemoteDevice)m_DevicesFound.GetAt(m_RemoteNameCounter); 390. HCI_ReqRemoteName (0, 391. device.tAddress, 392. device.tPageScanPeriodMode, 393. device.tPageScanMode, 394. device.tClockOffset); 395. } 396. else 397. { 174 Chapter 9: Bluetooth Programming 398. 399. 400. 401. 402. 403. 404. 405. 406. 407. 408. 409. 410. 411. 412. 413. 414. 415. 416. 417. 418. 419. 420. 421. 422. 423. ShowAllDevicesFound(); } } void CHCIInformationCommandsDlg::OnHciInquiryEvt(void **ppMsg) { HCI_TInquiryEvt *ptInquiryEvt; CRemoteDevice device; ptInquiryEvt =(HCI_TInquiryEvt *) *ppMsg; device.tAddress = ptInquiryEvt->tAddress; device.tPageScanMode = ptInquiryEvt->tPageScanMode; device.tPageScanPeriodMode = ptInquiryEvt->tPageScanPeriodMode, device.tClockOffset = ptInquiryEvt->tClockOffset; device.tCod = ptInquiryEvt->tCod; device.tPageScanRepMode = ptInquiryEvt->tPageScanRepMode; AddDevice(device); } void CHCIInformationCommandsDlg::OnHciStartCnf(void **ppMsg) { HCI_TStartCnf *ptStartCnf = (HCI_TStartCnf *)*ppMsg; ptStartCnf = ptStartCnf; HCI_ReqConfigurePort(0,PORTSETTINGS); } void CHCIInformationCommandsDlg::OnButton1() { AfxMessageBox("Request to select INTERFACE \nCommand:SIL_SetDevice(0,SIL_SERIAL)"); SIL_SetDevice(0,SIL_SERIAL); 424. } 425. 426. void CHCIInformationCommandsDlg::OnButton2() 427. { 428. AfxMessageBox("Request to read local device version\nCommand:HCI_ReqReadLocalVersion(0)"); 429. HCI_ReqReadLocalVersion(0); 430. } 431. void CHCIInformationCommandsDlg::OnHciReadLocalVersionCnf(void **ppMsg) 432. { 433. HCI_TReadLocalVersionCnf *tver = (HCI_TReadLocalVersionCnf *)*ppMsg; 434. AfxMessageBox("Returned Local Version\nEvent:HCI_READ_LOCAL_VERSION_CNF"); 435. CString str; 436. str.Format("Version: %d",tver->tHciVersion); 437. m_ver.SetWindowText(str); 438. } 439. void CHCIInformationCommandsDlg::OnHciReadLocalVersionCnfNeg(void **ppMsg) 440. { 441. AfxMessageBox("Read Local version Failed:\nEvent:HCI_READ_LOCAL_VERSION_CNF_NEG"); 442. } 443. void CHCIInformationCommandsDlg::OnButton3() 444. { 445. AfxMessageBox("HCI_ReqWriteLoopbackMode(1,HCI_LOOPBACK_NONE)"); 446. HCI_ReqWriteLoopbackMode(1, HCI_LOOPBACK_ LOCAL); AfxMessageBox("Returned Packet Details\nEvent:HCI_DATA_INFO_CNF").info->tMaxAclPackets). 456. • stop=1: 1 stop bit. 455. 466. 462. HCI_ReqDataInfo(1). 474. 468. } void CHCIInformationCommandsDlg::OnButton7() { OnInquiry() .info->tMaxScoPackets). 471. See the following table for more details. 24–73.SetWindowText(str). SeqNr = thdr->uiSeqNr.info->tMaxAclPacketSize). ♦ Line 23: The PORTSETTINGS is a constant in which the serial port parameters are defined.SetWindowText(str). • parity=N: parity is NONE. } void CHCIInformationCommandsDlg::OnHciWriteLoopbackModeCnfNeg(void **ppMsg) { AfxMessageBox("Failed to set Local LoopBack"). 450. m_ScoCount.Chapter 9: Bluetooth Programming 175 447. 449. • Baud=57600: Transmission speed is 57600 bps. 473. str. 453. 458. and 183–186.info->tMaxScoPacketSize). } void CHCIInformationCommandsDlg::OnButton5() { AfxMessageBox("Request to get supported packet details\n Command:HCI_ReqDataInfo(1)"). 124–143. m_AclCount. 459.Format("%d". ♦ Line 74: m_pServerEvents is an instance of Events Class.Format("%d". str.SetWindowText(str). 148–181. m_ScoSize. 477. ♦ Lines 77–87: The DDX_Control functions manage data transfer between dialog box controls and CWnd data members of the dialog box. } void CHCIInformationCommandsDlg::OnHciWriteLoopbackModeCnf(void **ppMsg) { AfxMessageBox("Local LoopBack Success"). str. 452. 454. particularly Lines 13–17. 448. } void CHCIInformationCommandsDlg::OnHciDataInfoCnf(void **ppMsg) { HCI_TDataInfoCnf *info = (HCI_TDataInfoCnf *)*ppMsg. 463. 451. 479. } Code Description Note that the VC++ MFC application wizard automatically generates some portions of the code. • data=8: 8 data bits. • COM1: The serial port address. m_AclSize. MSG_TControlHdr *thdr = (MSG_TControlHdr *)*ppMsg. 472. 475. ♦ Lines 18–22: Declaration of a union containing AEX MSG CALL function call and pfn.Format("%d". str. 476. 457. . 467. 478. 461. CString str. 465.SetWindowText(str). 470. 464. 480. pointer to the function. 469. 460.Format("%d". Button ID Function Name IDC_BUTTON1 OnButton1 IDC_BUTTON2 OnButton2 . BLUETOOTH Event Handler Function Name COM_START_CNF OnComStartCnf COM_START_CNF_NEG OnComStartCnfNeg COM_VERSION_CNF OnComVersionCnf HCI_CONFIGURE_PORT_CNF OnHciConfigurePortConfirm HCI_CONFIGURE_PORT_CNF_NEG OnHciConfigurePortConfirm Negative HCI_INQUIRY_CNF OnHciInquiryCnf HCI_INQUIRY_EVT OnHciInquiryEvt HCI_LOCAL_ADDRESS_CNF OnHciLocalAddressCnf HCI_LOCAL_ADDRESS_CNF_NEG OnHciLocalAddressCnfNeg HCI_REMOTE_NAME_CNF OnHciRemoteNameCnf HCI_REMOTE_NAME_CNF_NEG OnHciRemoteNameCnfNeg HCI_START_CNF OnHciStartCnf HCI_READ_LOCAL_VERSION_CNF OnHciReadLocalVersionCnf HCI_READ_LOCAL_VERSION_CNF_NEG OnHciReadLocalVersionCnfNeg HCI_WRITE_LOOPBACK_MODE_CNF OnHciWriteLoopbackModeCnf HCI_WRITE_LOOPBACK_MODE_CNF_NEG nHciWriteLoopbackModeCnfNeg HCI_DATA_INFO_CNF OnHciDataInfoCnf SIL_SET_DEVICE_CNF OnSilSetDeviceCnf SIL_SET_DEVICE_CNF_NEG OnSilSetDeviceCnfNeg ♦ Lines 115–119: The ON_BN_CLICKED message map macro indicates which function will handle a specified button click. Each button has a unique ID and function call associated with it (see the following table). See the following table for more details.176 Chapter 9: Bluetooth Programming Dialog box control CWnd Data member IDC_EDIT1 m_add IDC_LIST1 m_DeviceList IDC_EDIT8 m_ScoCount IDC_EDIT7 m_ScoSize IDC_EDIT6 m_AclCount IDC_EDIT5 m_AclSize IDC_EDIT2 m_ver ♦ Lines 91–122: The ON_BLUETOOTH_EVENT message map macro indicates which function will handle a specified BLUETOOTH event. PORTSETTINGS) is a BLUETOOTH SDK API to send a command to configure the serial port with the settings Defined in PORTSETTINGS. ♦ Line 195: If the event is a BLUETOOTH event.tInquiryLength. • Parameter2: Lower address part ={0x9E. LPARAM lParam) is a member function of CHCIInformationCommandsDlg Class. Unmapped BLUETOOTH events are ignored by the application. The parameters are as follows: • Parameter1: sequence number=1 (the response for this request should also have the same sequence number). • WPARAM wParam: Additional information. If it is a mapped BLUETOOTH event. WPARAM wParam.Chapter 9: Bluetooth Programming 177 IDC_BUTTON3 OnButton3 IDC_BUTTON5 OnButton5 IDC_BUTTON7 OnButton7 ♦ Line 144: The current CHCIInformationCommandsDlg dialog box is initialized to an Events class member called m_pParentDialog to receive all outgoing events generated by BT_COMServer. ♦ Lines 269–275: SIL SET DEVICE CNF event makes the ON BLUETOOTH EVENT macro to call OnSilSetDeviceCnf(void **ppMsg) message-handler function. ♦ Lines 187–202: WindowProc(UINT message. ♦ Lines 203–240: OnBluetoothEvent(UINT message. The following are the paramaters associated with this function: • UINT messag: Specifies the Windows message to be processed.tInquiryLength. • LPARAM lParam: Additional information.tNrOfResponses) is a BLUETOOTH command to discover the nearby remote BLUETOOTH devices.0x8B.0x33} • Parameter3: Maximum amount of time specified before the Inquiry is halted = 2 seconds • Parameter4: Maximum number of responses from the Inquiry = 0 (0 indicates that it allows unlimited number of responses) A message box appears to indicate that the command has been issued.tLap. which provides a Windows procedure to dispatch BLUETOOTH events to the CHCIInformationCommandsDlg Dialog box through the Windows message map. the function VOS_Free((void **)lParam) is used. lParam) function. wParam.tLap. This function checks whether the received message is a mapped BLUETOOTH event or not. A message box indicates that the serial interface selection is a success. The parameters are as follows: • Parameter1: sequence number = 0 • Parameter2: port settings = PORTSETTINGS . ♦ Line 192: Condition to check whether the received message is a BLUETOOTH event. it invokes OnBluetoothEvent (message. HCI_ReqConfigurePort(0. WPARAM wParam. it calls the corresponding message-map function. LPARAM lParam ) is a virtual function. ♦ Line 199: To free the message received from the BT COMserver. ♦ Lines 241–248: HCI_ReqInquiry(1.tNrOfResponses) causes the BLUETOOTH module to send either HCI INQUIRY CNF or HCI INQUIRY CNF NEG event corresponding to success or failure. HCI_ReqInquiry(1. ♦ Lines 308–322: HCI LOCAL ADDRESS CNF event makes the ON BLUETOOTH EVENT macro to call OnHciLocalAddressCnf(void **ppMsg) message handler function. • tLocalAddress is a structure of type HCI_TLocalAddressCnf that contains the local BLUETOOTH device address tAddress as its member. ♦ Lines 288–292: HCI CONFIGURE PORT CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnHciConfigurePortConfirmNegative(void **ppMsg) message handler function. A message box indicates that the RFCOMM could not start. A message box indicates that the serial interface selection has failed. ♦ Lines 323–327: HCI LOCAL ADDRESS CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnHciLocalAddressCnfNeg(void **ppMsg) message-handler function. A message box indicates that the retrieval of the local BLUETOOTH Device address failed. A message box indicates that the port configuration has failed. A message box displays that the port configuration is a success. This address is formatted to be displayed in the Edit control. A message box shows that the command has been issued. ♦ Lines 276–279: SIL SET DEVICE CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnSilSetDeviceCnfNeg(void **ppMsg) message-handler function. • Parameter1: sequence number = 0 • HCI_ReqLocalAddress(0) causes the BLUETOOTH module to fire either HCI LOCAL ADDRESS CNF or HCI LOCAL ADDRESS CNF NEG event corresponding to success or failure. ♦ Lines 328–351: HCI INQUIRY CNF event makes the ON BLUETOOTH EVENT macro to call OnHciInquiryCnf(void **ppMsg) message-handler function. A message box indicates that the local BLUETOOTH device address has been retrieved. A message box appears to let the user know that the command has been issued. • Parameter1: sequence number = 0 • COM_ReqStart(0) causes the BLUETOOTH module to fire either a COM START CNF or COM START CNF NEG event corresponding to success or failure. A message box indicates that the inquiry was sent to nearby BLUETOOTH radios successfully.PORTSETTINGS) causes the BLUETOOTH module to fire either HCI CONFIGURE PORT CNF or HCI CONFIGURE PORT CNF NEG event corresponding to success or failure. ♦ Lines 280–287: HCI CONFIGURE PORT CNF event makes the ON BLUETOOTH EVENT macro to call OnHciConfigurePortConfirm(void **ppMsg) message-handler function. . ♦ Lines 294–301: COM START CNF event makes the ON BLUETOOTH EVENT macro to call OnComStartCnf(void **ppMsg) message handler function. ♦ Lines 302–307: COM START CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnComStartCnfNeg(void **ppMsg) message-handler function. • COM_ReqStart(0) is a BLUETOOTH SDK API to send a command to start RFCOMM service on BLUETOOTH stack. • HCI_ReqLocalAddress(0) is a BLUETOOTH command to request Local BLUETOOTH Device address. A message box indicates that RFCOMM component has been started. A message box shows that the command has been issued.178 Chapter 9: Bluetooth Programming HCI_ReqConfigurePort(0. ♦ Lines 401–420: When an inquiry is generated by a Bluetooth device.tClockOffset). .tAddress.tAddress.tClockOffset).GetSize() returns the number of nearby BLUETOOTH devices. is a BLUETOOTH command to request remote BLUETOOTH device address. the corresponding message map function OnButton1 will be called. • The HCI_ReqRemoteName (0. As soon as the nearby BLUETOOTH device addresses are retrieved. device. the method ShowAllDevices() is used to display to the user.tPageScanMode. device. method is called to get the next remote BLUETOOTH device address. A message box shows that the command has been issued. Message boxes will appear whenever a remote BLUETOOTH device address is returned.tPageScanPeriodMode. A message box indicates that the retrieval of the remote BLUETOOTH device name has failed. ♦ Lines 352–377: HCI REMOTE NAME CNF event makes the ON BLUETOOTH EVENT macro to call OnHciRemoteNameCnf(void **ppMsg) message-handler function. • The HCI_ReqRemoteName (0. it gets one of the remote devices into device structure. ♦ Lines 378–400: HCI REMOTE NAME CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnHciRemoteNameCnfNeg(void **ppMsg) message handler function. ♦ The parameters are necessary when there is no existing connection between local BLUETOOTH device and the remote BLUETOOTH device. device.Chapter 9: Bluetooth Programming 179 • m_DevicesFound. device. device. A message box indicates that the name of a remote BLUETOOTH device has been retrieved successfully. • Parameter1: sequence number=0 • Parameter2 : address variable to hold the remote BLUETOOTH device address • Parameter3: page scan period mode • Parameter4: page scan mode • Parameter5: estimation of clock offset of the device It causes the BLUETOOTH module to fire either HCI REMOTE NAME CNF or HCI REMOTE NAME CNF NEG event corresponding to success or failure. device.tAddress.tClockOffset). ONHCI INQUIRY EVENT is generated and OnHciInquiryEvt function is called. method is called until all the remote BLUETOOTH device addresses are retrieved.tPageScanMode. which are used to request information about remote BLUETOOTH device. device. device.tPageScanPeriodMode. If the number of BLUETOOTH devices is greater than zero. device. device.tPageScanMode. device. ♦ Lines 421–424: When IDC BUTTON1 is clicked. The device structure contains members. device. • HCI_ReqRemoteName (0.tPageScanPeriodMode. SIL_SERIAL) is a BLUETOOTH SDK API to send a command to select the serial interface on the BLUETOOTH module.180 Chapter 9: Bluetooth Programming • SIL_SetDevice(0. • HCI_ReqWriteLoopbackMode(1. • Parameter1: sequence number =1 • Parameter2: Local loop back mode • HCI_ReqWriteLoopbackMode(1. A message box appears to show the user that the command has been issued. . • tver is a structure of type HCI TReadLocalVersionCnf which contains local BLUETOOTH device version tHciVersion as its member. This version number is formatted to be displayed in the Edit control. ♦ Lines 454–457: HCI WRITE LOOPBACK MODE CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnHciWriteLoopbackModeCnfNeg(void **ppMsg) message-handler function. the corresponding message map function OnButton3 is called. ♦ Lines 439–442: HCI READ LOCAL VERSION CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnHciReadLocalVersionCnfNeg(void **ppMsg) message handler function.SIL_SERIAL) causes the BLUETOOTH module to fire either SIL SET DEVICE CNF or SIL SET DEVICE CNF NEG event corresponding to success or failure. HCI_LOOPBACK_ LOCAL) is a BLUETOOTH command to set the BLUETOOTH module in local loop back mode. A message box indicates that the local BLUETOOTH device version has been retrieved. A message box will be displayed to indicate that the command has been issued. ♦ Lines 458–471: HCI DATA INFO CNF event makes the ON BLUETOOTH EVENT macro to call OnHciDataInfoCnf(void **ppMsg) message-handler function. A message box indicates that local loop back has been set. A message box indicates that local loop back setting has failed. A message box appears to let the user know that the command has been issued. ♦ Lines 426–430: When IDC BUTTON2 is clicked. ♦ Lines 443–447: When IDC BUTTON3 is clicked. • HCI_ReqReadLocalVersion(0) is a BLUETOOTH command to get the version of the BLUETOOTH module. the corresponding message-map function OnButton2 will be called. ♦ Lines 448–453: HCI WRITE LOOPBACK MODE CNF event makes the ON BLUETOOTH EVENT macro to call OnHciWriteLoopbackModeCnf(void **ppMsg) message-handler function. • Parameter1: sequence number = 0 • HCI_ReqReadLocalVersion(0) causes the BLUETOOTH module to fire either HCI READ LOCAL VERSION CNF or HCI READ LOCAL VERSION CNF NEG event corresponding to success or failure. A message box indicates that the local BLUETOOTH device supported packet information has been retrieved. ♦ Lines 431–438: HCI READ LOCAL VERSION CNF event makes the ON BLUETOOTH EVENT macro to call OnHciReadLocalVersionCnf(void **ppMsg) message handler function. • Parameter1: sequence number of the interface = 0 • Parameter2: type of interface = SIL SERIAL • SIL_SetDevice(0. HCI_LOOPBACK_ LOCAL) causes the BLUETOOTH module to fire either an HCI LOOPBACK LOCAL CNF or HCI LOOPBACK LOCAL CNF NEG event corresponding to success or failure. A message box indicates that the local BLUETOOTH device version retrieval failed. #include <exp/bt. { 12. Listing 9-3 is a header file for constant definitions and class declaration. virtual ~CRemoteDevice(). This OnButton7() in turn calls the function OnInquiry(). ♦ Lines 472–476: When IDC BUTTON5 is clicked. 28. #endif .h © 2001 Dreamtech Software India Inc. 19. 2. #if _MSC_VER > 1000 6. #pragma once 7. the corresponding message-handler function OnButton5 is called. uint16 tClockOffset. CRemoteDevice(CString sAddress. 26. CString m_Name. ♦ Lines 477–480: After the IDC BUTTON7 is clicked. 23. the corresponding message handler function OnButton7 is called. 29. class CRemoteDevice 11. private: 27. • HCI_ReqDataInfo(1) is a BLUETOOTH command to get the supported packet information of the BLUETOOTH module. 20. // RemoteDevice.Chapter 9: Bluetooth Programming 181 Info is a structure of type HCI_TdataInfoCnf. uint8 tPageScanPeriodMode. All Rights Reserved 1.CString sName). 16. 18. maximum number of ACL packets. HCI_TCod tCod. A message box appears to show the user that the command has been issued. #include <exp/hci. 17. }. #if !defined(AFX_DEVICE_H__E7DA5337_C36C_11D3_B6C6_0060082D5EF1 __INCLUDED_) 4. #define AFX_DEVICE_H__E7DA5337_C36C_11D3_B6C6_0060082D5EF1__ INCLUDED_ 5.h> 9. 25. CRemoteDevice(). //////////////////////////////////////////////////////////// 3. 15. uint8 tPageScanRepMode. Listing 9-3: RemoteDevice. BT_TAddress tAddress. public: 13. #endif // _MSC_VER > 1000 8. CString GetName(). uint8 tPageScanMode. CString GetAddress (). void SetName(CString sName). Info contains maximum size of ACL packet. 30. 14.h: interface for the CRemoteDevice class. • Parameter1: sequence number = 1 • HCI_ReqDataInfo(1) causes the BLUETOOTH module to fire either HCI DATA INFO CNF or HCI DATA INFO CNF NEG event corresponding to success or failure. 21. 22. void SetAddress (CString sAddress).h> 10. 24. CString m_Address. The packet information contains ACL packet details and as well as SCO packet details. maximum size of SCO packet and maximum number of SCO packets as its members. The packet information is formatted to be displayed in Edit controls. sprintf(s. m_Address. 15.Empty(). CRemoteDevice::CRemoteDevice(CString sAddress. 28. #undef THIS_FILE 8.ucByte1. 45. Listing 9-4: RemoteDevice. static char THIS_FILE[]=__FILE__. } 29.tAddress.//sAddress. return (CString) s. and Lines 10 to 30 are for CRemoteDevice class declaration with public and private members. 37. m_Name = sName. 2. { 19. return m_Name.cpp: implementation of the CRemoteDevice class. // ////////////////////////////////////////////////////////////// 3.h" 6. tAddress. { 44. 20. #ifdef _DEBUG 7.tAddress.h" 4. } . m_Address = sAddress. The various methods and variables used are explained in the Listing 9-4. { 27. 21. #include "RemoteDevice. //RemoteDevice. which gives the source code for RemoteDevice. 41.ucByte2. tAddress. #endif 11. void CRemoteDevice::SetName(CString sName) 30. } 25. } 17. All Rights Reserved 1. } 22.cpp © 2001 Dreamtech Software India Inc. 36. } 33. CString sAddress.ucByte4. 38. char s[80]."%02X%02X%02X%02X%02X%02X".ucByte5). CRemoteDevice::CRemoteDevice() 13.h" 5. CString CRemoteDevice::GetName() 43.ucByte3. { 31. CRemoteDevice::~CRemoteDevice() 23.cpp. } 42.Empty(). #include "stdafx. 12. void CRemoteDevice::SetAddress (CString sAddress) 26. 39.CString sName) 18. #define new DEBUG_NEW 10. m_Address = sAddress. tAddress.ucByte0. Lines 8 and 9 are for including the necessary Bluetooth header files. m_Name. 40. 9. m_Name = sName. #include "HCI Information Commands. TAddress. CString CRemoteDevice::GetAddress () 34. { 35. 32. { 14.182 Chapter 9: Bluetooth Programming Code Description Lines 1 to 7 are automatically generated. 16. { 24. DECLARE_DYNCREATE(Events) 5. IConnectionPointContainer *m_pConnectionPointContainer. ♦ Lines 33–41: GetAddress() member function is defined to return the BLUETOOTH device address as formatted string. 18. Listing 9-5 is the header file for the necessary declarations for the COM components. IVOSProcess *m_pVOSProcessInterface. virtual ~Events(). //}}AFX_DISPATCH 21. 7. public: 6. DECLARE_MESSAGE_MAP() 19. afx_msg SCODE MsgReceived(VARIANT FAR *pvMsg. CHCIInformationCommandsDlg *m_pParentDialog. protected: 13. All Rights Reserved 1. 8. IConnectionPoint *m_pConnectionPoint. 2. }. ♦ Lines 29–32: SetName(CString sName) member function is defined to initialize BLUETOOTH device name to a data member of CremoteDevice class. ♦ Lines 22–23: CRemoteDevice destructor is defined to destruct the class. 10. lines 1–10 are automatically generated by the MFC application wizard. class CHCIInformationCommandsDlg. ♦ Lines 25–28: SetAddress (CString sAddress) member function is defined to initialize BLUETOOTH device address to a data member of CRemoteDevice class. public: 11. public: 9. DECLARE_INTERFACE_MAP() 23. LONG SenderID).Chapter 9: Bluetooth Programming 183 Code Description In Listing 9-4. virtual void OnFinalRelease(). 17. ♦ Lines 42–45: GetName() member function is defined to return the BLUETOOTH device name in the form of a data member of CRemoteDevice class. Events(). #endif . class Events : public CCmdTarget 3. 14. 12. 15. { 4. IVOSProcess *m_pVOSProcess. Explanations for the rest of the code are as follows: ♦ Lines 12–16: CRemoteDevice constructor is defined and used to free the content stored in variables m_Address and m_Name by applying the Empty() method. 16. private: 24. ♦ Lines 17–21: CRemoteDevice constructor is overloaded to initialize the remote BLUETOOTH device address and its name. 25. 20. DWORD m_ConnectionPointID. Listing 9-5: Events. DECLARE_DISPATCH_MAP() 22.h © 2001 Dreamtech Software India Inc. h" 6. #define new DEBUG_NEW 11. All Rights Reserved 1. // make a connection to the BT_COMServer 22. #include <exp\SafeArray. #ifdef _DEBUG 10. #include "HCI Information CommandsDlg. 24. MessageBox(NULL.h" */ 16. // first make contact to the BT_COMServer 27.MB_OK). { 21. } 36. Events::Events() 20. IMPLEMENT_DYNCREATE(Events.h> 9. 26. #include "events. 19.h" 4. clsid = CLSID_VOSProcess. #include "HCI Information Commands. 23. 28.cpp : implementation file 2. #endif 14.cpp. 39. static char THIS_FILE[] = __FILE__.h" 7. CoInitialize(NULL).NULL.h" 3.h> 8. #undef THIS_FILE 12. //Get Connection point container for BT_COMServer . (void **)&m_pVOSProcessInterface). Listing 9-6: Events. 40. 15. 17._T("No Instance Created"). CCmdTarget) 18. extern IVOSProcess* Server. the necessary COM server component variables are declared in Listing 9-5. EnableAutomation(). HRESULT hr=CoCreateInstance (CLSID_VOSProcess.IID_IVOSProcess. CLSID clsid. 31.NULL. (void **)&m_pVOSProcess).MB_OK). MessageBox(NULL. // Events. #include <exp\vos2com._T("No VosProcess Supported"). // Get interface form BT_COMServer 29. { 33.h" 5.CLSCTX_LOCAL_SERVER. if (FAILED(hr)) 37. #include "WinError. #include "stdafx. The use of the variables is evident in the Listing 9-6. } 41.cpp © 2001 Dreamtech Software India Inc. 34.184 Chapter 9: Bluetooth Programming Code Description For the Bluetooth PC reference stack to access the COM component. 35. exit(0). else 32. m_pVOSProcess = NULL. 25. { 38. if (SUCCEEDED(hr)) 30. hr=m_pVOSProcess->QueryInterface(IID_IVOSProcess.NULL. 13. which gives the source code for Events. exit(0). /* variable declared in vos2com. 58. 54. break. exit(0). 76. 79."). break. } MessageBox(NULL.Chapter 9: Bluetooth Programming 185 42. 64. (void **)&m_pConnectionPointContainer). 49. 66. 65.NULL. 59. 80.MB_OK). 46. 78. 84. For example. if (SUCCEEDED(hr)) { // Pointer to the client's advise sink . 56. &m_ConnectionPointID). } . default: MessageBox(NULL. exit(0).").MB_OK). 63.MB_OK)._T("The connection point has already reached its limit of connections and cannot accept any more. 81. case CONNECT_E_CANNOTCONNECT : MessageBox(NULL. either pointer may be NULL. 52.NULL._T("error not defined"). 61.NULL. 55. 51.MB_OK). m_pConnectionPointContainer->Release().MB_OK). 45. 68. 44. hr=m_pVOSProcess-> QueryInterface(IID_IConnectionPointContainer. hr=m_pConnectionPoint->Advise(lpServerDispatch._T("No IConnectionPointContainer supported"). 57. 82.NULL. 43._T("No connection point"). if (SUCCEEDED(hr)) { // then get connection point hr=m_pConnectionPointContainer-> FindConnectionPoint(DIID__IVOSProcessEvents._T("The value in pUnk or pdwCookie is not valid._T("Advise failed"). } } else { MessageBox(NULL.NULL. 60. 72. 75. 62._T("The sink does not support the interface required by this connection point. 77. 50.NULL. break. exit(0). 69. case CONNECT_E_ADVISELIMIT : MessageBox(NULL.MB_OK).NULL. } } else { MessageBox(NULL. 47. 83. 53."). break. 73. if (((hr!=S_OK))||(m_ConnectionPointID==0)) { switch (hr) { case E_POINTER : MessageBox(NULL.MB_OK). m_ServerEvents will receive all // outgoing events from the BT_COMServer LPDISPATCH lpServerDispatch = GetIDispatch(TRUE).&m_pConnectionPoint). 70. 71. 67. 48. 74. { 132. if (m_pVOSProcess) 87. //}}AFX_MSG_MAP 115. 123. { 0x425E3D83. DISP_FUNCTION(Events. BEGIN_DISPATCH_MAP(Events. CCmdTarget) 112. 124. 135. } 102. { 0x98. 0xB0. { 96. VTS_VARIANT VTS_I4 ) 119. INTERFACE_PART(Events. . 127. 86. // OnFinalRelease is called. IID_IServerEvents. //Access to Server functions 89. tMemHeader *ptDummy. } 93. { 104. // deletes the object. 0x90. 0x1C. 98. } 111. VT_ERROR. Add additional cleanup required for your 107. LONG SenderID) 131. MsgReceived.the ClassWizard will add and remove mapping macros here. END_INTERFACE_MAP() 130. //{{AFX_DISPATCH_MAP(Events) 118. 90. 0x11D3. 0x00. 0x90. BEGIN_INTERFACE_MAP(Events. // TODO: Add your dispatch handler code here 133. Events::~Events() 95. if (m_pConnectionPoint) 97. SCODE Events::MsgReceived(VARIANT FAR *pvMsg. 100. CCmdTarget) 117. 110. 122. 0x7714. // NOTE . { 88. 134. 114. m_pVOSProcessInterface->Release(). // When the last reference for an automation object is released 105. SAFEARRAY FAR* psaMsg. 0x35 } }. //}}AFX_DISPATCH_MAP 120. 99. InitVOSProcesses(). } 94. 109. 92. 108. The base class will automatically 106. // object before calling the base class.186 Chapter 9: Bluetooth Programming 85. BEGIN_MESSAGE_MAP(Events. 101. CCmdTarget::OnFinalRelease(). "method MsgReceived". static const IID IID_IServerEvents = 126. void Events::OnFinalRelease() 103. Server = m_pVOSProcess. m_pConnectionPointContainer->Release(). 91. END_DISPATCH_MAP() 121. 0x27. //{{AFX_MSG_MAP(Events) 113. Dispatch) 129. m_pConnectionPoint->Release(). 125. END_MESSAGE_MAP() 116. MSG_TMsg *ptMsg. CCmdTarget) 128. m_pConnectionPoint->Unadvise(m_ConnectionPointID). as shown in Figure 9-1. 146. ♦ Line 25: the CoInitialize(NULL). the main window appears. // Calculate beginning of memory header ptDummy = (tMemHeader*)((char*)ptMsg-(sizeof(tMemHeader)sizeof(void *))). . ♦ Line 22: EnableAutomation() function is called to enable OLE automation for theBT COMSERVER component. the lines 9–13. } //Retrieve SafeArray from the variant type psaMsg = (SAFEARRAY FAR*) V_ARRAY(pvMsg). 145. Explanations for the remaining code are as follows.(WPARAM) ptMsg->tHdr. ♦ Lines 89 and 90: This code is to access all the outgoing events from BT COMSERVER.tID. 140. ♦ Lines 47–88: This code generates diagnostic messages in the form of message boxes. 138. 142. // Gerrit: Sender filling added.(LPARAM) &ptMsg). ♦ Line 46: Gets connection point for BT COMSERVER. ♦ Lines 14–16: Variables declaration. a switch statement is used to take care of different cases. 141.(LPARAM)&ptMsg). function is used to initialize the COM library. and 111–120 are automatically generated by the class wizard. WM_BLUETOOTH_EVENT. 144.tID. a series of messages are displayed. Code Description In Listing 9-6.Chapter 9: Bluetooth Programming 187 136. 17. WM_BLUETOOTH_EVENT. ♦ Lines 102–110: OnFinalRelease is called when the last reference for an automation Object is released to clean up the objects. ♦ Line 27: This function is called to get an instance of BT COMSERVER. clsid is the ID of the COM component. return S_OK. Code Output After you build the project in the VC++ environment and execute its application. // convert the SafeArray to Bluetooth Stack message ptMsg = (MSG_TMsg *)SafeArrayToMsg(psaMsg). ♦ Lines 130–146: SendMessage(m_pParentDialog->m_hWnd. ♦ Lines 94–101: The destructor is defined to release the memory for all pointers. ♦ Lines 31–45: If creation of COM component instance creation fails. 139. SendMessage(m_pParentDialog->m_hWnd. 137.(WPARAM) ptMsg->tHdr. ♦ Lines 111–120: This code is generated by MFC application wizard. 143. function is used to send events to CHCIInformationDlg. ptDummy->tSender = (VOS_TProcess) SenderID. ♦ Lines 29 and 30: This function is called to get the interface associated with the BT COMSERVER. It shows that the command HCI_ReqConfigurePort(0. . It shows that the command SIL_SetDevice(0. After the OK button is clicked on the previous message box. After the OK button in the previous message box is clicked.188 Chapter 9: Bluetooth Programming Figure 9-1: Output of HCI Application The screen in Figure 9-1 contains the following buttons: ♦ button1: GET LOCAL DEVICE ADDRESS ♦ button2: GET DEVICE VERSION ♦ button3: SUPPORTED PACKET DETAILS ♦ button4: REMOTE DEVICE DETAILS ♦ button5: TEST LOCAL LOOPBACK After button1 (GET LOCAL DEVICE ADDRESS) is clicked.SIL_SERIAL) has been issued. the following message box appears. It shows that the event SIL_SET_DEVICE_CNF has been generated.PORTSETTINGS) has been issued. the following message box appears. the following message box appears. It shows that the command COM_ReqStart(0) has been issued. It shows that the command HCI_LOCAL_ADDRESS_CNF has been issued. It shows that the command HCI_CONFIGURE_PORT_CNF has been issued. the following message box appears. the following message box appears. After clicking the OK button. It shows that the command HCI_ReqLocalAddress(0) has been issued. the following message box appears. After you click the OK button. the following message box appears. It shows that the command COM_START_CNF has been issued. After clicking the OK button.Chapter 9: Bluetooth Programming 189 After the OK button is clicked. the following message box appears. . After clicking the OK button. After clicking the OK button. It shows that the command HCI_READ_LOCAL_VERSION_CNF has been issued.190 Chapter 9: Bluetooth Programming After you click the OK button. the local device address is displayed in the edit box. as shown in Figure 92. Figure 9-2: Window showing the Local Device Address After button2 (GET DEVICE VERSION) is clicked. It shows that the command HCI_ReqReadLocalVersion(0) has been issued. the following message box appears. . the following message box appears. After clicking the OK button.Chapter 9: Bluetooth Programming 191 After you click the OK button. as shown in Figure 93. Figure 9-3: Window showing the Device Version After button3 (SUPPORTED PACKET DETAILS) is clicked. It shows that the command HCI_ReqDataInfo(1) has been issued. the following message box appears. local device VERSION is displayed in the edit box. . the following message box appears. It shows that the event HCI_DATA_INFO_CNF has been returned. as shown in Figure 9-4.tAddress. the following message box appears.tLap.tPa geScanMode.tNrOfResponses) has been issued. It shows that the command HCI_ReqInquiry(1.192 Chapter 9: Bluetooth Programming After the OK button is clicked.device.device.tPageScanPeriodMode. the following message box appears. It shows that the command HCI_ReqRemoteName(10. After clicking the OK button. the supported packet details displays in the corresponding edit boxes. the following message box appears. After clicking the OK button. It shows that the event HCI_INQUIRY_CNF has been returned. Figure 9-4: Window showing the Supported Packet Details After button4 (REMOTE DEVICE DETAILS) is clicked. .device.tClockOffset) has been issued.device.tInquiryLength. .HCI_LOOPBACK_NONE) has been issued. the Remote device address displays in the corresponding edit box. the following message box appears. the following message box appears on the screen. Figure 9-5: Window showing the Remote Device Details After button5 (TEST LOCAL LOOPBACK) is clicked. It shows that the event HCI_REMOTE_NAME_CNF has been returned. as shown in Figure 9-5. It indicates that the command HCI_ReqWriteLoopbackMode(1.Chapter 9: Bluetooth Programming 193 After clicking the OK button. After the OK button is clicked. h. ♦ EVENTS: Same function as in HCI. the next step is to discover the services available on other Bluetooth devices. The corresponding header file is CommandsDlg. Registering and Discovering Services: SDP Programming This example illustrates how to register a service in a Bluetooth device and how to access the service from other Bluetooth devices. The corresponding header file is RS232.h. The Service Discovery Protocol (SDP) is used to achieve this. . one can provide a print service. This module is implemented with CPrintProfile class in the file named PrintProfile.h. We will see how to register a print service. Now that we have completed the HCI programming to make the stack talk to the Bluetooth module and also to obtain the information about the remote Bluetooth devices.CPP. This module is implemented with CSDPInformationCommandsDlg class in the file named SDP Information CommandsDlg. Listing 9-7 gives the source code for the header file CommandsDlg. The software consists of the following five modules: ♦ GUI: This module provides the user interface to register a Bluetooth service. Database Manager. For each command generated by the user. Click OK to return to the main window. is used.cpp. For the service registration. ♦ PRINTSERVICE: This module defines a print profile to implement print service. ♦ REMOTEDEVICE: Same function as in HCI. the following message box appears. Click Cancel on the main window to quit from the application.194 Chapter 9: Bluetooth Programming After you click the OK button.cpp. which is a part of the SDP. The corresponding header file is PrintProfile. The print profile provides the necessary information about print service to remote Bluetooth devices. ♦ RS232: This module registers the defined print service in the Database of Bluetooth stack by calling DBM (Database Manager). This module is implemented with CRS232 class in the file named RS232. This service has to be registered so that the other PC can first discover the service and then use it.h. in which necessary library files are imported and variables and classes are declared. the Bluetooth module fires the corresponding Bluetooth event. Of the two Bluetooth-enabled PCs. The user can identify whether the issued command is successful or not by getting the fired event information in the message boxes. \ 23. uiBtEventID. #pragma once 9. (AFX_PMSG)(AFX_PMSGW)(void (AFX_MSG_CALL CWnd::*)(void **))&memberFxn }. #endif // _MSC_VER > 1000 10.pMsg) \ 26. memberFxn) \ 22.1. public: 36. 4. // ClassWizard generated virtual function overrides . //{{AFX_DATA(CSDPInformationCommandsDlg) 41. #define ON_BLUETOOTH_EVENT(uiBtEventID. 24. // standard constructor 38. #define WM_BLUETOOTH_EVENT (WM_USER + 100) 20. #include "RS232.0. 45. 42. #include "Events. enum { IDD = IDD_SDPINFORMATIONCOMMANDS_DIALOG }. SendMessage((HWND)this_hWnd. { 34. #if _MSC_VER > 1000 8. // Construction 35. // SDP Information CommandsDlg. #include "RemoteDevice. // Dialog Data 40. 30.h © 2001 Dreamtech Software India Inc.h" 15. #define AFX_SDPINFORMATIONCOMMANDSDLG_H__93104A63_A111_11D2_B76C_0080C805A679__INCLUD ED_ 6. 18. 25.(LPARAM) &pMsg) 27.(WPARAM)uiBtEventID. 7. 17. 19. 37. CSDPInformationCommandsDlg(CWnd* pParent = NULL). 39. { WM_BLUETOOTH_EVENT.h : header file 2. void SetDevice(). #include <afxtempl. 21. // 3. 32. #define SEND_BT_EVENT(uiBtEventID. 28. 29.h" 14.h" 13.0.Chapter 9: Bluetooth Programming 195 Listing 9-7: CommandsDlg. // NOTE: the ClassWizard will add data members here 43.WM_BLUETOOTH_EVENT. //}}AFX_DATA 44. // CSDPInformationCommandsDlg dialog 31. 11. #if !defined(AFX_SDPINFORMATIONCOMMANDSDLG_H__93104A63_A111_11D2_B76C_0080C805A67 9 INCLUDED_) 5. 12. class CSDPInformationCommandsDlg : public CDialog 33.h> 16. All Rights Reserved 1. // Generated message map functions //{{AFX_MSG(CSDPInformationCommandsDlg) virtual BOOL OnInitDialog(). 51. 52. virtual LRESULT WindowProc(UINT message. m_RFServerChannel. 60. 76. 66. //{{AFX_VIRTUAL(CSDPInformationCommandsDlg) protected: virtual void DoDataExchange(CDataExchange* pDX). 73. 86. }. 80. 75. 79. 64. 74. Lines 19–29 define the constants and members for the prototypes. 70. //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. 82. 47. afx_msg void OnPaint(). 54. LPARAM lParam). 84. 53. WPARAM wParam. Events *m_pServerEvents. 57. //}}AFX_MSG DECLARE_MESSAGE_MAP() private: BOOL OnBluetoothEvent(UINT message. 69. 68. #endif // !defined(AFX_SDPINFORMATIONCOMMANDSDLG_H__93104A63_A111_11D2_B76C_ 0080C805A679 INCLUDED_) Code Description In Listing 9-7. 83. 61. All Rights Reserved . LPARAM lParam). Lines 12–15 are include files to import the necessary header files. 78. These variables and methods are explained in the detailed explanation provided for Listing 9-8. 72. LPARAM lParam). 56.CRemoteDevice&> m_DevicesFound. 58. afx_msg void OnDbmStartCnf(void **ppMsg). 71. 81. CRS232 *m_pSerialPort. int m_ServiceCounter.cpp © 2001 Dreamtech Software India Inc.cpp file. afx_msg void OnStart(). 48. WPARAM wParam. 63. afx_msg HCURSOR OnQueryDragIcon(). 50. 62. 77. 65. afx_msg void OnDbmRegisterCnfNeg(void **ppMsg). 55. 49. 67. CArray <CRemoteDevice. Lines 30–86 give the class definition with the necessary variables and methods required in the CommandDLg. afx_msg void OnRegisterService(). Listing 9-8: CommandDlg. 85. //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon. uint16 uint8 m_RFCommHandle. 59. afx_msg void OnSysCommand(UINT nID. afx_msg void OnDbmRegisterCnf(void **ppMsg). int m_RemoteNameCounter.196 Chapter 9: Bluetooth Programming 46. lines 4–11 are automatically added by the VC++ application wizard. { 33. // Dialog Data 46. #include <exp\dbm. #include "SDP Information CommandsDlg. #include "stdafx. #include <exp\sds. #ifdef _DEBUG 24. static char THIS_FILE[] = __FILE__. 36. #undef THIS_FILE 26.h" 6. #include <exp\hci_drv. 48.h> 18. //{{AFX_VIRTUAL(CAboutDlg) 52. 8. 45. }. #define new DEBUG_NEW 25. 4. 22. #include <exp\sd. // CAboutDlg dialog used for App About 39. virtual void DoDataExchange(CDataExchange* pDX).cpp : implementation file 2.Chapter 9: Bluetooth Programming 197 1.h> 17. 10. { 42.h> 20. //}}AFX_DATA 49. protected: 53. // SDP Information CommandsDlg. // ClassWizard generated virtual function overrides 51. //}}AFX_VIRTUAL .h> 11.h> 14. #include <exp\com.h> 15.h> 13. 37.h> 12. 27. enum { IDD = IDD_ABOUTBOX }. #include <exp\hci. #endif 28. 44. CAboutDlg(). 30. 21.h> 19. 50. 9. 35. #include <exp\msg.h> 16. // generic member function pointer 34. 23. 40. union MessageMapFunctions 32. #include <exp\vos2com. 29. //{{AFX_DATA(CAboutDlg) 47. void (AFX_MSG_CALL CWnd::*pfn_btf)(void **). #include "SDP Information Commands. AFX_PMSG pfn. #include <exp\scm. class CAboutDlg : public CDialog 41. //DDX/DDV support 54. ///////////////////////////////////////////////////////////////////////////// 38. // 3. 31.h" 5. #include <exp\sil.h" 7. public: 43. 79. 93. 75. //{{AFX_DATA_MAP(CSDPInformationCommandsDlg) 100.198 Chapter 9: Bluetooth Programming 55. 57. 99. 61. } 92. { 98. 59. ON_WM_SYSCOMMAND() 107. 95. 78. 104. 66. 65. } 103. // NOTE: the ClassWizard will add DDX and DDV calls here 101. 77. pParent) { //{{AFX_DATA_INIT(CSDPInformationCommandsDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME). 74. 58. 82. 60. 68. 91. 84. 63. 73. ON_WM_PAINT() 108. 90. 56. 76. 64. 80. 70. 89. CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSDPInformationCommandsDlg dialog CSDPInformationCommandsDlg::CSDPInformationCommandsDlg(CWnd* pParent /*=NULL*/) : CDialog(CSDPInformationCommandsDlg::IDD. // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }. 69. void CSDPInformationCommandsDlg::DoDataExchange(CDataExchange* 97. 96. CDialog) 105. 81. //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg. 87. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX). 86. m_pServerEvents = new Events(). CDialog::DoDataExchange(pDX). 71. 85. 83. BEGIN_MESSAGE_MAP(CSDPInformationCommandsDlg. 67. //{{AFX_MSG_MAP(CSDPInformationCommandsDlg) 106. ON_WM_QUERYDRAGICON() pDX) . //}}AFX_DATA_MAP 102. 62. 94. 72. 88. CDialog::OnSysCommand(nID. } 162. 146. 157. ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF. // when the application's main window is not a dialog 143. ///////////////////////////////////////////////////////////////////////////// 117. } 158." menu item to system menu. The framework does this automatically 142. BOOL CSDPInformationCommandsDlg::OnInitDialog() 120. SetIcon(m_hIcon. // Set the icon for this dialog. 161. 124. 137. TRUE). CDialog::OnInitDialog(). // return TRUE unless you set the focus to a control 149.OnDbmStartCnf) 111. 141. CString strAboutMenu. // IDM_ABOUTBOX must be in the system command range.. 128. CAboutDlg dlgAbout. if (!strAboutMenu. // TODO: Add extra initialization here 147. m_pServerEvents->m_pParentDialog = this. END_MESSAGE_MAP() 115. { 153. IDM_ABOUTBOX. } . CMenu* pSysMenu = GetSystemMenu(FALSE). } 139. 156. pSysMenu->AppendMenu(MF_STRING. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX). 126. //}}AFX_MSG_MAP 114. strAboutMenu. strAboutMenu). LPARAM lParam) 152. // Add "About. else 159. 130.IsEmpty()) 135. 133. 123. return TRUE. 134.OnDbmRegisterCnf) 112. ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF_NEG. { 121.OnDbmRegisterCnfNeg) 113.. // CSDPInformationCommandsDlg message handlers 118. } 150. { 132. 125. } 140. ON_BLUETOOTH_EVENT(DBM_START_CNF. 127. FALSE). 119. dlgAbout. if ((nID & 0xFFF0) == IDM_ABOUTBOX) 154. lParam). { 136. pSysMenu->AppendMenu(MF_SEPARATOR).Chapter 9: Bluetooth Programming 199 109.DoModal(). 122. 151. SetIcon(m_hIcon. // Set big icon 144. 116.LoadString(IDS_ABOUTBOX). 148. ASSERT(IDM_ABOUTBOX < 0xF000). 138. if (pSysMenu != NULL) 131. { 160. ON_BN_CLICKED(IDC_BUTTON1. OnStart) 110. // Set small icon 145. void CSDPInformationCommandsDlg::OnSysCommand(UINT nID. 129. { 155. Height() . if (message == WM_BLUETOOTH_EVENT) 208. } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. 211. 166. 189.200 Chapter 9: Bluetooth Programming 163. 197. int y = (rect. 176. 206. GetClientRect(&rect). 200.cyIcon + 1) / 2. // TODO: Add your specialized code here and/or call the base class 205. For MFC applications using the document/view model. ptMsg = (MSG_TMsg**)lParam. CRect rect. } else { CDialog::OnPaint(). 202. } 194. 190. 195. 188. { 209. { 204. // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON). if (*ptMsg != NULL) 215. 174. MSG_TMsg **ptMsg. 173.GetSafeHdc(). int cyIcon = GetSystemMetrics(SM_CYICON). m_hIcon). } . // Draw the icon dc. 198. OnBluetoothEvent( message. (WPARAM) dc. 181. 180. 187. // If you add a minimize button to your dialog. 178. // it is a Bluetooth event so call the corresponding handlefunction 210. 216. 196. VOS_Free((void **)lParam). 179. 213. 182. 207. LPARAM lParam) 203. 0). void CSDPInformationCommandsDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this). 199.DrawIcon(x. 191. 185. LRESULT CSDPInformationCommandsDlg::WindowProc(UINT message. 170. // this is automatically done for you by the framework.Width() . 172. /* free the message received from the bluetooth server */ 214. // device context for painting SendMessage(WM_ICONERASEBKGND. WPARAM wParam. 165. 171. lParam). 193. 164. HCURSOR CSDPInformationCommandsDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon. 168. 167. 201. 212. y. 183. 169. you will need the code below // to draw the icon. wParam. int x = (rect.cxIcon + 1) / 2. 186. 177. 192. 175. 184. #else 230. . DBM_ReqStart(0). #else 238. pMessageMap != NULL. 237. pMessageMap != NULL. lParam). 224. for (pMessageMap = GetMessageMap(). // C version of search routine 242. } 256. #ifdef _AFXDLL 227. 228. #endif 233. lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]). // TODO: Add your control notification handler code here 268. 257. pMessageMap = pMessageMap->pBaseMap) 232. // found it 248. union MessageMapFunctions mmf. // look through message map to see if it applies to us 226. const AFX_MSGMAP* pMessageMap. #endif 240. // Note: catches BEGIN_MESSAGE_MAP(CMyClass. { 267. //lets call the function to handle the message 252.pfn = lpEntry->pfn. BOOL CSDPInformationCommandsDlg::OnBluetoothEvent(UINT message. } 258. void CSDPInformationCommandsDlg::OnStart() 266. } 261. WPARAM wParam. 265. 241. } 271. 231. { 245. return TRUE.Chapter 9: Bluetooth Programming 201 217. CMyClass)! 235. /* unable to find a handler function for this Bluetooth event */ 259. wParam. 218. 223. 262. 254. while (lpEntry->nSig != AfxSig_end) 244. if ((lpEntry->nMessage == message) && (lpEntry->nCode == wParam)) 246. } 263. } 219. 243. { 222. 250. ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()). 225. return CDialog::WindowProc(message. { 234. AfxMessageBox("DBM_ReqStart(0)"). (((CWnd *)this)->*mmf. return FALSE. for (pMessageMap = GetMessageMap(). LPARAM lParam) 221. 253. lpEntry++. 255. 269. mmf. ASSERT(pMessageMap != pMessageMap->pBaseMap). 260. const AFX_MSGMAP_ENTRY* lpEntry. return FALSE. #ifdef _AFXDLL 236. 270. 220.pfn_btf)((void **)lParam). 239. 264. { 247. 249. pMessageMap = (*pMessageMap->pfnGetBaseMap)()) 229. 251. 276. and variables. DBM_TRegisterServiceCnf *ptRegisterCnf = (DBM_TRegisterServiceCnf *) *ppMsg. ♦ Line 93: The m_pServerEvents is an instance of the Events class. // write the profile in DBM m_pSerialPort->WriteProfile(ptRegisterCnf->ulDbmHandle).202 Chapter 9: Bluetooth Programming 272. 301. 308. } void CSDPInformationCommandsDlg::OnDbmRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. 284. 278. 275. 296. AfxMessageBox("DBM Start Confirmation"). 294. } Code Description ♦ Lines 1–19: All the necessary function prototypes and variables are included in this class. ♦ Lines 96–102: Visual C++ class wizard adds the lines for DDX and DDV. 291. 300. void CSDPInformationCommandsDlg::OnDbmStartCnf(void **ppMsg) { CString sAddress. Some of these included files exports Bluetooth APIs. 302. // let the user know MessageBox(_T("Could not register to Data Base Manager")). 298. 310. 305. 281. 289. 303. constants. 307. 309. 306. ♦ Lines 83–94: Visual C++ editor adds this default class initialization code. 282. ptStartCnf =(DBM_TStartCnf *) *ppMsg. 274. DBM_TStartCnf *ptStartCnf. 299. 273. 297. } void CSDPInformationCommandsDlg::OnDbmRegisterCnf(void **ppMsg) { AfxMessageBox("DBM Register Service Confirmation"). . AfxMessageBox("New Service Was Registered"). 292. 290. 277. 283. ♦ Lines 31–35: The union named MessageMapFunctions is defined. DestroyWindow(). 304. 285. 286. 293. ♦ Lines 38–82: These lines indicate the MFC Application Wizard framework for About dialog. 279. 280. 288. ♦ Lines 23–27: Visual C++ editor generates these lines to give a common framework for all MFC applications through the application wizard. 287. 295. // Create Profile for SerialPort m_pSerialPort = new CRS232(PROFILE_SERIAL). ♦ Lines 202 to 218: The method WindowProc(UINT message. which is used to send a command to start the Database Manager on BLUETOOTH module. • ON_WM_SYSCOMMAND () • ON_WM_PAINT () • ON_WM_QUERYDRAGICON () ♦ The ON BLUETOOTH EVENT message map macro indicates which function handles a specified BLUETOOTH event. WPARAM wParam.Chapter 9: Bluetooth Programming 203 ♦ Lines 104–114: The following message map macros are default macros provided by VC++ MFC Application Wizard. ♦ Lines 195–198: OnQueryDragIcon()method is defined by Visual C++ MFC application wizard to create an ICON for the current dialog. • DBM_ReqStart(0) is a BLUETOOTH SDK API. ♦ Lines 272–285: DBM START CNF event makes the ON BLUETOOTH EVENT macro to call OnDbmStartCnf(void **ppMsg) message handler function. ♦ Lines 220–262: The method OnBluetoothEvent(UINT message. the corresponding message-handler function OnStart() is called. Button ID Function Name IDC_BUTTON1 OnStart ♦ Lines 117–149: OnInitDialog() method is provided by Visual C++ MFC Application wizard to initialize necessary information. • m_pSerialPort = new CRS232(PROFILE_SERIAL) — After the Database Manager has been started. — This statement is used to associate current dialog with the Events class member to get all the outgoing events from BT COMSERVER. • m_pServerEvents->m_pParentDialog = this. ♦ Lines 168–191: OnPaint() method is defined by Visual C++ MFC application wizard to Paint controls on the current dialog. LPARAMlParam) is also discussed in the HCI Information Commands programming application. BLUETOOTH Event Handler Function Name BM_START_CNF OnDbmStartCnf DBM_REGISTER_SERVICE_CNF OnDbmRegisterCnf DBM_REGISTER_SERVICE_CNF OnDbmRegisterCnf ♦ The ON BN CLICKED message map macro indicates which button click handles a specified Bluetooth event (see the following table). A Message Box indicates that the start of Database Manager is a success. ♦ Lines 151–162: OnSysCommand(UINT nID. LPARAM lParam) is discussed in the HCI Information Commands programming application. WPARAM wParam. The following table provides more details. ♦ Lines 265–270: When the button IDC BUTTON1 is clicked. the profile for serial port can be created to implement BLUETOOTH print service. . • Parameter1: sequence number of the interface=0 • DBM_ReqStart(0) causes the BLUETOOTH module to fire either a DBM START CNF or DBM START CNF NEG event corresponding to success or failure. LPARAM lParam) method is provided by Visual C++ MFC application wizard to model the dialog. h> 10. protected: 31. 26.h. class CPrintProfile 17. Listing 9-9 gives the source code for the header file PrintProfile. #pragma once 6. public: 19. 24. 33. #define AFX_PRINTPROFILE_H__B020C543_F4C6_11D3_B6C4_00105A680F8F__INCLUDED_ 3. 15. Listing 9-9: PrintProfile. 21.cpp. uint32 m_ulSRPHandle. 4. #if !defined(AFX_PRINTPROFILE_H__B020C543_F4C6_11D3_B6C4_00105A680F8F__INCLUDE) 2. #define PROFILE_SERIAL ((uint16) 6) 12. The current dialog box will be destroyed. 30. 32. #define SRP_SERIAL_SERVICENAME_OFFSET ((uint16) 0x0000) 14. • The WriteProfile(ptRegisterCnf->ulDbmHandle) is a member function of class CRS232 which is written to add descriptors and attributes for the service ♦ Lines 302–310: DBM REGISTER SERVICE CNF NEG event makes the ON BLUETOOTH EVENT macro to call OnDbmRegisterCnfNeg(void **ppMsg) message handler function. 11. 25. 27. 22. A message box indicates that the registration of a service with Database Manager has failed. 20. 16. 23. virtual void WriteProfile(uint32 ulSRPHandle). { 18.h © 2001 Dreamtech Software India Inc. uint32 GetSRPHandle(). . virtual ~CPrintProfile(). #include <exp\standard. 9. #if _MSC_VER > 1000 5. #define SRP_SERIAL_GENERIC_SERIALPORT_UUID ((uint16) 0x1101) 13.204 Chapter 9: Bluetooth Programming ♦ Lines 287 to 300: DBM REGISTER SERVICE CNF event makes the ON BLUETOOTH EVENT macro to call OnDbmRegisterCnf(void **ppMsg) messagehandler function. All Rights Reserved //PrintProfile.h declarations of variables implemented in PrintProfile. 28. uint16 m_uiProfileId. A Message Box indicates that the registration of a service with Database Manager is a success. 29. This file contains the declarations of variables implemented in PrintProfile. CPrintProfile(uint16 uiId). #endif // _MSC_VER > 1000 7.cpp 1. CPrintProfile(). 8. void GetProfileName(char **pcName). 48. Listing 9-10: PrintProfile. 42. static char THIS_FILE[]=__FILE__. 20. #endif Code Description In Listing 9-9. void AddDesc_ServiceClassIDList(uint16 uiSeqnr. void void AddAttr_ServiceName(uint16 uiSeqnr. 38. 24. 5. char *m_pcName. which are described in Listing 9-10. 13. 29. #ifdef _DEBUG 11. CPrintProfile::CPrintProfile() 18. 36. //PrintProfile. #undef THIS_FILE 12. 47. #include "PrintProfile.h> 8. . char *pcTextName. 37.h> 9.h" 4. 21. #include <exp\vos2com. All Rights Reserved 1.DBM_ServiceDiscoveryDB).cpp: implementation of the CProfile class. 41. #include <exp\dbm. 28. 44. 40. 3. the lines 1 to 6 are automatically generated by the VC++ application wizard. 43. 10. }. #include "stdafx. 7. 45. Line 9 is for inclusion of the header file. } 23. uint16 uiSize). uint16 uiServiceClassValue). 46. 17. { 19. #define new DEBUG_NEW 14. 2. 22. 27. Lines 11 to 13 are define statements as required by the Bluetooth SDK. m_ulSRPHandle = 0. CPrintProfile::CPrintProfile(uint16 uiId) 25. #endif 15. m_uiProfileId = uiId. 16. m_uiProfileId = 0.cpp © 2001 Dreamtech Software India Inc. Lines 16 to 48 are for class declaration with the necessary variables and methods. { 26. uint16 uiOffset. DBM_ReqRegisterService(uiId. 35. 39. m_ulSRPHandle = 0.Chapter 9: Bluetooth Programming 205 34.h" 6. AddAttr_ProtocolDescriptorList(uint16 uiSeqnr). 40. 60. } CPrintProfile::~CPrintProfile() { } void CPrintProfile::WriteProfile(uint32 ulSRPHandle) { m_ulSRPHandle = ulSRPHandle. 32. tDescriptor. } 72. &tDescriptor). 70. uint16 uiServiceClassValue) 54. 52. 59. void CPrintProfile::AddAttr_ProtocolDescriptorList(uint16 uiSeqnr) 75. 49. 38. } uint32 CPrintProfile::GetSRPHandle() { return m_ulSRPHandle. 47. tDescriptorUuid. 44.uiNrOfParams = 0. { 55. 42. 62. 41. m_ulSRPHandle. 68. memcpy(tDescriptorUuid. 46.&tDescriptorUuid. 31. DBM_TAttributeValue tAttribute. 73.uiSizeOfValueInBytes = 0. tDescriptor. 64. tDescriptorUuid. 77. AfxMessageBox("DBM_ReqAddDescriptor (uiSeqnr. m_ulSRPHandle. tAttribute. 51. 79. 37. VOS_Free((void**)&tDescriptorUuid.pucDescriptorUuidValue = (uint8*) VOS_Alloc(sizeof(uint16)). 45. . sizeof(uint16)). DBM_ReqAddDescriptor (uiSeqnr.pucValue = NULL. 57.206 Chapter 9: Bluetooth Programming 30. 48. tAttribute. 34. } void CPrintProfile::AddDesc_ServiceClassIDList(uint16 uiSeqnr. 78.pucValue = NULL.tType = DBM_DET_NULL. { 76.pucDescriptorUuidValue). 50. 80. DBM_TDescriptorValue tDescriptor. /* Add Descriptor */ 67.pucDescriptorUuidValue. 66. 69. 39.tType = DBM_DET_UUID16. 71. BT_SERVICE_CLASS_ID_LIST. 56. 65. 63. &uiServiceClassValue. 43. 61. tDescriptor. 35. 58. 53. 74. 33. &tDescriptor)"). 36. } void CPrintProfile::GetProfileName(char **pcName) { *pcName = m_pcName.&tDescriptorUuid. BT_SERVICE_CLASS_ID_LIST. DBM_TDescriptorUuid tDescriptorUuid. &uiSize. else 108. void CPrintProfile::AddAttr_ServiceName(uint16 uiSeqnr. 83. 119. BT_PROTOCOL_DESCRIPTOR_LIST.pucValue + sizeof(uint16). DBM_TAttributeValue tAttribute. DBM_ReqAddAttribute (uiSeqnr. memcpy(tAttribute. DBM_ReqAddAttribute (uiSeqnr. m_ulSRPHandle.pucValue). 111. AfxMessageBox("DBM_ReqAddAttribute (uiSeqnr. memcpy(pucTemp. m_ulSRPHandle. 103. } Code Description ♦ Lines 3–8: The header files required for this application are included. pucTemp = tAttribute. { 101. 96.pucValue = (uint8 *)VOS_Alloc((uint16)(uiSize + sizeof(uint8))). VOS_Free((void**)&tAttribute. (uint16)(BT_SERVICE_NAME(uiOffset)). } 99. 89. 113. 94. &tAttribute)"). { 88.tType = DBM_DET_STRING8.pucValue + sizeof(uint32). uint16 uiSize) 87. } 107. &uiSize. BT_PROTOCOL_DESCRIPTOR_LIST. else if (uiSize < 65536) 100. { 109. if (uiSize < 256) 92.pucValue. ♦ Lines 10–14: The Visual C++ editor provided these lines to give a common framework for all applications using the MFC Application Wizard. 91. { 93. (uiSize)). memcpy(pucTemp. uint8 *pucTemp. .tType = DBM_DET_STRING8. (uiSize)). 105.pucValue. &tAttribute).&tAttribute). uint16 uiOffset. /* Add Attribute */ 82. 114. 118.pucValue = (uint8 *)VOS_Alloc((uint16)(uiSize + sizeof(uint32))). memcpy(tAttribute. 104. char *pcTextName. 102. m_ulSRPHandle. 98. memcpy(pucTemp. 97. sizeof(uint16)). m_ulSRPHandle. (uiSize)). 116. 120.Chapter 9: Bluetooth Programming 207 81. pcTextName.pucValue + sizeof(uint8). tAttribute. 84. &uiSize. pcTextName. sizeof(uint8)). &tAttribute)").pucValue. /* Add Attribute */ 117. 112. 106. pucTemp = tAttribute.tType = DBM_DET_STRING16. 110.pucValue = (uint8 *)VOS_Alloc((uint16)(uiSize + sizeof(uint16))). } 115. pcTextName. 86. } 85. tAttribute. pucTemp = tAttribute. memcpy(tAttribute. tAttribute. 90. AfxMessageBox("DBM_ReqAddAttribute (uiSeqnr. (uint16)(BT_SERVICE_NAME(uiOffset)). 95. tAttribute. sizeof(uint32)). tAttribute. tAttribute. • DBM_ReqRegisterService (uiId. 3. ♦ Lines 74–84: DBM_ReqAddAttribute (uiSeqnr. BT_SERVICE_CLASS_ID_LIST. • Parameter1: user-defined Database manager handle. in which variables required for RS232.h © 2001 Dreamtech Software India Inc. ♦ Lines 38–41: m_ulSRPHandle = ulSRPHandle.DBM_ServiceDiscoveryDB) is a Bluetooth SDK API used to send a command to register a service with the Database Manager on a Bluetooth module. m_ulSRPHandle. is used to add service name. CRS232(uint16 uiId).208 Chapter 9: Bluetooth Programming ♦ Lines 17–22: The default constructor is defined to initialize service handle and Database Manager handles to zero.h" class CRS232 : public CPrintProfile { public: CRS232(). ♦ Lines 24–31: The constructor is overridden to accept user-defined input for profileID. is used to add a descriptor for service class ID list. &tDescriptor). Listing 9-11 gives the source code for the header file RS232.H #if !defined(AFX_RS232_H__F8A72756_F4EB_11D3_B6C4_00105A680F8F__INCLUDED_) #define AFX_RS232_H__F8A72756_F4EB_11D3_B6C4_00105A680F8F__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "PrintProfile. virtual ~CRS232(). 17. &tAttribute). BT_PROTOCOL_DESCRIPTOR_LIST. 16. 7.cpp are declared. //RS232. ♦ Lines 47–50: This method is used to return the profile name. Listing 9-11: RS232. m_ulSRPHandle. 4. 9.&tAttribute).&tDescriptorUuid. . (uint16)(BT_SERVICE_NAME(uiOffset)). indicates that the service record handle is stored in the member variable of the class. 5. ♦ Lines 33–36: The destructor is used to destruct the class. 14. is used to add a descriptor for protocol list. • DBM_ReqRegisterService (uiId. ♦ Lines 43–46: This method is declared to get the handle of service record. 11.h. 6. m_ulSRPHandle. 18. 15. 8. • Parameter2: service discovery database. 12. 10. ♦ Lines 53–71: DBM_ReqAddDescriptor (uiSeqnr. 2.DBM_ServiceDiscoveryDB) causes the Bluetooth module to fire either DBM REGISTER SERVICE CNF or DBM REGISTER SERVICE CNF NEG event corresponding to success or failure. 13. ♦ Lines 86–120: DBM_ReqAddAttribute (uiSeqnr. All Rights Reserved 1. }. DBM_ServiceDiscoveryDB )"). 26. { 24. CRS232::CRS232(uint16 uiId) 23.cpp © 2001 Dreamtech Software India Inc. { . DBM_ReqRegisterService(m_uiProfileId. 20. AfxMessageBox("DBM_ReqRegisterService(m_uiProfileId. m_ulSRPHandle = 0. { 13. and Lines 11–27 are for class declaration. m_pcName = "Print Service\0". 33. 27. 20. 21. 24. m_pcName = NULL. #include "RS232. 31. 27. m_uiProfileId = uiId. static char THIS_FILE[]=__FILE__. #endif Code Description In Listing 9-11. 30. CRS232::~CRS232() 18. void WriteProfile(uint32 ulSRPHandle). #include "stdafx. 29. } 32. 14. 8. #define new DEBUG_NEW 9. #ifdef _DEBUG 6. void CRS232::WriteProfile(uint32 ulSRPHandle) 34. The variables and methods used in the class are described in Listing 9-12.h" 2. #undef THIS_FILE 7. 17. #endif 10. 28. 22.h> 5. Listing 9-12: RS232. 26. 25. 15. #include <exp\dbm. } 21. 22. All Rights Reserved //RS232. { 19.h" 3.CPP 1. 4. } 16. line 9 is an include file. 25.Chapter 9: Bluetooth Programming 209 19.DBM_ServiceDiscoveryDB). the lines 2–7 are generated by VC++ application wizard. CRS232::CRS232() 12. 11. 23. 39. ♦ Lines 11–15: Constructor for the class. (uint16) strlen(m_pcName)). SRP_SERIAL_SERVICENAME_OFFSET. AddDesc_ServiceClassIDList(0. The remaining lines are generated by Visual C++ editor to give a common framework for all applications using the MFC application wizard. 42. SRP_SERIAL_SERVICENAME_OFFSET. AddAttr_ServiceName(2. 51. 46. 47. This window has one button labeled Register New Service. 45. ♦ Lines 33–51: WriteProfile (uint32 ulSRPHandle) is defined to call the following functions: • AddDesc_ServiceClassIDList(0. AfxMessageBox("Next 3 Commands For Reg. 40.DBM_ServiceDiscoveryDB). 43. • m_pcName. 41. 49. Code Description ♦ Lines 1–9: Lines 1–4 are for inclusion of header files. m_pcName. 38. ♦ Lines 22–31: The constructor is overridden to call DBM_ReqRegisterService(m_uiProfileId. 44. . the main window is displayed (see Figure 9-6). the following message box appears to show that the command DBM_ReqStart(0) has been issued. 48. • AddAttr_ProtocolDescriptorList(1). Code Output When the application is built in the VC++ environment and executed. ♦ Lines 17–20: Destructor for the class. AddAttr_ProtocolDescriptorList(1).SRP_SERIAL_GENERIC_SERIALPORT_UUID). } m_ulSRPHandle = ulSRPHandle. • AddAttr_ServiceName(2. Figure 9-6: Register New Service window After this button is clicked.210 Chapter 9: Bluetooth Programming 35. Print Service"). 50.SRP_SERIAL_GENERIC_SERIALPORT_UUID).(uint16) strlen(m_pcName)). 36. 37. the following message box appears. After the OK button is clicked.DBM_ServiceDiscoveryDB) has been issued. Click OK to issue the following commands.Chapter 9: Bluetooth Programming 211 After clicking the OK button. the following message box appears to show that the command DBM ReqRegisterService(m_uiProfileId. After the OK button is clicked. After clicking the OK button. the following message box appears indicating the confirmation of the previous command. the following message box appears to show the confirmation for the previous command. . the print service is displayed. Using HCI. and RFCOMM API calls of the PC Reference Stack. The server provides the file service. The sample chat client program can be used to see the service from the remote Bluetooth device.cpp. This module is implemented with the classes Cservice and CconnectionInfo in the files named Service.cpp and ConnectionInfo.cpp respectively. The file is transferred from a client Bluetooth device to a server Bluetooth device. The software contains the following three modules: ♦ Common module (common to both the server and the client): The common module provides the mechanism to set up an ACL link and to access the service. File Transfer Application This full-fledged application demonstrates a file transfer utility. ♦ Client module: The client module gets the service from the server and transfers a file over RFCOMM. SDP. The client module is implemented with the class CRadioFileClientDlg in the file named RadioFileClientDlg. we develop an application to transfer a file from one Bluetooth-enabled PC to another Bluetooth-enabled PC over a Bluetooth radio link. and when the Get Services button is clicked in the main window.212 Chapter 9: Bluetooth Programming The following message box shows the service has been registered with the Database Manager. . which is to be accessed by the client. 11. 13. 21.cpp. 20.h © 2001 Dreamtech Software India Inc. The functionality of these variables will be evident in Service. 16. 19. public: 6.h" 3. 14. CService().cpp.h> 3. }. 9. The explanation of the variables is given in the code description of Service. #include "stdafx.cpp is given in Listings 9-13.h" 5. 8.cpp. 10. 1.h" 4. #include "RadioChat. The server module is implemented with the class CRadioFileServerDlg in the file named RadioFileServerDlg. Service. 23. Listing 9-13: Service. and ConnectionInfo. class CService 4. // Service.cpp © 2001 Dreamtech Software India Inc. #include <exp/vos. #include "Service. #include <exp/standard. 2. 12. void SetService(CString sService). Listing 9-14:Service. CString m_sService.h> . CString GetService(). uint16 m_CurrentNumber. uint8 m_pAttributeData[100].Chapter 9: Bluetooth Programming 213 ♦ Server module: The server module registers a service with the Database Manager and the file service is made available to all nearby clients. 15. Common Module The source code for Service. private: 22. The detailed explanation for the variables and methods used along with Bluetooth function calls are explained with reference to the CPP files. All Rights Reserved 1. Code Description Listing 9-13 is the header file in which variables used in Service. char m_pServiceName[100]. All Rights Reserved // Service.h.cpp: implementation of the CService class. 9-15 and 9-16. uint16 m_SDCHandle. 9-14. { 5. uint16 m_AttributeListByteCount.h: interface for the CService class. 17. 7. 2.h. The header files contain the statements for inclusion of other header files including the library files and declarations of variables and methods for the classes used in the CPP files. ConnectionInfo.cpp. 18. respectively.cpp are declared. uint32 m_ServiceRecordHandle. CService(CString sService). virtual ~CService(). 34. #define new DEBUG_NEW 10. All Rights Reserved . ♦ Line 6–10: These lines are included by VC++ to provide a common framework for all MFC applications. { 20. 16. #endif 11. m_sService. 31. 18. m_sService = sService. } Code Description ♦ Line 1–5: The files required to implement service are included.214 Chapter 9: Bluetooth Programming 6. #undef THIS_FILE 8. ♦ Line 31–38: The method returns the service name and service handle in the form of a formatted string. void CService::SetService (CString sService) 27. 15. 23. return sService. 29.m_pServiceName). 35. CService::CService(CString sService) 19. Listing 9-15: ConnectionInfo.Empty(). 21. CString sService. static char THIS_FILE[]=__FILE__. 9. { 28. 12.m_SDCHandle. ♦ Line 26–29: The method is defined to initialize the specified service to the member variable m_sService.h © 2001 Dreamtech Software India Inc. ♦ Line 23–25: The default destructor is defined. } 30. { 33. The m_sService is initialized to contain an empty string. } 22. ♦ Line 18–21: The default constructor is overridden to initialize the user service to member variable of Cservice class. sService. { 14. CService::CService() 13. 37. ♦ Line 12–16: The default constructor is defined. } 26. { 25. 36. CService::~CService() 24. m_sService = sService. Service Name %s"). } 17.Format(_T("%d. #ifdef _DEBUG 7. CString CService::GetService () 32. 38. All Rights Reserved 1. uint8 tPacketType. uint16 tClockOffset.h 1. uint8 18.. //ConnectionInfo. }.h" #include "RadioChat. BT_TAddress tAddress. 3. uiAttributeListByteCount. uint16 19. 5. Code Description The variables declared in Listing 9-15 are used in the program ConnectionInfo. BT_THandle 16. 15. uint16 17. uint32 20. 7.cpp.cpp © 2001 Dreamtech Software India Inc. 9.Chapter 9: Bluetooth Programming 215 //ConnectionInfo. uint16 uiMaxFrameSize. 10. 18. ulServiceRecordHandle. uiRFCommHandle.h> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__. uint32 ulDbmHandle. 7. The functionality of these variables will be evident in the code description given for ConnectionInfo. 20. int8 22. 22. CConnectionInfo(). ulDbmHandle = 0. 13. 8. tAclHandle. uint8 tPageScanRepMode. pcServiceName[100].h" #include <exp/vos. 11. { 4.h> #include <exp/com. 11. uint16 uiServiceClass. } CConnectionInfo::~CConnectionInfo() { } . class CConnectionInfo 3. pucAttributeData[100]. #define new DEBUG_NEW #endif CConnectionInfo::CConnectionInfo() { uiMaxFrameSize = COM_DEFAULT_MFS. Listing 9-16: ConnectionInfo. 14. 13. 21.h> 2.cpp. 14. #include <exp/bt. 8. 2. 6. 12. 16. uint8 tPageScanMode.h" #include "ConnectionInfo. uint16 21. 10. 9. uiSdcHandle. 6. 19. 15. 17. public: 5. 12. virtual ~CConnectionInfo(). tAclHandle = 0. 4.cpp #include "stdafx. h> 9. and RFCOMM parameters.h © 2001 Dreamtech Software India Inc. #include "ConnectionInfo.h and RadioFileClientDlg. (AFX_PMSG)(AFX_PMSGW)(void (AFX_MSG_CALL CWnd::*)(void **))&memberFxn }. public: 35. ♦ Line 8–12: These lines are included by VC++ to provide a common framework for all MFC applications.h> 10. Client Module The source code for RadioFileClientDlg. 11.1. \ 14. CListBox m_ChatArea. #define WM_BLUETOOTH_EVENT (WM_USER + 100) 12. #include <exp\sd.WM_BLUETOOTH_EVENT. 18. #include <afxtempl. respectively. 3. // RadioFileClientDlg. private: 25. 15. virtual BOOL DestroyWindow(). 24. . 30. All Rights Reserved 1. enum { IDD = IDD_RADIOCHAT_DIALOG }.cpp are given in Listings 9-17 and 9-18. //{{AFX_VIRTUAL(CRadioFileClientDlg) 34. //{{AFX_DATA(CRadioFileClientDlg) 28.h> 8. 23. CEdit m_InputChat. 32. ~CRadioFileClientDlg().0. 26. 31. { WM_BLUETOOTH_EVENT. 27. //}}AFX_DATA 33. ♦ Line 20–22: The default destructor is defined.216 Chapter 9: Bluetooth Programming Code Description ♦ Line 1–6: The files required to implement CConnectionInfo class are included.(WPARAM)uiBtEventID.h" 5. BOOL OnBluetoothEvent(UINT message. ♦ Line 14–19: The default constructor is defined to initialize the ACL link. void InitSecurityClient(). LPARAM lParam). 29.h" 6. #define SEND_BT_EVENT(uiBtEventID. CConnectionInfo m_ConnectionInfo.h" 4. Database Manager (DBM). CRadioFileClientDlg(CWnd* pParent = NULL).0. WPARAM wParam. #include "Events. uiBtEventID. CTreeCtrl m_tree. SendMessage((HWND)this>m_hWnd. class CRadioFileClientDlg : public CDialog 19. #include <exp\BT_COMServer. #define ON_BLUETOOTH_EVENT(uiBtEventID. Listing 9-17: RadioFileClientDlg.(LPARAM) &pMsg) 17. { 20.h : header file 2.pMsg) \ 16. memberFxn) \ 13. #include "Remotedevice.h" 7.// standard constructor 22. #include "service. public: 21. 88. 68. //{{AFX_MSG(CRadioFileClientDlg) 61. afx_msg void OnComStartCnf(void **ppMsg). 78. 67. afx_msg HCURSOR OnQueryDragIcon(). afx_msg void OnCloseapplication(). 59. afx_msg void OnScmRegisterCnf(void **ppMsg). afx_msg void OnHCIUsb(). int m_ServiceCounter. afx_msg void OnScmConnectEvt(void **ppMsg). afx_msg void OnConnectAcceptInd(void **ppMsg). afx_msg void OnScmDisconnectEvt(void **ppMsg). 51. afx_msg void OnSdStartCnf(void **ppMsg). 70. 44. 39. 43. void ShowAllServicesFound(). void AddDevice(CString sAddress. virtual LRESULT WindowProc(UINT message. 86. void AddService(CService service).CDevice&> m_DevicesFound. afx_msg void OnSerialport(). 83. afx_msg void OnConnect(). void ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf). 69. virtual void DoDataExchange(CDataExchange* pDX). afx_msg void OnInquiry(). afx_msg void OnScmRegisterCnfNeg(void **ppMsg). 76. 74. afx_msg void OnScmDeRegisterCnf(void **ppMsg). 66. 48. LPARAM lParam).Chapter 9: Bluetooth Programming 217 36. 79. void ReceiveServiceRecordHandle(SD_TServiceAttributeCnf *tServiceAttributeCnf). 72. int index. afx_msg void OnPaint(). 65. afx_msg void OnSelDevice().CService&> m_ServicesFound. 89. 75. 71. 81. virtual BOOL OnInitDialog(). CString sName). 60. afx_msg void OnComVersionCnf(void **ppMsg). 57. 52. Events *m_pServerEvents. 54. 87. 58. . 56. protected: 53. 47. 49. void AskForServiceName(). void ShowAllDevicesFound(). 84. 77. 62. 80. public: 41. 45. afx_msg void OnScmConnectCnfNeg(void **ppMsg). 64. CArray <CService. void AddDevice(CDevice device). afx_msg void OnScmDeRegisterCnfNeg(void **ppMsg). HICON m_hIcon. 90. protected: 37. void AddService(CString sService). void AskForServiceRecordHandle(). int m_RemoteNameCounter. afx_msg void OnScmDisconnectCnf(void **ppMsg). void HandleReturn(). 82. 63. afx_msg void OnDestroy(). afx_msg void OnSelservices(). 73. afx_msg void OnSysCommand(UINT nID. // DDX/DDV support 38. afx_msg void OnScmDisconnectCnfNeg(void **ppMsg). //}}AFX_VIRTUAL 40. WPARAM wParam. 50. CArray <CDevice. afx_msg void OnScmPincodeInd(void **ppMsg). afx_msg void OnHCISerial(). 42. afx_msg void OnGetservices(). afx_msg void OnScmConnectCnf(void **ppMsg). 55. 85. LPARAM lParam). afx_msg void OnComStartCnfNeg(void **ppMsg). 46. 136. 115. 92. 109. 101. afx_msg void OnHciWriteConnectTimeoutCnfNeg(void **ppMsg). afx_msg void OnHciWriteConnectTimeoutCnf(void **ppMsg). 96. 138. afx_msg void OnHciLocalAddressCnfNeg(void **ppMsg). 99. 131. 98. afx_msg void OnComDataInd(void **ppMsg). 95. 137. afx_msg void OnBrowse(). 112. afx_msg void OnHciStartCnf(void **ppMsg). 94. 124. afx_msg void OnComConnectCnfNeg(void **ppMsg). afx_msg void OnHciWriteNameCnfNeg(void **ppMsg). 107. afx_msg void OnHciWriteScanEnableCnf(void **ppMsg).218 Chapter 9: Bluetooth Programming 91. afx_msg void OnComDataCnfNeg(void **ppMsg). afx_msg void OnComDisconnectCnfNeg(void **ppMsg). 104. 133. afx_msg void OnHciWriteScanEnableCnfNeg(void **ppMsg). //}}AFX_MSG DECLARE_MESSAGE_MAP() }. 120. 93. 123. afx_msg void OnSdDisconnectCnf(void **ppMsg). 103. 127. afx_msg void OnDbmAddDescriptorCnf(void **ppMsg). afx_msg void OnComDataCnf(void **ppMsg). afx_msg void OnDbmUnRegisterServiceCnfNeg(void **ppMsg). . afx_msg void OnDbmUnRegisterServiceCnf(void **ppMsg). 106. 145. afx_msg void OnHciInquiryEvt(void **ppMsg). afx_msg void OnComDisconnectCnf(void **ppMsg). afx_msg void OnSdConnectCnf(void **ppMsg). afx_msg void OnDbmAddDescriptorCnfNeg(void **ppMsg). afx_msg void OnHciWriteCodCnf(void **ppMsg). 143. 125. afx_msg void OnSdConnectCnfNeg(void **ppMsg). 97. afx_msg void OnHciWriteEncryptionModeCnf(void **ppMsg). afx_msg void OnSilReqDeviceCnfNeg(void **ppMsg). 134. afx_msg void OnDbmRegisterServiceCnfNeg(void **ppMsg). afx_msg void OnSdServiceAttributeCnf(void **ppMsg). 122. 139. afx_msg void OnSilReqDeviceCnf(void **ppMsg). afx_msg void OnSilSetDeviceCnfNeg(void **ppMsg). 105. afx_msg void OnHciConfigurePortConfirm(void **ppMsg). afx_msg void OnHciWriteAuthenticationModeCnfNeg(void **ppMsg). afx_msg void OnHciConfigurePortConfirmNegative(void **ppMsg). afx_msg void OnHciWriteAuthenticationModeCnf(void **ppMsg). afx_msg void OnSilSetDeviceCnf(void **ppMsg). 146. afx_msg void OnHciWriteNameCnf(void **ppMsg). 130. afx_msg void OnSdServiceAttributeCnfNeg(void **ppMsg). 111. afx_msg void OnHciRemoteNameCnfNeg(void **ppMsg). 135. afx_msg void OnComDisconnectEvt(void **ppMsg). 132. 142. 108. afx_msg void OnHciInquiryCnf(void **ppMsg). 144. 116. afx_msg void OnSdServiceSearchCnfNeg(void **ppMsg). afx_msg void OnComConnectCnf(void **ppMsg). afx_msg void OnHciWritePageTimeoutCnf(void **ppMsg). 129. 140. afx_msg void OnHciLocalAddressCnf(void **ppMsg). 126. 117. 100. 114. afx_msg void OnHciWritePageTimeoutCnfNeg(void **ppMsg). afx_msg void OnDbmRegisterServiceCnf(void **ppMsg). 102. 110. 141. afx_msg void OnHciWriteEncryptionModeCnfNeg(void **ppMsg). afx_msg void OnHciRemoteNameCnf(void **ppMsg). afx_msg void OnSdServiceSearchCnf(void **ppMsg). 113. 121. 128. afx_msg void OnHciWriteCodCnfNeg(void **ppMsg). 118. 119. #undef THIS_FILE 20. 17. virtual void DoDataExchange(CDataExchange* pDX).h" 3. { 38. #include <exp/sd.h" 7.'0'.h> 6.'0'.'0'. #define InterSelUSB ((uint8) 1) 33. 27. #include "Events. AFX_PMSG pfn. //}}AFX_VIRTUAL .hdevice1.'0'.'0'. CAboutDlg(). void (AFX_MSG_CALL CWnd::*pfn_btf)(void **).h> 12.h" 2.h contains the include statements to include other header files and library files as required by the Bluetooth SDK. 35.'3'.'4'. 40. 29. { 26.'0'.}.h" 4.h> 15. It also contains all variables. Listing 9-18: RadioFileClientDlg.h> 9. }. #define PINCODE_LENGTH ((SCM_TPincodeLength) 4) 30. 28. #ifdef _DEBUG 18.0x04}. member functions. #include <process. static char THIS_FILE[] = __FILE__.Chapter 9: Bluetooth Programming 219 The header file RadioFileClientDlg. //{{AFX_DATA(CAboutDlg) 41.'0'.h> 10. 21. static const HCI_TCod _tCod={0x20. 24.'0'. #define InterSelSerial ((uint8) 0) 32. 36.h> 11. #define new DEBUG_NEW 19. All Rights Reserved //RadioFileClientDlg. #include <exp/com. #endif 22.h> 16.'0'.'0'.cpp 1. #include <exp/vos2com.'0'. #include <exp/dbm. 42.h> 8. #include <exp/hci_drv.'2'. 46. #include <exp/hci. class CAboutDlg : public CDialog 37. union MessageMapFunctions 25. #include "RadioFileClientDlg. #define PORTSETTINGS (uint8 *)("COM1:Baud=57600 parity=N data=8 stop=1") 31. enum { IDD = IDD_ABOUTBOX }. #include <exp/scm.cpp © 2001 Dreamtech Software India Inc. #include "RadioChat. and classes required to implement the class CRadioFileClientDlg. HTREEITEM hPA. #include "stdafx. //{{AFX_VIRTUAL(CAboutDlg) 44. static const SCM_TPincode _tPincode = {'1'.h> 13.h" 5. #include <exp/sil. 23. //}}AFX_DATA 43. #include "windows.0x04. #define SRP_SERIAL_GENERIC_SERIALPORT_UUID ((uint16) 0x1101) 34.h> 14.'0'. protected: 45. public: 39. #include <exp/msg. OnScmPincodeInd) 102. }. void CRadioFileClientDlg::DoDataExchange(CDataExchange* pDX) 82. ON_WM_QUERYDRAGICON() 95.OnScmRegisterCnf) 99. BEGIN_MESSAGE_MAP(CRadioFileClientDlg.OnComStartCnfNeg) 97. ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF. void CAboutDlg::DoDataExchange(CDataExchange* pDX) 58. ON_BLUETOOTH_EVENT(COM_START_CNF_NEG. //{{AFX_MSG_MAP(CRadioFileClientDlg) 92. m_ChatArea).OnScmRegisterCnfNeg) 100. //}}AFX_MSG 50. { 59. ON_WM_PAINT() 94. //}}AFX_MSG_MAP 66. //{{AFX_MSG_MAP(CAboutDlg) 65. 79. { 70. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF. 74. DDX_Control(pDX.OnComStartCnf) 96. 73. { 83.RemoveAll(). { 54. BEGIN_MESSAGE_MAP(CAboutDlg. CDialog) 64. m_DevicesFound. //}}AFX_DATA_INIT 72. //{{AFX_DATA_INIT(CRadioFileClientDlg) 71. 78.OnScmConnectCnf) . } 81.220 Chapter 9: Bluetooth Programming 47. //{{AFX_MSG(CAboutDlg) 49. ON_BLUETOOTH_EVENT(COM_START_CNF. } 57. DECLARE_MESSAGE_MAP() 51. } 63. delete m_pServerEvents. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) 53. m_tree). CRadioFileClientDlg::CRadioFileClientDlg(CWnd* pParent /*=NULL*/) 68. { 77. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME). IDC_TREE1. //}}AFX_DATA_MAP 62. CDialog::DoDataExchange(pDX). m_pServerEvents = new Events(). DDX_Control(pDX. CDialog::DoDataExchange(pDX). } 90. ON_BLUETOOTH _EVENT(SCM_CONNECT_ACCEPT_IND. } 75. IDC_LIST1. ON_BLUETOOTH_EVENT(SCM_PINCODE_IND.RemoveAll(). DDX_Control(pDX. 86. //{{AFX_DATA_INIT(CAboutDlg) 55. //}}AFX_DATA_MAP 89. CDialog) 91. protected: 48. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF_NEG. ON_WM_SYSCOMMAND() 93. IDC_EDIT1. //}}AFX_DATA_INIT 56. pParent) 69. 88. m_ServicesFound. ON_BLUETOOTH_EVENT(COM_VERSION_CNF. 60. 80. 87. CRadioFileClientDlg::~CRadioFileClientDlg() 76. //{{AFX_DATA_MAP(CAboutDlg) 61. //{{AFX_DATA_MAP(CRadioFileClientDlg) 85.OnConnectAcceptInd) 101.OnComVersionCnf) 98. END_MESSAGE_MAP() 67. 52. : CDialog(CRadioFileClientDlg::IDD. 84. m_InputChat). OnHciWriteScanEnableCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF_NEG. OnSdServiceAttributeCnfNeg) ON_BLUETOOTH_EVENT(SD_DISCONNECT_CNF. OnHciLocalAddressCnf) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF_NEG.OnScmDeRegisterCnfNeg) ON_BLUETOOTH_EVENT(SD_START_CNF.OnSdServiceAttributeCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF_NEG. OnHciLocalAddressCnfNeg) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF. 122. 146. 127. 114.OnSdConnectCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF_NEG. 129. 143. 144. 107. 105. 141.OnDbmUnRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF_NEG. OnDbmRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF. 118.OnSdConnectCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF. 133. 125. 120. 134. OnHciWriteEncryptionModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF_NEG. 138. 137.OnDbmRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF_NEG. 115. 119.OnHciStartCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF. 140. 130. 123. OnHciWriteEncryptionModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF. 139.OnScmConnectCnfNeg) ON_BLUETOOTH_EVENT(SCM_CONNECT_EVT.OnScmDisconnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF. 116.OnHciRemoteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_START_CNF.OnHciWriteNameCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF_NEG.OnHciWriteCodCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF.OnScmConnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_EVT. 124. OnHciWriteConnectTimeoutCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF. OnHciWriteScanEnableCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF. OnHciConfigurePortConfirmNegative) ON_BLUETOOTH_EVENT(HCI_INQUIRY_CNF. 108. 121.OnScmDisconnectCnf) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF_NEG. 131.OnDbmAddDescriptorCnfNeg) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF.OnScmDeRegisterCnf) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF_NEG. ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF_NEG. 136.OnSdServiceSearchCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF_NEG. 135. 128. 145. 112. OnHciWriteAuthenticationModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF_NEG.OnHciConfigurePortConfirm) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF_NEG. OnDbmUnRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF.Chapter 9: Bluetooth Programming 221 103.OnHciRemoteNameCnf) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF_NEG.OnHciWriteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF. 142.OnSdDisconnectCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF.OnHciInquiryCnf) ON_BLUETOOTH_EVENT(HCI_INQUIRY_EVT. 126. 132. 111. OnHciWriteConnectTimeoutCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF_NEG. 106.OnHciInquiryEvt) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF.OnSdServiceSearchCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF.OnHciWritePageTimeoutCnf) .OnScmDisconnectCnfNeg) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF.OnHciWriteCodCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF_NEG. 109.OnDbmAddDescriptorCnf) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF_NEG. 104. 117.OnSdStartCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF. 110. OnHciWriteAuthenticationModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF. 113. 147. InitSecurityClient(). . 201. if (!strAboutMenu. 190. hPA = m_tree. 172. 153. tvInsert.222 Chapter 9: Bluetooth Programming 148. 155. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX).InsertItem(&tvInsert).item. 168. 152. 198. OnSilSetDeviceCnfNeg) ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF. 170. OnHciWritePageTimeoutCnfNeg) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF. 196.pszText = _T("RemoteRadios").OnComConnectCnfNeg ) ON_BLUETOOTH_EVENT(COM_DATA_IND. 200.OnComDisconnectCnfNeg ) ON_BN_CLICKED(IDC_BUTTON1. ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF_NEG. } LRESULT CRadioFileClientDlg::WindowProc(UINT message. if (message == WM_BLUETOOTH_EVENT) { OnBluetoothEvent( message. OnSilSetDeviceCnf) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF_NEG.OnComDataInd ) ON_BLUETOOTH_EVENT(COM_DATA_CNF. OnSilReqDeviceCnf) ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF_NEG.mask = TVIF_TEXT. 192.OnComDisconnectCnf ) ON_BLUETOOTH_EVENT(COM_DISCONNECT_CNF_NEG. CMenu* pSysMenu = GetSystemMenu(FALSE). 175. 163. strAboutMenu. 174. 181. 159.OnComConnectCnf ) ON_BLUETOOTH_EVENT(COM_CONNECT_CNF_NEG. 164. 178. FALSE). 194.item. 167. 149. 187. 193.OnComDataCnf ) ON_BLUETOOTH_EVENT(COM_DATA_CNF_NEG.LoadString(IDS_ABOUTBOX). 184. 169. 154. 188. 197. 180. 177. wParam. tvInsert. LPARAM lParam) { MSG_TMsg **ptMsg. 171. // Set small icon m_pServerEvents->m_pParentDialog = this. 157. lParam). 158. pSysMenu->AppendMenu(MF_STRING. 162. 150.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR). 199. index = 0. 160. return TRUE. tvInsert. 191. 165. 161. TVINSERTSTRUCT tvInsert. tvInsert. } } SetIcon(m_hIcon. if (*ptMsg != NULL) VOS_Free((void **)lParam). 151. TRUE). 173. 185. 179. OnBrowse) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CRadioFileClientDlg::OnInitDialog() { CDialog::OnInitDialog(). WPARAM wParam.hParent =NULL. 195. ptMsg = (MSG_TMsg**)lParam. if (pSysMenu != NULL) { CString strAboutMenu. 183.hInsertAfter = NULL. IDM_ABOUTBOX. OnSilReqDeviceCnfNeg) ON_BLUETOOTH_EVENT(COM_CONNECT_CNF. 176. 189. strAboutMenu). 166. ASSERT(IDM_ABOUTBOX < 0xF000).OnComDisconnectEvt ) ON_BLUETOOTH_EVENT(COM_DISCONNECT_CNF. 156. 186. // Set big icon SetIcon(m_hIcon.OnComDataCnfNeg ) ON_BLUETOOTH_EVENT(COM_DISCONNECT_EVT. 182. pMessageMap != NULL. { 254. union MessageMapFunctions mmf. for (pMessageMap = GetMessageMap(). 209. } 245. { 242. if ((nID & 0xFFF0) == IDM_ABOUTBOX) 241.DoModal(). } 238. 223. { 227. 231. ASSERT(pMessageMap != pMessageMap->pBaseMap). return FALSE. lParam). #endif 216. LPARAM lParam) 239. return FALSE. pMessageMap != NULL. } 232. 255. dlgAbout. 211.GetSafeHdc(). const AFX_MSGMAP* pMessageMap. if (IsIconic()) 253. } 250. return CDialog::WindowProc(message. } 236. #ifdef _AFXDLL 218. CDialog::OnSysCommand(nID. 230. if ((lpEntry->nMessage == message) && (lpEntry->nCode == wParam)) 226. { 217. #else 213. . int cxIcon = GetSystemMetrics(SM_CXICON). { 252. while (lpEntry->nSig != AfxSig_end) 224. CAboutDlg dlgAbout. 208. 214. lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]). } 205. (((CWnd *)this)->*mmf. 256. } 249. } 234. 219. 229. (WPARAM) dc. ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()). { 225. { 240.pfn = lpEntry->pfn. 0). 228. #else 220. #endif 222. lpEntry++.Chapter 9: Bluetooth Programming 223 202. 243. 248. 237. pMessageMap = pMessageMap->pBaseMap) 215. void CRadioFileClientDlg::OnPaint() 251. 221. LPARAM lParam) 206. { 247. const AFX_MSGMAP_ENTRY* lpEntry. 204. #ifdef _AFXDLL 210. 233. lParam). WPARAM wParam. { 207. else 246. } 203. CPaintDC dc(this). 235. for (pMessageMap = GetMessageMap(). pMessageMap = (*pMessageMap->pfnGetBaseMap)()) 212. SendMessage(WM_ICONERASEBKGND. BOOL CRadioFileClientDlg::OnBluetoothEvent(UINT message. mmf. wParam.pfn_btf)((void **)lParam). void CRadioFileClientDlg::OnSysCommand(UINT nID. 244. return TRUE. 286. 298. GetClientRect(&rect). 259.Width() . } void CRadioFileClientDlg::InitSecurityClient() { SIL_SetDevice(0. dc. 262. tConfigurePort = tConfigurePort. 277. 270. 278. m_hIcon). 297. 299. 301. 283. 281. 275. 294. 261. CRect rect. 285.PORTSETTINGS). } else { CDialog::OnPaint(). COM_ReqStart(0). 273. 279. if(ptReq->uiDevice == SIL_USB) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is USB")). if(ptReq->uiDevice == SIL_SERIAL) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is SERIAL")). 269. int x = (rect. 280. 266.DrawIcon(x. 272. HCI_ReqConfigurePort(0. } void CRadioFileClientDlg::OnSilSetDeviceCnf(void **ppMsg) { ppMsg = ppMsg. 287. 300.Height() . } } HCURSOR CRadioFileClientDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon. 303. ptReq = (SIL_TReqDevice*) *ppMsg. 289. 267. 282. 284. } void CRadioFileClientDlg::OnSilSetDeviceCnfNeg(void **ppMsg) { SIL_TSetDevice* ptSetDevice. ptSetDevice = (SIL_TSetDevice*)*ppMsg.cyIcon + 1) / 2. MessageBox(_T("Device Request FAILED!")). 290. 263.cxIcon + 1) / 2.224 Chapter 9: Bluetooth Programming 257. 260. 288. 307. 271. 264.SIL_SERIAL). 296. 306. y. int y = (rect. } void CRadioFileClientDlg::OnHciConfigurePortConfirmNegative(void **ppMsg) . } void CRadioFileClientDlg::OnSilReqDeviceCnf(void **ppMsg) { SIL_TReqDevice* ptReq. 305. 304. } void CRadioFileClientDlg::OnHciConfigurePortConfirm(void **ppMsg) { HCI_TConfigurePortCnf *tConfigurePort = (HCI_TConfigurePortCnf *)*ppMsg. } void CRadioFileClientDlg::OnSilReqDeviceCnfNeg(void **ppMsg) { ppMsg = ppMsg. 274. int cyIcon = GetSystemMetrics(SM_CYICON). 295. 276. 291. if(ptSetDevice->tHdr. 302. 309. 268. 292. 258. 308. 293. 265.iResult == SIL_ERR_DEVICE) SIL_ReqDevice(0). ucByte1. void CRadioFileClientDlg::OnHciWriteEncryptionModeCnfNeg(void **ppMsg) 358. tConfigurePort = tConfigurePort. 346.ucByte0. ppMsg = ppMsg. 333. 350. void CRadioFileClientDlg::OnHciLocalAddressCnfNeg(void **ppMsg) 342. wsprintf(&lpStr[0]. . { 317. ppMsg = ppMsg. MessageBox(_T("Could not open port")). 351. } 327. } 357.ucByte5). 332. tLocalAddress->tAddress. void CRadioFileClientDlg::OnHciLocalAddressCnf(void **ppMsg) 328. SetWindowText(_T(lpStr)). 337. 355. charlpStr[59].HCI_AUTH_DISABLE). 326. 312. tLocalAddress->tAddress. 336. 339. } 347. 313. void CRadioFileClientDlg::OnComStartCnf(void **ppMsg) 316. 320. tStartCnfNeg = tStartCnfNeg. } 321. 340. } 352.ucByte2. { 343. SetWindowText(_T("DEVICE NOT FOUND")). SD_ReqStart(0). { 363. HCI_ReqWriteEncryptionMode(0. void CRadioFileClientDlg::OnHciWriteEncryptionModeCnf(void **ppMsg) 353. ppMsg = ppMsg. tLocalAddress->tAddress. SD_ReqStart(0). { 349. 356. } 315. HCI_TConfigurePortCnfNeg *tConfigurePort = (HCI_TConfigurePortCnfNeg *)*ppMsg. } 361. 319. HCI_TLocalAddressCnf *tLocalAddress = (HCI_TLocalAddressCnf *)*ppMsg. { 311. HCI_ReqWriteConnectTimeout(0. { 329. 318. 331. { 354.Chapter 9: Bluetooth Programming 225 310. 345. HCI_ReqLocalAddress(0). 334. "BD_ADDRESS: 0x%02X%02X%02X%02X%02X%02X\0".ucByte4. void CRadioFileClientDlg::OnComStartCnfNeg(void **ppMsg) 322. tLocalAddress->tAddress. { 323. 335. void CRadioFileClientDlg::OnSdStartCnf(void **ppMsg) 348. tStartCnf = tStartCnf. 314. ppMsg = ppMsg. COM_TStartCnf *tStartCnf = (COM_TStartCnf *)*ppMsg. 338. 324. 344. COM_TStartCnfNeg *tStartCnfNeg = (COM_TStartCnfNeg *)*ppMsg. 364. { 359.ucByte3. 325.HCI_ENCRYPTION_OFF). ppMsg = ppMsg. 330.0x1FA0). 360. MessageBox(_T("Could not start RFCOMM")). HCI_ReqWriteAuthenticationMode(0. tLocalAddress->tAddress. void CRadioFileClientDlg::OnHciWriteAuthenticationModeCnf(void **ppMsg) 362. tLocalAddress->tAddress. } 341. HCI_ReqWriteName (0.8000). 399. void CRadioFileClientDlg::OnHciWriteCodCnfNeg(void **ppMsg) 407. void CRadioFileClientDlg::OnHciWritePageTimeoutCnfNeg(void **ppMsg) 389. 369. } . void CRadioFileClientDlg::OnHciWritePageTimeoutCnf(void **ppMsg) 380. } 366. } 392. ppMsg = ppMsg. { 390. 401. 394. } 379. } 415. } 388. 387. 405. } 410. 386. { 381. { 368. 384. 393. ppMsg = ppMsg. ppMsg = ppMsg. void CRadioFileClientDlg::OnHciWriteConnectTimeoutCnfNeg(void **ppMsg) 376. void CRadioFileClientDlg::OnHciWriteAuthenticationModeCnfNeg(void **ppMsg) 367. 396. } 370. 400. void CRadioFileClientDlg::OnHciWriteNameCnf(void **ppMsg) 411. ppMsg = ppMsg. ppMsg = ppMsg.HCI_PAGE_SCAN_ENABLED | HCI_INQUIRY_SCAN_ENABLED). 413. 374. { 412. 391. 373. { 372. 378. void CRadioFileClientDlg::OnHciWriteConnectTimeoutCnf(void **ppMsg) 371. 383. 397. 418. 409. 382. { 403.226 Chapter 9: Bluetooth Programming 365. ppMsg = ppMsg. HCI_ReqWriteScanEnable(0. HCI_ReqWriteCod(0. ppMsg = ppMsg. ppMsg = ppMsg. void CRadioFileClientDlg::OnHciWriteNameCnfNeg(void **ppMsg) 416. ppMsg = ppMsg. 404._tCod).(HCI_TName*) "BT File"). 414. { 408. { 377. } 375. 385. { 417. } 406. 398. void CRadioFileClientDlg::OnHciWriteCodCnf(void **ppMsg) 402. HCI_ReqWritePageTimeout(0. 395. 466.GetSize().SCM_SECURITY_HANDLER).tPageScanMode. 455. } } void CRadioFileClientDlg::OnHciRemoteNameCnf(void **ppMsg) { HCI_TRemoteNameCnf *ptRemoteNameCnf. device. 432. 457. } void CRadioFileClientDlg::OnHciInquiryCnf(void **ppMsg) { HCI_TInquiryCnf *ptInquiryCnf. 445. 438. tRegisterCnf = tRegisterCnf. 463. 420.Chapter 9: Bluetooth Programming 227 419. 422. 433. } } void CRadioFileClientDlg::OnScmRegisterCnfNeg(void **ppMsg) { SCM_TRegisterCnfNeg *tRegisterCnfNeg = (SCM_TRegisterCnfNeg *)*ppMsg. 440. 441. 472. 461. 465. HCI_ReqRemoteName(10. 474. 448.GetAt(m_RemoteNameCounter). 430. 473. 454. 444. device. count = m_DevicesFound.tPageScanPeriodMode. 449. 421. 436.SCM_MONITOR_GROUP). 428. 468. 470. 464. 450. 453. 462. 435. ptInquiryCnf =(HCI_TInquiryCnf *) *ppMsg. 423. 424. tRegisterCnfNeg = tRegisterCnfNeg. m_RemoteNameCounter = 0. 467. device. } void CRadioFileClientDlg::OnHciWriteScanEnableCnfNeg(void **ppMsg) { ppMsg = ppMsg. MessageBox(_T("Could not register to SCM")). SCM_ReqRegister(0.tClockOffset ). } else { AfxMessageBox("No device found"). 427. 460. 447. 431. 458. 459. 452. 469. 443. CDevice device. 434. 471. int count. device. 439. if (tRegisterCnf->tHdr. void CRadioFileClientDlg::OnHciWriteScanEnableCnf(void **ppMsg) { ppMsg = ppMsg. 426. CDevice device.uiSeqNr == 0) { SCM_ReqRegister(1. int count. 425. } void CRadioFileClientDlg::OnScmRegisterCnf(void **ppMsg) { SCM_TRegisterCnf *tRegisterCnf = (SCM_TRegisterCnf *)*ppMsg. 442.tAddress. 446. } else { OnInquiry(). . 437. 451. 429. if (count > 0) { device = (CDevice) m_DevicesFound. char sName[248]. 456. m_ConnectionInfo. 530. ptRemoteNameCnf =(HCI_TRemoteNameCnf *) *ppMsg.SetName((CString)sName).tClockOffset ). } } void CRadioFileClientDlg::OnScmConnectCnf(void **ppMsg) { SCM_TConnectCnf *tConnectCnf = (SCM_TConnectCnf *)*ppMsg.GetSize(). 527. 478. 489. 507. 483. HCI_ReqRemoteName(10.tAddress.tClockOffset ). 504. 511. if (count > m_RemoteNameCounter) { device = (CDevice) m_DevicesFound. 476. 498.GetAt(m_RemoteNameCounter). 524. 500. 513. device.GetSize(). 529. device. int count. 516. m_RemoteNameCounter++. 526.tPageScanPeriodMode. } void CRadioFileClientDlg::OnScmConnectCnfNeg(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 502. 503. sprintf(sName. 481. 501. 493. 482. 492. m_DevicesFound[m_RemoteNameCounter].tAclHandle = tConnectCnf->tHandle. m_RemoteNameCounter++. tConnectCnfNeg = tConnectCnfNeg. } else { ShowAllDevicesFound(). 520.228 Chapter 9: Bluetooth Programming 475. device. 528. AfxMessageBox("connected"). ptRemoteNameCnfNeg =(HCI_TRemoteNameCnfNeg *) *ppMsg. 484. device. 523. 485. 518. m_DevicesFound[m_RemoteNameCounter]. 517. . device. } } void CRadioFileClientDlg::OnHciRemoteNameCnfNeg(void **ppMsg) { HCI_TRemoteNameCnfNeg *ptRemoteNameCnfNeg.GetAt(m_RemoteNameCounter).&ptRemoteNameCnf->tName). 515. 506. 512. 494. if (count > m_RemoteNameCounter) { device = (CDevice) m_DevicesFound. count = m_DevicesFound.tPageScanMode. AfxMessageBox("No Connection made"). device. 490. 487. } else { ShowAllDevicesFound(). 497. 495.tAddress. HCI_ReqRemoteName(10.tPageScanPeriodMode. 499. 525. 491. count = m_DevicesFound. device. 505. 479. 522. device. 486. 508. 521. 496. 488. 477. 510. tConnectCnf = tConnectCnf. 509. 514. 480. CDevice device. m_ConnectionInfo. 519. OnGetservices() .tPageScanMode."%s".SetName ((CString)_T("UNKNOWN")).tAddress = tConnectCnf->tAddress. 543. 544.uiSdcHandle. uint8 ucNrOfUuids. uint32 *pulSRHandles. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof (uint16))). 564. SD_ReqServiceSearch (0. SD_TConnectCnf *tConnectCnf = (SD_TConnectCnf *)*ppMsg. void CRadioFileClientDlg::OnSdServiceSearchCnf(void **ppMsg) 554. MessageBox(str). SD_TServiceSearchCnf *tServiceSearchCnf = (SD_TServiceSearchCnf *)*ppMsg. { 534. } 546. ucNrOfAttr = 1. 541. m_ConnectionInfo.SetAtGrow(m_ServiceCounter.iResult). 535.m_ServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList. uiMaxRecords. 565. } 532. ucNrOfUuids. ptSearchPatternList[0]. CString str. 540. pulSRHandles = (uint32*)VOS_Alloc(((uint16) (uiCurrentServiceRecordCount*sizeof(uint32)))).uiSdcHandle. service.uiUuid16 = SRP_SERIAL_GENERIC_SERIALPORT_UUID . ptSearchPatternList = (SD_TUuid*)VOS_Alloc((uint16)(ucNrOfUuids * sizeof(SD_TUuid))).eUuidType = SD_DET_UUID16. 552. 575. 563. 570. ptSearchPatternList[0]. ptSearchPatternList). 568. void CRadioFileClientDlg::OnSdConnectCnfNeg(void **ppMsg) 547. 542. 538. 536. uint16 uiMaxRecords. pulSRHandles[0]. void CRadioFileClientDlg::OnSdConnectCnf(void **ppMsg) 533. SD_TUuid *ptSearchPatternList. 539. 567. 559. uiMaxRecords = 6. { 548. SD_TConnectCnfNeg *tConnectCnfNeg = (SD_TConnectCnfNeg *)*ppMsg. 561.m_SDCHandle = m_ConnectionInfo. (uiCurrentServiceRecordCount*sizeof(uint32))). 571.Format("Could not connect to SD . (void*)memcpy(pulSRHandles. SD_ReqServiceAttribute(1. puiAttributeIDList[0] = BT_SERVICE_NAME(0).tConnectCnfNeg>tHdr. uiCurrentServiceRecordCount = tServiceSearchCnf>uiCurrentServiceRecordCount.uiSdcHandle = tConnectCnf->uiSdcHandle. 545. m_ConnectionInfo. { 555.TUuid. str. 573. 562. puiAttributeIDList). m_ConnectionInfo. ucNrOfUuids = 1. 572. ucNrOfAttr. VOS_Free((void**)&puiAttributeIDList). Error %d". uint8 ucNrOfAttr. VOS_Free((void**)&pulSRHandles).uiSdcHandle. 569. 558. &tServiceSearchCnf->ulServiceRecordHandleList.service). m_ServicesFound. 557. m_ConnectionInfo. 550.ulServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList. . uint16 *puiAttributeIDList.Chapter 9: Bluetooth Programming 229 531. 549. 574. 566. } 553. 551. uint16 uiCurrentServiceRecordCount. 556. CService service. 537. service. 560. void CRadioFileClientDlg::OnSdDisconnectCnf(void **ppMsg) 614. uint16 uiDescriptorUuidValue. 580.200). 616. AfxMessageBox("Service Attribute Cnf"). } 577. 599. 598. 625. CService service. 596. { 621. error %d". default: 602. SD_TServiceAttributeCnf *tServiceAttributeCnf = (SD_TServiceAttributeCnf *)*ppMsg. Error %d". str. SD_ReqDisconnect(0. break. DBM_TDescriptorValue tDescriptorValue.230 Chapter 9: Bluetooth Programming 576. SD_TServiceAttributeCnfNeg *tConnectCnfNeg = (SD_TServiceAttributeCnfNeg *)*ppMsg. 610. OnSelservices(). 595. MessageBox(str). DBM_TRegisterServiceCnf *tRegisterCnf = (DBM_TRegisterServiceCnf *)*ppMsg. void CRadioFileClientDlg::OnDbmRegisterServiceCnf(void **ppMsg) 620. str. tConnectCnfNeg = tConnectCnfNeg. 611. 612.Format("Service Search Confirm Negative. AfxMessageBox("SD_ReqDisconnect(0. } 604. break. break. CString str. ppMsg = ppMsg. 623. 608.iResult).uiSeqNr) 590.uiSdcHandle)"). { 615. Beep (1000. } 585. 582. { 579.m_ConnectionInfo. 589. 609. tConnectCnfNeg = tConnectCnfNeg.tConnectCnfNeg>tHdr. 601.Format("Service Attribute Confirm negative. 594. { 591. 603. void CRadioFileClientDlg::OnSdServiceAttributeCnfNeg(void **ppMsg) 606. ReceiveServiceRecordHandle(tServiceAttributeCnf). 588. AskForServiceRecordHandle(). 581.m_ConnectionInfo. } 605. { 587. void CRadioFileClientDlg::OnSdServiceAttributeCnf(void **ppMsg) 586. 624.iResult). ReceiveServiceName(tServiceAttributeCnf). switch (tServiceAttributeCnf->tHdr. SD_TServiceSearchCnfNeg *tConnectCnfNeg = (SD_TServiceSearchCnfNeg *)*ppMsg. void CRadioFileClientDlg::OnSdServiceSearchCnfNeg(void **ppMsg) 578. case 2: 597. m_ConnectionInfo. 583.ulDbmHandle = tRegisterCnf->ulDbmHandle. . 622. { 607. DBM_TDescriptorUuid tDescriptor. MessageBox(str). case 1: 592. 593.tConnectCnfNeg->tHdr.uiSdcHandle). } 613. 600. 618. CString str. 584. } 619. 617. &tDescriptorValue). tDescriptorValue. 672. 645. 676. 658. 663. 642. 674. *tDescriptorValue. } void CRadioFileClientDlg::OnConnectAcceptInd(void **ppMsg) { SCM_TConnectAcceptInd *ptConnectAcceptInd. tConnectCnfNeg = tConnectCnfNeg. device. 675. 643. 648. tDescriptorValue. 679.pucValue--. 639. 661.tPageScanMode = ptInquiryEvt->tPageScanMode. 666. 630. Beep (1000. 680. 654. 632. 652. device. uiDescriptorUuidValue = BT_PSM_COM.pucAttributeData [m_ConnectionInfo. ptInquiryEvt =(HCI_TInquiryEvt *) *ppMsg. 670. SCM_SLAVE). 633. VOS_Free((void**) &tDescriptorValue. device.pucValue = (uint8 *) VOS_Alloc( (sizeof(uint16)) ). 640. 635. 655. 650. 649.tClockOffset = ptInquiryEvt->tClockOffset. ptConnectAcceptInd =(SCM_TConnectAcceptInd *) *ppMsg. tDescriptorValue. DBM_ReqAddDescriptor(0. SCM_RspConnectAccept((MSG_TMsg **)ppMsg. 664. 657. 646. ptConnectAcceptInd->tAddress. 678. *ppMsg = NULL.tType = DBM_DET_UUID16. 659. 677. SD_ReqDisconnect(0. m_ConnectionInfo.200). } void CRadioFileClientDlg::OnDbmRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg. tDescriptor. tDescriptorValue. 665. 671.pucValue). 629. 644. 641. } void CRadioFileClientDlg::OnDbmAddDescriptorCnf(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. OnConnect(). CDevice device. 653. 634. MessageBox(_T("Could not register the service to DBM")). 651.uiAttributeListByteCount .1]. 638. 669. tDescriptor. 628.ulDbmHandle. 673.pucValue = DBM_DET_UINT8. 627. tDescriptorValue. 637. } void CRadioFileClientDlg::OnDbmAddDescriptorCnfNeg(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 656.uiSizeOfValueInBytes = 2.uiNrOfParams = 1.uiSdcHandle).pucValue++.tPageScanPeriodMode = ptInquiryEvt->tPageScanPeriodMode. 662.m_ConnectionInfo. 660. MessageBox(_T("Not possible to Register to DBM")). 636.Chapter 9: Bluetooth Programming 231 626. 667.tAddress = ptInquiryEvt->tAddress. 631. SCM_POS_RESULT. &tDescriptor. } void CRadioFileClientDlg::OnHciInquiryEvt(void **ppMsg) { HCI_TInquiryEvt *ptInquiryEvt. BT_PROTOCOL_DESCRIPTOR_LIST. device.pucValue = m_ConnectionInfo. tConnectCnfNeg = tConnectCnfNeg.pucDescriptorUuidValue = (uint8*) &uiDescriptorUuidValue. 668. 647. . *tDescriptorValue. 232 Chapter 9: Bluetooth Programming 681. 725.tPageScanRepMode = ptInquiryEvt->tPageScanRepMode. 700. } void CRadioFileClientDlg::OnScmPincodeInd(void **ppMsg) { SCM_TPincodeInd *ptPincodeInd. 690. } void CRadioFileClientDlg::OnScmConnectEvt(void **ppMsg) { SCM_TConnectEvt *tConnectEvt = (SCM_TConnectEvt *)*ppMsg. 728. tConnectEvt = tConnectEvt. 693. }while(iCharCount <= 11). 731. } void CRadioFileClientDlg::OnScmDisconnectEvt(void **ppMsg) { ppMsg = ppMsg.tAddress = tConnectEvt->tAddress. 721. 688. _tPincode. cpStr[iCharCount-10] = cpVerStr[iCharCount]. } void CRadioFileClientDlg::OnComVersionCnf(void **ppMsg) { CAboutDlg Abodlg. 694. 699. 689. ptPincodeInd->tAddress. 711. COM_TVersionCnf* ptVersionCnf. ptVersionCnf = (COM_TVersionCnf *) *ppMsg. 724. PINCODE_LENGTH). 691. ucNrOfAttr = 1.tCod = ptInquiryEvt->tCod. 696. 729. Abodlg. 733. ptStartCnf = ptStartCnf. 717. 702. 701.tAclHandle = tConnectEvt->tHandle. 683. HCI_ReqConfigurePort(0. 727. m_ConnectionInfo. 710. 726. 686. } void CRadioFileClientDlg::AskForServiceName() { uint16 *puiAttributeIDList. 720. device. 695. 685. 707. m_ConnectionInfo. cpVerStr = &ptVersionCnf->cVersion. 723. 705. 708. 715. 732. 716. 697. 684. 709. 706. uint8 ucNrOfAttr. 718. AddDevice(device). 682. cpStr[3] = ((char)0). SCM_RspPincode((MSG_TMsg **)ppMsg. . 687.PORTSETTINGS). char cpStr[3]. 730. 712. 704. int8 iCharCount = 9. OnCloseapplication(). 703. 713. m_ConnectionInfo. 735. 719. 692. do { iCharCount++. 722.DoModal(). 714. 734. } void CRadioFileClientDlg::OnHciStartCnf(void **ppMsg) { HCI_TStartCnf *ptStartCnf = (HCI_TStartCnf *)*ppMsg. ptPincodeInd =(SCM_TPincodeInd *) *ppMsg. 698. device.tAclHandle = 0. SCM_POS_RESULT. char* cpVerStr = NULL. 750. 769. { 779.m_AttributeListByteCount). 756. } 741. m_ConnectionInfo. SD_ReqServiceAttribute(2. 780.uiAttributeListByteCount).ulServiceRecordHandle. uint8 ucNrOfAttr. m_ConnectionInfo. puiAttributeIDList[1] = BT_PROTOCOL_DESCRIPTOR_LIST.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. m_ServiceCounter++.uiSdcHandle. m_ConnectionInfo. 745. 749. (void*)memcpy(m_ConnectionInfo.m_pAttributeData[6]). 758. } 777. service.uiSdcHandle.m_pServiceName[service. m_ConnectionInfo. puiAttributeIDList). 751. 765. 770. 737. 763. ucNrOfAttr. SD_ReqServiceAttribute(0. 760. service. service. &service. uint16 *puiAttributeIDList. 757.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. 754. 740. . void CRadioFileClientDlg::ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf) 742. m_ConnectionInfo. 748. service.Chapter 9: Bluetooth Programming 233 736. CService service.m_pAttributeData[6]] = NULL. puiAttributeIDList). ucNrOfAttr = 2. 747. &tServiceAttributeCnf->ucAttributeData. m_ServicesFound. 759. { 768. 755.service). 774.m_pAttributeData[7]. service = m_ServicesFound.m_pAttributeData[6]] = NULL. { 743.m_pServiceName. m_ConnectionInfo. 739. } 766.pucAttributeData. ucNrOfAttr. 771. (void*)memcpy(service. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof (uint16))). 744. 752. service. 746. service.m_pAttributeData[7]. ShowAllServicesFound().m_SDCHandle = tServiceAttributeCnf->uiSdcHandle.m_pAttributeData[6]). service = m_ServicesFound.ulServiceRecordHandle. (void*)memcpy(service.GetAt(m_ServiceCounter). 775.m_pAttributeData. m_ConnectionInfo. void CRadioFileClientDlg::ReceiveServiceRecordHandle (SD_TServiceAttributeCnf *tServiceAttributeCnf) 778. VOS_Free((void**)&puiAttributeIDList). (void*)memcpy(m_ConnectionInfo.SetAt(m_ServiceCounter. 762. &tServiceAttributeCnf->ucAttributeData. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof (uint16))). &service. puiAttributeIDList[0] = BT_SERVICE_NAME(0). 781. 773. 776.GetAt(m_ServiceCounter-1).uiAttributeListByteCount = tServiceAttributeCnf->uiAttributeListByteCount.pcServiceName[service. CService service. 738. VOS_Free((void**)&puiAttributeIDList). puiAttributeIDList[0] = BT_SERVICE_RECORD_HANDLE. 772. service. 753. 761.pcServiceName. 764. void CRadioFileClientDlg::AskForServiceRecordHandle() 767. 804.m_pAttributeData. 821. 825. 793.uiAttributeListByteCount = tServiceAttributeCnf >uiAttributeListByteCount.uiAttributeListByteCount).m_ConnectionInfo. 784. } void CRadioFileClientDlg::OnScmDeRegisterCnf(void **ppMsg) { SCM_TDeRegisterCnf *ptDeRegisterCnf = (SCM_TDeRegisterCnf *) *ppMsg. 815. 823.tAclHandle>0) { SCM_ReqDisconnect(0.m_ConnectionInfo. 814. } else { DestroyWindow(). 787. 805.ulDbmHandle > 0) { DBM_ReqUnRegisterService(3. } } void CRadioFileClientDlg::OnScmDeRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. m_ServicesFound. 829. 822. 828.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 832. 783. 795. 811. service.SCM_SECURITY_HANDLER). 808. 812. 831.SetAt(m_ServiceCounter-1.m_AttributeListByteCount). 809. DestroyWindow(). switch (ptDeRegisterCnf->tHdr. 813. 801. } else { if (m_ConnectionInfo. 785.SCM_MONITOR_GROUP). service. MessageBox(_T("Could not unregister from SCM")). m_ServiceCounter++. 830. default: break. } void CRadioFileClientDlg::OnDbmUnRegisterServiceCnf(void **ppMsg) { ppMsg = ppMsg. 796. 827. 798. m_ConnectionInfo. 788. 792.ulDbmHandle). 819. 816. 800. 835.tAclHandle). 790. 794. &tServiceAttributeCnf->ucAttributeData.uiSeqNr) { case 1: SCM_ReqDeRegister(2. 820. } void CRadioFileClientDlg::OnCloseapplication() { SCM_ReqDeRegister(1. &tServiceAttributeCnf->ucAttributeData. 799. 826. 791. 824. if (m_ConnectionInfo. 803.234 Chapter 9: Bluetooth Programming 782.pucAttributeData. 789. 806. break. 810. 786. 797. (void*)memcpy(m_ConnectionInfo.service). } } break. (void*)memcpy(service. 802. 817. 807. 834.tAclHandle>0) . m_ConnectionInfo. 818. 833. case 2: if (m_ConnectionInfo. } void CRadioFileClientDlg::ShowAllDevicesFound() { CDevice device. } void CRadioFileClientDlg::AddService(CService service) { m_ServicesFound. 887. 869. 841. DestroyWindow().GetSize().tAclHandle = 0. 882. 876.Add(service).Chapter 9: Bluetooth Programming 235 836. 858. for (i=0. 870. 881. DestroyWindow(). 862. 851. 874. 888. i++) { device = m_DevicesFound.InsertItem(device.GetAddress(). 848. 838. 886. 873. 866. MessageBox(_T("Not possible to UnRegister from DBM")). 854. hPA. 846. 867. 864. 859. 885.i. 877. 856. 883. m_ConnectionInfo.tAclHandle). 861. 843. 844. 889. { SCM_ReqDisconnect(0. 872.m_ConnectionInfo. . 878.GetAt(i). 837. i < iFound. hdevice1=m_tree. } BOOL CRadioFileClientDlg::DestroyWindow() { return CDialog::DestroyWindow(). 839. 852. 890. } } void CRadioFileClientDlg::AddService(CString sService) { CService service(sService). m_ServicesFound. AfxMessageBox("device1"). 880. iFound = m_DevicesFound. 853. } void CRadioFileClientDlg::OnScmDisconnectCnf(void **ppMsg) { ppMsg = ppMsg. 847. 891. int iFound. int iFound. 871.Add(service). 860. MessageBox(_T("Could not remove ACL connection")). OnSelDevice(). 840. TVI_SORT). 850. 849. DestroyWindow(). 842. 884. } void CRadioFileClientDlg::OnScmDisconnectCnfNeg(void **ppMsg) { ppMsg = ppMsg. 865. 875.i. 879. } else { DestroyWindow(). } } void CRadioFileClientDlg::OnDbmUnRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg. 863. 845. 855. 868. 857. } void CRadioFileClientDlg::ShowAllServicesFound() { CService service. 941. 902. 946. SCM_MANDATORY_PAGE_SCAN_MODE. (uint16)m_ConnectionInfo.GetAt(0). iFound = m_ServicesFound.tInquiryLength. 925.GetSize(). 945.tAddress. 913. DBM_StackDB).TVI_LAST). 920. 934.tAddress.tAclHandle. 901. device = m_DevicesFound. m_tree. . 908. 923. 935.GetAt(i). 933.SD_DEFAULT_MFS. 940. 0.InsertItem(service. 918. for (i=0. 899. 900. 917.tNrOfResponses). 907. 898. 904.tLap. 943. 896. 916.GetService(). 924. 939. device. 912.ulServiceRecordHandle = service.GetAt(0). m_ConnectionInfo. 922. HCI_TNrOfResponses tNrOfResponses = 0. } void CRadioFileClientDlg::OnGetservices() { m_ServiceCounter = 0. 942. 944. 921. 938. 895. HCI_TInquiryLength tInquiryLength = 2. 894.hdevice1. } } void CRadioFileClientDlg::AddDevice(CDevice device) { m_DevicesFound. 909.0x33}. 903. service = m_ServicesFound. i < iFound. } void CRadioFileClientDlg::OnConnect() { COM_ReqConnect(0. } void CRadioFileClientDlg::OnComConnectCnf(void **ppMsg) { COM_TConnectCnf *ptConnectCnf = (COM_TConnectCnf *) *ppMsg.ulDbmHandle. SD_ReqConnect(0. 927. } void CRadioFileClientDlg::OnInquiry() { HCI_TLap tLap = {0x9E. 911.uiMaxFrameSize).m_ServiceRecordHandle. 919. 937.Add(device). 905. SCM_NOT_ACCEPT_ROLE_SWITCH). i++) { service = m_ServicesFound. 897.236 Chapter 9: Bluetooth Programming 892. 928. } void CRadioFileClientDlg::OnSelservices() { CService service. 926. 930. m_ConnectionInfo. HCI_ReqInquiry(1.0x8B. m_ConnectionInfo. 914. m_ConnectionInfo. } void CRadioFileClientDlg::OnSelDevice() { CDevice device. SCM_ReqConnect(0. 932. SCM_DM1. 929. 910.tAclHandle).tAddress = device. 915. DBM_ReqRegisterService(0. 936.m_ConnectionInfo. 931. SCM_R1. 893. 906. } 953. } 988. 967. } 960. pucData = COM_DataExtract((MSG_TDataMsg *)*ppMsg.InsertString(index. COM_TConnectCnfNeg *ptConnectCnfNeg = (COM_TConnectCnfNeg *) *ppMsg. 992. MessageBox(_T("Could not send data on RFCOMM channel")). Sleep(100). 978. uint16 uiHandle. } 995. { 990. for (i=0. COM_TDisconnectCnf *ptDisconnectCnf = (COM_TDisconnectCnf *)*ppMsg.uiRFCommHandle = 0.Chapter 9: Bluetooth Programming 237 947.uiRFCommHandle = 0. 1001. { 997. 958. 971. ptDisconnectCnf = ptDisconnectCnf. CHAR sData[80]. 964. } 983. Beep (1000. 999.uiHandle). m_ConnectionInfo. 991. 965. void CRadioFileClientDlg::OnComDisconnectCnfNeg(void **ppMsg) . 957. 959. 982.ucSeqNr. ppMsg = ppMsg.(CString)sData).COM_POS_RESULT. 952. i < uiLength.200). EndModalLoop(0). { 981. } 976. 966. ppMsg = ppMsg. { 962. 987. ptConnectCnfNeg = ptConnectCnfNeg. 993. 951. void CRadioFileClientDlg::OnComDataCnf(void **ppMsg) 980. void CRadioFileClientDlg::OnComConnectCnfNeg(void **ppMsg) 954. sData[i] = pucData[i] . } 1002. m_ConnectionInfo. 950.200). COM_TDisconnectEvt *ptDisconnectEvt = (COM_TDisconnectEvt *)*ppMsg. index++. m_ChatArea. 969. 948. m_ConnectionInfo. 977. i++) 973. 970. { 985. } 979. 949.uiRFCommHandle = 0. 963. MessageBox(_T("Could not create a RFCOMM connection")). 998. m_ConnectionInfo. { 955. COM_TDataInd *tDataInd = (COM_TDataInd *)*ppMsg. &uiLength. { 974. void CRadioFileClientDlg::OnComDisconnectEvt(void **ppMsg) 989. Beep (1000. ptDisconnectEvt = ptDisconnectEvt. 975. 956. 1000. &uiHandle). 968. 994. void CRadioFileClientDlg::OnComDisconnectCnf(void **ppMsg) 996. 986. void CRadioFileClientDlg::OnComDataCnfNeg(void **ppMsg) 984. uint16 uiLength. uint8 *pucData. 972.uiRFCommHandle = ptConnectCnf->uiHandle. EndModalLoop(0). int i. COM_RspData(tDataInd->tHdr. void CRadioFileClientDlg::OnComDataInd(void **ppMsg) 961. MessageBox(_T(" RFCOMM connection")). 1020. 1037. pucData[i]=sBuffer[i]. 1034. tFile. sFile.SetWindowText(fPath). 1036. uint16 iCount=0. 1045. 1046."All Files(*. 1005.GetLength().GetLength(). COM_TDisconnectCnfNeg *ptDisconnectCnfNeg = (COM_TDisconnectCnfNeg *)*ppMsg. 1027. 1054.OFN_OVERWRITEPROMPT| OFN_FILEMUSTEXIST. sFile. 1021. m_InputChat. fPath = dialog. CFile file.m_ConnectionInfo. 1035."". if(dialog.Open(fPath. 1013.NULL).Write((void*)buffer.GetLength().f1[1].cc). char cc[200].pucData.fLength). MessageBox(_T("Could not Disconnect the RFCOMM connection")). itoa(fnLength.(uint16)(iCount + 1)). GetCurrentDirectory(200. 1030. sBuffer=(unsigned char *)malloc(iCount). 1043. 1012. unsigned char *buffer. 1033. 1041. tFile. } 1008. tFile. int fnLength. 1029.SeekToEnd(). if (iCount > 0) 1047. { 1048. 1018.238 Chapter 9: Bluetooth Programming 1003. 1039. { 1023.i < iCount.iCount).f1.*)"). tFile.Close().uiRFCommHandle . 1011. { 1010. COM_DataSend(0. 1032. 1016. return.NULL).i. dialog. 1040.m_ofn.Open("temp". fnLength = fName.Open("temp". file. { 1051.sFile. tFile. 1014. CString fName.Read((void*)buffer. 1052.GetFileName().GetPathName().fPath. 1044. file.Read((void*)sBuffer. 1024. 1007.Write(fName. 1015. uint8 *pucData. file. pucData[i]=0. } 1025. 1017. SetCurrentDirectory(cc). fName = dialog. for (i=0.lpstrInitialDir= cc. fLength=(int)file. } 1053.CFile::modeRead.fnLength). 1028. buffer=(unsigned char *)malloc(fLength). i++) 1050. { 1004. tFile.CFile::modeCreate|CFile::modeWrite| CFile::modeRead.DoModal()==IDCANCEL) 1022. 1006. 1038. 1019. ptDisconnectCnfNeg = ptDisconnectCnfNeg. 1042.NULL). 1049.Close()."*". 1026. void CRadioFileClientDlg::OnBrowse() 1009. 1031. CFileDialog dialog(1.sizeof(f1)).fLength. pucData = COM_DataAlloc((uint16)iCount+1). .10).CFile::modeRead.fLength). iCount=(uint16)sFile.Write((void*)f1.tFile.*sBuffer. fName). 1058. ♦ Line 34: Constant for Bluetooth pincode is defined. ♦ Lines 67–74: This is constructor framework provided by VC++ MFC application by putting the filename as class name. DeleteFile("temp"). sFile. It is provided with every VC++ MFC application.SetWindowText(_T("")).InsertString(index. ♦ Lines 31–32: Constants for serial port interface and USB interface are defined. 1061. index++. ♦ Line 23: The variables hPA and hdevice1 are required to implement a tree. ♦ Lines 36–66: The About dialog is the default dialog to give the information about current application. ♦ Line 35: Constant for Security Manager’s pincode.Format("%s Sent to Server". 1062. 1059.cpp. Dialog box control CWnd Data member IDC_LIST1 m_ChatArea IDC_EDIT1 m_InputChat IDC_TREE1 m_tree ♦ Lines 90–163: The ON BLUETOOTH EVENT message map macro indicates which function handles a specified BLUETOOTH event. m_pServerEvents is an instance of Events class. m_ChatArea.Close(). ♦ Line 33: Constant for generic serial port ID is defined.Chapter 9: Bluetooth Programming 239 1055. ♦ Lines 75–80: The destructor is defined to free the memory for member variables and class references. str. ♦ Lines 17–21: The VC++ editor includes these lines to provide a common framework for the MFC Application Wizard. The important events and the handler function names as specified in the PC reference stack are listed in the following table. ♦ Line 24–28: The union MessageMapFunctions is defined. ♦ Line 29: A constant is defined for PINCODE length. BLUETOOTH Event Handler Function Name COM_START_CNF OnComStartCnf COM_START_CNF_NEG OnComStartCnfNeg COM_VERSION_CNF OnComVersionCnf SCM_REGISTER_CNF OnScmRegisterCnf . 1057. 1060.(CString)str). ♦ Line 30: Explained in HCIInformationCommandsDlg. It includes pfn. } CString str. } 1063. m_InputChat. 1056. a pointer to AFX MSG CALL and the function call. ♦ Lines 81–89: The DDX Control functions manage data transfer between dialog box controls and CWnd data members of the dialog box (see the following table). Code Description ♦ Line 1–15: The files required to implement CRadioFileClientDlg class are included. 240 Chapter 9: Bluetooth Programming SCM_REGISTER_CNF_NEG OnScmRegisterCnfNeg SCM_CONNECT_ACCEPT_IND OnConnectAcceptInd SCM_PINCODE_IND OnScmPincodeInd SCM_CONNECT_CNF OnScmConnectCnf SCM_CONNECT_CNF_NEG OnScmConnectCnfNeg SCM_CONNECT_EVT OnScmConnectEvt SCM_DISCONNECT_EVT OnScmDisconnectEvt SCM_DISCONNECT_CNF OnScmDisconnectCnf SCM_DISCONNECT_CNF_NEG OnScmDisconnectCnfNeg SCM_DEREGISTER_CNF OnScmDeRegisterCnf SCM_DEREGISTER_CNF_NEG OnScmDeRegisterCnfNeg SD_START_CNF OnSdStartCnf SD_CONNECT_CNF OnSdConnectCnf SD_CONNECT_CNF_NEG OnSdConnectCnfNeg SD_SERVICE_SEARCH_CNF OnSdServiceSearchCnf SD_SERVICE_SEARCH_CNF_NEG OnSdServiceSearchCnfNeg SD_SERVICE_ATTRIBUTE_CNF OnSdServiceAttributeCnf SD_SERVICE_ATTRIBUTE_CNF_NEG OnSdServiceAttributeCnfNeg SD_DISCONNECT_CNF OnSdDisconnectCnf DBM_REGISTER_SERVICE_CNF OnDbmRegisterServiceCnf DBM_REGISTER_SERVICE_CNF_NEG OnDbmRegisterServiceCnfNeg DBM_UNREGISTER_SERVICE_CNF OnDbmUnRegisterServiceCnf DBM_UNREGISTER_SERVICE_CNF_NEG OnDbmUnRegisterServiceCnfNeg DBM_ADD_DESCRIPTOR_CNF OnDbmAddDescriptorCnf DBM_ADD_DESCRIPTOR_CNF_NEG OnDbmAddDescriptorCnfNeg HCI_CONFIGURE_PORT_CNF OnHciConfigurePortConfirm HCI_CONFIGURE_PORT_CNF_NEG OnHciConfigurePortConfirmNegat ive HCI_INQUIRY_CNF OnHciInquiryCnf HCI_INQUIRY_EVT OnHciInquiryEvt HCI_LOCAL_ADDRESS_CNF OnHciLocalAddressCnf HCI_LOCAL_ADDRESS_CNF_NEG OnHciLocalAddressCnfNeg HCI_REMOTE_NAME_CNF OnHciRemoteNameCnf HCI_REMOTE_NAME_CNF_NEG OnHciRemoteNameCnfNeg HCI_START_CNF OnHciStartCnf HCI_WRITE_SCAN_ENABLE_CNF OnHciWriteScanEnableCnf . To insert an item as a node of the tree the method InsertItem (&tvInsert) is used. ♦ Lines 193–204: This code has been explained in HCIInformationCommandsDlg. The index variable is used to insert messages in the list box.cpp file ♦ Lines 183–192: TVINSERTSTRUCT is used to define a structure for a tree implementation. ♦ Lines 289–297: When SIL_ReqDevice(0) command is called. The SIL REQ DEVICE CNF event calls corresponding .cpp ♦ Lines 205–237: This code has been explained in HCIInformationCommandsDlg.Chapter 9: Bluetooth Programming 241 HCI_WRITE_SCAN_ENABLE_CNF_NEG OnHciWriteScanEnableCnfNeg HCI_WRITE_AUTHENTICATION_MODE_CNF OnHciWriteAuthenticationModeCn f HCI_WRITE_AUTHENTICATION_MODE_CNF_NEG OnHciWriteAuthenticationModeCn fNeg HCI_WRITE_ENCRYPTION_MODE_CNF OnHciWriteEncryptionModeCnf HCI_WRITE_ENCRYPTION_MODE_CNF_NEG OnHciWriteEncryptionModeCnfNeg HCI_WRITE_COD_CNF OnHciWriteCodCnf HCI_WRITE_COD_CNF_NEG OnHciWriteCodCnfNeg HCI_WRITE_NAME_CNF OnHciWriteNameCnf HCI_WRITE_NAME_CNF_NEG OnHciWriteNameCnfNeg HCI_WRITE_CONNECT_TIMEOUT_CNF OnHciWriteConnectTimeoutCnf HCI_WRITE_CONNECT_TIMEOUT_CNF_NEG OnHciWriteConnectTimeoutCnfNeg HCI_WRITE_PAGE_TIMEOUT_CNF OnHciWritePageTimeoutCnf HCI_WRITE_PAGE_TIMEOUT_CNF_NEG OnHciWritePageTimeoutCnfNeg SIL_SET_DEVICE_CNF OnSilSetDeviceCnf SIL_SET_DEVICE_CNF_NEG OnSilSetDeviceCnfNeg SIL_REQ_DEVICE_CNF OnSilReqDeviceCnf SIL_REQ_DEVICE_CNF_NEG OnSilReqDeviceCnfNeg COM_CONNECT_CNF OnComConnectCnf COM_CONNECT_CNF_NEG OnComConnectCnfNeg COM_DATA_IND OnComDataInd COM_DATA_CNF OnComDataCnf COM_DATA_CNF_NEG OnComDataCnfNeg COM_DISCONNECT_EVT OnComDisconnectEvt COM_DISCONNECT_CNF OnComDisconnectCnf COM_DISCONNECT_CNF_NEG OnComDisconnectCnfNeg ♦ Lines 164–182: This code has been explained in SDP Information CommandsDlg. ♦ Lines 238–288: This code is explained in HCIInformationCommandsDlg. m_tree is a member variable to create nodes for a tree. the corresponding BLUETOOTH Event SIL REQ DEVICE CNF is fired.cpp. This Bluetooth event handling code is required to handle the Bluetooth events and is taken from the PC Reference stack code.cpp. ♦ Lines 366–369: HCI WRITE AUTHENTICATION MODE CNF NEG event invokes this method. ♦ Lines 357–360: HCI WRITE ENCRYPTION MODE CNF NEG event invokes this method.HCI_ENCRYPTION_OFF) sets encryption mode to OFF. ♦ Lines 375–378: HCI WRITE CONNECT TIMEOUT CNF NEG event invokes this method. ♦ Lines 526–531: If the link setup fails. This function gives a diagnostic message during the connection if the interface type has been changed. ♦ Lines 532–545: This method requests a search procedure to find out a particular service. ♦ Lines 347–351: HCI_ReqWriteEncryptionMode(0. . it invokes OnInquiry () method. ♦ Lines 361–365: HCI_ReqWriteConnectTimeout(0. This command fires either the HCI WRITE ENCRYPTION MODE CNF or HCI WRITE ENCRYPTION MODE CNF NEG event corresponding to success or failure. Otherwise.cpp file._tCod) writes COD of the local device.cpp.242 Chapter 9: Bluetooth Programming message-handler function OnSilReqDeviceCnf(void **ppMsg). this method is invoked. ♦ Lines 352–356: HCI_ReqWriteAuthenticationMode(0. the message box displays the message “No connection made”. The SIL REQ DEVICE CNF NEG event calls corresponding message-handler function OnSilReqDeviceCnfNeg(void **ppMsg). ♦ Lines 415–418: HCI WRITE NAME CNF NEG event invokes this method. this method is invoked. ♦ Lines 419–423 : Request to register Security Manager. ♦ Lines 546–552: When SD CONNECT CNF NEG event has been fired. ♦ Lines 517–525: When the link setup is successful.0x1FA0) sets the timeout value OX1FAO for HCI connection. ♦ Lines 303–346: This code is explained in HCIInformationCommandsDlg. A message box appears to show the failed command. it again asks to register service with a different group. (HCI_Tname*) “BT File”) changes the Bluetooth device name to BT File. ♦ Lines 370–374: HCI_ReqWritePageTimeout(0. OnGetServices() method is called to get services. ♦ Lines 298–302: If the command SIL_ReqDevice(0) has failed. The message box will display that the device request failed. ♦ Lines 447–516: This code is explained in HCIInformationDlg.8000) sets page maximum time-out value to wait for the Response. ♦ Lines 428–440: If the sequence number is zero. This command fires either the HCI WRITE AUTHENTICATION MODE CNF or HCI WRITE AUTHENTICATION MODE CNF NEG event corresponding to success or failure.HCI_AUTH_DISABLE) disables the authentication mode. ♦ Lines 410–414: Request to change scan settings to either page scan mode or inquiry scan mode. the message box displays indicating that the device is unable to connect to service discovery. ♦ Lines 441–446: If the registration of Security Manager fails. the corresponding event SIL REQ DEVICE CNF NEG will be fired. ♦ Lines 424–427: HCI_WRITE_SCAN_ENABLE_CNF_NEG event invokes this method. ♦ Lines 388–391: HCI WRITE PAGE TIMEOUT CNF NEG event invokes this method. ♦ Lines 401–405: HCI_ReqWriteName (0. ♦ Lines 406–409: HCI WRITE COD CNF NEG event invokes this method. ♦ Lines 379–387: HCI_ReqWriteCod(0. ♦ Lines 850–855: The current dialog will be destroyed after receiving the SCM DISCONNECT CNF Event. ♦ Lines 741–765: The retrieved attributes of the requested service are stored and displayed in the dialog box. ♦ Lines 731–740: This method sends a request to retrieve the attributes of the particular service specified in the BT SERVICE NAME. ♦ Lines 793–796: The Security Manager’s SCM SECURITY HANDLER is de-registered from Bluetooth module. ♦ Lines 797–825: The Security Manager’s SCM MONITOR GROUP is de-registered from Bluetooth module.m_ConnectionInfo. the message box displays that the service search has failed. the ACL handle and Bluetooth device address are returned and stored. the diagnostic message is displayed in the message box.cpp file. ♦ Lines 862–865: The destroy window method is defined to destroy the current dialog. provided the ACL Link is there. ♦ Lines 766–776: This method sends a request to retrieve the service record handle and protocol descriptor list.Chapter 9: Bluetooth Programming 243 ♦ Lines 553 to 576: This method sends a request to get attributes of a particular service on a remote Bluetooth device. the diagnostic message is displayed.uiSdcHandle) ♦ Lines 605–612: If retrieval of service attribute fails. the response is sent to the server. In the next step. ♦ Lines 613–618: When SD_DISCONNECT_CNF event is fired. ♦ Lines 585–604: When the SD SERVICE SEARCH CNF event is fired for the first time. this message handler function invokes ReceiveServiceName(tServiceAttributeCnf). ♦ Lines 577–584: When the SD SERVICE SEARCH CNF NEG event is fired. it will deregister that service. the message box displays the diagnostic message. the Security manager’s disconnect request will be sent. ♦ Lines 826–831: Corresponding to the negative event. ♦ Lines 672–684: This code is explained in HCIInformationCommandsDlg. the diagnostic message is displayed. When SD SERVICE SEARCH CNF event is fired for the second time. ♦ Lines 714–730: This code retrieves the version of RFCOMM and displays in the dialog box. . ♦ Lines 777–792: This method stores the requested service record handle to display on the user interface. ♦ Lines 832–843: After the de-registration of DBM service has been confirmed. ♦ Lines 856–861: After the SCM DISCONNECT CNF NEG event is received. OnCloseApplication () will be invoked. Otherwise. ♦ Lines 844–849: When the de-registration of DBM service has not been confirmed.cpp file. this message handler function invokes SD_ReqDisconnect(0. ♦ Lines 685–694: After the pincode is received by the client. ♦ Lines 619–671: This code is explained in SDPInformationCommandsDlg.cpp file. ♦ Lines 702–707: When the Security Manager disconnect event is fired. if the DBM service has not yet been de-registered. ♦ Lines 708–713: This code is explained in HCIInformationCommandsdlg. ♦ Lines 695–701: After the Security Manager connect event is fired. the function OnSelservices() is invoked. the Security Manager sends a request to disconnect it. the application requests to register a retrieved service in local Database Manager. ♦ Lines 1002–1007: The message box shows that the RFCOMM cannot be disconnected. ♦ Lines 924–930: After a service is selected.244 Chapter 9: Bluetooth Programming ♦ Lines 866–878: The retrieved remote devices names are added as child nodes to the root node of the tree.cpp file. COM DataSend is a function to send the data to the remote BLUETOOTH device. The filename and the path of the selected file are obtained and the selected file is opened to read the content. ♦ Lines 983–987: The message box displays that the data cannot be sent on RFCOMM channel. The temporary file is deleted. ♦ Lines 1008–1063: After the button IDC BUTTON1 is clicked. Code Output When the preceding application is built in the VC++ environment and executed. ♦ Lines 979–982: The message is stored when the COM DATA CNF event has been received. ♦ Lines 943–952: After RFCOMM connection is confirmed. The memory is allocated to store the content of temporary file and the read data is copied into the memory variable. ♦ Lines 936–942: The local RFCOMM module requests the connection with the remote RFCOMM module. ♦ Lines 988–994: After COM DISCONNECT EVENT is fired. The length and name of the selected file are written into a temporary file by reading from the selected file and writing into the temporary file. the window in Figure 97 appears. ♦ Lines 995–1001: After the COM DISCONNECT CNF is fired. the application requests to establish connection with Security Manager. A temporary file is created in write mode. ♦ Lines 899–902: The found devices are added to m_DevicesFound structure. the dialog is closed. ♦ Lines 910–922: After a device is selected. The current directory is selected in which the file dialog has to be opened. the message box appears to Show that the issued command is a success. The selected file and temporary files are closed. ♦ Lines 960–978: The command to read the incoming data from the remote device is issued. ♦ Lines 888–898: The available services on a particular remote BLUETOOTH device is displayed as their child nodes. the dialog is closed. ♦ Lines 879–887: The found service is added to m_ServicesFound structure. ♦ Lines 903–909: This code is explained in HCIInformationCommandsDlg. The status of the file transmission displays in the list box. The length of the selected file is also obtained. .*”. ♦ Lines 931–935: The application requests connection to discover services on remote devices. the corresponding message handler function OnBrowse () is called. The File dialog has been created with filter “*. The response is sent to the remote device to tell that the data has been received. ♦ Lines 953–959: The message box displays that the establishment of RFCOMM connection has failed. h> 10. When this button is clicked. #define ON_BLUETOOTH_EVENT(uiBtEventID.0. class CRadioFileServerDlg : public CDialog 20.h> 11. // RadioFileServerDlg.h> 9. respectively. SendMessage((HWND)this-> m_hWnd. #include "Remotedevice. 19. #include "service. CRadioFileServerDlg dialog 12. #include "RS232. Server Module Listings 9-19 and 9-20 give the source code of RadioFileServerDlg. #include "ConnectionInfo. #include <exp\sd.h" 7. Listing 9-19: RadioFileServerDlg. (AFX_PMSG)(AFX_PMSGW)(void (AFX_MSG_CALL CWnd::*)(void **))&memberFxn }. All Rights Reserved 1. #define SEND_BT_EVENT(uiBtEventID.Chapter 9: Bluetooth Programming 245 Figure 9-7: Output of the Client Module The left side of the dialog in Figure 9-7 displays the Bluetooth device address of the server and available services on the server in the form of a tree structure.(LPARAM) &pMsg) 18.h © 2001 Dreamtech Software India Inc. uiBtEventID.h" 4.h : header file 2.(WPARAM)uiBtEventID. #include <afxtempl. { 21.0. The status file dispatch appears in the list box designed above the button.h" 8. #define WM_BLUETOOTH_EVENT (WM_USER + 100) 13.h" 6. . #include "Events.WM_BLUETOOTH_EVENT.h and RadioFileServerDlg. #include <exp\BT_COMServer. { WM_BLUETOOTH_EVENT.cpp. \ 15.h" 5.pMsg) \ 17. 3.1. the file dialog appears to enable the user to select and send a file. memberFxn) \ 14. The right side of the above dialog contains one button labeled Browse File To Send. 16. 73. 27. 58. LPARAM lParam). int m_ServiceCounter. 41. 31. public: 23. CServerEvents *m_pServerEvents. 48. LPARAM lParam). // ClassWizard generated virtual function overrides 39. 26. afx_msg HCURSOR OnQueryDragIcon(). virtual BOOL DestroyWindow(). private: 28. 61. ~CRadioFileServerDlg(). CListBox m_ChatArea. // Generated message map functions 71. 43. void ShowAllServicesFound(). 30. //}}AFX_DATA 37. void AskForServiceRecordHandle().246 Chapter 9: Bluetooth Programming 22. afx_msg void OnPaint(). 25. 38. void AddDevice(CDevice device). protected: 60. uint8 m_RFServerChannel. 35. . CConnectionInfo m_ConnectionInfo. 36. 75. 45. 29. CString sName). 52. 68. 66. CTreeCtrl m_tree. void AskForServiceName(). HICON m_hIcon. WPARAM wParam. CRS232 *m_pSerialPort. virtual LRESULT WindowProc(UINT message. CArray <CDevice. 54. //{{AFX_DATA(CRadioFileServerDlg) 32. void AddService(CService service). afx_msg void OnSysCommand(UINT nID. 24. uint16 m_RFCommHandle. 50.CDevice&> m_DevicesFound. //{{AFX_VIRTUAL(CRadioFileServerDlg) 40. 62. virtual BOOL OnInitDialog(). virtual void DoDataExchange(CDataExchange* pDX). 67. 46. 34. 53. 63. //}}AFX_VIRTUAL 47. void AddService(CString sService). CRadioFileServerDlg(CWnd* pParent = NULL). 51. enum { IDD = IDD_RADIOCHAT_DIALOG }. WPARAM wParam. int m_RemoteNameCounter. void ShowAllDevicesFound(). BOOL OnBluetoothEvent(UINT message. 64. 65. LPARAM lParam). void AddDevice(CString sAddress.CService&> m_ServicesFound. 70. CArray <CService. void ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf). 57. void InitSecurityClient(). 55. protected: 44. CEdit m_InputChat. 69. public: 42. 33. int index. 74. //{{AFX_MSG(CRadioFileServerDlg) 72. public: 49. 56. void ReceiveServiceRecordHandle(SD_TServiceAttributeCnf *tServiceAttributeCnf). 59. 104. 111. afx_msg void OnSerialport(). afx_msg void OnComConnectInd(void **ppMsg). afx_msg void OnSdDisconnectCnf(void **ppMsg). 115. afx_msg void OnComRegisterCnf(void **ppMsg).Chapter 9: Bluetooth Programming 247 76. 110. 91. 100. afx_msg void OnComStartCnfNeg(void **ppMsg). 78. 122. afx_msg void OnSelservices(). 113. 131. afx_msg void OnScmDisconnectCnf(void **ppMsg). 109. afx_msg void OnComDataCnf(void **ppMsg). 105. 120. 128. afx_msg void OnHciConfigurePortConfirm(void **ppMsg). afx_msg void OnSdServiceSearchCnf(void **ppMsg). afx_msg void OnHciConfigurePortConfirmNegative(void **ppMsg). afx_msg void OnScmDisconnectCnfNeg(void **ppMsg). 123. 86. 114. 116. 130. 107. 99. afx_msg void OnGetservices(). afx_msg void OnSdServiceSearchCnfNeg(void **ppMsg). afx_msg void OnScmRegisterCnf(void **ppMsg). afx_msg void OnConnectAcceptInd(void **ppMsg). afx_msg void OnDbmUnRegisterServiceCnf(void **ppMsg). afx_msg void OnScmConnectCnfNeg(void **ppMsg). afx_msg void OnDbmRegisterServiceCnfNeg(void **ppMsg). afx_msg void OnDbmUnRegisterServiceCnfNeg(void **ppMsg). 119. . afx_msg void OnCloseapplication(). afx_msg void OnComDataInd(void **ppMsg). 84. 103. 101. afx_msg void OnSelDevice(). afx_msg void OnScmPincodeInd(void **ppMsg). afx_msg void OnSdConnectCnfNeg(void **ppMsg). afx_msg void OnHciRemoteNameCnfNeg(void **ppMsg). afx_msg void OnComFillPdlCnf(void **ppMsg). 96. 83. 121. 125. 85. afx_msg void OnDbmAddDescriptorCnf(void **ppMsg). afx_msg void OnScmDeRegisterCnf(void **ppMsg). 97. 81. 80. afx_msg void OnDestroy(). afx_msg void OnConnect(). afx_msg void OnSdServiceAttributeCnfNeg(void **ppMsg). 93. afx_msg void OnComVersionCnf(void **ppMsg). 112. 98. afx_msg void OnScmDeRegisterCnfNeg(void **ppMsg). afx_msg void OnScmRegisterCnfNeg(void **ppMsg). afx_msg void OnComFillPdlCnfNeg(void **ppMsg). afx_msg void OnDbmAddDescriptorCnfNeg(void **ppMsg). afx_msg void OnSdConnectCnf(void **ppMsg). 102. 127. 88. 126. afx_msg void OnComDataCnfNeg(void **ppMsg). 95. afx_msg void OnHciRemoteNameCnf(void **ppMsg). afx_msg void OnHciLocalAddressCnf(void **ppMsg). afx_msg void OnScmDisconnectEvt(void **ppMsg). afx_msg void OnDbmRegisterServiceCnf(void **ppMsg). afx_msg void OnSdStartCnf(void **ppMsg). afx_msg void OnComStartCnf(void **ppMsg). afx_msg void OnScmConnectEvt(void **ppMsg). 79. 108. 77. 82. afx_msg void OnScmConnectCnf(void **ppMsg). 118. 94. afx_msg void OnHciLocalAddressCnfNeg(void **ppMsg). 129. 89. 124. 90. afx_msg void OnHCISerial(). afx_msg void OnComRegisterCnfNeg(void **ppMsg). 92. afx_msg void OnHciInquiryCnf(void **ppMsg). afx_msg void OnSdServiceAttributeCnf(void **ppMsg). 106. 117. afx_msg void OnInquiry(). afx_msg void OnHCIUsb(). 87. afx_msg void OnHciInquiryEvt(void **ppMsg). h> 8.h> 15. These variables are used in the RadioFileServerDlg. afx_msg void OnSilSetDeviceCnfNeg(void **ppMsg). 139. 141. }. #include <exp/sd. 138. 152. #include "windows. 150. 140. afx_msg void OnHciWriteScanEnableCnf(void **ppMsg).h" 4. 157. 146. 135.h> 13.h> 11. 147. 142. afx_msg void OnSilSetDeviceCnf(void **ppMsg). 160. afx_msg void OnHciWriteNameCnf(void **ppMsg). #include "RadioFileServerDlg.h" 2.h> 6. 148. 136.h" 3. afx_msg void OnHciWriteConnectTimeoutCnfNeg(void **ppMsg). afx_msg void OnHciWriteEncryptionModeCnf(void **ppMsg). #include <process. afx_msg void OnHciWriteCodCnf(void **ppMsg). The code explanation given for RadioFileServerDlg. 145.h> 10. 134. #include <exp/vos2com. DECLARE_MESSAGE_MAP() 159. afx_msg void OnHciWriteEncryptionModeCnfNeg(void **ppMsg).cpp. afx_msg void OnHciWriteCodCnfNeg(void **ppMsg).248 Chapter 9: Bluetooth Programming 132.h> . 149. afx_msg void OnComConnectCnfNeg(void **ppMsg). afx_msg void OnHciWriteConnectTimeoutCnf(void **ppMsg). 151. #include <exp/hci. #include <exp/dbm. afx_msg void OnHciWriteAuthenticationModeCnf(void **ppMsg). afx_msg void OnSilReqDeviceCnfNeg(void **ppMsg). afx_msg void OnHciWriteScanEnableCnfNeg(void **ppMsg). //}}AFX_MSG 158.h> 14. #include "RadioChat. afx_msg void OnComConnectCnf(void **ppMsg). afx_msg void OnSdsStartCnf(void **ppMsg).cpp will clarify the use of the various variables. 154. 137. afx_msg void OnHciWriteNameCnfNeg(void **ppMsg). 144. afx_msg void OnHciStartCnf(void **ppMsg). Code Description Listing 9-19 is the header file in which the necessary variables are declared.h" 7.cpp 1. afx_msg void OnHciWritePageTimeoutCnfNeg(void **ppMsg). afx_msg void OnButton2(). #include "stdafx. #include <exp/com. afx_msg void OnHciWriteAuthenticationModeCnfNeg(void **ppMsg). Listing 9-20: RadioFileServerDlg. 143. #include <exp/scm. #include "Events.cpp © 2001 Dreamtech Software India Inc. #include <exp/hci_drv. #include <exp/sds. afx_msg void OnHciWritePageTimeoutCnf(void **ppMsg). #include <exp/msg.h> 12.h" 5. 155.h> 9. afx_msg void OnSilReqDeviceCnf(void **ppMsg). 156. 153. 133. All Rights Reserved // RadioFileServerDlg. 40.'0'. 58. 46. 42.'0'. 31.h> #include <exp/Bstr.'0'. 22. 69. 34. 48.hdevice1. #include <exp/sil. 38. 45. 21. #define PINCODE_LENGTH ((SCM_TPincodeLength) 4) static const SCM_TPincode _tPincode = {'1'. 29.'0'. 43. 55. 41. 65. //}}AFX_DATA //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX). 25. 44. 51. #define PORTSETTINGS (uint8 *)("COM1:Baud=57600 parity=N data=8 stop=1") #define InterSelSerial ((uint8) 0) #define InterSelUSB ((uint8) 1) #define SRP_SERIAL_GENERIC_SERIALPORT_UUID ((uint16) 0x1101) static const HCI_TCod _tCod={0x20. union MessageMapFunctions { AFX_PMSG pfn. //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }. 32.'0'.'4'.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__. 60.'2'. 30. 50. 39.'3'. 18. 52.0x04. 64.'0'. 33. // DDX/DDV support //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }. 59. 62.'0'. }. void (AFX_MSG_CALL CWnd::*pfn_btf)(void **). class CAboutDlg : public CDialog { public: CAboutDlg().'0'.}. 20. #endif HTREEITEM hPA. 28. 49. 53.'0'. 37. 35. 63. 68. 23.'0'. 36. 54. 19.0x04}. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX). 56. 57. //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg.'0'.Chapter 9: Bluetooth Programming 249 16. CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() . 66. 27. 17.'0'. 47. 26. 24. 61. 67. 92.OnScmDisconnectCnfNeg) 118. ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF_NEG. ON_BLUETOOTH_EVENT(COM_FILL_PDL_CNF_NEG. //{{AFX_DATA_INIT(CRadioFileServerDlg) 74. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF_NEG. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF. } 85. ON_BLUETOOTH_EVENT(COM_REGISTER_CNF. ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF.OnScmConnectEvt) 115. 78. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME). //{{AFX_DATA_MAP(CRadioFileServerDlg) 89. m_DevicesFound.OnScmRegisterCnfNeg) 110.OnScmDisconnectEvt) 116.OnComFillPdlCnfNeg ) 104.OnComFillPdlCnf ) 103. BEGIN_MESSAGE_MAP(CRadioFileServerDlg. 88. m_InputChat). delete m_pServerEvents. // NOTE: the ClassWizard will add member initialization here 75. 91.250 Chapter 9: Bluetooth Programming 70. ON_BLUETOOTH_EVENT(SD_START_CNF.OnComDataInd ) 100. ON_BLUETOOTH_EVENT(COM_REGISTER_CNF_NEG.OnComRegisterCnf ) 101.OnComRegisterCnfNeg ) 102. ON_BLUETOOTH_EVENT(SCM_PINCODE_IND. { 87. { 73. //}}AFX_DATA_MAP 93.OnSdServiceAttributeCnf) .OnScmDeRegisterCnf) 119. void CRadioFileServerDlg::DoDataExchange(CDataExchange* pDX) 86. ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF. CRadioFileServerDlg::~CRadioFileServerDlg() 80. : CDialog(CRadioFileServerDlg::IDD.OnComConnectInd ) 105. CDialog::DoDataExchange(pDX). ON_BLUETOOTH_EVENT(COM_START_CNF_NEG. ON_BLUETOOTH_EVENT(SD_CONNECT_CNF.OnScmDisconnectCnf) 117. IDC_LIST1. CRadioFileServerDlg::CRadioFileServerDlg(CWnd* pParent /*=NULL*/) 71. 82.OnScmPincodeInd) 112. DDX_Control(pDX. 90. ON_BLUETOOTH_EVENT(COM_FILL_PDL_CNF. ON_BLUETOOTH_EVENT(SCM_CONNECT_ACCEPT_IND. 84. m_ServicesFound.OnConnectAcceptInd) 111. ON_BLUETOOTH_EVENT(COM_DATA_IND. m_pServerEvents = new CServerEvents().OnSdServiceSearchCnf) 124. ON_WM_SYSCOMMAND() 97. ON_BLUETOOTH_EVENT(COM_CONNECT_IND. 77. ON_BLUETOOTH_EVENT(SCM_CONNECT_EVT.OnSdServiceSearchCnfNeg) 125.OnSdStartCnf) 121. ON_BLUETOOTH_EVENT(COM_START_CNF. { 81. IDC_EDIT1.OnScmConnectCnfNeg) 114. ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF_NEG. } 79. //{{AFX_MSG_MAP(CRadioFileServerDlg) 96.OnComStartCnfNeg) 107.OnComStartCnf) 106. ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF_NEG.RemoveAll(). ON_WM_QUERYDRAGICON() 99. pParent) 72.OnScmConnectCnf) 113. m_tree). ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF_NEG.OnSdConnectCnf) 122. ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF. } 94. ON_BLUETOOTH_EVENT(COM_VERSION_CNF. DDX_Control(pDX. ON_WM_PAINT() 98. IDC_TREE1. //}}AFX_DATA_INIT 76. ON_BLUETOOTH_EVENT(SD_CONNECT_CNF_NEG. ON_BLUETOOTH_EVENT(SCM_DISCONNECT_EVT.RemoveAll().OnScmRegisterCnf) 109. DDX_Control(pDX. m_ChatArea). 83. ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF. ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF.OnScmDeRegisterCnfNeg) 120.OnSdConnectCnfNeg) 123. CDialog) 95.OnComVersionCnf) 108. OnSdsStartCnf) ON_BN_CLICKED(IDC_BUTTON2. OnDbmRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF. OnHciWriteConnectTimeoutCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF. 156. 139. 152.OnHciWritePageTimeoutCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF_NEG. 133.OnHciRemoteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_START_CNF. 169. 127. 166. 144. OnHciWriteAuthenticationModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF_NEG. 164.OnHciWriteScanEnableCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF_NEG. 160.OnHciWriteCodCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF. 137. 151. ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF_NEG. OnHciWriteEncryptionModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF.OnHciRemoteNameCnf) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF_NEG. OnHciWritePageTimeoutCnfNeg) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF. OnHciLocalAddressCnfNeg) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF.OnHciWriteNameCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF_NEG. 135.Chapter 9: Bluetooth Programming 251 126. OnHciWriteConnectTimeoutCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF_NEG. 134. 141. OnHciWriteScanEnableCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF. 146. 129. 130. OnHciWriteAuthenticationModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF. 132. OnSilReqDeviceCnf) ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF_NEG. OnHciConfigurePortConfirmNegative) ON_BLUETOOTH_EVENT(HCI_INQUIRY_CNF. 142. 131. 158.OnHciInquiryEvt) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF. 149. 155. 150. 168. 159. 140.OnDbmAddDescriptorCnf) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF_NEG. 136. OnHciWriteEncryptionModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF_NEG.OnHciWriteCodCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF_NEG.OnSdDisconnectCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF. 165. OnSilSetDeviceCnf) ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF_NEG. OnSilSetDeviceCnfNeg) ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF. 161.OnDbmRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF_NEG. 145. 148. 138. OnButton2) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CRadioFileServerDlg::OnInitDialog() . 167. 163.OnHciConfigurePortConfirm) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF_NEG. 147. 162.OnHciWriteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF. 128. OnSilReqDeviceCnfNeg) ON_BLUETOOTH_EVENT(COM_CONNECT_CNF. OnHciLocalAddressCnf) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF_NEG. OnDbmUnRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF. 143.OnDbmAddDescriptorCnfNeg) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF. OnSdServiceAttributeCnfNeg) ON_BLUETOOTH_EVENT(SD_DISCONNECT_CNF.OnHciInquiryCnf) ON_BLUETOOTH_EVENT(HCI_INQUIRY_EVT.OnHciStartCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF. 153. 154.OnComConnectCnf ) ON_BLUETOOTH_EVENT(COM_CONNECT_CNF_NEG. 157.OnDbmUnRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF_NEG.OnComConnectCnfNeg ) ON_BLUETOOTH_EVENT(SDS_START_CNF. LoadString(IDS_ABOUTBOX). return CDialog::WindowProc(message. 182.SetWindowText("Type And Press Enter To Send Your Message").mask = TVIF_TEXT. tvInsert. 190. 196. 191.pszText = _T("RemoteRadios"). OnBluetoothEvent( message. InitSecurityClient(). SetIcon(m_hIcon. { 214. lParam). VOS_Free((void **)lParam). tvInsert. 209. #else 220. 188.IsEmpty()) 180. 174. lParam). if (*ptMsg != NULL) 208. 216. } 184. } 185. 211. 215. } 199. FALSE). return TRUE. 203. TVINSERTSTRUCT tvInsert. 187.item. MSG_TMsg **ptMsg. pMessageMap != NULL. for (pMessageMap = GetMessageMap(). 207. CMenu* pSysMenu = GetSystemMenu(FALSE). pSysMenu->AppendMenu(MF_SEPARATOR). ptMsg = (MSG_TMsg**)lParam. LRESULT CRadioFileServerDlg::WindowProc(UINT message. wParam. pMessageMap = (*pMessageMap->pfnGetBaseMap)()) 219. 178. const AFX_MSGMAP* pMessageMap. 186. pMessageMap = pMessageMap->pBaseMap) 222. 221. #endif . tvInsert. 197.hParent =NULL. 218. TRUE). { 177. ASSERT(IDM_ABOUTBOX < 0xF000). { 171. 175. m_pServerEvents->m_pParentDialog = this.item. tvInsert. index=0. 173. SetIcon(m_hIcon. WPARAM wParam. CString strAboutMenu. 200. LPARAM lParam) 213. { 181. strAboutMenu). 179. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX). 193. 194. 189. if (pSysMenu != NULL) 176. pSysMenu->AppendMenu(MF_STRING. { 202. 192. for (pMessageMap = GetMessageMap(). if (!strAboutMenu. wParam.InsertItem(&tvInsert).252 Chapter 9: Bluetooth Programming 170. { 205. m_InputChat. LPARAM lParam) 201. IDM_ABOUTBOX. CDialog::OnInitDialog(). pMessageMap != NULL. BOOL CRadioFileServerDlg::OnBluetoothEvent(UINT message. } 210. 206. 172. strAboutMenu. } 212. WPARAM wParam. 198. if (message == WM_BLUETOOTH_EVENT) 204. hPA = m_tree. 183. const AFX_MSGMAP_ENTRY* lpEntry. #ifdef _AFXDLL 217. 195.hInsertAfter = NULL. { 247. 265.Chapter 9: Bluetooth Programming 253 223. (((CWnd *)this)->*mmf. else 253. m_hIcon). { 234. 237. if (IsIconic()) 260. } 245. { 224. { . 268. { 261. return FALSE. { 249. lParam). 244. { 254. ASSERT(pMessageMap != pMessageMap->pBaseMap). } 241. return TRUE. 235. } 275. CDialog::OnPaint(). 238. 226. 267. void CRadioFileServerDlg::OnSysCommand(UINT nID. union MessageMapFunctions mmf. { 259. while (lpEntry->nSig != AfxSig_end) 231. } 276. 228.cyIcon + 1) / 2. dc.cxIcon + 1) / 2.Height() . dlgAbout. else 272. HCURSOR CRadioFileServerDlg::OnQueryDragIcon() 277. GetClientRect(&rect). lpEntry++. CDialog::OnSysCommand(nID. CRect rect.pfn_btf)((void **)lParam). 236. SendMessage(WM_ICONERASEBKGND. (WPARAM) dc. int cxIcon = GetSystemMetrics(SM_CXICON). return FALSE. 230. } 243. int cyIcon = GetSystemMetrics(SM_CYICON). lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]). } 271. 255. } 252.DoModal(). 270. #else 227. #ifdef _AFXDLL 225. void CRadioFileServerDlg::OnPaint() 258. 266. } 257. 0). 263. LPARAM lParam) 246. if ((nID & 0xFFF0) == IDM_ABOUTBOX) 248. 242. CAboutDlg dlgAbout. } 239. 240. 250.GetSafeHdc(). 269. if ((lpEntry->nMessage == message) && (lpEntry->nCode == wParam)) 233.Width() .DrawIcon(x. ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()). 274. 262. 251. { 232. y. 264. { 273.pfn = lpEntry->pfn. CPaintDC dc(this). int x = (rect. } 256. int y = (rect. mmf. #endif 229. 313. 285. 283. 303. 282. 290. HCI_ReqConfigurePort(0. } void CRadioFileServerDlg::OnSilSetDeviceCnfNeg(void **ppMsg) { SIL_TSetDevice* ptSetDevice. HCI_ReqLocalAddress(0). } void CRadioFileServerDlg::OnHciConfigurePortConfirmNegative(void **ppMsg) { HCI_TConfigurePortCnfNeg *tConfigurePort = (HCI_TConfigurePortCnfNeg *)*ppMsg. return (HCURSOR) m_hIcon.PORTSETTINGS). } void CRadioFileServerDlg::OnSilSetDeviceCnf(void **ppMsg) { ppMsg = ppMsg. MessageBox(_T("Could not open port")). 326. 292. 301. 305. 300. 306. 298. 287.254 Chapter 9: Bluetooth Programming 278. 314. 324. tConfigurePort = tConfigurePort. 284. 293. 329. 286. 288. if(ptReq->uiDevice == SIL_USB) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is USB")). ptSetDevice = (SIL_TSetDevice*)*ppMsg. . } void CRadioFileServerDlg::OnComStartCnfNeg(void **ppMsg) { COM_TStartCnfNeg *tStartCnfNeg = (COM_TStartCnfNeg *)*ppMsg. 321. ptReq = (SIL_TReqDevice*) *ppMsg. 322.iResult == SIL_ERR_DEVICE) SIL_ReqDevice(0). } void CRadioFileServerDlg::OnSilReqDeviceCnfNeg(void **ppMsg) { ppMsg = ppMsg. 312. 280. 311. 279. 304. MessageBox(_T("Device Request FAILED!")). 289. 315. 325. 327. 328. } void CRadioFileServerDlg::OnComStartCnf(void **ppMsg) { COM_TStartCnf *tStartCnf = (COM_TStartCnf *)*ppMsg. 317. } void CRadioFileServerDlg::OnSilReqDeviceCnf(void **ppMsg) { SIL_TReqDevice* ptReq. 307. 296. if(ptSetDevice->tHdr. 294. 309. 297. 308. 281. 316.SIL_SERIAL). 318. 323. 330. 299. COM_ReqStart(0). 291. tStartCnf = tStartCnf. 302. if(ptReq->uiDevice == SIL_SERIAL) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is SERIAL")). 319. tConfigurePort = tConfigurePort. } void CRadioFileServerDlg::InitSecurityClient() { SIL_SetDevice(0. 320. 310. 295. } void CRadioFileServerDlg::OnHciConfigurePortConfirm(void **ppMsg) { HCI_TConfigurePortCnf *tConfigurePort = (HCI_TConfigurePortCnf *)*ppMsg. MessageBox(_T("Could not start RFCOMM")).HCI_ENCRYPTION_OFF). char lpStr[59]. { 336. ppMsg = ppMsg.HCI_AUTH_DISABLE). 347.Chapter 9: Bluetooth Programming 255 331. SetWindowText(_T(lpStr)). ppMsg = ppMsg. tLocalAddress->tAddress. 362. 342. } 334. 346. void CRadioFileServerDlg::OnHciWriteAuthenticationModeCnf(void **ppMsg) 369. void CRadioFileServerDlg::OnHciWriteConnectTimeoutCnfNeg(void **ppMsg) 383. ppMsg = ppMsg. HCI_ReqWriteEncryptionMode(0. 343.ucByte4.ucByte2. 337. 332. } 377. 351. } . 338. tStartCnfNeg = tStartCnfNeg. SD_ReqStart(0). 372. HCI_ReqWritePageTimeout(0. 380. 340. void CRadioFileServerDlg::OnHciLocalAddressCnf(void **ppMsg) 335. tLocalAddress->tAddress. SD_ReqStart(0). 363. void CRadioFileServerDlg::OnSdStartCnf(void **ppMsg) 355. void CRadioFileServerDlg::OnHciWriteEncryptionModeCnf(void **ppMsg) 360. 357.0x1FA0). HCI_ReqWriteConnectTimeout(0. tLocalAddress->tAddress. wsprintf(&lpStr[0].ucByte3. ppMsg = ppMsg. { 350. { 361. } 364.ucByte1. ppMsg = ppMsg. ppMsg = ppMsg. } 348. void CRadioFileServerDlg::OnHciWriteConnectTimeoutCnf(void **ppMsg) 378. 358. 333.ucByte0. 339. } 359. } 354. 352. { 366. 341. HCI_ReqWriteAuthenticationMode(0. { 356. { 370. { 375. 371.ucByte5). HCI_TLocalAddressCnf *tLocalAddress = (HCI_TLocalAddressCnf *)*ppMsg. tLocalAddress->tAddress. { 379. ppMsg = ppMsg. 381. tLocalAddress->tAddress. 344. void CRadioFileServerDlg::OnHciWriteEncryptionModeCnfNeg(void **ppMsg) 365. tLocalAddress->tAddress. } 368. 367. } 382. 376. } 373. void CRadioFileServerDlg::OnHciWriteAuthenticationModeCnfNeg(void **ppMsg) 374. SetWindowText(_T("DEVICE NOT FOUND")). 353.8000). "BD_ADDRESS: 0x%02X%02X%02X%02X%02X%02X\0". 385. 345. { 384. ppMsg = ppMsg. void CRadioFileServerDlg::OnHciLocalAddressCnfNeg(void **ppMsg) 349. } void CRadioFileServerDlg::OnHciWriteNameCnf(void **ppMsg) { ppMsg = ppMsg. 440. } void CRadioFileServerDlg::OnHciWriteScanEnableCnf(void **ppMsg) { ppMsg = ppMsg. 407. 403. 436. HCI_ReqWriteCod(0. 401. int count. 396. void CRadioFileServerDlg::OnHciWritePageTimeoutCnf(void **ppMsg) { ppMsg = ppMsg. 399. CDevice device.(HCI_TName*) "BT Chat"). 394. 417. 431. } void CRadioFileServerDlg::OnHciWritePageTimeoutCnfNeg(void **ppMsg) { ppMsg = ppMsg. 421. HCI_ReqWriteName (0. 412. 413. 411. 428. 414. 397. 418. } void CRadioFileServerDlg::OnHciWriteNameCnfNeg(void **ppMsg) { ppMsg = ppMsg. 433. HCI_ReqWriteScanEnable(0. 423.256 Chapter 9: Bluetooth Programming 386. 424. . 392. 426. 404. } void CRadioFileServerDlg::OnHciWriteCodCnfNeg(void **ppMsg) { ppMsg = ppMsg. 419. 393. 387. 405. 409. SCM_ReqRegister(0. 438. 415. } void CRadioFileServerDlg::OnHciInquiryCnf(void **ppMsg) { HCI_TInquiryCnf *ptInquiryCnf. 430. 420. 435. 432. 388. 406. 416. } void CRadioFileServerDlg::OnHciWriteCodCnf(void **ppMsg) { ppMsg = ppMsg. 429. 422._tCod). 402. 389. 400. 398. 410. 437. 390. 395. 434. 391. 439. 427. 425.SCM_SECURITY_HANDLER).HCI_PAGE_SCAN_ENABLED | HCI_INQUIRY_SCAN_ENABLED). } void CRadioFileServerDlg::OnHciWriteScanEnableCnfNeg(void **ppMsg) { ppMsg = ppMsg. 408. 442. CDevice device.tAddress. 485. 492. 467. m_RemoteNameCounter++. if (count > 0) { device = (CDevice) m_DevicesFound. device. 466. 471. int count. 490.Chapter 9: Bluetooth Programming 257 441. 487. 464.GetSize(). 491. m_RemoteNameCounter = 0. .GetAt(m_RemoteNameCounter). device. 480. 493. 447. m_DevicesFound[m_RemoteNameCounter]. ptRemoteNameCnfNeg =(HCI_TRemoteNameCnfNeg *) *ppMsg.GetSize(). 448. 472. 494. HCI_ReqRemoteName(10. 460. 457. count = m_DevicesFound. 489. 479. HCI_ReqRemoteName(10. 452. if (count > m_RemoteNameCounter) { device = (CDevice) m_DevicesFound. 451. 478. 449. device. } else { ShowAllDevicesFound().GetAt(m_RemoteNameCounter).tClockOffset ). char sName[248]. 469.SetName((CString)_T("UNKNOWN")). device.tPageScanMode. 488.&ptRemoteNameCnf->tName). sprintf(sName. 476. CDevice device.GetAt(m_RemoteNameCounter).tClockOffset ). count = m_DevicesFound.tPageScanPeriodMode.tAddress. ptRemoteNameCnf =(HCI_TRemoteNameCnf *) *ppMsg. 482. 463. device.tAddress. 486. m_RemoteNameCounter++. device. 444. 495. 484. 443.SetName((CString)sName).tPageScanPeriodMode. 473. 453. device. 468. int count. 454. 481. count = m_DevicesFound. 455. } } void CRadioFileServerDlg::OnHciRemoteNameCnf(void **ppMsg) { HCI_TRemoteNameCnf *ptRemoteNameCnf. 483. device. 450.tPageScanMode. HCI_ReqRemoteName(10. 458. ptInquiryCnf =(HCI_TInquiryCnf *) *ppMsg. 465. if (count > m_RemoteNameCounter) { device = (CDevice) m_DevicesFound. 474. 446. 462."%s". } else { AfxMessageBox("No device found").GetSize(). 496. 456. 470. 461. 475. 445. } } void CRadioFileServerDlg::OnHciRemoteNameCnfNeg(void **ppMsg) { HCI_TRemoteNameCnfNeg *ptRemoteNameCnfNeg. 459. m_DevicesFound[m_RemoteNameCounter]. device. 477. 537. m_ConnectionInfo. Error %d". 546. //SRP_HEADSET_UUID. device. ucNrOfUuids. 524. ptSearchPatternList[0]. 535.iResult). } void CRadioFileServerDlg::OnScmConnectCnfNeg(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 516.TUuid. 509. 538. } void CRadioFileServerDlg::OnSdConnectCnfNeg(void **ppMsg) { SD_TConnectCnfNeg *tConnectCnfNeg = (SD_TConnectCnfNeg *)*ppMsg. ptSearchPatternList[0]. 542. 530.258 Chapter 9: Bluetooth Programming 497.uiSdcHandle = tConnectCnf->uiSdcHandle. uint16 uiCurrentServiceRecordCount. 502. 501.tAclHandle = tConnectCnf->tHandle. 534. m_ConnectionInfo. 515. 536. 519. m_ConnectionInfo. 517. SD_TUuid *ptSearchPatternList. ptSearchPatternList = (SD_TUuid*)VOS_Alloc((uint16)(ucNrOfUuids * sizeof(SD_TUuid))). 544. ucNrOfUuids = 1. 540. ptSearchPatternList). 510. 543. CString str. 547. uint8 ucNrOfUuids.tPageScanPeriodMode. 503. AfxMessageBox("No Connection made"). 523. 512. SD_ReqServiceSearch (0. MessageBox(str). str. 504.Format("Could not connect to SD . } void CRadioFileServerDlg::OnSdConnectCnf(void **ppMsg) { SD_TConnectCnf *tConnectCnf = (SD_TConnectCnf *)*ppMsg. 529. 499. 532. 541. 545. 500. 507.eUuidType = SD_DET_UUID16. 498. uint32 *pulSRHandles. device. . 539.tConnectCnfNeg>tHdr. 505. 506. m_ConnectionInfo. 533. 514. uint16 uiMaxRecords. 528. 521.tAddress = tConnectCnf->tAddress. 513. AfxMessageBox("connected").uiUuid16 = SRP_SERIAL_GENERIC_SERIALPORT_UUID . 531. uiMaxRecords. 527. } else { ShowAllDevicesFound().uiSdcHandle. tConnectCnf = tConnectCnf. } void CRadioFileServerDlg::OnSdServiceSearchCnf(void **ppMsg) { SD_TServiceSearchCnf *tServiceSearchCnf = (SD_TServiceSearchCnf *)*ppMsg. 525.tPageScanMode. 526. 508. device. tConnectCnfNeg = tConnectCnfNeg. 520. OnGetservices() . 522. 511.tClockOffset ). } } void CRadioFileServerDlg::OnScmConnectCnf(void **ppMsg) { SCM_TConnectCnf *tConnectCnf = (SCM_TConnectCnf *)*ppMsg. 518. uiMaxRecords = 6. AskForServiceRecordHandle(). SD_ReqServiceAttribute(1. } 575. VOS_Free((void**)&pulSRHandles). 589. &tServiceSearchCnf->ulServiceRecordHandleList. pulSRHandles = (uint32*) VOS_Alloc(((uint16)(uiCurrentServiceRecordCount*sizeof(uint32)))).m_SDCHandle = m_ConnectionInfo. 571. SD_ReqDisconnect(0. (uiCurrentServiceRecordCount*sizeof(uint32))). 588. 572. 555. service.service). puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). 556.m_ConnectionInfo. 564. break. SD_TServiceSearchCnfNeg *tConnectCnfNeg = (SD_TServiceSearchCnfNeg *)*ppMsg. CService service. 559. uint16 *puiAttributeIDList. default: 590. uint8 ucNrOfAttr. 550. uiCurrentServiceRecordCount = tServiceSearchCnf>uiCurrentServiceRecordCount. SD_TServiceAttributeCnf *tServiceAttributeCnf = (SD_TServiceAttributeCnf *)*ppMsg. 557. 565. tConnectCnfNeg = tConnectCnfNeg. (void*)memcpy(pulSRHandles. { 581. CService service.uiSeqNr) 580. break. puiAttributeIDList). ReceiveServiceName(tServiceAttributeCnf). 563. break. pulSRHandles[0]. 584.SetAtGrow(m_ServiceCounter. 585. m_ConnectionInfo. } 592. MessageBox(str). 574. 549.m_ServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList. 558. 591. void CRadioFileServerDlg::OnSdServiceAttributeCnfNeg(void **ppMsg) .Format("Service Search Confirm Negative. 583. CString str. switch (tServiceAttributeCnf->tHdr. 561. 560. 566. case 2: 586. m_ServicesFound. ReceiveServiceRecordHandle(tServiceAttributeCnf). void CRadioFileServerDlg::OnSdServiceSearchCnfNeg(void **ppMsg) 568. puiAttributeIDList[0] = BT_SERVICE_NAME(0). ucNrOfAttr. str. 570. 552. 587. 553.uiSdcHandle. ucNrOfAttr = 1. 573.tConnectCnfNeg>tHdr.Chapter 9: Bluetooth Programming 259 548. 554. 551. VOS_Free((void**)&puiAttributeIDList). { 577. 578. 562. } 567.uiSdcHandle.ulServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList. { 569. void CRadioFileServerDlg::OnSdServiceAttributeCnf(void **ppMsg) 576.iResult).uiSdcHandle). } 593. m_ConnectionInfo. service. Error %d". 579. case 1: 582. SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. void CRadioFileServerDlg::OnDbmAddDescriptorCnfNeg(void **ppMsg) 627. ptConnectAcceptInd =(SCM_TConnectAcceptInd *) *ppMsg. { 603. 639.200). 619. 637. 629. void CRadioFileServerDlg::OnHciInquiryEvt(void **ppMsg) 643. SCM_RspConnectAccept((MSG_TMsg **)ppMsg. CDevice device. Beep (1000. str. 600. } 620. COM_ReqRegister(PROFILE_SERIAL. 597. 612. MessageBox(_T("Could not register the service to DBM")). SCM_TConnectAcceptInd *ptConnectAcceptInd.tConnectCnfNeg->tHdr. tConnectCnfNeg = tConnectCnfNeg. void CRadioFileServerDlg::OnDbmRegisterServiceCnfNeg(void **ppMsg) 615. 613. SCM_POS_RESULT. { 628. 0). 646.260 Chapter 9: Bluetooth Programming 594. ptInquiryEvt =(HCI_TInquiryEvt *) *ppMsg. { 622. } 607. *ppMsg = NULL. 636. } 601. 617. 645. CString str. tConnectCnfNeg = tConnectCnfNeg. ptConnectAcceptInd->tAddress. 618. } 642. 606. 625.iResult). void CRadioFileServerDlg::OnDbmRegisterServiceCnf(void **ppMsg) 608. 610. 596. tConnectCnfNeg = tConnectCnfNeg. } 632. error %d". { 634. { 595. Beep (1000. { 609.Format("Service Attribute Confirm negative. 599. { 616. 605. 638. { 644. 640. SCM_SLAVE). SD_TServiceAttributeCnfNeg *tConnectCnfNeg = (SD_TServiceAttributeCnfNeg *)*ppMsg. 623. m_pSerialPort->WriteProfile(ptRegisterCnf->ulDbmHandle). OnSelservices(). HCI_TInquiryEvt *ptInquiryEvt. MessageBox(_T("Could not register to Data Base Manager")). void CRadioFileServerDlg::OnSdDisconnectCnf(void **ppMsg) 602.200). 631. 604. 598. ppMsg = ppMsg. void CRadioFileServerDlg::OnConnectAcceptInd(void **ppMsg) 633. void CRadioFileServerDlg::OnDbmAddDescriptorCnf(void **ppMsg) 621. . SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. MessageBox(str). 635. DestroyWindow(). 624. 641. DBM_TRegisterServiceCnf *ptRegisterCnf = (DBM_TRegisterServiceCnf *) *ppMsg. } 614. } 626. ppMsg = ppMsg. 630. 611. 677. 692. 688. m_ConnectionInfo. char cpStr[3]. } void CRadioFileServerDlg::OnScmPincodeInd(void **ppMsg) { SCM_TPincodeInd *ptPincodeInd. 681. OnCloseapplication(). cpVerStr = &ptVersionCnf->cVersion.tPageScanRepMode = ptInquiryEvt->tPageScanRepMode. m_ConnectionInfo. _tPincode. 663. 699. 671. 687. 693. 650. int8 iCharCount = 9. SCM_RspPincode((MSG_TMsg **)ppMsg. 682. 701. 700. SCM_POS_RESULT. char* cpVerStr = NULL. 694. 653. 685. 679. 672.tClockOffset = ptInquiryEvt->tClockOffset. 697. ptPincodeInd =(SCM_TPincodeInd *) *ppMsg. 673.tCod = ptInquiryEvt->tCod. 678. m_ConnectionInfo.PORTSETTINGS). 690. cpStr[iCharCount-10] = cpVerStr[iCharCount].tAddress = tConnectEvt->tAddress. device. } void CRadioFileServerDlg::OnScmDisconnectEvt(void **ppMsg) { ppMsg = ppMsg. } void CRadioFileServerDlg::AskForServiceName() { .tAddress = ptInquiryEvt->tAddress. device. } void CRadioFileServerDlg::OnComVersionCnf(void **ppMsg) { CAboutDlg Abodlg. 655. 654. 676.DoModal(). AddDevice(device). PINCODE_LENGTH). do { iCharCount++. 651. 695. cpStr[3] = ((char)0). ptVersionCnf = (COM_TVersionCnf *) *ppMsg. device. device. 657.tAclHandle = 0. 689. 686. ptPincodeInd->tAddress. device. 669. 702. } void CRadioFileServerDlg::OnHciStartCnf(void **ppMsg) { HCI_TStartCnf *ptStartCnf = (HCI_TStartCnf *)*ppMsg. 648. } void CRadioFileServerDlg::OnScmConnectEvt(void **ppMsg) { SCM_TConnectEvt *tConnectEvt = (SCM_TConnectEvt *)*ppMsg. 691. 674.tPageScanMode = ptInquiryEvt->tPageScanMode. COM_TVersionCnf* ptVersionCnf. 652. 660. 649. 656. HCI_ReqConfigurePort(0.tPageScanPeriodMode = ptInquiryEvt->tPageScanPeriodMode. 684. 680. 659. tConnectEvt = tConnectEvt.Chapter 9: Bluetooth Programming 261 647. 664. 683. 662. 661. device. 675. 670. 665. Abodlg. }while(iCharCount <= 11). 698.tAclHandle = tConnectEvt->tHandle. ptStartCnf = ptStartCnf. 696. 667. 658. 666. 668. 742.262 Chapter 9: Bluetooth Programming 703. m_ConnectionInfo. m_ConnectionInfo. 716.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount.service). puiAttributeIDList).SetAt(m_ServiceCounter.m_pServiceName. 745.pcServiceName.ulServiceRecordHandle.GetAt(m_ServiceCounter-1). SD_ReqServiceAttribute(2. } 736. void CRadioFileServerDlg::AskForServiceRecordHandle() 737.uiSdcHandle. 724. uint16 *puiAttributeIDList. 743. 707. ucNrOfAttr. &tServiceAttributeCnf->ucAttributeData. m_ConnectionInfo.m_pAttributeData[6]] = NULL. void CRadioFileServerDlg::ReceiveServiceRecordHandle (SD_TServiceAttributeCnf *tServiceAttributeCnf) 748.m_pAttributeData[7]. 735. puiAttributeIDList[0] = BT_SERVICE_NAME(0). 744. puiAttributeIDList[1] = BT_PROTOCOL_DESCRIPTOR_LIST. 741. SD_ReqServiceAttribute(0. 750. } 747. 732. &service. } 711.m_AttributeListByteCount). ucNrOfAttr = 1.m_pAttributeData[6]). 714.uiAttributeListByteCount). (void*)memcpy(service. m_ServiceCounter++. 708. 722.ulServiceRecordHandle. 729.pcServiceName[service. service. m_ConnectionInfo. CService service. VOS_Free((void**)&puiAttributeIDList). (void*)memcpy(service. 709. &tServiceAttributeCnf->ucAttributeData. 717.uiSdcHandle.GetAt(m_ServiceCounter). 734. 739. (void*)memcpy(m_ConnectionInfo. 733. .m_pAttributeData[6]] = NULL. 730. ucNrOfAttr = 2.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle.m_pAttributeData. 705. 704. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). 727. { 713. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). m_ConnectionInfo. m_ConnectionInfo. 725. (void*)memcpy(m_ConnectionInfo. 723. 715. 726. { 738. service. m_ConnectionInfo. service = m_ServicesFound.m_pAttributeData[6]). 719.m_pServiceName[service.pucAttributeData. &service. 740. VOS_Free((void**)&puiAttributeIDList). service. uint8 ucNrOfAttr. puiAttributeIDList). 721. puiAttributeIDList[0] = BT_SERVICE_RECORD_HANDLE. 706. service = m_ServicesFound. 728. service. 718. 746. service. void CRadioFileServerDlg::ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf) 712. 731. uint8 ucNrOfAttr. 710. m_ServicesFound. service.uiAttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. { 749. ucNrOfAttr. 720. CService service. ShowAllServicesFound(). uint16 *puiAttributeIDList.m_pAttributeData[7]. 775. } } void CRadioFileServerDlg::OnScmDeRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. 787. } else { DestroyWindow(). 786. 767. 768. 765.Chapter 9: Bluetooth Programming 263 751. service. 785. 763.uiSeqNr) { case 1: SCM_ReqDeRegister(2. 793.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. 773. (void*)memcpy(service. 778. 792. break.SCM_MONITOR_GROUP). } else { if (m_ConnectionInfo. MessageBox(_T("Could not unregister from SCM")). m_ServiceCounter++.SCM_SECURITY_HANDLER). default: break. case 2: if (m_ConnectionInfo. 784. service. 779.uiAttributeListByteCount). 799. } void CRadioFileServerDlg::OnCloseapplication() { SCM_ReqDeRegister(1. 796. 759. 797.SetAt(m_ServiceCounter-1. . 800.tAclHandle>0) { SCM_ReqDisconnect(0. 803. 756.ulDbmHandle). 758. 761. 798. } } break. 788. 760.ulDbmHandle > 0) { DBM_ReqUnRegisterService(3. 770.m_AttributeListByteCount). 766. 771.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 801. 772. &tServiceAttributeCnf->ucAttributeData. 795.service). 780. 754. 802. 774. 769. switch (ptDeRegisterCnf->tHdr. } void CRadioFileServerDlg::OnDbmUnRegisterServiceCnf(void **ppMsg) { ppMsg = ppMsg.uiAttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 789. m_ConnectionInfo. 782. 753. 783. 776. DestroyWindow(). 790. (void*)memcpy(m_ConnectionInfo. 764. 752. service. 777. &tServiceAttributeCnf->ucAttributeData.m_ConnectionInfo.m_ConnectionInfo. 791.tAclHandle). 757.m_pAttributeData. 804. 781. 794. 762.pucAttributeData. 755. m_ServicesFound. } void CRadioFileServerDlg::OnScmDeRegisterCnf(void **ppMsg) { SCM_TDeRegisterCnf *ptDeRegisterCnf = (SCM_TDeRegisterCnf *) *ppMsg. m_ConnectionInfo. MessageBox(_T("Not possible to UnRegister from DBM")). 834. 828. 831. 859. 827. 850. 830. . 858. DestroyWindow(). 856. 813. 811. DestroyWindow(). 809. 816. 815. int iFound. 855.tAclHandle = 0. 829.i. } BOOL CRadioFileServerDlg::DestroyWindow() { return CDialog::DestroyWindow(). DestroyWindow(). 835. 838. 824. 822.InsertItem(device.GetAt(i). 808. } void CRadioFileServerDlg::ShowAllServicesFound() { CService service. 847.GetAddress(). 851. m_ConnectionInfo. 852.tAclHandle).m_ConnectionInfo. } void CRadioFileServerDlg::OnScmDisconnectCnfNeg(void **ppMsg) { ppMsg = ppMsg. 837. for (i=0. 842. 819. 820.GetSize(). 839.Add(service). 832. 817. } } void CRadioFileServerDlg::OnDbmUnRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg. } void CRadioFileServerDlg::ShowAllDevicesFound() { CDevice device. TVI_SORT). } void CRadioFileServerDlg::OnScmDisconnectCnf(void **ppMsg) { ppMsg = ppMsg. 844. 846. 857. 853. int iFound. 841. 854. 845. 826. 807. MessageBox(_T("Could not remove ACL connection")). 860. 823. } void CRadioFileServerDlg::AddService(CService service) { m_ServicesFound. 849. } else { DestroyWindow(). 814.Add(service). m_ServicesFound. 806. 836. } } void CRadioFileServerDlg::AddService(CString sService) { CService service(sService). 810. 812. 833. hPA. 843.tAclHandle>0) { SCM_ReqDisconnect(0.264 Chapter 9: Bluetooth Programming 805. 818.i. OnSelDevice(). i++) { device = m_DevicesFound. 848. i < iFound. 825. 840. if (m_ConnectionInfo. iFound = m_DevicesFound. 821. hdevice1=m_tree. } void CRadioFileServerDlg::OnComConnectCnfNeg(void **ppMsg) { COM_TConnectCnfNeg *ptConnectCnfNeg = (COM_TConnectCnfNeg *) *ppMsg.TVI_LAST). 886. 907. 913. for (i=0.GetAt(i). 865. 914. 898. 869. 881. 894. device = m_DevicesFound. 911. SCM_MANDATORY_PAGE_SCAN_MODE. 862.0x8B.tAddress = device. service = m_ServicesFound.GetSize(). 901. 910.tLap.SD_DEFAULT_MFS. Beep (1000. } void CRadioFileServerDlg::OnInquiry() { HCI_TLap tLap = {0x9E. SD_ReqConnect(0.GetService(). 909. Sleep(100).tAddress. 880.tAddress. 0.tInquiryLength. SCM_ReqConnect(0. } void CRadioFileServerDlg::OnSelservices() { CService service. 896. i < iFound.InsertItem(service. /* I don't make use of the SeqNr. 867.tNrOfResponses). } void CRadioFileServerDlg::OnComConnectCnf(void **ppMsg) { COM_TConnectCnf *ptConnectCnf = (COM_TConnectCnf *) *ppMsg. 889. 888. 908. 902. m_ConnectionInfo. 890. 891. } void CRadioFileServerDlg::OnSelDevice() { CDevice device. 879. Beep (1000. 876. 868. 871. 877. DBM_ReqRegisterService(0. 883.200).200). i++) { service = m_ServicesFound.ulServiceRecordHandle = service. SCM_NOT_ACCEPT_ROLE_SWITCH). 892. } void CRadioFileServerDlg::OnGetservices() { m_ServiceCounter = 0. m_ConnectionInfo. 887. 915. SCM_R1.Add(device). */ device.Chapter 9: Bluetooth Programming 265 861. 900. m_ConnectionInfo.tAclHandle). HCI_ReqInquiry(1.0x33}. 884. m_tree. SCM_DM1. 897.m_ServiceRecordHandle. 872. 906. } } void CRadioFileServerDlg::AddDevice(CDevice device) { m_DevicesFound. 874. 893. 873. 899. MessageBox(_T(" RFCOMM connection")).m_ConnectionInfo. DBM_StackDB). 866. HCI_TInquiryLength tInquiryLength = 2. . 895. 882. 903. 864.uiRFCommHandle = ptConnectCnf->uiHandle. 878.GetAt(0). 870. 863.hdevice1. 904. HCI_TNrOfResponses tNrOfResponses = 0.GetAt(0). 875. 912. 885. 905. iFound = m_ServicesFound. 929. 948. DestroyWindow(). 951. MessageBox(_T("Not possible to register to RFCOM")). 917. char *pcName = NULL. 937. m_pSerialPort = new CRS232(PROFILE_SERIAL). 938. } void CRadioFileServerDlg::OnButton2() { SCM_ReqRegister(0. 925. } void CRadioFileServerDlg::OnComRegisterCnf(void **ppMsg) { COM_TRegisterCnf *ptRegisterCnf = (COM_TRegisterCnf *)*ppMsg.SCM_MONITOR_GROUP). 954. 923. COM_ReqFillPdl(PROFILE_SERIAL. 919. 969. 941. m_RFServerChannel = ptRegisterCnf->ucServerChannel. 947. m_ConnectionInfo.uiRFCommHandle = 0. 960. 942. 955. } void CRadioFileServerDlg::OnScmRegisterCnf(void **ppMsg) //2 { ppMsg = ppMsg. 926. CString sName. 956. (uint16)m_pSerialPort->GetSRPHandle()). } void CRadioFileServerDlg::OnComFillPdlCnfNeg(void **ppMsg) { ppMsg = ppMsg. 922. MessageBox(_T("Could not create a RFCOMM connection")). 927. } void CRadioFileServerDlg::OnSdsStartCnf(void **ppMsg) { CString sAddress. 950. 924. SDS_TStartCnf *ptStartCnf. 939. . 968. 932. 966. MessageBox(_T("Not possible to register to SCM")). 920. 930. 958. 964. 933. 967. MessageBox(_T("Not possible to fill PDL for RF COM")). m_pSerialPort->GetProfileName(&pcName). 935. 953. Beep(1000. 971. 944. 949. 962. 921. } void CRadioFileServerDlg::OnComRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. ptMsg = ptMsg.100). 936. 918. 965. ptFillPdlCnf = ptFillPdlCnf. 961. SDS_ReqStart(0). ptConnectCnfNeg = ptConnectCnfNeg. DestroyWindow(). 940. 957. 945. 928. ptStartCnf =(SDS_TStartCnf *) *ppMsg. 959.266 Chapter 9: Bluetooth Programming 916. 952. 931. ptRegisterCnf->ucServerChannel. } void CRadioFileServerDlg::OnScmRegisterCnfNeg(void **ppMsg) //2 { SCM_TRegisterCnfNeg *ptMsg = (SCM_TRegisterCnfNeg *) *ppMsg. 934. 970. } void CRadioFileServerDlg::OnComFillPdlCnf(void **ppMsg) { COM_TFillPdlCnf *ptFillPdlCnf = (COM_TFillPdlCnf *)*ppMsg. 946. 963. 943. COM_TConnectInd *tConnectInd = (COM_TConnectInd *)*ppMsg. index++. 985. 981. } 975. COM_RspConnect((MSG_TMsg **)ppMsg. buff3=(char *)malloc(a). file2. 980.a). } . 1012. m_ChatArea. 999. 1018. uint16 uiHandle.buff2).NULL). buff2=(char *)malloc(fnLength).CFile::modeRead. file2.InsertString(index.GetLength()-1-fnLength. 986. 1016. 1013.1). 997.a). 978. 1014. COM_TDataInd *tDataInd = (COM_TDataInd *)*ppMsg. file1. 1020. 973. COM_RspData(tDataInd->tHdr. void CRadioFileServerDlg::OnComConnectInd(void **ppMsg) 976.file2. fnLength = atoi(buff1).COM_POS_RESULT. file2. 1003. for (i=0.i. CString str. buff2[fnLength] = 0.Write((void*)buff3.uiHandle). file1. 974. 1019.COM_POS_RESULT. 990. DeleteFile("temp").tConnectInd>uiMaxFrameSize). 1022. m_RFCommHandle = tConnectInd->uiHandle.NULL). &uiHandle).Format("%s Was Received From Client". 1021. &uiLength.Open("temp".fnLength). 994.ucSeqNr. file1. 1010. buffer[i] = pucData[i]. DestroyWindow(). 1024. uint8 *pucData. pucData = COM_DataExtract((MSG_TDataMsg *)*ppMsg. 1008. 1000. buffer = (unsigned char *)malloc(uiLength).Close(). 1017.*buff3.Open(buff2.*buff2. } 982. 993. CFile file1. 1023. i < uiLength. 987. 989. 1004. 998. fclose(file). 1015. uint16 uiLength.Read((void*)buff3. a = file1. { 977. str. 995. int fnLength. unsigned char *buffer. { 1002. { 984. 992.Chapter 9: Bluetooth Programming 267 972. char buff1[1].a. void CRadioFileServerDlg::OnComDataInd(void **ppMsg) 983."wb+"). putc(buffer[i]. file1. 1009. file = fopen("temp".Close().(CString)str). 1011. 1006.Read((void*)buff1. 1007. *ppMsg = NULL. 979. 988. FILE *file.CFile::modeCreate|CFile::modeWrite. file1. 996.file). } 1005. i++) 1001. 991.Read((void*)buff2. ♦ Lines 85–93: Explained in RadioFileClientDlg. ♦ Lines 79–84: The destructor is defined to free the memory for member variables and class references. ♦ Lines 26–78: Explained in RadioFileClientDlg. The following table lists the various Bluetooth events and their associated handler functions.cpp file. ♦ Lines 94–168: The ON BLUETOOTH EVENT message map macro indicates which function will handle a specified Bluetooth event. ♦ Line 25: The variables hPA.cpp file.hdevice1 are required to implement a tree. ♦ Lines 19–23: The VC++ Editor adds this code to provide a common framework for the MFC Application Wizard.268 Chapter 9: Bluetooth Programming Code Description ♦ Lines 1–17: The files required to implement CRadioServerDlg class are included. BLUETOOTH Event Handler Function Name COM_DATA_IND OnComDataInd COM_REGISTER_CNF OnComRegisterCnf COM_REGISTER_CNF_NEG OnComRegisterCnfNeg COM_FILL_PDL_CNF OnComFillPdlCnf COM_FILL_PDL_CNF_NEG OnComFillPdlCnfNeg COM_CONNECT_IND OnComConnectInd COM_START_CNF OnComStartCnf COM_START_CNF_NEG OnComStartCnfNeg COM_VERSION_CNF OnComVersionCnf COM_CONNECT_CNF OnComConnectCnf COM_CONNECT_CNF_NEG OnComConnectCnfNeg SCM_REGISTER_CNF OnScmRegisterCnf SCM_REGISTER_CNF_NEG OnScmRegisterCnfNeg SCM_CONNECT_ACCEPT_IND OnConnectAcceptInd SCM_PINCODE_IND OnScmPincodeInd SCM_CONNECT_CNF ONScmConnectCnf SCM_CONNECT_CNF_NEG OnScmConnectCnfNeg SCM_CONNECT_EVT OnScmConnectEvt SCM_DISCONNECT_EVT OnScmDisconnectEvt SCM_DISCONNECT_CNF OnScmDisconnectCnf SCM_DISCONNECT_CNF_NEG OnScmDisconnectCnfNeg SCM_DEREGISTER_CNF OnScmDeRegisterCnf SCM_DEREGISTER_CNF_NEG OnScmDeRegisterCnfNeg SD_START_CNF OnSdStartCnf . Chapter 9: Bluetooth Programming 269 SD_CONNECT_CNF OnSdConnectCnf SD_CONNECT_CNF_NEG OnSdConnectCnfNeg SD_SERVICE_SEARCH_CNF OnSdServiceSearchCnf SD_SERVICE_SEARCH_CNF_NEG OnSdServiceSearchCnfNeg SD_SERVICE_ATTRIBUTE_CNF OnSdServiceAttributeCnf SD_SERVICE_ATTRIBUTE_CNF_NEG OnSdServiceAttributeCnfNeg SD_DISCONNECT_CNF OnSdDisconnectCnf DBM_REGISTER_SERVICE_CNF OnDbmRegisterServiceCnf DBM_REGISTER_SERVICE_CNF_NEG OnDbmRegisterServiceCnfNeg DBM_UNREGISTER_SERVICE_CNF OnDbmUnRegisterServiceCnf DBM_UNREGISTER_SERVICE_CNF_N EG OnDbmUnRegisterServiceCnfNeg DBM_ADD_DESCRIPTOR_CNF OnDbmAddDescriptorCnf DBM_ADD_DESCRIPTOR_CNF_NEG OnDbmAddDescriptorCnfNeg HCI_CONFIGURE_PORT_CNF OnHciConfigurePortConfirm HCI_CONFIGURE_PORT_CNF_NEG OnHciConfigurePortConfirmNeg ative HCI_INQUIRY_CNF OnHciInquiryCnf HCI_INQUIRY_EVT OnHciInquiryEvt HCI_LOCAL_ADDRESS_CNF OnHciLocalAddressCnf HCI_LOCAL_ADDRESS_CNF_NEG OnHciLocalAddressCnfNeg HCI_REMOTE_NAME_CNF OnHciRemoteNameCnf HCI_REMOTE_NAME_CNF_NEG OnHciRemoteNameCnfNeg HCI_START_CNF OnHciStartCnf HCI_WRITE_SCAN_ENABLE_CNF OnHciWriteScanEnableCnf HCI_WRITE_SCAN_ENABLE_CNF_NE G OnHciWriteScanEnableCnfNeg HCI_WRITE_AUTHENTICATION_MOD E_CNF OnHciWriteAuthenticationMode Cnf HCI_WRITE_AUTHENTICATION_MOD E_CNF_NEG OnHciWriteAuthenticationMode CnfNeg HCI_WRITE_ENCRYPTION_MODE_CN F OnHciWriteEncryptionModeCnf HCI_WRITE_ENCRYPTION_MODE_CN F_NEG OnHciWriteEncryptionModeCnfN eg HCI_WRITE_COD_CNF OnHciWriteCodCnf HCI_WRITE_COD_CNF_NEG OnHciWriteCodCnfNeg HCI_WRITE_NAME_CNF OnHciWriteNameCnf . ♦ Lines 684–871: Explained in RadioFileClientDlg. ♦ Lines 678–683: Explained in HCIInformationCommandsDlg. ♦ Lines 982–1024: When the data arrival indication has been received by the server.cpp file.cpp file. ♦ Lines 655–677: Explained in RadioFileClientDlg. ♦ Lines 930–936: If the security manager registration fails.cpp file. The filename and the length of the file are obtained. remote device name is retrieved. ♦ Lines 879–920: Explained in RadioFileClientDlg. ♦ Lines 925–929: After the security manager registration is confirmed. the command to fill the DBM component with protocol specified parameters of COM component is issued. the request to start service discovery component is issued. ♦ Lines 921–924: Request to register Security Manager with the attribute SCM MONITOR GROUP.cpp file.cpp file. ♦ Lines 937–943: After the service discovery component start is confirmed.270 Chapter 9: Bluetooth Programming HCI_WRITE_NAME_CNF_NEG OnHciWriteNameCnfNeg HCI_WRITE_CONNECT_TIMEOUT_CN F OnHciWriteConnectTimeoutCnf HCI_WRITE_CONNECT_TIMEOUT_CN F_NEG OnHciWriteConnectTimeoutCnfN eg HCI_WRITE_PAGE_TIMEOUT_CNF OnHciWritePageTimeoutCnf HCI_WRITE_PAGE_TIMEOUT_CNF_N EG OnHciWritePageTimeoutCnfNeg SIL_SET_DEVICE_CNF OnSilSetDeviceCnf SIL_SET_DEVICE_CNF_NEG OnSilSetDeviceCnfNeg SIL_REQ_DEVICE_CNF OnSilReqDeviceCnf SIL_REQ_DEVICE_CNF_NEG OnSilReqDeviceCnfNeg SDS_START_CNF OnSdsStartCnf ♦ Lines 169–606: Explained in RadioFileClientDlg.cpp file.cpp file. It sends the response to indicate that the data from the remote device has been received successfully. ♦ Lines 642–654: Explained in HCIInformationCommandsDlg. ♦ Lines 968–974: If filling up the DBM component with COM specific parameters fails. ♦ Lines 975–981: Explained in CradioFileClientDlg. ♦ Lines 872–878: Explained in HCIInformationCommandsDlg. The temporary file is opened in read mode.cpp file. the instance of CRS232 is created. ♦ Lines952–957: If the RFCOMM registrations are not confirmed. it gets data from the remote Bluetooth device. A . ♦ Lines 944–951: After the RFCOMM registration is confirmed.cpp file. A temporary file is opened in write mode to copy the received data into that file and then closed. The first character is checked to see the length of the filename. ♦ Lines 607–641: Explained in SDPInformationCommandsDlg. the diagnostic message displays in the message box. the diagnostic message is displayed. the diagnostic message will be displayed on the message box. ♦ Lines 958–967: After filling up the DBM component with COM specific parameters is finished. we create a text chat utility through which two Bluetooth-enabled PCs can exchange small messages. This module is implemented with the classes Cservice and CconnectionInfo in the files named Service. The file received from the other Bluetooth device will be stored here with the same name.h (of the PC reference stack). The temporary file is deleted. If larger files are to be transferred. The code is same as that of the file transfer application. Figure 9-8: Output of the Server Module The right portion of this server-side screen displays the message that the file has been received. the window in Figure 9-8 is displayed.cpp. In this example. The two files are closed. meaning 127 bytes. it can be displayed on a WML browser or emulator. This text file can be a WML file containing a set of WML cards. The status of file transmission is displayed in the dialog box. if the application is built in the VC++ environment. the following modifications are required: In product. The client module is implemented with the class CRadioChatClientDlg in the file named RadioChatClientDlg. COM MAX MFS has to be set to 32K. The software contains the following three modules: ♦ Common Module (common to both server and client): The common module provides a mechanism to setup ACL link and to access the service. Application: Chat In this application. Code Output At the server side. When the WML code is received by the Bluetooth device.Chapter 9: Bluetooth Programming 271 file with the received filename is opened in write mode. we transferred a text file from one device to another. the file size is limited to the RFCOMM packet size. . ♦ Client module: The client module gets the service from the server and exchanges the data over RFCOMM.cpp and ConnectionInfo. The browser interprets this file and the WML cards are displayed.cpp respectively. Also note that in this application. The data is read from the temporary file and copied into the created file. The examples we discussed in Chapter 8 essentially work on this principle — a WAP server discovers the nearby Bluetooth devices and does a file transfer of the WML file to be displayed on the WAP browser. (AFX_PMSG)(AFX_PMSGW)(void (AFX_MSG_CALL CWnd::*)(void **))&memberFxn }. . virtual LRESULT WindowProc(UINT message. BOOL OnBluetoothEvent(UINT message. respectively. 23. LPARAM lParam).h © 2001 Dreamtech Software India Inc.h" 6. void InitSecurityClient(). 18. 31. public: 21.cpp. #define ON_BLUETOOTH_EVENT(uiBtEventID. #define SEND_BT_EVENT(uiBtEventID. // DDX/DDV support 38.// standard constructor 22. The server module is implemented with the class CRadioChatServerDlg in the file named RadioChatServerDlg.pMsg) \ 16.(LPARAM) &pMsg) 17.h and RadioChatClientDlg. \ 14. #include "Remotedevice.0.h" 7.h : header file 2. ~CRadioChatClientDlg(). public: 35. SendMessage((HWND)this>m_hWnd. //}}AFX_DATA 33. //{{AFX_DATA(CRadioFileClientDlg) 28.h" 4. #include <afxtempl.1. 30. All Rights Reserved 1. CEdit m_InputChat. #include "service. 15. virtual void DoDataExchange(CDataExchange* pDX). { WM_BLUETOOTH_EVENT. #define WM_BLUETOOTH_EVENT (WM_USER + 100) 12.WM_BLUETOOTH_EVENT. private: 25.0.h> 10. { 20. CListBox m_ChatArea.(WPARAM)uiBtEventID. uiBtEventID.h> 8. enum { IDD = IDD_RADIOCHAT_DIALOG }. virtual BOOL DestroyWindow(). //{{AFX_VIRTUAL(CRadioFileClientDlg) 34. 39. 27. WPARAM wParam. 26. 36. void HandleReturn(). memberFxn) \ 13. class CRadioChatClientDlg : public CDialog 19.272 Chapter 9: Bluetooth Programming ♦ Server module: The server module registers a service with DBM.h> 9. 32. #include "ConnectionInfo. #include <exp\BT_COMServer. CTreeCtrl m_tree. #include "Events. The chat service is made available to all nearby clients. #include <exp\sd. Client Module Listings 9-21 and 9-22 give the source code for RadioChatClientDlg. public: 41. 11. //}}AFX_VIRTUAL 40.h" 5. CConnectionInfo m_ConnectionInfo. 29. CRadioChatClientDlg(CWnd* pParent = NULL).cpp. 3. Listing 9-21: RadiochatClientDlg. LPARAM lParam). // RadioChatClientDlg. WPARAM wParam. 24. protected: 37. int m_ServiceCounter. afx_msg void OnSelDevice(). 54. void ShowAllDevicesFound(). afx_msg void OnSdStartCnf(void **ppMsg). 91. void AddService(CString sService).CService&> m_ServicesFound. virtual BOOL OnInitDialog(). 47. 52. void AddDevice(CDevice device). 67. 65. 71. afx_msg void OnCloseapplication(). afx_msg void OnSdServiceSearchCnfNeg(void **ppMsg). 81. 69. 58. afx_msg void OnSdServiceAttributeCnf(void **ppMsg). 92. afx_msg void OnPaint(). 75. CArray <CService. afx_msg void OnComVersionCnf(void **ppMsg). void ReceiveServiceRecordHandle(SD_TServiceAttributeCnf *tServiceAttributeCnf). afx_msg void OnGetservices(). afx_msg void OnHCIUsb(). 88. afx_msg void OnScmRegisterCnf(void **ppMsg). afx_msg void OnSerialport(). Events *m_pServerEvents. 96. void AskForServiceRecordHandle(). 46. afx_msg void OnConnectAcceptInd(void **ppMsg). CArray <CDevice. afx_msg void OnHCISerial(). HICON m_hIcon. 90. 49. 50. 44. 72. 89. 84. afx_msg void OnComStartCnfNeg(void **ppMsg). 80. 76. 62. 68. void AskForServiceName(). afx_msg void OnSelservices(). 82. afx_msg void OnScmPincodeInd(void **ppMsg). 48. 87. LPARAM lParam). 64. 78. afx_msg void OnConnect(). 93. afx_msg void OnSdServiceSearchCnf(void **ppMsg). afx_msg void OnScmDisconnectEvt(void **ppMsg). 55. 60. protected: 53. 73. 86. . afx_msg void OnScmDeRegisterCnfNeg(void **ppMsg). afx_msg void OnSdServiceAttributeCnfNeg(void **ppMsg). 59. CString sName). afx_msg void OnComStartCnf(void **ppMsg). afx_msg void OnScmRegisterCnfNeg(void **ppMsg). afx_msg void OnScmDisconnectCnf(void **ppMsg). 51. 63. 79. afx_msg void OnScmConnectCnf(void **ppMsg). 74. afx_msg void OnSysCommand(UINT nID. afx_msg void OnScmDisconnectCnfNeg(void **ppMsg). 56. int index. afx_msg void OnDestroy(). 66. 85. afx_msg void OnScmConnectEvt(void **ppMsg). void AddDevice(CString sAddress. void ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf). void ShowAllServicesFound().CDevice&> m_DevicesFound. void AddService(CService service). afx_msg void OnScmDeRegisterCnf(void **ppMsg). afx_msg void OnSdConnectCnfNeg(void **ppMsg).Chapter 9: Bluetooth Programming 273 42. 45. afx_msg void OnSdConnectCnf(void **ppMsg). 83. 57. afx_msg HCURSOR OnQueryDragIcon(). 70. //{{AFX_MSG(CRadioChatClientDlg) 61. 43. 77. afx_msg void OnScmConnectCnfNeg(void **ppMsg). 94. 95. int m_RemoteNameCounter. afx_msg void OnInquiry(). 112. afx_msg void OnHciLocalAddressCnfNeg(void **ppMsg). 126. 137. 133. 146. 98. 125. Code Description This header file contains all variables. 121. afx_msg void OnSilReqDeviceCnf(void **ppMsg). afx_msg void OnComConnectCnfNeg(void **ppMsg). 101. afx_msg void OnHciWriteNameCnf(void **ppMsg). 135. 111. afx_msg void OnHciWriteScanEnableCnf(void **ppMsg). 124. afx_msg void OnDbmUnRegisterServiceCnfNeg(void **ppMsg). . 103. afx_msg void OnHciWriteConnectTimeoutCnf(void **ppMsg). 106. 140. 105. 129. afx_msg void OnSilSetDeviceCnf(void **ppMsg). 102. afx_msg void OnHciInquiryEvt(void **ppMsg). afx_msg void OnHciStartCnf(void **ppMsg). afx_msg void OnSilReqDeviceCnfNeg(void **ppMsg). 127. afx_msg void OnHciWriteEncryptionModeCnfNeg(void **ppMsg). 130. afx_msg void OnHciInquiryCnf(void **ppMsg). 120. afx_msg void OnDbmAddDescriptorCnf(void **ppMsg). 109. member functions. 115. 131. afx_msg void OnHciWritePageTimeoutCnf(void **ppMsg). afx_msg void OnComDisconnectEvt(void **ppMsg). 142. 122. afx_msg void OnHciWriteAuthenticationModeCnf(void **ppMsg). 116. 143. 141. 108. afx_msg void OnSdDisconnectCnf(void **ppMsg). 132. and classes required to implement the class CRadioChatClientDlgcpp. 138. afx_msg void OnDbmAddDescriptorCnfNeg(void **ppMsg). afx_msg void OnHciRemoteNameCnfNeg(void **ppMsg). afx_msg void OnHciWriteConnectTimeoutCnfNeg(void **ppMsg). 110. 107. afx_msg void OnHciWriteEncryptionModeCnf(void **ppMsg). 139. afx_msg void OnComDataCnf(void **ppMsg). //}}AFX_MSG DECLARE_MESSAGE_MAP() }. afx_msg void OnComDisconnectCnfNeg(void **ppMsg). 119. afx_msg void OnHciWriteCodCnf(void **ppMsg). 99. afx_msg void OnComDataCnfNeg(void **ppMsg). 118. afx_msg void OnComDisconnectCnf(void **ppMsg). afx_msg void OnHciWritePageTimeoutCnfNeg(void **ppMsg). 145. 100. afx_msg void OnDbmRegisterServiceCnfNeg(void **ppMsg). afx_msg void OnBrowse(). afx_msg void OnHciConfigurePortConfirm(void **ppMsg). 113. afx_msg void OnHciRemoteNameCnf(void **ppMsg). afx_msg void OnHciWriteAuthenticationModeCnfNeg(void **ppMsg). 144.274 Chapter 9: Bluetooth Programming 97. afx_msg void OnHciConfigurePortConfirmNegative(void **ppMsg). afx_msg void OnHciWriteNameCnfNeg(void **ppMsg). afx_msg void OnSilSetDeviceCnfNeg(void **ppMsg). 123. 104. afx_msg void OnComConnectCnf(void **ppMsg). 114. afx_msg void OnComDataInd(void **ppMsg). afx_msg void OnHciWriteScanEnableCnfNeg(void **ppMsg). afx_msg void OnDbmUnRegisterServiceCnf(void **ppMsg). 134. afx_msg void OnHciWriteCodCnfNeg(void **ppMsg). 128. afx_msg void OnHciLocalAddressCnf(void **ppMsg). 117. 136. afx_msg void OnDbmRegisterServiceCnf(void **ppMsg). 37.'0'. 29. virtual void DoDataExchange(CDataExchange* pDX).}.'0'. #include <exp/vos2com. 22.cpp © 2001 Dreamtech Software India Inc.hdevice1. //}}AFX_VIRTUAL 49. static char THIS_FILE[] = __FILE__. enum { IDD = IDD_ABOUTBOX }.'0'.0x04. #undef THIS_FILE 21. #include <exp/com. All Rights Reserved 1. 44. // RadioChatClientDlg. #define InterSelSerial ((uint8) 0) 34. #define SRP_SERIAL_GENERIC_SERIALPORT_UUID ((uint16) 0x1101) 36. #include <process.h> 7.h" 5. class CAboutDlg : public CDialog 39.h> 14. void (AFX_MSG_CALL CWnd::*pfn_btf)(void **).h> 17. 42. #define PORTSETTINGS (uint8 *)("COM1:Baud=57600 parity=N data=8 stop=1") 33. static const SCM_TPincode _tPincode = {'1'.h> 11. #ifdef _DEBUG 19. { 27. 30. #include "Events. }.h> 16. union MessageMapFunctions 26. #define PINCODE_LENGTH ((SCM_TPincodeLength) 4) 31. //}}AFX_DATA 45.'0'.'4'. 48.'0'. 24. 38. #include <exp/hci. 32. AFX_PMSG pfn. #endif 23. #define InterSelUSB ((uint8) 1) 35.'0'. HTREEITEM hPA.h> 13. 25.'0'. #include "windows. protected: 50.h> 9. #include <exp/dbm.'2'.'0'. #include <exp/hci_drv. 28. #define new DEBUG_NEW 20. #include "stdafx.cpp : implementation file 2.h> 10. #include "RadioChat.0x04}.'0'. #include "RadioChatClientDlg. //{{AFX_VIRTUAL(CAboutDlg) 46.h> 15.h> 12.h" 8. //{{AFX_DATA(CAboutDlg) 43. static const HCI_TCod _tCod={0x20. #include <exp/scm.h" 4.h" 3.'0'.h" 6. #include <exp/msg.'3'. //{{AFX_MSG(CAboutDlg) .Chapter 9: Bluetooth Programming 275 Listing 9-22: RadioChatClientDlg. #include <exp/sd.'0'. protected: 47. { 40.'0'. CAboutDlg(). public: 41. #include <exp/sil. 18. 91. { 80. BEGIN_MESSAGE_MAP(CRadioChatClientDlg. ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF_NEG. ON_BLUETOOTH_EVENT(COM_START_CNF_NEG. //{{AFX_DATA_INIT(CAboutDlg) 57. DDX_Control(pDX. CDialog) 66. //{{AFX_DATA_MAP(CRadioChatClientDlg) 88. CDialog::DoDataExchange(pDX). } 78.RemoveAll(). IDC_LIST1. } 59. //{{AFX_DATA_INIT(CRadioChatClientDlg) 74. m_tree). { 73. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME). ON_BLUETOOTH_EVENT(SCM_CONNECT_ACCEPT_IND. DDX_Control(pDX. } 84.OnScmConnectCnf) 106. m_pServerEvents = new Events(). //}}AFX_MSG_MAP 68.RemoveAll(). //{{AFX_DATA_MAP(CAboutDlg) 63. //{{AFX_MSG_MAP(CAboutDlg) 67. 54. 77. ON_WM_PAINT() 97. OnConnectAcceptInd) 104. //{{AFX_MSG_MAP(CRadioChatClientDlg) 95.OnScmPincodeInd) 105.276 Chapter 9: Bluetooth Programming 51. ON_BLUETOOTH_EVENT(SCM_PINCODE_IND. { 56. 81. { 61. BEGIN_MESSAGE_MAP(CAboutDlg. } 93. void CRadioChatClientDlg::DoDataExchange(CDataExchange* pDX) 85. END_MESSAGE_MAP() 69. CDialog) 94. { 86. 89.OnComStartCnf) 99. CRadioChatClientDlg::CRadioChatClientDlg(CWnd* pParent /*=NULL*/) 71. m_InputChat). ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF_NEG. m_DevicesFound. //}}AFX_DATA_INIT 58. 62. //}}AFX_DATA_MAP 92. //}}AFX_DATA_MAP 64. m_ServicesFound. void CAboutDlg::DoDataExchange(CDataExchange* pDX) 60. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF. 70. : CDialog(CRadioChatClientDlg::IDD. CRadioChatClientDlg::~CRadioChatClientDlg() 79. ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF. CDialog::DoDataExchange(pDX). 82. IDC_EDIT1. ON_WM_QUERYDRAGICON() 98. DECLARE_MESSAGE_MAP() 53.OnComStartCnfNeg) 100. m_CharArea). OnScmConnectCnfNeg) . CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) 55. ON_WM_SYSCOMMAND() 96. } 65.OnComVersionCnf) 101. delete m_pServerEvents. 83. OnScmRegisterCnfNeg) 103.OnScmRegisterCnf) 102. 76. DDX_Control(pDX. ON_BLUETOOTH_EVENT(COM_START_CNF. //}}AFX_MSG 52. IDC_TREE1. ON_BLUETOOTH_EVENT(COM_VERSION_CNF. }. 90. //}}AFX_DATA_INIT 75. 87. pParent) 72. 143. 113. OnSdServiceSearchCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF. OnHciRemoteNameCnf) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF_NEG.OnHciInquiryEvt) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF.OnSdConnectCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF_NEG.OnHciWriteCodCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF_NEG. OnHciWriteCodCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF. OnHciWriteEncryptionModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF_NEG. 110. 109. 126.OnHciInquiryCnf) ON_BLUETOOTH_EVENT(HCI_INQUIRY_EVT. OnScmDeRegisterCnfNeg) ON_BLUETOOTH_EVENT(SD_START_CNF. 127. 136. OnHciWriteScanEnableCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF_NEG. 134. 141. 139. OnDbmAddDescriptorCnf) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF_NEG.OnScmDisconnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF. OnHciWriteNameCnfNeg) . OnHciWriteAuthenticationModeCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_ CNF_NEG. 111. 133. 131. 123. 114. 124. 117. 146. 119.OnHciStartCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF. OnHciWriteEncryptionModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF. OnHciLocalAddressCnf) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF_NEG. OnDbmUnRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF.Chapter 9: Bluetooth Programming 277 107. 147.OnSdConnectCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF. OnDbmRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF_NEG. 121. 125. 135. 128. 112.OnScmConnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_EVT. OnSdServiceAttributeCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF_NEG. 108. OnSdServiceSearchCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF_NEG.OnScmDeRegisterCnf) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF_NEG. 137. 132. OnHciConfigurePortConfirmNegative) ON_BLUETOOTH_EVENT(HCI_INQUIRY_CNF. OnHciLocalAddressCnfNeg) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF. OnDbmRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF. 144. 142. OnHciWriteScanEnableCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF. 115. OnScmDisconnectCnfNeg) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF. 138.OnHciWriteNameCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF_NEG. 118. 140. OnDbmAddDescriptorCnfNeg) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF. OnHciWriteAuthenticationModeCnfNeg) ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF. OnHciConfigurePortConfirm) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF_NEG. 145. 130. 129. 122. 116. ON_BLUETOOTH_EVENT(SCM_CONNECT_EVT. OnDbmUnRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF_NEG. 120. OnHciRemoteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_START_CNF. OnSdServiceAttributeCnfNeg) ON_BLUETOOTH_EVENT(SD_DISCONNECT_CNF.OnSdStartCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF.OnSdDisconnectCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF.OnScmDisconnectCnf) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF_NEG. ON_BLUETOOTH_EVENT(COM_DISCONNECT_CNF_NEG.hInsertAfter = NULL. 175. ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF.OnComDataCnfNeg ) 161. } 182. return TRUE. { 178. OnSilSetDeviceCnfNeg) 154. WPARAM wParam. ON_BLUETOOTH_EVENT(COM_DISCONNECT_EVT. tvInsert. ASSERT(IDM_ABOUTBOX < 0xF000). pSysMenu->AppendMenu(MF_SEPARATOR). tvInsert.IDM_ABOUTBOX. { 174. 180. ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF_NEG. SetIcon(m_hIcon. 184. pSysMenu->AppendMenu(MF_STRING. hPA = m_tree. 179. strAboutMenu.278 Chapter 9: Bluetooth Programming 148. LPARAM lParam) 195. m_pServerEvents->m_pParentDialog = this. 176. BOOL CRadioChatClientDlg::OnInitDialog() 167.OnComDataInd ) 159.OnComDisconnectCnf ) 163. 193.OnComConnectCnf ) 157. ON_BLUETOOTH_EVENT(COM_DATA_CNF_NEG. 188. OnSilReqDeviceCnfNeg) 156. if (message == WM_BLUETOOTH_EVENT) 198. 197. ON_BLUETOOTH_EVENT(COM_DISCONNECT_CNF. OnComConnectCnfNeg ) 158. OnComDisconnectCnfNeg ) 164.pszText = _T("RemoteRadios"). if (!strAboutMenu. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX). LRESULT CRadioChatClientDlg::WindowProc(UINT message. if (pSysMenu != NULL) 173. ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF. 185. FALSE). END_MESSAGE_MAP() 166. { 196.item.IsEmpty()) 177. CString strAboutMenu. OnHciWriteConnectTimeoutCnfNeg) 150.LoadString(IDS_ABOUTBOX).item. } 181. OnHciWritePageTimeoutCnf) 151. { . TRUE).OnComDisconnectEvt ) 162.hParent =NULL. } 194. ON_BLUETOOTH_EVENT(COM_CONNECT_CNF_NEG. ON_BLUETOOTH_EVENT(COM_CONNECT_CNF. 192. 186. 169. OnHciWriteConnectTimeoutCnf) 149. 172. 191. TVINSERTSTRUCT tvInsert. ON_BLUETOOTH_EVENT(COM_DATA_CNF. tvInsert. 171. ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF. ON_BLUETOOTH_EVENT(COM_DATA_IND. MSG_TMsg **ptMsg. ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF. CMenu* pSysMenu = GetSystemMenu(FALSE). 170. //}}AFX_MSG_MAP 165. 190. OnSilSetDeviceCnf) 153. SetIcon(m_hIcon. 187. tvInsert. OnHciWritePageTimeoutCnfNeg) 152.InsertItem(&tvInsert). OnSilReqDeviceCnf) 155. { 168.OnComDataCnf ) 160. CDialog::OnInitDialog().mask = TVIF_TEXT. ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF_NEG. 183. strAboutMenu). ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF_NEG. ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF_NEG. InitSecurityClient(). 189. pMessageMap = pMessageMap->pBaseMap) 216.pfn = lpEntry->pfn. for (pMessageMap = GetMessageMap(). lParam). } 250. wParam. #endif 223. 230. #ifdef _AFXDLL 211. 249. 210. lParam). void CRadioChatClientDlg::OnPaint() 252. LPARAM lParam) 240. wParam. return FALSE.pfn_btf)((void **)lParam). pMessageMap = (*pMessageMap->pfnGetBaseMap)()) 213. 205. pMessageMap != NULL. #else 214. { 253. 229. ptMsg = (MSG_TMsg**)lParam. ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()). 245. return CDialog::WindowProc(message. 200. { 228. 244. #endif 217. (((CWnd *)this)->*mmf. if ((nID & 0xFFF0) == IDM_ABOUTBOX) 242. } 251. union MessageMapFunctions mmf. 224. 215. mmf. const AFX_MSGMAP_ENTRY* lpEntry. 203. if((lpEntry->nMessage==message)&&(lpEntry->nCode== wParam)) 227. { 208. 236.DoModal(). lpEntry++. { 226. CDialog::OnSysCommand(nID. { 248. return FALSE. 209. 234. dlgAbout. while (lpEntry->nSig != AfxSig_end) 225. 232. #else 221. } 237. if (IsIconic()) . 238. 220. } 246. #ifdef _AFXDLL 219. 212. pMessageMap != NULL. VOS_Free((void **)lParam). OnBluetoothEvent( message. ASSERT(pMessageMap != pMessageMap->pBaseMap). return TRUE. { 243. LPARAM lParam) 207. } 239. 201. void CRadioChatClientDlg::OnSysCommand(UINT nID. WPARAM wParam. } 233. lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]). } 204.Chapter 9: Bluetooth Programming 279 199. const AFX_MSGMAP* pMessageMap. } 206. } 235. else 247. 222. for (pMessageMap = GetMessageMap(). { 218. 231. lParam). BOOL CRadioChatClientDlg::OnBluetoothEvent(UINT message. if (*ptMsg != NULL) 202. CAboutDlg dlgAbout. { 241. 269. if(ptSetDevice->tHdr. } else { CDialog::OnPaint(). 278. 283. GetClientRect(&rect).Width() . SendMessage(WM_ICONERASEBKGND. 300. 282. 265. 272. } void CRadioChatClientDlg::OnSilSetDeviceCnf(void **ppMsg) { ppMsg = ppMsg. 287. 289. 290. 270. 275. 303. 263. int cxIcon = GetSystemMetrics(SM_CXICON). } void CRadioChatClientDlg::InitSecurityClient() { SIL_SetDevice(0. ptSetDevice = (SIL_TSetDevice*)*ppMsg. 284. 267. 286.Height() . 266. 295. 281. dc. 306.SIL_SERIAL).cyIcon + 1) / 2. m_hIcon). 293. int y = (rect. 274. 268. 255. } void CRadioChatClientDlg::OnSilReqDeviceCnf(void **ppMsg) { SIL_TReqDevice* ptReq. if(ptReq->uiDevice == SIL_SERIAL) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is SERIAL")). 256. } } HCURSOR CRadioChatClientDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon. 296.cxIcon + 1) / 2. 294. int x = (rect. 297.PORTSETTINGS). 285. 305. MessageBox(_T("Device Request FAILED!")). 279. 259. 291. CRect rect. 292. 280. 258. 271.iResult == SIL_ERR_DEVICE) SIL_ReqDevice(0). ptReq = (SIL_TReqDevice*) *ppMsg. 298. } void CRadioChatClientDlg::OnHciConfigurePortConfirm(void **ppMsg) { HCI_TConfigurePortCnf *tConfigurePort=(HCI_TConfigurePortCnf *)*ppMsg. 260. int cyIcon = GetSystemMetrics(SM_CYICON). 262. } void CRadioChatClientDlg::OnSilSetDeviceCnfNeg(void **ppMsg) { SIL_TSetDevice* ptSetDevice. 288. 261.GetSafeHdc(). 299.280 Chapter 9: Bluetooth Programming 254. 304. 301. 257. if(ptReq->uiDevice == SIL_USB) MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is USB")). } void CRadioChatClientDlg::OnSilReqDeviceCnfNeg(void **ppMsg) { ppMsg = ppMsg. 276. . HCI_ReqConfigurePort(0. 0). 302. y. (WPARAM) dc. 264. { CPaintDC dc(this). 273.DrawIcon(x. 277. HCI_TConfigurePortCnfNeg *tConfigurePort = (HCI_TConfigurePortCnfNeg *)*ppMsg. COM_TStartCnf *tStartCnf = (COM_TStartCnf *)*ppMsg. 337. tLocalAddress->tAddress. 315. 325. } 342. MessageBox(_T("Could not open port")). tStartCnfNeg = tStartCnfNeg. ppMsg = ppMsg. } 328. wsprintf(&lpStr[0]. tStartCnf = tStartCnf. { 312. 331. 309. MessageBox(_T("Could not start RFCOMM")).HCI_ENCRYPTION_OFF). 321. 308. void CRadioChatClientDlg::OnComStartCnf(void **ppMsg) 317. 346. 345. SD_ReqStart(0). SD_ReqStart(0). 351. 334. 332. 326.HCI_AUTH_DISABLE). } 353. } 348. ppMsg = ppMsg. void CRadioChatClientDlg::OnHciLocalAddressCnf(void **ppMsg) 329.ucByte5). char lpStr[59]. tLocalAddress->tAddress. { 360. 357. void CRadioChatClientDlg::OnHciLocalAddressCnfNeg(void **ppMsg) 343. tConfigurePort = tConfigurePort. tLocalAddress->tAddress. void CRadioChatClientDlg::OnSdStartCnf(void **ppMsg) 349. tConfigurePort = tConfigurePort. } 310. 340. void CRadioChatClientDlg::OnHciWriteEncryptionModeCnf(void **ppMsg) 354. HCI_ReqWriteAuthenticationMode(0. void CRadioChatClientDlg::OnComStartCnfNeg(void **ppMsg) 323. HCI_ReqWriteEncryptionMode(0. void CRadioChatClientDlg::OnHciConfigurePortConfirmNegative(void **ppMsg) 311.Chapter 9: Bluetooth Programming 281 307. 335.ucByte4. 319. HCI_TLocalAddressCnf *tLocalAddress = (HCI_TLocalAddressCnf *)*ppMsg. ppMsg = ppMsg.ucByte0. SetWindowText(_T(lpStr)). 338. 339. 347. { 318. 314. HCI_ReqLocalAddress(0). void CRadioChatClientDlg::OnHciWriteEncryptionModeCnfNeg(void **ppMsg) 359. .ucByte1.ucByte2. 327. 320. { 344. { 350. SetWindowText(_T("DEVICE NOT FOUND")). ppMsg = ppMsg. 333. "BD_ADDRESS: 0x%02X%02X%02X%02X%02X%02X\0". tLocalAddress->tAddress. } 316. 341. { 355. 313. } 358. tLocalAddress->tAddress. COM_ReqStart(0). tLocalAddress->tAddress. 336. 352. { 330. 356. COM_TStartCnfNeg *tStartCnfNeg = (COM_TStartCnfNeg *)*ppMsg.ucByte3. { 324. } 322. 397. 374.282 Chapter 9: Bluetooth Programming 361. 381. . 370. 372. 395. 411. 400. HCI_ReqWriteCod(0. 404. } void CRadioChatClientDlg::OnHciWriteAuthenticationModeCnf(void **ppMsg) { ppMsg = ppMsg. 391. HCI_ReqWriteName (0. 390. 412.8000). HCI_ReqWriteConnectTimeout(0. 388. 383. 394. 408. } void CRadioChatClientDlg::OnHciWriteNameCnf(void **ppMsg) { ppMsg = ppMsg. 386. 409._tCod). } void CRadioChatClientDlg::OnHciWriteAuthenticationModeCnfNeg(void **ppMsg) { ppMsg = ppMsg. 398. } void CRadioChatClientDlg::OnHciWritePageTimeoutCnf(void **ppMsg) { ppMsg = ppMsg. 410. 387. 385. 378.(HCI_TName*) "BT Chat").HCI_PAGE_SCAN_ENABLED | HCI_INQUIRY_SCAN_ENABLED). 393. 384. 396. HCI_ReqWriteScanEnable(0. 365. 415. 382. 366. 392. 375. 362. HCI_ReqWritePageTimeout(0. 380. 371. } void CRadioChatClientDlg::OnHciWriteCodCnfNeg(void **ppMsg) { ppMsg = ppMsg. 376. 407. 373. 414. } void CRadioChatClientDlg::OnHciWriteCodCnf(void **ppMsg) { ppMsg = ppMsg. } void CRadioChatClientDlg::OnHciWriteConnectTimeoutCnfNeg(void **ppMsg) { ppMsg = ppMsg. 379. 401. 368.0x1FA0). 377. 399. } void CRadioChatClientDlg::OnHciWritePageTimeoutCnfNeg(void **ppMsg) { ppMsg = ppMsg. 363. 364. 406. 402. 389. 405. 403. 367. } void CRadioChatClientDlg::OnHciWriteConnectTimeoutCnf(void **ppMsg) { ppMsg = ppMsg. 413. 369. HCI_ReqRemoteName(10. 444. count = m_DevicesFound. if (count > 0) { device = (CRemoteDevice) m_DevicesFound. 431. 455. 450. device. 427. 468.tPageScanPeriodMode. 418.tPageScanMode. ptInquiryCnf =(HCI_TInquiryCnf *) *ppMsg.SCM_SECURITY_HANDLER).GetSize(). MessageBox(_T("Could not register to SCM")). } else { AfxMessageBox("No device found"). 461. device. 469.SCM_MONITOR_GROUP). 467. 435. 449. } void CRadioChatClientDlg::OnHciInquiryCnf(void **ppMsg) { HCI_TInquiryCnf *ptInquiryCnf. CRemoteDevice device. 466. device. 456. SCM_ReqRegister(0. 447. } void CRadioChatClientDlg::OnScmRegisterCnf(void **ppMsg) { SCM_TRegisterCnf *tRegisterCnf = (SCM_TRegisterCnf *)*ppMsg. 430. } else { OnInquiry(). 437. tRegisterCnfNeg = tRegisterCnfNeg. 458. } void CRadioChatClientDlg::OnHciWriteNameCnfNeg(void **ppMsg) { ppMsg = ppMsg. 432. 462. 463. 423. 425. 424. } void CRadioChatClientDlg::OnHciWriteScanEnableCnf(void **ppMsg) { ppMsg = ppMsg. 433. 422. 454. 470. 440. if (tRegisterCnf->tHdr. device. 439. 438. 448.tClockOffset ). 446. 471. m_RemoteNameCounter = 0. 445. 419. } } void CRadioChatClientDlg::OnHciRemoteNameCnf(void **ppMsg) .GetAt(m_RemoteNameCounter). 426. 442.Chapter 9: Bluetooth Programming 283 416. 417. 464. 460. 429.uiSeqNr == 0) { SCM_ReqRegister(1. 421. int count. 441. 443. } } void CRadioChatClientDlg::OnScmRegisterCnfNeg(void **ppMsg) { SCM_TRegisterCnfNeg *tRegisterCnfNeg = (SCM_TRegisterCnfNeg *)*ppMsg. tRegisterCnf = tRegisterCnf. 465. 451. 457. 434. 420. 452. 453.tAddress. } void CRadioChatClientDlg::OnHciWriteScanEnableCnfNeg(void **ppMsg) { ppMsg = ppMsg. 428. 436. 459. int count. 496. 474. 479. device.tAddress. } else { ShowAllDevicesFound(). device. 498. device. device. 522. 490. int count.GetSize(). 505. 493. 481. m_RemoteNameCounter++. count = m_DevicesFound. CRemoteDevice device.GetSize(). count = m_DevicesFound. 514. if (count > m_RemoteNameCounter) { device = (CRemoteDevice) m_DevicesFound. 486."%s". 500. 507. m_ConnectionInfo. 491. 502. device. 497. 499. m_ConnectionInfo. 494.tAddress = tConnectCnf->tAddress. 516. 519.tClockOffset ).284 Chapter 9: Bluetooth Programming 472. 489. } } void CRadioChatClientDlg::OnScmConnectCnf(void **ppMsg) { SCM_TConnectCnf *tConnectCnf = (SCM_TConnectCnf *)*ppMsg. 510. { HCI_TRemoteNameCnf *ptRemoteNameCnf. 513. 487. 509.tAddress. 477. 478. 525. device. 512.tAclHandle = tConnectCnf->tHandle. m_DevicesFound[m_RemoteNameCounter]. 515. 518.SetName((CString)sName). } } void CRadioChatClientDlg::OnHciRemoteNameCnfNeg(void **ppMsg) { HCI_TRemoteNameCnfNeg *ptRemoteNameCnfNeg. 527.SetName((CString)_T("UNKNOWN")). 517. 484. m_DevicesFound[m_RemoteNameCounter]. 483.tPageScanMode. char sName[248]. sprintf(sName. 506. tConnectCnf = tConnectCnf. OnGetservices() .&ptRemoteNameCnf->tName).tPageScanPeriodMode. 476. 511. 495. 503. 504. 485. device.tPageScanPeriodMode. 523. ptRemoteNameCnfNeg =(HCI_TRemoteNameCnfNeg *) *ppMsg. HCI_ReqRemoteName(10. 508. CDevice device. } else { ShowAllDevicesFound(). 473. AfxMessageBox("connected"). 492. 475. 501. 526. ptRemoteNameCnf =(HCI_TRemoteNameCnf *) *ppMsg.tPageScanMode. device.tClockOffset ). } . HCI_ReqRemoteName(10. 520. 524. if (count > m_RemoteNameCounter) { device = (CRemoteDevice) m_DevicesFound. 521. m_RemoteNameCounter++. 480.GetAt(m_RemoteNameCounter).GetAt(m_RemoteNameCounter). 488. 482. m_ConnectionInfo.eUuidType = SD_DET_UUID16. ptSearchPatternList[0]. service. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). 537. ucNrOfUuids. uint8 ucNrOfUuids. 553. CString str. 568. (uiCurrentServiceRecordCount*sizeof(uint32))). uint32 *pulSRHandles. 544. 564. 571. 529. 532. 559. 555. 552. str. uint16 *puiAttributeIDList. 551. 545. . 572. 543. AfxMessageBox("No Connection made"). 547. 567.uiUuid16 = SRP_SERIAL_GENERIC_SERIALPORT_UUID . 565.uiSdcHandle = tConnectCnf->uiSdcHandle. MessageBox(str). puiAttributeIDList[0] = BT_SERVICE_NAME(0). pulSRHandles = (uint32*)OS_Alloc(((uint16) (uiCurrentServiceRecordCount*sizeof(uint32)))). uint16 uiCurrentServiceRecordCount. 570. void CRadioChatClientDlg::OnScmConnectCnfNeg(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. &tServiceSearchCnf->ulServiceRecordHandleList. 541. } void CRadioChatClientDlg::OnSdConnectCnf(void **ppMsg) { SD_TConnectCnf *tConnectCnf = (SD_TConnectCnf *)*ppMsg. } void CRadioChatClientDlg::OnSdServiceSearchCnf(void **ppMsg) { SD_TServiceSearchCnf *tServiceSearchCnf = (SD_TServiceSearchCnf *)*ppMsg. 569. ptSearchPatternList = (SD_TUuid*)VOS_Alloc((uint16)(ucNrOfUuids * sizeof(SD_TUuid))). 557. SD_TUuid *ptSearchPatternList. 539. uiMaxRecords. 558. } void CRadioChatClientDlg::OnSdConnectCnfNeg(void **ppMsg) { SD_TConnectCnfNeg *tConnectCnfNeg = (SD_TConnectCnfNeg *)*ppMsg. uiCurrentServiceRecordCount = tServiceSearchCnf>uiCurrentServiceRecordCount. 534. 546. ptSearchPatternList). uiMaxRecords = 6. 536. 533.iResult).tConnectCnfNeg>tHdr. tConnectCnfNeg = tConnectCnfNeg. 563. 530.TUuid. CService service. 550.ulServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList. ucNrOfUuids = 1. 562. uint8 ucNrOfAttr.Chapter 9: Bluetooth Programming 285 528.m_SDCHandle = m_ConnectionInfo. m_ConnectionInfo. 556.uiSdcHandle. ucNrOfAttr = 1. 560. 573. (void*)memcpy(pulSRHandles. 554.Format("Could not connect to SD . 540. 548.uiSdcHandle. 549. 561. SD_ReqServiceSearch (0. 531. 535. 566. ptSearchPatternList[0]. 538. m_ConnectionInfo. Error %d". 542. uint16 uiMaxRecords. m_ConnectionInfo. break. { 590. break. void CRadioChatClientDlg::OnDbmRegisterServiceCnf(void **ppMsg) 622. 611. service. 596. 583. } 615. tConnectCnfNeg = tConnectCnfNeg. tConnectCnfNeg = tConnectCnfNeg.uiSeqNr) 593. SD_TServiceSearchCnfNeg *tConnectCnfNeg = (SD_TServiceSearchCnfNeg *)*ppMsg.tConnectCnfNeg->tHdr. void CRadioChatClientDlg::OnSdServiceAttributeCnfNeg(void **ppMsg) 608. 614. 592. MessageBox(str). 591. 579. error %d". 578.286 Chapter 9: Bluetooth Programming 574. 575. SD_TServiceAttributeCnfNeg *tConnectCnfNeg = (SD_TServiceAttributeCnfNeg *)*ppMsg. 584. 586. str.Format("Service Search Confirm Negative.uiSdcHandle. case 2: 599. CString str.uiSdcHandle). case 1: 595. { 594. 585. { . ReceiveServiceName(tServiceAttributeCnf).m_ServiceRecordHandle = tServiceSearchCnf>ulServiceRecordHandleList.Format("Service Attribute Confirm negative. Error %d". void CRadioChatClientDlg::OnSdDisconnectCnf(void **ppMsg) 616. 587. { 617. 576. SD_ReqDisconnect(0. 601. } 588. ReceiveServiceRecordHandle(tServiceAttributeCnf). 618.m_ConnectionInfo.iResult). 612. } 607. 605. SD_ReqServiceAttribute(1. AskForServiceRecordHandle(). void CRadioChatClientDlg::OnSdServiceAttributeCnf(void **ppMsg) 589. { 582. pulSRHandles[0]. 603.service). } 606. } 621. puiAttributeIDList). } 580. { 609. MessageBox(str). 597. default: 604. 600. ppMsg = ppMsg. 598. void CRadioChatClientDlg::OnSdServiceSearchCnfNeg(void **ppMsg) 581. switch (tServiceAttributeCnf->tHdr. SD_TServiceAttributeCnf *tServiceAttributeCnf = (SD_TServiceAttributeCnf *)*ppMsg. break. m_ServicesFound. ucNrOfAttr. VOS_Free((void**)&pulSRHandles). 613. Beep (1000. 577. 610. CString str.uiSdcHandle)"). 620. OnSelservices(). AfxMessageBox("SD_ReqDisconnect(0.iResult).200).SetAtGrow(m_ServiceCounter. 619. 602. VOS_Free((void**)&puiAttributeIDList).m_ConnectionInfo.tConnectCnfNeg->tHdr. str. CService service. uiSdcHandle). 660. 650. MessageBox(_T("Not possible to Register to DBM")). 672. 654. SCM_SLAVE). 645. tDescriptorValue. 667. 663.pucValue = (uint8 *) VOS_Alloc( (sizeof(uint16)) ).ulDbmHandle.1].200). 630. tDescriptorValue. uiDescriptorUuidValue = BT_PSM_COM. DBM_TRegisterServiceCnf *tRegisterCnf = (DBM_TRegisterServiceCnf *)*ppMsg. *tDescriptorValue. 629. tConnectCnfNeg = tConnectCnfNeg.pucAttributeData [m_ConnectionInfo. 647. 652.pucDescriptorUuidValue = (uint8*) &uiDescriptorUuidValue. DBM_ReqAddDescriptor(0. 633. *tDescriptorValue. 649. 656. m_ConnectionInfo. 632. .uiNrOfParams = 1. 662. 624. 665. SCM_POS_RESULT. tDescriptor. BT_PROTOCOL_DESCRIPTOR_LIST. 648. 669. tConnectCnfNeg = tConnectCnfNeg.pucValue = m_ConnectionInfo.pucValue). 653. 639. 668. 673. 657.uiAttributeListByteCount . 636. 670. } void CRadioChatClientDlg::OnConnectAcceptInd(void **ppMsg) { SCM_TConnectAcceptInd *ptConnectAcceptInd. 644.ulDbmHandle = tRegisterCnf->ulDbmHandle. 637. tDescriptorValue. 671. 676. 642. OnConnect().pucValue--. 638. 625. 640. 641. DBM_TDescriptorValue tDescriptorValue. 664. tDescriptorValue. 661. MessageBox(_T("Could not register the service to DBM")). tDescriptorValue. uint16 uiDescriptorUuidValue. 635. } void CRadioChatClientDlg::OnDbmAddDescriptorCnf(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg.m_ConnectionInfo. 658. } void CRadioChatClientDlg::OnDbmRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg. SD_ReqDisconnect(0. &tDescriptor. 627. &tDescriptorValue). } void CRadioChatClientDlg::OnHciInquiryEvt(void **ppMsg) { HCI_TInquiryEvt *ptInquiryEvt. } void CRadioChatClientDlg::OnDbmAddDescriptorCnfNeg(void **ppMsg) { SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 659.uiSizeOfValueInBytes = 2. 675. 674. ptConnectAcceptInd =(SCM_TConnectAcceptInd *) *ppMsg. Beep (1000. 628. 626.pucValue = DBM_DET_UINT8. 631. tDescriptor. 655. VOS_Free((void**) &tDescriptorValue.tType = DBM_DET_UUID16. DBM_TDescriptorUuid tDescriptor. 666. 646. 643. 634. *ppMsg = NULL.pucValue++. ptConnectAcceptInd->tAddress. m_ConnectionInfo.Chapter 9: Bluetooth Programming 287 623. 651. SCM_RspConnectAccept((MSG_TMsg **)ppMsg. SCM_POS_RESULT. 724. 715.tAddress = ptInquiryEvt->tAddress. 692. 700. 710. 698. ptVersionCnf = (COM_TVersionCnf *) *ppMsg. char cpStr[3]. 704. 693.tPageScanRepMode = ptInquiryEvt->tPageScanRepMode. cpStr[iCharCount-10] = cpVerStr[iCharCount].tClockOffset = ptInquiryEvt->tClockOffset. char* cpVerStr = NULL. ptPincodeInd =(SCM_TPincodeInd *) *ppMsg. } void CRadioChatClientDlg::OnScmDisconnectEvt(void **ppMsg) { ppMsg = ppMsg. 705. 726. m_ConnectionInfo. 691. 714. 728. 731. 682. cpVerStr = &ptVersionCnf->cVersion. device. 707. m_ConnectionInfo. 725. 721. device. device. 711.tAclHandle = 0. device. device. 719. ptStartCnf = ptStartCnf. HCI_ReqConfigurePort(0. 708.tPageScanPeriodMode = ptInquiryEvt->tPageScanPeriodMode. 717. Abodlg. 713.tAclHandle = tConnectEvt->tHandle. 723. }while(iCharCount <= 11). 684. 696. } void CRadioChatClientDlg::OnScmConnectEvt(void **ppMsg) { SCM_TConnectEvt *tConnectEvt = (SCM_TConnectEvt *)*ppMsg.tAddress = tConnectEvt->tAddress. m_ConnectionInfo. 680. 716. } void CRadioChatClientDlg::OnScmPincodeInd(void **ppMsg) { SCM_TPincodeInd *ptPincodeInd. 732. 722. ptInquiryEvt =(HCI_TInquiryEvt *) *ppMsg. 729. 685. 694. 678. 709. do { iCharCount++. 706. 695. 690. 683. 702. 730. 686. CRemoteDevice device. 727. 681. 712. 689. ptPincodeInd->tAddress. 703. 720. _tPincode.tPageScanMode = ptInquiryEvt->tPageScanMode. OnCloseapplication(). cpStr[3] = ((char)0). int8 iCharCount = 9. 701. } void CRadioChatClientDlg::OnComVersionCnf(void **ppMsg) { CAboutDlg Abodlg.288 Chapter 9: Bluetooth Programming 677. 687. 697. 679.DoModal(). 699. } void CRadioChatClientDlg::OnHciStartCnf(void **ppMsg) { HCI_TStartCnf *ptStartCnf = (HCI_TStartCnf *)*ppMsg. PINCODE_LENGTH). SCM_RspPincode((MSG_TMsg **)ppMsg. 688. 718. device. tConnectEvt = tConnectEvt.PORTSETTINGS). } . AddDevice(device). COM_TVersionCnf* ptVersionCnf.tCod = ptInquiryEvt->tCod. GetAt(m_ServiceCounter).uiAttributeListByteCount). puiAttributeIDList[0] = BT_SERVICE_NAME(0). 775. 755. puiAttributeIDList). &service. uint8 ucNrOfAttr. &service. 738. . service = m_ServicesFound. void CRadioChatClientDlg::AskForServiceName() 734. (void*)memcpy(m_ConnectionInfo. service. 754. m_ConnectionInfo. service. 759. m_ServicesFound.ulServiceRecordHandle.m_pAttributeData[6]] = NULL. m_ConnectionInfo.pcServiceName. void CRadioChatClientDlg::AskForServiceRecordHandle() 772. 762. { 773.uiSdcHandle. service. service.SetAt(m_ServiceCounter. &tServiceAttributeCnf->ucAttributeData. ucNrOfAttr. VOS_Alloc(service. uint16 *puiAttributeIDList.m_pAttributeData[6] + 1). 777.pcServiceName[service. m_ConnectionInfo. 764.m_pServiceName. 776. ShowAllServicesFound(). 758. m_ConnectionInfo.m_pAttributeData. SD_ReqServiceAttribute(2. CService service. service. service. puiAttributeIDList = (uint16*)VOS_Alloc((uint16) (ucNrOfAttr*sizeof(uint16))).m_AttributeListByteCount).m_pAttributeData[6]). 742. 761.m_pAttributeData[7]. VOS_Free((void**)&puiAttributeIDList). { 745. } 743. 748. 779. (void*)memcpy(m_ConnectionInfo. uint8 ucNrOfAttr. 749. 746. (void*)memcpy(service. 756. VOS_Alloc(service. 760. 757. puiAttributeIDList[1] = BT_PROTOCOL_DESCRIPTOR_LIST. m_ConnectionInfo.uiSdcHandle. 740. puiAttributeIDList[0] = BT_SERVICE_RECORD_HANDLE. 750. puiAttributeIDList = (uint16*)VOS_Alloc((uint16) (ucNrOfAttr*sizeof(uint16))). ucNrOfAttr = 1. 778. VOS_Alloc(service. SD_ReqServiceAttribute(0. (void*)memcpy(service.Chapter 9: Bluetooth Programming 289 733. void CRadioChatClientDlg::ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf) 744. 752.ulServiceRecordHandle. 768.m_AttributeListByteCount). 763. 739.m_pServiceName[service.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. uint16 *puiAttributeIDList. 770.uiAttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 753. ucNrOfAttr. /* +1 for the NULL char */ 765.m_AttributeListByteCount).service). &tServiceAttributeCnf->ucAttributeData. 766. } 771. 736. ucNrOfAttr = 2.m_pAttributeData[7].m_pAttributeData[6]). m_ConnectionInfo. 737. 769. 741.pucAttributeData.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 751. 774. 767.m_pAttributeData[6]] = NULL. puiAttributeIDList). m_ServiceCounter++. { 735. 747. m_ConnectionInfo. } 803. 821. m_ConnectionInfo. void CRadioChatClientDlg::ReceiveServiceRecordHandle(SD_TServiceAttributeCnf *tServiceAttributeCnf) 783.GetAt(m_ServiceCounter-1). 786. void CRadioChatClientDlg::OnScmDeRegisterCnf(void **ppMsg) 804. else 823. } 782. 806. 792.290 Chapter 9: Bluetooth Programming 780.SCM_MONITOR_GROUP). 796. } 822. SCM_ReqDeRegister(1. 794.SetAt(m_ServiceCounter-1. break. 787.ulDbmHandle). if (m_ConnectionInfo. { 820.tAclHandle>0) 819. { 808. 785. } 832. case 2: 812. 790. if (m_ConnectionInfo. void CRadioChatClientDlg::OnScmDeRegisterCnfNeg(void **ppMsg) . 781.pucAttributeData. default: 829. break. service = m_ServicesFound.SCM_SECURITY_HANDLER). } 826. 828.m_AttributeListByteCount). 811. { 805.ulDbmHandle > 0) 813. VOS_Alloc(service. SCM_TDeRegisterCnf *ptDeRegisterCnf = (SCM_TDeRegisterCnf *) *ppMsg. { 801. 802.uiSeqNr) 807.m_ConnectionInfo. } 831. 788. SCM_ReqDisconnect(0. 793. { 818. 830. 789. 815. CService service. } 816. DBM_ReqUnRegisterService(3.tAclHandle). (void*)memcpy(service.m_pAttributeData. 798.uiAttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. 810. { 784. break. service. void CRadioChatClientDlg::OnCloseapplication() 800. m_ConnectionInfo. { 814. 825.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. SCM_ReqDeRegister(2. m_ServiceCounter++.service). 795.m_AttributeListByteCount). DestroyWindow(). } 799. &tServiceAttributeCnf->ucAttributeData.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount. service. &tServiceAttributeCnf->ucAttributeData. switch (ptDeRegisterCnf->tHdr. (void*)memcpy(m_ConnectionInfo. m_ServicesFound. service. case 1: 809.m_ConnectionInfo. { 824. 797.uiAttributeListByteCount). VOS_Free((void**)&puiAttributeIDList). 791. else 817. } 827. GetAddress(). m_ServicesFound. i < iFound. 881. 876. } } void CRadioChatClientDlg::OnDbmUnRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg.Add(service). 838. 862.tAclHandle>0) { SCM_ReqDisconnect(0. 836.Chapter 9: Bluetooth Programming 291 833. 842. 872. iFound = m_DevicesFound. 861. TVI_SORT). hdevice1=m_tree. 880. 853. 839. DestroyWindow(). m_ConnectionInfo. AfxMessageBox("device1"). 840. 866.m_ConnectionInfo. 885. 846. 888. MessageBox(_T("Not possible to UnRegister from DBM")). 847. 883. } void CRadioChatClientDlg::OnScmDisconnectCnfNeg(void **ppMsg) { ppMsg = ppMsg. DestroyWindow(). 869. } else { DestroyWindow(). for (i=0. 855. hPA. } void CRadioChatClientDlg::ShowAllDevicesFound() { CRemoteDevice device. OnSelDevice(). 844. 849. 865. 882. 870. 867. 887. . MessageBox(_T("Could not remove ACL connection")). 837. 854. 871. 874. DestroyWindow(). 859. 856. } void CRadioChatClientDlg::OnDbmUnRegisterServiceCnf(void **ppMsg) { ppMsg = ppMsg. 868. 884. 841. int iFound. 875. 843. 860. 851. 848.InsertItem(device. 873. DestroyWindow(). 877. 834. 857. } } void CRadioChatClientDlg::AddService(CString sService) { CService service(sService).i.GetAt(i). 835. 850. 864. } BOOL CRadioChatClientDlg::DestroyWindow() { return CDialog::DestroyWindow(). 845. 863. i++) { device = m_DevicesFound. 852. 878. if (m_ConnectionInfo. { ppMsg = ppMsg. } void CRadioChatClientDlg::OnScmDisconnectCnf(void **ppMsg) { ppMsg = ppMsg.tAclHandle = 0. 886.tAclHandle). 879. MessageBox(_T("Could not unregister from SCM")).GetSize(). 858. 935. 938.tLap.Add(device). 943. 905. i < iFound. 914. 902. 937. SCM_DM1.292 Chapter 9: Bluetooth Programming 889. 931. 942. 941.tAddress. DBM_StackDB). int iFound. 917.0x33}. 892. 910.hdevice1. 0. 903. 898. 913. 899. DBM_ReqRegisterService(0.SD_DEFAULT_MFS.tAddress = device.i. 918. 890.ulServiceRecordHandle = service. SD_ReqConnect(0.0x8B. HCI_TNrOfResponses tNrOfResponses = 0.GetAt(0).TVI_LAST). 893. 911. } void CRadioChatClientDlg::AddService(CService service) { m_ServicesFound. } void CRadioChatClientDlg::OnSelservices() { CService service. 927. } void CRadioChatClientDlg::OnGetservices() { m_ServiceCounter = 0. 909.Add(service).tAclHandle). 936. 939. iFound = m_ServicesFound. } void CRadioChatClientDlg::ShowAllServicesFound() { CService service. 926.tNrOfResponses). } void CRadioChatClientDlg::OnSelDevice() { CRemoteDevice device. 897. 940. 921. HCI_TInquiryLength tInquiryLength = 2. 933.tAddress. device = m_DevicesFound. 901. 896. 916. } } void CRadioChatClientDlg::AddDevice(CRemoteDevice device) { m_DevicesFound. 919. i++) { service = m_ServicesFound. for (i=0. 904. m_tree. device. 891.tInquiryLength. SCM_MANDATORY_PAGE_SCAN_MODE. 923. } void CRadioChatClientDlg::OnConnect() { . SCM_NOT_ACCEPT_ROLE_SWITCH). 925. 900. } void CRadioChatClientDlg::OnInquiry() { HCI_TLap tLap = {0x9E. 894. service = m_ServicesFound. m_ServiceRecordHandle. 934.GetAt(i). 908. SCM_R1. 895. 928. 915. 930.GetAt(0).GetSize(). 924. 907. 922. 920.GetService(). SCM_ReqConnect(0. 932.InsertItem(service.m_ConnectionInfo. m_ConnectionInfo. 929. HCI_ReqInquiry(1. m_ConnectionInfo. 906. 912. &uiLength. 953. 957. MessageBox(_T("Could not create a RFCOMM connection")). 992. 997. 967. 949. 968. m_ConnectionInfo. 991. 965. 971. 999. uint16 uiLength. } m_ChatArea. } void CRadioChatClientDlg::OnComDataCnf(void **ppMsg) { ppMsg = ppMsg. COM_RspData(tDataInd->tHdr. 969. 947. m_ConnectionInfo.tAclHandle. 986. 993. 966. 972.200). } void CRadioChatClientDlg::OnComConnectCnfNeg(void **ppMsg) { COM_TConnectCnfNeg *ptConnectCnfNeg = (COM_TConnectCnfNeg *) *ppMsg. 988. CHAR sData[80]. EndModalLoop(0). } void CRadioChatClientDlg::OnComDisconnectEvt(void **ppMsg) { COM_TDisconnectEvt *ptDisconnectEvt = (COM_TDisconnectEvt *)*ppMsg. m_ConnectionInfo. Beep (1000.COM_POS_RESULT. 996. 960.200).uiMaxFrameSize). 952. 978. 946. 985. 989. &uiHandle). 979. MessageBox(_T(" RFCOMM connection")). 963. 981. 973.uiRFCommHandle = ptConnectCnf->uiHandle. 984. } void CRadioChatClientDlg::OnComConnectCnf(void **ppMsg) { COM_TConnectCnf *ptConnectCnf = (COM_TConnectCnf *) *ppMsg. MessageBox(_T("Could not send data on RFCOMM channel")). 955. Sleep(100).uiHandle). 990. ptConnectCnfNeg = ptConnectCnfNeg. m_ConnectionInfo. i < uiLength.uiRFCommHandle = 0. } void CRadioChatClientDlg::OnComDisconnectCnf(void **ppMsg) . 961. m_ConnectionInfo.ucSeqNr. 962.ReceiveMessageFromClient((CString)sData). 977. 964. for (i=0. 948. Beep (1000. 974. 975.Chapter 9: Bluetooth Programming 293 944. (uint16)m_ConnectionInfo. 987. 958. pucData = COM_DataExtract((MSG_TDataMsg *)*ppMsg. 954. 951.uiRFCommHandle = 0. ptDisconnectEvt = ptDisconnectEvt. 995. } void CRadioChatClientDlg::OnComDataInd(void **ppMsg) { COM_TDataInd *tDataInd = (COM_TDataInd *)*ppMsg. COM_ReqConnect(0. } void CRadioChatClientDlg::OnComDataCnfNeg(void **ppMsg) { ppMsg = ppMsg. 976. 983. 970. 950. uint8 *pucData. 994. 980. 959. uint16 uiHandle. i++) { sData[i] = pucData[i] . 982.ulDbmHandle. 998. 956. 945. int i. { 1020. for (i=0.} Code Description The code of file transfer application is reused here to the maximum possible extent. { 1033. m_ConnectionInfo. ♦ Lines 1–964: Explained in RadioFileClientDlg. 1021. } 1041. 1015. pucData[i] = sChatStr[i]. void CRadioChatClientDlg::HandleReturn() 1013. The differences are explained below. } void CRadioChatClientDlg::OnComDisconnectCnfNeg(void **ppMsg) { COM_TDisconnectCnfNeg *ptDisconnectCnfNeg = (COM_TDisconnectCnfNeg *)*ppMsg.pucData. (uint16)(iCount + 1)). return CDialog::PreTranslateMessage(pMsg).cpp file. HandleReturn(). { 1037. MessageBox(_T("Could not Disconnect the RFCOMM connection")). } 1025. m_InputChat.uiRFCommHandle.m_ConnectionInfo.294 Chapter 9: Bluetooth Programming 1000. ♦ Lines 983–1011: Explained in RadioFileClientDlg. 1003. if (iCount > 0) 1019. if (pMsg->message == WM_KEYDOWN) 1034. if (pMsg->wParam == VK_RETURN) 1036. 1028. The data that has been read is added to chat area in the dialog box. { 1035. ptDisconnectCnf = ptDisconnectCnf. 1017. ♦ Lines 965–982: After the Bluetooth module fires the COM DATA IND event. 1038. 1001. COM_DataSend(0. } 1040. 1018. { COM_TDisconnectCnf *ptDisconnectCnf = (COM_TDisconnectCnf *)*ppMsg. 1027. uint16 iCount. } 1030.SendMessageToServer((CString)sChatStr). 1007.80). 1024.GetWindowText(sChatStr. 1008. 1009. 1005. 1004. CHAR sChatStr[80]. 1029. i++) 1022. 1039. uint8 *pucData. . 1042. 1026. } 1031. 1011. BOOL CRadioChatClientDlg::PreTranslateMessage(MSG* pMsg) 1032. m_ChatArea. { 1014. iCount = (uint16) m_InputChat. 1010.SetWindowText(_T("")). i < iCount.uiRFCommHandle = 0.cpp file. The response is sent to the server to indicate that the data has been received. pucData = COM_DataAlloc((uint16)(iCount + 1)). pucData[i] = 0. { 1023. } 1012. ptDisconnectCnfNeg = ptDisconnectCnfNeg. 1006. the command to read the incoming data from the server is issued. return FALSE. 1016.i. EndModalLoop(0). 1002. the screen in Figure 9-9 is displayed.h> 10. #include "Events. #include <exp\sd.h" 8. The services supported by the server will be added to the BLUETOOTH device address node.h" 7. The data will be displayed in the chat area list box. #include <exp\BT_COMServer. Code Output When the application is built in the VC++ environment. the function HandleReturn is invoked to send the data to the remote device. Listing 9-23: Source Code for RadioChatServerDlg. #include "ConnectionInfo.h : header file 2. The left side of the screen shows a tree structure. Figure 9-9: Output of the Client Module Server Module Listings 9-23 and 9-24 give the source code of RadioChatServerDlg. #include <afxtempl. When the client device gets connected to the server Bluetooth device. its address is added to the root as a child node.h" 5. ♦ Lines 1031–1042: As soon as the enter key is pressed. This tree structure contains one root node named RemoteRadios. #include "Remotedevice. #include "service. // RadioChatServerDlg.h and RadioChatServerDlg.h © 2001 Dreamtech Software India Inc. 3.Chapter 9: Bluetooth Programming 295 ♦ Lines 1012–1030: The data entered in the chat input will be retrieved and sent to the remote Bluetooth peer device.h> .cpp. All Rights Reserved 1.h" 6. The right side of the screen contains one edit box and list boxes to display the exchange of messages. #include "RS232.h> 9. The user has to press Enter in the edit box to send the message to the server.h" 4. respectively. CTreeCtrl m_tree. void AskForServiceRecordHandle(). 53. 36. public: 49. void InitSecurityClient(). CRS232 *m_pSerialPort. 30. . void AskForServiceName().(LPARAM) &pMsg) 18.pMsg) \ 17. 33. CListBox m_ChatArea. 50. LPARAM lParam). 58. int index. //{{AFX_DATA(CRadioFileServerDlg) 32. #define SEND_BT_EVENT(uiBtEventID. HICON m_hIcon. //}}AFX_DATA 37. 56. 31. 62. 34. // ClassWizard generated virtual function overrides 39. void AddDevice(CString sAddress. void ShowAllServicesFound(). CRadioChatServerDlg dialog 12. 48. { WM_BLUETOOTH_EVENT. CRadioChatServerDlg(CWnd* pParent = NULL). BOOL OnBluetoothEvent(UINT message. 38. 61. public: 42. protected: 44. 63. 51.0. 57. ~CRadioChatServerDlg(). CConnectionInfo m_ConnectionInfo. 35. protected: 60. \ 15. 55. 52. 46. void AddDevice(CDevice device). void ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf). 19. #define ON_BLUETOOTH_EVENT(uiBtEventID.0. 22. 25. 29. 26. 43. (AFX_PMSG)(AFX_PMSGW)(void (AFX_MSG_CALL CWnd::*)(void **))&memberFxn }. void AddService(CService service). SendMessage((HWND)this-> m_hWnd. 16. public: 23.296 Chapter 9: Bluetooth Programming 11. virtual void DoDataExchange(CDataExchange* pDX). { 21. 45. 54. void ReceiveServiceRecordHandle(SD_TServiceAttributeCnf *tServiceAttributeCnf). CString sName). CEdit m_InputChat. virtual BOOL DestroyWindow().(WPARAM)uiBtEventID. class CRadioChatServerDlg : public CDialog 20. WPARAM wParam. CServerEvents *m_pServerEvents. //{{AFX_VIRTUAL(CRadioFileServerDlg) 40. uiBtEventID. WPARAM wParam. private: 28. void ShowAllDevicesFound(). 41. //}}AFX_VIRTUAL 47. 24.WM_BLUETOOTH_EVENT. void AddService(CString sService). #define WM_BLUETOOTH_EVENT (WM_USER + 100) 13. memberFxn) \ 14.1. virtual LRESULT WindowProc(UINT message. enum { IDD = IDD_RADIOCHAT_DIALOG }. LPARAM lParam). 27. 59. afx_msg void OnComDataInd(void **ppMsg). afx_msg void OnScmRegisterCnf(void **ppMsg). int m_RemoteNameCounter. 82. afx_msg HCURSOR OnQueryDragIcon(). 84. afx_msg void OnComRegisterCnf(void **ppMsg). afx_msg void OnScmDeRegisterCnfNeg(void **ppMsg). 67. afx_msg void OnComConnectInd(void **ppMsg). 65. 104. 74. 73. 70. afx_msg void OnSdServiceAttributeCnfNeg(void **ppMsg). afx_msg void OnDbmRegisterServiceCnfNeg(void **ppMsg). afx_msg void OnSdServiceSearchCnf(void **ppMsg). // Generated message map functions //{{AFX_MSG(CRadioFileServerDlg) virtual BOOL OnInitDialog(). 81. 108. afx_msg void OnConnect(). 97. 88. 102. afx_msg void OnScmPincodeInd(void **ppMsg). 117. CArray <CDevice. afx_msg void OnHCIUsb(). 106. afx_msg void OnHCISerial(). 115. afx_msg void OnSdStartCnf(void **ppMsg). 99. afx_msg void OnSelDevice().Chapter 9: Bluetooth Programming 297 64. afx_msg void OnComStartCnf(void **ppMsg). afx_msg void OnScmDeRegisterCnf(void **ppMsg). 107. 80. afx_msg void OnScmConnectEvt(void **ppMsg). afx_msg void OnScmRegisterCnfNeg(void **ppMsg). afx_msg void OnConnectAcceptInd(void **ppMsg). afx_msg void OnSdServiceAttributeCnf(void **ppMsg). 87. afx_msg void OnComFillPdlCnfNeg(void **ppMsg). afx_msg void OnSdConnectCnf(void **ppMsg). afx_msg void OnScmDisconnectCnfNeg(void **ppMsg). 78. afx_msg void OnScmDisconnectCnf(void **ppMsg). 103. afx_msg void OnSdServiceSearchCnfNeg(void **ppMsg). 95.CService&> m_ServicesFound. uint8 m_RFServerChannel. afx_msg void OnSelservices(). 94. 113. 118. 101.CDevice&> m_DevicesFound. afx_msg void OnComFillPdlCnf(void **ppMsg). afx_msg void OnGetservices(). 92. int m_ServiceCounter. afx_msg void OnDbmRegisterServiceCnf(void **ppMsg). 83. afx_msg void OnSysCommand(UINT nID. afx_msg void OnComVersionCnf(void **ppMsg). uint16 m_RFCommHandle. 105. 112. afx_msg void OnComRegisterCnfNeg(void **ppMsg). afx_msg void OnScmConnectCnfNeg(void **ppMsg). afx_msg void OnScmDisconnectEvt(void **ppMsg). 72. 89. 77. 98. 86. afx_msg void OnInquiry(). 76. afx_msg void OnDestroy(). 119. 85. 71. afx_msg void OnSdDisconnectCnf(void **ppMsg). 75. afx_msg void OnSdConnectCnfNeg(void **ppMsg). 109. afx_msg void OnComDataCnfNeg(void **ppMsg). afx_msg void OnComDataCnf(void **ppMsg). 79. 110. 90. afx_msg void OnPaint(). CArray <CService. afx_msg void OnCloseapplication(). LPARAM lParam). 114. 66. 116. afx_msg void OnSerialport(). 93. 69. afx_msg void OnScmConnectCnf(void **ppMsg). 96. 111. 68. afx_msg void OnComStartCnfNeg(void **ppMsg). . 100. 91. 133. afx_msg void OnHciWriteAuthenticationModeCnfNeg(void **ppMsg). afx_msg void OnSdsStartCnf(void **ppMsg). 152. 149. 126. #include "RadioChat.h" 5. 160. 136. 121. Code Description In this file. 127.cpp © 2001 Dreamtech Software India Inc. afx_msg void OnHciWriteEncryptionModeCnf(void **ppMsg). afx_msg void OnHciLocalAddressCnfNeg(void **ppMsg). }. 130. afx_msg void OnDbmAddDescriptorCnf(void **ppMsg). afx_msg void OnSilReqDeviceCnfNeg(void **ppMsg). Listing 9-24: Source code for RadioChatServerDlg. afx_msg void OnSilSetDeviceCnfNeg(void **ppMsg). afx_msg void OnHciRemoteNameCnfNeg(void **ppMsg). afx_msg void OnHciWriteCodCnf(void **ppMsg). 145. 146. 134. afx_msg void OnHciConfigurePortConfirmNegative(void **ppMsg). 132. all variables. #include "Events. and classes necessary to implement CRadioChatServerDlg class were declared. 137. afx_msg void OnHciWriteConnectTimeoutCnf(void **ppMsg). 122. afx_msg void OnHciWriteScanEnableCnfNeg(void **ppMsg).h" . 154. 141. afx_msg void OnDbmAddDescriptorCnfNeg(void **ppMsg). constants. afx_msg void OnComConnectCnfNeg(void **ppMsg). 138. afx_msg void OnButton2(). //}}AFX_MSG 158. afx_msg void OnDbmUnRegisterServiceCnf(void **ppMsg). methods. afx_msg void OnHciStartCnf(void **ppMsg). afx_msg void OnHciRemoteNameCnf(void **ppMsg). afx_msg void OnHciWriteCodCnfNeg(void **ppMsg). 153. afx_msg void OnHciWriteAuthenticationModeCnf(void **ppMsg). 148. afx_msg void OnHciInquiryEvt(void **ppMsg). 129. 128. afx_msg void OnDbmUnRegisterServiceCnfNeg(void **ppMsg). #include "RadioChatServerDlg. DECLARE_MESSAGE_MAP() 159. 156. afx_msg void OnSilSetDeviceCnf(void **ppMsg). afx_msg void OnHciWriteNameCnfNeg(void **ppMsg). afx_msg void OnHciWriteScanEnableCnf(void **ppMsg). 124. afx_msg void OnHciWriteNameCnf(void **ppMsg). 135. afx_msg void OnHciInquiryCnf(void **ppMsg).h" 3. 142. 147. afx_msg void OnComConnectCnf(void **ppMsg). afx_msg void OnHciLocalAddressCnf(void **ppMsg). afx_msg void OnHciWritePageTimeoutCnfNeg(void **ppMsg). afx_msg void OnHciWritePageTimeoutCnf(void **ppMsg). afx_msg void OnHciConfigurePortConfirm(void **ppMsg). 131. afx_msg void OnHciWriteConnectTimeoutCnfNeg(void **ppMsg). 123. 155. 125. 140.cpp : implementation file 2. 139. 143. #include "stdafx. 157. 150. // RadioChatServerDlg. 144. afx_msg void OnHciWriteEncryptionModeCnfNeg(void **ppMsg).298 Chapter 9: Bluetooth Programming 120.h" 4. 151. All Rights Reserved 1. afx_msg void OnSilReqDeviceCnf(void **ppMsg). }. 47. // ClassWizard generated virtual function overrides 49. #ifdef _DEBUG 21.h> 12.h> 17.}. { 42. #include <exp/sds. public: 43. #include <exp/dbm. class CAboutDlg : public CDialog 41. 44.'0'. 59. //}}AFX_MSG 57.'0'.h> 19. CAboutDlg(). #endif 25.'0'.h> 11.h> 7. #include <exp/sil. 24. union MessageMapFunctions 28.0x04}.h> 18. #include <exp/com.'0'.0x04. //}}AFX_DATA 48.'2'. #include <exp/msg. #include <exp/hci_drv. 52. 32. //{{AFX_DATA(CAboutDlg) 46. CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) 60. // Implementation 54.'0'. protected: 55. #define PORTSETTINGS (uint8 *)("COM1:Baud=57600 parity=N data=8 stop=1") 35. #include <process. 40. 27.'4'. 31. static const HCI_TCod _tCod={0x20.Chapter 9: Bluetooth Programming 299 6. HTREEITEM hPA. #define SRP_SERIAL_GENERIC_SERIALPORT_UUID(uint16) 0x1101) 38.'0'.'0'. #include <exp/hci.hdevice1.h" 8. static const SCM_TPincode _tPincode = {'1'. 34.h> 10.h> 13. { . 30.h> 9. //{{AFX_MSG(CAboutDlg) 56.'3'.'0'.'0'. // Dialog Data 45. 20. }. static char THIS_FILE[] = __FILE__. { 29.h> 14.'0'. #define PINCODE_LENGTH ((SCM_TPincodeLength) 4) 33. #include <exp/scm. virtual void DoDataExchange(CDataExchange* pDX). //{{AFX_VIRTUAL(CAboutDlg) 50. //}}AFX_VIRTUAL 53. #include <exp/Bstr. #include <exp/vos2com. protected: 51. #undef THIS_FILE 23. #include <exp/sd.h> 15. #define InterSelUSB ((uint8) 1) 37. 39. AFX_PMSG pfn.'0'. #define new DEBUG_NEW 22. #include "windows. DECLARE_MESSAGE_MAP() 58. #define InterSelSerial ((uint8) 0) 36.h> 16. 26.'0'. enum { IDD = IDD_ABOUTBOX }. void (AFX_MSG_CALL CWnd::*pfn_btf)(void **). //{{AFX_DATA_INIT(CAboutDlg) 62. CRadioChatServerDlg::CRadioChatServerDlg(CWnd* pParent /*=NULL*/) 77.RemoveAll(). ON_BLUETOOTH_EVENT(COM_START_CNF. //{{AFX_DATA_INIT(CRadioChatServerDlg) 80. } 93. BEGIN_MESSAGE_MAP(CRadioChatServerDlg. : CDialog(CRadioChatServerDlg::IDD. ON_BLUETOOTH_EVENT(COM_FILL_PDL_CNF_NEG. 76. CDialog) 71. //{{AFX_DATA_MAP(CAboutDlg) 68. { 95. END_MESSAGE_MAP() 75. //{{AFX_DATA_MAP(CRadioChatServerDlg) 97.OnComStartCnfNeg) 116. 85. } 70. ON_BLUETOOTH_EVENT(COM_VERSION_CNF. // NOTE: the ClassWizard will add member initialization here 81. 83. 89. m_DevicesFound. m_pServerEvents = new Events(). delete m_pServerEvents. 99. ON_WM_PAINT() 106. //}}AFX_DATA_MAP 69.OnComDataInd ) 109.OnComStartCnf) 115. void CAboutDlg::DoDataExchange(CDataExchange* pDX) 65. //}}AFX_DATA_INIT 82. IDC_TREE1. 98. BEGIN_MESSAGE_MAP(CAboutDlg. ON_WM_QUERYDRAGICON() 107. pParent) 78. DDX_Control(pDX. IDC_LIST1. m_ServicesFound. { 66. DDX_Control(pDX. //{{AFX_MSG_MAP(CAboutDlg) 72.OnComVersionCnf) . } 86. CDialog::DoDataExchange(pDX). 84.OnComRegisterCnf ) 110. void CRadioChatServerDlg::DoDataExchange(CDataExchange* pDX) 94. { 79. ON_WM_SYSCOMMAND() 105. ON_BLUETOOTH_EVENT(COM_CONNECT_IND. 96. ON_BLUETOOTH_EVENT(COM_FILL_PDL_CNF.OnComFillPdlCnfNeg ) 113. m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME). m_ChatArea). ON_BLUETOOTH_EVENT(COM_REGISTER_CNF_NEG. //}}AFX_DATA_MAP 101. 67.OnComRegisterCnfNeg ) 111. 100. 108. CRadioChatServerDlg::~CRadioChatServerDlg() 87. 90. // No message handlers 73. DDX_Control(pDX. { 88.300 Chapter 9: Bluetooth Programming 61.OnComConnectInd ) 114. //}}AFX_DATA_INIT 63. //}}AFX_MSG_MAP 74. 91.OnComFillPdlCnf ) 112. m_tree). } 102. ON_BLUETOOTH_EVENT(COM_START_CNF_NEG. ON_BLUETOOTH_EVENT(COM_DATA_IND. ON_BLUETOOTH_EVENT(COM_REGISTER_CNF. 92. } 64. CDialog) 103. CDialog::DoDataExchange(pDX). //{{AFX_MSG_MAP(CRadioChatServerDlg) 104. m_InputChat). IDC_EDIT1.RemoveAll(). 155.OnHciWriteScanEnableCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF_NEG.OnScmRegisterCnf) ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF_NEG. OnHciConfigurePortConfirmNegative) ON_BLUETOOTH_EVENT(HCI_INQUIRY_CNF. 120. OnHciWriteEncryptionModeCnf) 159. 147. OnHciLocalAddressCnf) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF_NEG.OnScmConnectCnf) ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF_NEG. 142.OnScmPincodeInd) ON_BLUETOOTH_EVENT(SCM_CONNECT_CNF. 148. 131. 134. OnSdServiceAttributeCnfNeg) ON_BLUETOOTH_EVENT(SD_DISCONNECT_CNF. OnDbmUnRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF.OnSdConnectCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF.OnHciRemoteNameCnf) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF_NEG.OnHciConfigurePortConfirm) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF_NEG. OnHciWriteEncryptionModeCnfNeg) 160. ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF.Chapter 9: Bluetooth Programming 301 117. 130. OnHciLocalAddressCnfNeg) ON_BLUETOOTH_EVENT(HCI_REMOTE_NAME_CNF. 121.OnSdConnectCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF_NEG. 135.OnHciInquiryEvt) ON_BLUETOOTH_EVENT(HCI_LOCAL_ADDRESS_CNF. 122.OnDbmRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF_NEG.OnSdStartCnf) ON_BLUETOOTH_EVENT(SD_CONNECT_CNF. 143. ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF. 139. 153.OnSdServiceSearchCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_SEARCH_CNF_NEG. 146. 129. 118.OnScmConnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_EVT. 132. 133.OnHciInquiryCnf) ON_BLUETOOTH_EVENT(HCI_INQUIRY_EVT.OnSdServiceAttributeCnf) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF_NEG. ON_BLUETOOTH_EVENT(HCI_WRITE_ENCRYPTION_MODE_CNF_NEG. OnHciWriteAuthenticationModeCnfNeg) 158.OnDbmAddDescriptorCnf) ON_BLUETOOTH_EVENT(DBM_ADD_DESCRIPTOR_CNF_NEG. 151. 136. 123.OnScmRegisterCnfNeg) ON_BLUETOOTH_EVENT(SCM_CONNECT_ACCEPT_IND. 137. 138. OnDbmAddDescriptorCnfNeg) ON_BLUETOOTH_EVENT(HCI_CONFIGURE_PORT_CNF.OnScmDeRegisterCnf) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF_NEG. 156. OnHciWriteAuthenticationModeCnf) 157. 150. ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF_NEG. OnDbmUnRegisterServiceCnf) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF_NEG.OnHciRemoteNameCnfNeg) ON_BLUETOOTH_EVENT(HCI_START_CNF. 126. 145.OnScmDeRegisterCnfNeg) ON_BLUETOOTH_EVENT(SD_START_CNF.OnScmDisconnectCnf) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF_NEG.OnScmDisconnectCnfNeg) ON_BLUETOOTH_EVENT(SCM_DEREGISTER_CNF. 124. OnDbmRegisterServiceCnfNeg) ON_BLUETOOTH_EVENT(DBM_UNREGISTER_SERVICE_CNF. 125.OnSdDisconnectCnf) ON_BLUETOOTH_EVENT(DBM_REGISTER_SERVICE_CNF. 119.OnHciWriteCodCnf) . 128. 140. 141.OnScmConnectCnfNeg) ON_BLUETOOTH_EVENT(SCM_CONNECT_EVT. ON_BLUETOOTH_EVENT(SCM_REGISTER_CNF.OnConnectAcceptInd) ON_BLUETOOTH_EVENT(SCM_PINCODE_IND. ON_BLUETOOTH_EVENT(HCI_WRITE_AUTHENTICATION_MODE_CNF. 152. OnHciWriteScanEnableCnfNeg) 154. 144.OnSdServiceSearchCnfNeg) ON_BLUETOOTH_EVENT(SD_SERVICE_ATTRIBUTE_CNF.OnScmDisconnectEvt) ON_BLUETOOTH_EVENT(SCM_DISCONNECT_CNF. 127. 149.OnHciStartCnf) ON_BLUETOOTH_EVENT(HCI_WRITE_SCAN_ENABLE_CNF. mask = TVIF_TEXT.SetWindowText("Type And Press Enter To Send Your Message"). TRUE). 184.item. OnSilSetDeviceCnfNeg) 170. 202.OnHciWriteCodCnfNeg) 162.hInsertAfter = NULL. OnHciWriteConnectTimeoutCnf) 165. pSysMenu->AppendMenu(MF_SEPARATOR). 200. 206.IsEmpty()) 192. { 181. return TRUE. ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF_NEG. FALSE). SetIcon(m_hIcon. 198. CMenu* pSysMenu = GetSystemMenu(FALSE). 183. 199. m_pServerEvents->m_pParentDialog = this. BOOL CRadioChatServerDlg::OnInitDialog() 180.302 Chapter 9: Bluetooth Programming 161. 194. //}}AFX_MSG_MAP 177. ON_BLUETOOTH_EVENT(HCI_WRITE_PAGE_TIMEOUT_CNF.hParent =NULL. 203. . END_MESSAGE_MAP() 178. IDM_ABOUTBOX. ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF. 182. 205. OnButton2) 176. } 196. ON_BLUETOOTH_EVENT(COM_CONNECT_CNF_NEG. 209. 187. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX). OnHciWriteConnectTimeoutCnfNeg) 166.OnComConnectCnf ) 173. if (pSysMenu != NULL) 188. 204. ON_BLUETOOTH_EVENT(HCI_WRITE_COD_CNF_NEG.InsertItem(&tvInsert). 211. hPA = m_tree. OnSilSetDeviceCnf) 169. } 197. ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF. 208. if (!strAboutMenu. 191. CDialog::OnInitDialog(). strAboutMenu.OnHciWriteNameCnfNeg) 164. 210. OnHciWritePageTimeoutCnfNeg) 168. index=0. tvInsert. InitSecurityClient(). 201. ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF_NEG. pSysMenu->AppendMenu(MF_STRING. CString strAboutMenu. tvInsert. 186. ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF_NEG. ON_BLUETOOTH_EVENT(SDS_START_CNF. 179. ON_BN_CLICKED(IDC_BUTTON2. OnSilReqDeviceCnfNeg) 172. ON_BLUETOOTH_EVENT(COM_CONNECT_CNF. OnSilReqDeviceCnf) 171. ON_BLUETOOTH_EVENT(SIL_REQ_DEVICE_CNF_NEG. strAboutMenu). 212.item.pszText = _T("RemoteRadios"). TVINSERTSTRUCT tvInsert.LoadString(IDS_ABOUTBOX).OnSdsStartCnf) 175.OnComConnectCnfNeg ) 174. 185. ASSERT(IDM_ABOUTBOX < 0xF000). 207. { 189.OnHciWriteNameCnf) 163. ON_BLUETOOTH_EVENT(HCI_WRITE_CONNECT_TIMEOUT_CNF. ON_BLUETOOTH_EVENT(HCI_WRITE_NAME_CNF. { 193. SetIcon(m_hIcon. tvInsert. OnHciWritePageTimeoutCnf) 167. 190. m_InputChat. tvInsert. ON_BLUETOOTH_EVENT(SIL_SET_DEVICE_CNF_NEG. 195. WPARAM wParam. } 231. wParam. 234. 236. lParam). #endif 250. ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()). #endif 243. { 244. pMessageMap = pMessageMap->pBaseMap) 242. 263. ASSERT(pMessageMap != pMessageMap->pBaseMap). 266. 220. OnBluetoothEvent( message. 227. mmf. if (message == WM_BLUETOOTH_EVENT) 221. ptMsg = (MSG_TMsg**)lParam. lpEntry = (AFX_MSGMAP_ENTRY*)(&pMessageMap->lpEntries[0]). const AFX_MSGMAP_ENTRY* lpEntry. for (pMessageMap = GetMessageMap(). 253. 258. #else 248. wParam. #ifdef _AFXDLL 246. WPARAM wParam. 229. 247. 215. 225. MSG_TMsg **ptMsg. const AFX_MSGMAP* pMessageMap. pMessageMap = (*pMessageMap->pfnGetBaseMap)()) 239. lParam). { 255.pfn = lpEntry->pfn. if ((lpEntry->nMessage == message) && (lpEntry->nCode == wParam)) 256. { 217. LPARAM lParam) 216. 245. 238. pMessageMap != NULL. pMessageMap != NULL. for (pMessageMap = GetMessageMap(). { 222. (((CWnd *)this)->*mmf. LRESULT CRadioChatServerDlg::WindowProc(UINT message. return TRUE. 223. 251. } 214. 261. VOS_Free((void **)lParam). if (*ptMsg != NULL) 226. { 257. union MessageMapFunctions mmf. 224. return CDialog::WindowProc(message. 219. lpEntry++. #ifdef _AFXDLL 237. 252. while (lpEntry->nSig != AfxSig_end) 254. 218. } 265.Chapter 9: Bluetooth Programming 303 213. #else 240. { 233. 249. BOOL CRadioChatServerDlg::OnBluetoothEvent(UINT message. 241. 262. 260. 235. 264.pfn_btf)((void **)lParam). } 228. 259. } . LPARAM lParam) 232. 230. 301. 308. 281. } else { CDialog::OnPaint(). 285.GetSafeHdc(). 318. 291. } return FALSE. 278. 302. SendMessage(WM_ICONERASEBKGND. 0).Height() .cxIcon + 1) / 2. 277. 295.DrawIcon(x.SIL_SERIAL). 292. 280. 321. 290. int y = (rect. int cxIcon = GetSystemMetrics(SM_CXICON). 282. 309. 273. 307.cyIcon + 1) / 2. 314. 283. (WPARAM) dc. 294. 296. return FALSE. } void CRadioChatServerDlg::OnSysCommand(UINT nID. 284. 300. m_hIcon). 322. int cyIcon = GetSystemMetrics(SM_CYICON). 297. y. 298. GetClientRect(&rect). . lParam). 315. 299.DoModal(). 311. CRect rect. 287. 272. } void CRadioChatServerDlg::InitSecurityClient() { SIL_SetDevice(0. 313. int x = (rect. 274. 306. 270. 304. dlgAbout. } else { CDialog::OnSysCommand(nID. 286. 275. 316. 269. 293. 319.304 Chapter 9: Bluetooth Programming 267. 279.Width() . 310. 317. 305. 268. 288. } void CRadioChatServerDlg::OnSilSetDeviceCnf(void **ppMsg) { ppMsg = ppMsg. 312. } } HCURSOR CRadioChatServerDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon. LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout. 276. 303. dc. } } void CRadioChatServerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this). 289. 271. 320. 367. 348. 362. 327. 343. void CRadioChatServerDlg::OnComStartCnf(void **ppMsg) 372. 339. COM_ReqStart(0). } 347. 369. void CRadioChatServerDlg::OnSilSetDeviceCnfNeg(void **ppMsg) 328.PORTSETTINGS). SIL_TReqDevice* ptReq. 332. 355. MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is SERIAL")). tStartCnf = tStartCnf. COM_TStartCnf *tStartCnf = (COM_TStartCnf *)*ppMsg.iResult == SIL_ERR_DEVICE) 333. HCI_TConfigurePortCnf *tConfigurePort = (HCI_TConfigurePortCnf *)*ppMsg. void CRadioChatServerDlg::OnSilReqDeviceCnfNeg(void **ppMsg) 349. void CRadioChatServerDlg::OnSilReqDeviceCnf(void **ppMsg) 337. 360. 346. MessageBox(_T("NOT Possible To Change Interface\nCurrent HCI Interface is USB")). if(ptReq->uiDevice == SIL_SERIAL) 342. 352. MessageBox(_T("Device Request FAILED!")). { 373. SIL_ReqDevice(0). 330. 326. 336. 324. tConfigurePort = tConfigurePort. 353. ptSetDevice = (SIL_TSetDevice*)*ppMsg. void CRadioChatServerDlg::OnHciConfigurePortConfirm(void **ppMsg) 356. if(ptReq->uiDevice == SIL_USB) 344. } 371. 368. tConfigurePort = tConfigurePort. 340. HCI_ReqConfigurePort(0. 341. ppMsg = ppMsg. void CRadioChatServerDlg::OnHciConfigurePortConfirmNegative(void **ppMsg) 364. { 365. MessageBox(_T("Could not open port")). } 363. { 329. 375. } 354.Chapter 9: Bluetooth Programming 305 323. } 325. . 361. 366. { 350. 334. 370. if(ptSetDevice->tHdr. ptReq = (SIL_TReqDevice*) *ppMsg. 345. 331. { 338. SIL_TSetDevice* ptSetDevice. } 335. HCI_TConfigurePortCnfNeg *tConfigurePort = (HCI_TConfigurePortCnfNeg *)*ppMsg. 351. 359. { 357. 374. 358. 415.ucByte1. { 425. COM_TStartCnfNeg *tStartCnfNeg = (COM_TStartCnfNeg *)*ppMsg. } 404. SD_ReqStart(0). 378. void CRadioChatServerDlg::OnSdStartCnf(void **ppMsg) 411. 402. void CRadioChatServerDlg::OnHciLocalAddressCnfNeg(void **ppMsg) 405. { 429. 421. char lpStr[59].ucByte0. 392. HCI_ReqLocalAddress(0). 386.ucByte2.HCI_ENCRYPTION_OFF). HCI_TLocalAddressCnf *tLocalAddress = (HCI_TLocalAddressCnf *)*ppMsg. } 410. MessageBox(_T("Could not start RFCOMM")). 397. tLocalAddress->tAddress. { 382. tLocalAddress->tAddress. ppMsg = ppMsg.ucByte4. tLocalAddress->tAddress. } 388. ppMsg = ppMsg. void CRadioChatServerDlg::OnHciWriteEncryptionModeCnf(void **ppMsg) 418. 385. tStartCnfNeg = tStartCnfNeg. 400. 430. void CRadioChatServerDlg::OnComStartCnfNeg(void **ppMsg) 381. 422. { 412. 413.306 Chapter 9: Bluetooth Programming 376. 399. tLocalAddress->tAddress. 393. } 423. 407. void CRadioChatServerDlg::OnHciWriteAuthenticationModeCnf(void **ppMsg) 428. 387. ppMsg = ppMsg. tLocalAddress->tAddress.HCI_AUTH_DISABLE). 420. 384. SD_ReqStart(0). 396. 408. 398. 416. void CRadioChatServerDlg::OnHciLocalAddressCnf(void **ppMsg) 389. "BD_ADDRESS: 0x%02X%02X%02X%02X%02X%02X\0".ucByte3. 403. 401. 377. 394. 414. ppMsg = ppMsg. { 406. { 390. . HCI_ReqWriteEncryptionMode(0. ppMsg = ppMsg. } 380.ucByte5). HCI_ReqWriteAuthenticationMode(0. SetWindowText(_T(lpStr)). } 417. 426. } 427. 409. tLocalAddress->tAddress. wsprintf(&lpStr[0]. 379. void CRadioChatServerDlg::OnHciWriteEncryptionModeCnfNeg(void **ppMsg) 424. 383. 395. SetWindowText(_T("DEVICE NOT FOUND")). { 419. 391. HCI_ReqWriteCod(0. 438.0x1FA0). 452. 476. } void CRadioChatServerDlg::OnHciWriteConnectTimeoutCnf(void **ppMsg) { ppMsg = ppMsg. 478. 484. 481. 441. } void CRadioChatServerDlg::OnHciWritePageTimeoutCnf(void **ppMsg) { ppMsg = ppMsg. 474. 434. 472. 446. 469. HCI_ReqWritePageTimeout(0. 459. 477. 437. HCI_ReqWriteConnectTimeout(0.Chapter 9: Bluetooth Programming 307 431. 462. 444. 442. 473. 471. 450. 436. 447. 482. 470. 440. 448. } void CRadioChatServerDlg::OnHciWriteCodCnfNeg(void **ppMsg) { ppMsg = ppMsg. 458. 443. 456. } void CRadioChatServerDlg::OnHciWritePageTimeoutCnfNeg(void **ppMsg) { ppMsg = ppMsg. 449. } void CRadioChatServerDlg::OnHciWriteAuthenticationModeCnfNeg(void **ppMsg) { ppMsg = ppMsg. } . 460. 457._tCod).8000). 461. 486. } void CRadioChatServerDlg::OnHciWriteCodCnf(void **ppMsg) { ppMsg = ppMsg. 467. 464. 479. 465. 483. 463. 453. 451. } void CRadioChatServerDlg::OnHciWriteConnectTimeoutCnfNeg(void **ppMsg) { ppMsg = ppMsg. 445. 433. 480. 435. 439. 485. 466. 455. 468. 454. 475. 432. 528. device. 534.tPageScanPeriodMode. 526. 523. 492. 502. { 510. CRemoteDevice device. 490. void CRadioChatServerDlg::OnHciWriteNameCnf(void **ppMsg) 488. 506.GetSize().tAddress. 512. } 537. void CRadioChatServerDlg::OnHciWriteNameCnfNeg(void **ppMsg) 494. 529. } 535. { 533. ppMsg = ppMsg. { 521. 522. AfxMessageBox("remote name").tClockOffset ). 541. m_RemoteNameCounter = 0. } 507. 501. 524. HCI_TInquiryCnf *ptInquiryCnf. } 503. device. { 505. 517. 530. device = (CRemoteDevice) m_DevicesFound. ppMsg = ppMsg. 515. { 495. { 539. HCI_TRemoteNameCnf *ptRemoteNameCnf. { 499. 514. . void CRadioChatServerDlg::OnHciInquiryCnf(void **ppMsg) 509. if (count > 0) 520. void CRadioChatServerDlg::OnHciWriteScanEnableCnf(void **ppMsg) 498. ppMsg = ppMsg. void CRadioChatServerDlg::OnHciWriteScanEnableCnfNeg(void **ppMsg) 504. else 532.308 Chapter 9: Bluetooth Programming 487. 527. device. device. 516.tPageScanMode. 513. 496. 519. 525. char sName[248]. } 531. 511. 518. int count. } 497. HCI_ReqWriteScanEnable(0. } 493. ptInquiryCnf =(HCI_TInquiryCnf *) *ppMsg. CRemoteDevice device. 500.HCI_PAGE_SCAN_ENABLED | HCI_INQUIRY_SCAN_ENABLED). count = m_DevicesFound. void CRadioChatServerDlg::OnHciRemoteNameCnf(void **ppMsg) 538.GetAt(m_RemoteNameCounter). 536. HCI_ReqRemoteName(10. SCM_ReqRegister(0. ppMsg = ppMsg. AfxMessageBox("No device found"). 491. 508. 540.SCM_SECURITY_HANDLER). { 489. int count. } else { ShowAllDevicesFound().tPageScanPeriodMode. device. 582. 594. 597. device. 571. 596.Chapter 9: Bluetooth Programming 309 542.GetSize(). 588. 563. 580. 584. m_DevicesFound[m_RemoteNameCounter].GetSize(). 559. 578. device."%s". device. 583.SetName((CString)_T("UNKNOWN")).tAddress. if (count > m_RemoteNameCounter) { device = (CRemoteDevice) m_DevicesFound. sprintf(sName. 544.&ptRemoteNameCnf->tName). 562.tClockOffset ). 547. device. HCI_ReqRemoteName(10. 560. 561. 590.GetAt(m_RemoteNameCounter). } else { ShowAllDevicesFound(). 573. 576. m_RemoteNameCounter++. 574.SetName((CString)sName). 568. } } void CRadioChatServerDlg::OnScmConnectCnf(void **ppMsg) { . device. 575. 569.tPageScanMode. ptRemoteNameCnfNeg =(HCI_TRemoteNameCnfNeg *) *ppMsg. CRemoteDevice device. 579. if (count > m_RemoteNameCounter) { device = (CRemoteDevice) m_DevicesFound. 566. 586. 546. 554. 592. 589. count = m_DevicesFound. 577. 551.tPageScanPeriodMode. 595. 570. 558. 585. 564.GetAt(m_RemoteNameCounter).tAddress. } } void CRadioChatServerDlg::OnHciRemoteNameCnfNeg(void **ppMsg) { HCI_TRemoteNameCnfNeg *ptRemoteNameCnfNeg. device. 565. 593. 552. 549. 567. 548. m_DevicesFound[m_RemoteNameCounter].tPageScanMode. 581.tClockOffset ). 545. m_RemoteNameCounter++. 556. HCI_ReqRemoteName(10. 553. ptRemoteNameCnf =(HCI_TRemoteNameCnf *) *ppMsg. 572. 543. 591. int count. 555. 557. 587. device. count = m_DevicesFound. 550. SD_TConnectCnf *tConnectCnf = (SD_TConnectCnf *)*ppMsg. 620. 616. SCM_TConnectCnf *tConnectCnf = (SCM_TConnectCnf *)*ppMsg. SD_ReqServiceSearch (0. str. 603. SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 639. 615. ptSearchPatternList = (SD_TUuid*)VOS_Alloc((uint16) (ucNrOfUuids * sizeof(SD_TUuid))). uiMaxRecords. 625. m_ConnectionInfo. 610. } 627. void CRadioChatServerDlg::OnSdConnectCnfNeg(void **ppMsg) 628. 621. CString str. ptSearchPatternList[0]. 622. 640. CService service.tAddress = tConnectCnf->tAddress. uiMaxRecords = 6. void CRadioChatServerDlg::OnSdConnectCnf(void **ppMsg) 612. uint16 uiCurrentServiceRecordCount. 601. 623. 638. 642. ucNrOfUuids = 1. AfxMessageBox("connected"). void CRadioChatServerDlg::OnSdServiceSearchCnf(void **ppMsg) 635. //SRP_HEADSET_UUID.iResult). SD_TServiceSearchCnf *tServiceSearchCnf = (SD_TServiceSearchCnf *)*ppMsg. tConnectCnfNeg = tConnectCnfNeg.Format("Could not connect to SD .tAclHandle = tConnectCnf->tHandle. uint8 ucNrOfUuids. 624. Error %d". } 605.uiSdcHandle = tConnectCnf->uiSdcHandle. . AfxMessageBox("No Connection made"). uiCurrentServiceRecordCount = tServiceSearchCnf->uiCurrentServiceRecordCount. 646. 600. SD_TUuid *ptSearchPatternList. uint32 *pulSRHandles. 614. 626.uiUuid16 = SRP_SERIAL_GENERIC_SERIALPORT_UUID . { 629. &tServiceSearchCnf->ulServiceRecordHandleList. void CRadioChatServerDlg::OnScmConnectCnfNeg(void **ppMsg) 606. } 634. OnGetservices() . 617. tConnectCnfNeg->tHdr. 630. 633. MessageBox(str). pulSRHandles = (uint32*) VOS_Alloc(((uint16)(uiCurrentServiceRecordCount*sizeof(uint32)))). 619. m_ConnectionInfo. (void*)memcpy(pulSRHandles. 645. { 607. 644. 602. tConnectCnf = tConnectCnf. 609.uiSdcHandle. 599. { 613. 618. uint16 uiMaxRecords. 604.TUuid. m_ConnectionInfo. 608. 631. ptSearchPatternList[0]. m_ConnectionInfo. uint16 *puiAttributeIDList. 632.310 Chapter 9: Bluetooth Programming 598. ptSearchPatternList). ucNrOfUuids. 637. } 611. 641. { 636.eUuidType = SD_DET_UUID16. 643. uint8 ucNrOfAttr. SD_TConnectCnfNeg *tConnectCnfNeg = (SD_TConnectCnfNeg *)*ppMsg. AfxMessageBox("SD_ReqDisconnect(0. 658. SD_TServiceAttributeCnf *tServiceAttributeCnf = (SD_TServiceAttributeCnf *)*ppMsg. ReceiveServiceName(tServiceAttributeCnf). 657. 651. puiAttributeIDList[0] = BT_SERVICE_NAME(0). case 2: 681. void CRadioChatServerDlg::OnSdServiceAttributeCnf(void **ppMsg) 669.m_ConnectionInfo. 682. } 688. ReceiveServiceRecordHandle(tServiceAttributeCnf). 680. switch (tServiceAttributeCnf->tHdr. VOS_Free((void**)&pulSRHandles). puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). 653. m_ConnectionInfo. VOS_Free((void**)&puiAttributeIDList). 664.m_ServiceRecordHandle = tServiceSearchCnf->ulServiceRecordHandleList. MessageBox(str). 650. SD_ReqDisconnect(0. ucNrOfAttr = 1. CString str. } 660. 672. { 675. AskForServiceRecordHandle(). puiAttributeIDList). break. 685. AfxMessageBox("hai"). 679. void CRadioChatServerDlg::OnSdServiceSearchCnfNeg(void **ppMsg) 661. break. 673. pulSRHandles[0]. 666. 683.Chapter 9: Bluetooth Programming 311 647. m_ConnectionInfo. service. } 689.tConnectCnfNeg>tHdr.uiSdcHandle. tConnectCnfNeg = tConnectCnfNeg. (uiCurrentServiceRecordCount*sizeof(uint32))). 678. 654.ulServiceRecordHandle = tServiceSearchCnf->ulServiceRecordHandleList. void CRadioChatServerDlg::OnSdServiceAttributeCnfNeg(void **ppMsg) 690. CService service.SetAtGrow(m_ServiceCounter. . tConnectCnfNeg = tConnectCnfNeg.m_ConnectionInfo. str. SD_TServiceSearchCnfNeg *tConnectCnfNeg = (SD_TServiceSearchCnfNeg *)*ppMsg. case 1: 676. SD_ReqServiceAttribute(1. 659. 649.uiSdcHandle. ucNrOfAttr. 665.uiSdcHandle).uiSdcHandle)"). Error %d". 667. break. SD_TServiceAttributeCnfNeg *tConnectCnfNeg = (SD_TServiceAttributeCnfNeg *)*ppMsg. service. 671. 648. AfxMessageBox("sdser").m_SDCHandle = m_ConnectionInfo.Format("Service Search Confirm Negative. 677. default: 686. { 662. { 670. 684. } 668.uiSeqNr) 674. 655. 692. 656. 652.iResult). 693. 687. 663. m_ServicesFound. CString str. { 691.service). 739. 721. void CRadioChatServerDlg::OnDbmRegisterServiceCnf(void **ppMsg) 704. *ppMsg = NULL. Beep (1000. 0). 717. SCM_TConnectAcceptInd *ptConnectAcceptInd. } 703. SCM_SLAVE). 737. str. HCI_TInquiryEvt *ptInquiryEvt. 716. 723. 744. 726. 700. 734.200).tConnectCnfNeg>tHdr. { 747. { 720. ppMsg = ppMsg. ppMsg = ppMsg. 730. 706. SCM_RspConnectAccept((MSG_TMsg **)ppMsg. COM_ReqRegister(PROFILE_SERIAL. ptConnectAcceptInd->tAddress. 732. 695. 708. 725. tConnectCnfNeg = tConnectCnfNeg. void CRadioChatServerDlg::OnSdDisconnectCnf(void **ppMsg) 698. void CRadioChatServerDlg::OnConnectAcceptInd(void **ppMsg) 735. 701. MessageBox(_T("Could not register the service to DBM")). AfxMessageBox("star chat").200). AfxMessageBox("end chat"). DBM_TRegisterServiceCnf *ptRegisterCnf = (DBM_TRegisterServiceCnf *) *ppMsg. Beep (1000. SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. 742. 743. ptConnectAcceptInd =(SCM_TConnectAcceptInd *) *ppMsg. { 729. void CRadioChatServerDlg::OnDbmAddDescriptorCnf(void **ppMsg) 719. MessageBox(str). { 713. SCM_TConnectCnfNeg *tConnectCnfNeg = (SCM_TConnectCnfNeg *)*ppMsg. void CRadioChatServerDlg::OnDbmRegisterServiceCnfNeg(void **ppMsg) 712. SCM_POS_RESULT. tConnectCnfNeg = tConnectCnfNeg. } 733.Format("Service Attribute Confirm negative. . 696. 710. { 705. void CRadioChatServerDlg::OnDbmAddDescriptorCnfNeg(void **ppMsg) 728. 731. DestroyWindow(). } 745. { 699. m_pSerialPort->WriteProfile(ptRegisterCnf->ulDbmHandle). { 736.312 Chapter 9: Bluetooth Programming 694./* use this as sequence number */ 709. 740. error %d".iResult). 722. void CRadioChatServerDlg::OnHciInquiryEvt(void **ppMsg) 746. 702. 714. 707. } 718. 741. 738. } 697. OnSelservices(). MessageBox(_T("Could not register to Data Base Manager")). 715. 724. } 727. } 711. 757. 774. // remember some connection information 785. 797.tAclHandle = 0. 772. 784. device. 749.tClockOffset = ptInquiryEvt->tClockOffset. m_ConnectionInfo. void CRadioChatServerDlg::OnScmPincodeInd(void **ppMsg) 761. 786. ptInquiryEvt =(HCI_TInquiryEvt *) *ppMsg.tAclHandle = tConnectEvt->tHandle. tConnectEvt = tConnectEvt. CRemoteDevice device. // connection is removed 799. 773. 780. 794. 756.tCod = ptInquiryEvt->tCod. 770. 791. // Disable the get devices button on the screen 789. device. SCM_TConnectEvt *tConnectEvt = (SCM_TConnectEvt *)*ppMsg. void CRadioChatServerDlg::OnScmDisconnectEvt(void **ppMsg) 795. device. } 758. 788. SCM_TPincodeInd *ptPincodeInd. PINCODE_LENGTH). // m_Inquiry. // because you can not do a inquiry when a connection has been established 790.tPageScanRepMode = ptInquiryEvt->tPageScanRepMode.tAddress = tConnectEvt->tAddress. 751. device. 771. 802. SCM_POS_RESULT. // so we will end also this sequrity application 801. 750. 793. 755. ptPincodeInd->tAddress. 777. 767. m_ConnectionInfo. device. ppMsg = ppMsg. { 796. { 779. 776. device. /* request for a PIN-code from the remote side. 753. } 775. // this event is received because we are also registerd as SCM_MONITOR_GROUP 782.tPageScanMode = ptInquiryEvt->tPageScanMode. 759. } 792. .EnableWindow(FALSE). ptPincodeInd =(SCM_TPincodeInd *) *ppMsg. 754. 787.tPageScanPeriodMode = ptInquiryEvt->tPageScanPeriodMode. 798. { 762. 766. 764. /* Reply positive. */ 769. SCM_RspPincode((MSG_TMsg **)ppMsg. AddDevice(device). 800. 763. 783. 760. 752. 781. void CRadioChatServerDlg::OnScmConnectEvt(void **ppMsg) 778.Chapter 9: Bluetooth Programming 313 748. m_ConnectionInfo.tAddress = ptInquiryEvt->tAddress. 768. _tPincode. */ 765. char* cpVerStr = NULL.314 Chapter 9: Bluetooth Programming 803. 819. cpStr[3] = ((char)0). /* Read PDL attributes */ 854. 804. 856. 852. 832. } 814. 836. ptVersionCnf = (COM_TVersionCnf *) *ppMsg. 842. 833. 823. 806. int8 iCharCount = 9. 834. } 839. } 805. 857. 841.DoModal(). 816. 822. { 829. 837. void CRadioChatServerDlg::OnHciStartCnf(void **ppMsg) 807. 840.PORTSETTINGS). 855. 811. void CRadioChatServerDlg::AskForServiceName() 849. ucNrOfAttr = 1. HCI_TStartCnf *ptStartCnf = (HCI_TStartCnf *)*ppMsg. iCharCount++. OnCloseapplication(). 835. 838. 820. 830. { 850. 844. 827. . 813. 843. ptStartCnf = ptStartCnf. 821. uint8 ucNrOfAttr. 847. puiAttributeIDList[0] = BT_SERVICE_NAME(0). do 828. 848. COM_TVersionCnf* ptVersionCnf. 809. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))). { 808. void CRadioChatServerDlg::OnComVersionCnf(void **ppMsg) 817. 831. char cpStr[3]. 825. 845. 810. cpStr[iCharCount-10] = cpVerStr[iCharCount]. CAboutDlg Abodlg. 824. 853. 826. { 818. 851. HCI_ReqConfigurePort(0. uint16 *puiAttributeIDList. 815. 812. }while(iCharCount <= 11). 846.SetVersionText((CString) cpStr). Abodlg. cpVerStr = &ptVersionCnf->cVersion. //Abodlg. ucNrOfAttr. . 890. &service. m_ServiceCounter++.uiAttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount.m_pAttributeData[6]] = NULL. } 863. { 867. 883. 886. 891. 902. puiAttributeIDList). 871. m_ConnectionInfo. 892. /* +1 for the NULL char */ 888. 860. 897.m_pAttributeData[6]). 859. 878. service = m_ServicesFound.m_pServiceName. 903. */ 876.m_AttributeListByteCount). 885. 884. 880. m_ConnectionInfo. 865. 877. // m_ConnectionInfo.SetAt(m_ServiceCounter.uiSdcHandle. 868.ulServiceRecordHandle. CService service. service. VOS_Free((void**)&puiAttributeIDList). /* the name of the profile is received */ 870.m_pAttributeData = (uint8*) VOS_Alloc(service. 894. &tServiceAttributeCnf->ucAttributeData.m_pAttributeData[7]. 899. service. */ 900. 873. /* attribute message has the following format */ 872. SD_DET_SEQUENCE8|Lenth|SD_DET_UINT16|byte0|byte1|SD_DET_STRING8 |length of string|"Headset" 875. m_ConnectionInfo. (void*)memcpy(service. 882. (void*)memcpy(service. 889.m_AttributeListByteCount = tServiceAttributeCnf>uiAttributeListByteCount.m_pServiceName = (char*) VOS_Alloc(service. 869. service. 861. 862. m_ConnectionInfo. /* 874. 864. // service.pucAttributeData = (uint8*) VOS_Alloc(service.uiAttributeListByteCount). 887.GetAt(m_ServiceCounter). service. 896.m_AttributeListByteCount). 898.m_pServiceName[service.m_pAttributeData[6] + 1).m_pAttributeData.Chapter 9: Bluetooth Programming 315 858. 901.m_AttributeListByteCount). SD_ReqServiceAttribute(0. m_ServicesFound.service). 879. void CRadioChatServerDlg::ReceiveServiceName(SD_TServiceAttributeCnf *tServiceAttributeCnf) 866.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. // service. 895. service. /* also remember this in the connectioninfo class. &tServiceAttributeCnf->ucAttributeData.pucAttributeData. 904. // Remember necessary items. 881. 893. (void*)memcpy(m_ConnectionInfo. 905. 936. (void*)memcpy(service. void CRadioChatServerDlg::AskForServiceRecordHandle() 921. puiAttributeIDList[0] = BT_SERVICE_RECORD_HANDLE. 952. /* +1 for the NULL char */ 907. 930.m_pAttributeData[7]. 923. 949. 927. 938. 924. 937.m_SDCHandle = tServiceAttributeCnf->uiSdcHandle. /* Remember necessary items. service. 954. } 941. 942. .pcServiceName = (int8*) VOS_Alloc(service.m_pAttributeData = (uint8*) VOS_Alloc(service. m_ConnectionInfo. 932. 929. 914.m_pAttributeData[6] + 1). 909. CService service. 933. service = m_ServicesFound. 943. SD_ReqServiceAttribute(2. puiAttributeIDList = (uint16*)VOS_Alloc((uint16)(ucNrOfAttr*sizeof(uint16))).m_AttributeListByteCount).ulServiceRecordHandle. 919. 951.m_pAttributeData[6]). 916. m_ConnectionInfo. void RadioChatServerDlg::ReceiveServiceRecordHandle (SD_TServiceAttributeCnf *tServiceAttributeCnf) 944.pcServiceName. puiAttributeIDList[1] = BT_PROTOCOL_DESCRIPTOR_LIST. service.m_AttributeListByteCount). 913. 920. puiAttributeIDList). 953. 912. 931. { 945. 940. ucNrOfAttr = 2. &tServiceAttributeCnf->ucAttributeData. uint16 *puiAttributeIDList. service. { 922. VOS_Free((void**)&puiAttributeIDList). &service. /* Read PDL attributes */ 926. */ 950.316 Chapter 9: Bluetooth Programming 906. 915. (void*)memcpy(m_ConnectionInfo. 908. ShowAllServicesFound(). 928. uint8 ucNrOfAttr.m_pAttributeData[6]] = NULL. 955. 946. //m_SelService.EnableWindow(TRUE). 935.m_AttributeListByteCount = tServiceAttributeCnf->uiAttributeListByteCount. // m_ConnectionInfo. 939. ucNrOfAttr. service.pcServiceName[service. 948. m_ConnectionInfo. 917. 947. 934.m_pAttributeData. 911.uiSdcHandle. 925.GetAt(m_ServiceCounter-1). // service. 910. } 918. 977. 984. DBM_ReqUnRegisterService(3. { 1010. 959.pucAttributeData. void CRadioChatServerDlg::OnScmDeRegisterCnf(void **ppMsg) 991. 962. if (m_ConnectionInfo. 994. /* also remember this in the connectioninfo class. { 979. 968. case 1: // DeRegister from SECURITY HANDLER 997. m_ServicesFound. break. m_ConnectionInfo. 965. } 969. 976. 999. { 1008. 1000.Chapter 9: Bluetooth Programming 317 956. } 988. SCM_ReqDeRegister(2. case 2: // DeRegister from MONITOR GROUP 1001. // De Register from the component 983.tAclHandle>0) 1009. 990. { 1004.ulDbmHandle > 0) 1003. // unregister from DBM 1002. 957. 966.uiSeqNr) 995. 970. // First SCM 985. { 996. } 1006. 967. // Close the ACL Connection . if (m_ConnectionInfo.uiAttributeListByteCount = tServiceAttributeCnf->uiAttributeListByteCount. 989. SCM_TDeRegisterCnf *ptDeRegisterCnf = (SCM_TDeRegisterCnf *) *ppMsg. m_ConnectionInfo. 975.uiAttributeListByteCount). 971. 963. 972. 974. SCM_ReqDeRegister(1. 982. 958.m_ConnectionInfo. 960. 987. 993.service). (void*)memcpy(m_ConnectionInfo. */ 964.SCM_SECURITY_HANDLER). { 992. else 1007. switch (ptDeRegisterCnf->tHdr. 986. // unregister now from the monitor group 998.SetAt(m_ServiceCounter-1. m_ServiceCounter++. &tServiceAttributeCnf->ucAttributeData. 961. 980. 1005.ulDbmHandle).SCM_MONITOR_GROUP). // Application is about to close 981. void CRadioChatServerDlg::OnCloseapplication() 978. 973. 1065. 1018. 1058. 1051. 1019. 1048. 1060. 1032. 1042. 1034. 1027. } void CRadioChatServerDlg::OnScmDisconnectCnf(void **ppMsg) { ppMsg = ppMsg. // let the user know MessageBox(_T("Not possible to UnRegister from DBM")). 1061. 1057. 1028.m_ConnectionInfo. 1020. . } } void CRadioChatServerDlg::OnDbmUnRegisterServiceCnfNeg(void **ppMsg) { ppMsg = ppMsg. 1041. 1046. 1012. 1062. 1023. DestroyWindow(). 1050. } else { DestroyWindow(). 1044. 1024. 1037. } } void CRadioChatServerDlg::OnScmDeRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. 1026. 1033. default: break. 1064. 1038.m_ConnectionInfo. 1047. 1053. } } break. 1049. 1025. 1031. 1066.tAclHandle>0) { SCM_ReqDisconnect(0. 1030. 1035. 1036. // Close the application if (m_ConnectionInfo. 1059. SCM_ReqDisconnect(0.tAclHandle). 1029. 1017. 1063. 1054. 1052. 1055. 1039. 1021. } else { //Close the window program DestroyWindow(). } void CRadioChatServerDlg::OnDbmUnRegisterServiceCnf(void **ppMsg) { ppMsg = ppMsg. 1015. 1013. DestroyWindow().318 Chapter 9: Bluetooth Programming 1011. 1022. 1014.tAclHandle). 1056. 1016. 1045. 1040. MessageBox(_T("Could not unregister from SCM")). 1043. 1107. 1102. 1088. 1073. 1119. 1087. 1106. 1114. 1070. 1076. 1068. 1093. 1082. iFound = m_ServicesFound.InsertItem(device.tAclHandle = 0. 1108. 1092. 1118. i++) { device = m_DevicesFound. 1084. 1078.GetSize().GetAt(i). 1101. 1100. 1111. 1079. 1104. 1105. 1112. 1094. m_ServicesFound. i < iFound. AfxMessageBox("device1"). for (i=0. } void CRadioChatServerDlg::AddService(CService service) { m_ServicesFound. DestroyWindow(). int iFound. // connection is removed // so we will end also this sequrity application m_ConnectionInfo. 1083. 1091. 1090.Chapter 9: Bluetooth Programming 319 1067. } void CRadioChatServerDlg::ShowAllDevicesFound() { CRemoteDevice device. 1103. 1113. } void CRadioChatServerDlg::OnScmDisconnectCnfNeg(void **ppMsg) { ppMsg = ppMsg. 1081. } void CRadioChatServerDlg::ShowAllServicesFound() { CService service. } BOOL CRadioChatServerDlg::DestroyWindow() { // TODO: Add your specialized code here and/or call the base class return CDialog::DestroyWindow(). } } void CRadioChatServerDlg::AddService(CString sService) { CService service(sService). 1095. 1122. int iFound. 1075. 1071. 1074. 1120. 1116. 1069. 1072. 1096. 1099. 1085. 1077.Add(service). hdevice1=m_tree.i. i++) { . iFound = m_DevicesFound. 1117. i < iFound. 1121. TVI_SORT).Add(service).i.GetSize(). 1110. 1086. OnSelDevice(). 1109. 1097. for (i=0. 1115. 1098. 1080. // connection could not be removed removed MessageBox(_T("Could not remove ACL connection")). hPA. 1089.GetAddress(). DestroyWindow(). 1133. m_ConnectionInfo. 1166. 1158. 1125. SCM_R1. 1142.tAddress. 1168. 1134. 1160.GetAt(0). 1169. 1174. 1171. m_tree. 1173. 1130. 1136. 1132.tInquiryLength.Add(device). 1167. 1163. 1176. Sleep(100). 1146. 1157.tLap. 1151. HCI_TNrOfResponses tNrOfResponses = 0. 1165. m_ConnectionInfo.m_ConnectionInfo. 1128.TVI_LAST). 1138. 1152. SCM_MANDATORY_PAGE_SCAN_MODE. 1148. device = m_DevicesFound. 1126. 1170.0x33}. 1143.m_ServiceRecordHandle. } void CRadioChatServerDlg::OnGetservices() { m_ServiceCounter = 0.GetAt(i). m_ConnectionInfo. MessageBox(_T(" RFCOMM connection")).200).hdevice1. } . 1140. service = m_ServicesFound. } void CRadioChatServerDlg::OnSelDevice() { CRemoteDevice device. 1159. SCM_DM1. 1144. 1156. 1135. SCM_ReqConnect(0.tAclHandle). 1139. service = m_ServicesFound.tAddress = device.tNrOfResponses).GetService(). 1131.0x8B. 1129. 1177.SD_DEFAULT_MFS. Beep (1000. SCM_NOT_ACCEPT_ROLE_SWITCH). 1124. 1137. } void CRadioChatServerDlg::OnInquiry() { HCI_TLap tLap = {0x9E. } void CRadioChatServerDlg::OnSelservices() { CService service.tAddress. 1127. 1172. } void CRadioChatServerDlg::OnComConnectCnf(void **ppMsg) { COM_TConnectCnf *ptConnectCnf = (COM_TConnectCnf *) *ppMsg. device. 1178. 1141. 1154.200). 1153. 0. 1162.uiRFCommHandle = ptConnectCnf->uiHandle. 1150. 1149.ulServiceRecordHandle = service. DBM_StackDB). 1164. HCI_TInquiryLength tInquiryLength = 2. HCI_ReqInquiry(1.GetAt(0). SD_ReqConnect(0. 1175.320 Chapter 9: Bluetooth Programming 1123. Beep (1000. DBM_ReqRegisterService(0. 1145. 1161. } } void CRadioChatServerDlg::AddDevice(CRemoteDevice device) { m_DevicesFound. 1155.InsertItem(service. 1147. } void CRadioChatServerDlg::OnComFillPdlCnf(void **ppMsg) { COM_TFillPdlCnf *ptFillPdlCnf = (COM_TFillPdlCnf *)*ppMsg. 1206. } void CRadioChatServerDlg::OnButton2() { SCM_ReqRegister(0. ptMsg = ptMsg. MessageBox(_T("Could not create a RFCOMM connection")). 1200. 1215. DestroyWindow(). 1193. 1227. 1224. MessageBox(_T("Not possible to register to SCM")). 1214. void CRadioChatServerDlg::OnComConnectCnfNeg(void **ppMsg) { COM_TConnectCnfNeg *ptConnectCnfNeg = (COM_TConnectCnfNeg *) *ppMsg. 1196. 1198. 1182. } void CRadioChatServerDlg::OnSdsStartCnf(void **ppMsg) { CString sAddress. } void CRadioChatServerDlg::OnComRegisterCnf(void **ppMsg) { COM_TRegisterCnf *ptRegisterCnf = (COM_TRegisterCnf *)*ppMsg. ptStartCnf =(SDS_TStartCnf *) *ppMsg. 1212. 1186. 1194. ptRegisterCnf->ucServerChannel.SCM_MONITOR_GROUP). } void CRadioChatServerDlg::OnComRegisterCnfNeg(void **ppMsg) { ppMsg = ppMsg. m_ConnectionInfo. 1213.Chapter 9: Bluetooth Programming 321 1179. ptConnectCnfNeg = ptConnectCnfNeg. 1183. 1189. 1228. 1207. 1226. 1197. CString sName. 1217. 1180. 1208. SDS_TStartCnf *ptStartCnf. 1221. 1203. 1192. 1229. char *pcName = NULL. 1191. (uint16)m_pSerialPort->GetSRPHandle()). DestroyWindow(). 1233. 1223. m_pSerialPort->GetProfileName(&pcName). } void CRadioChatServerDlg::OnScmRegisterCnfNeg(void **ppMsg) //2 { SCM_TRegisterCnfNeg *ptMsg = (SCM_TRegisterCnfNeg *) *ppMsg. m_RFServerChannel = ptRegisterCnf->ucServerChannel.100). 1234. 1219. 1190. 1218. } void CRadioChatServerDlg::OnScmRegisterCnf(void **ppMsg) //2 { ppMsg = ppMsg. 1232. 1216. } void CRadioChatServerDlg::OnComFillPdlCnfNeg(void **ppMsg) . ptFillPdlCnf = ptFillPdlCnf. m_pSerialPort = new CRS232(PROFILE_SERIAL). 1222. 1205. COM_ReqFillPdl(PROFILE_SERIAL. 1202. 1184. 1187. SDS_ReqStart(0). 1201. 1230. 1199. 1209. 1188. 1220. 1231. 1181. 1204. 1225. 1185. 1195.uiRFCommHandle = 0. 1211. 1210. Beep(1000. MessageBox(_T("Not possible to register to RFCOM")). for (i=0.i. 1270. } 1260. 1286. 1277. index++. { 1236. COM_TConnectInd *tConnectInd = (COM_TConnectInd *)*ppMsg. 1265. { 1243. i < iCount. 1244. 1245. iCount = (uint16) m_InputChat. 1259. m_ChatArea. } 1264. 1262. void CRadioChatServerDlg::OnComConnectInd(void **ppMsg) 1242. { 1255. { 1273. 1240. 1271.pucData. { 1276. 1263. BOOL CRadioChatServerDlg::PreTranslateMessage(MSG* pMsg) 1252.SetWindowText(_T("")). return CDialog::PreTranslateMessage(pMsg). } 1284. MessageBox(_T("Not possible to fill PDL for RF COM")). { 1253. { 1288.322 Chapter 9: Bluetooth Programming 1235. COM_RspConnect((MSG_TMsg **)ppMsg. *ppMsg = NULL. { 1267. COM_DataSend(0. m_RFCommHandle = tConnectInd->uiHandle. 1282. 1249. if (pMsg->wParam == VK_RETURN) 1256. 1239. AfxMessageBox("In Comm Connection Ind"). void CRadioChatServerDlg::HandleReturn() 1266. DestroyWindow(). 1250. pucData = COM_DataAlloc((uint16)(iCount + 1)).(uint16)(iCount + 1)). pucData[i] = 0. COM_TDataInd *tDataInd = (COM_TDataInd *)*ppMsg. 1268. if (pMsg->message == WM_KEYDOWN) 1254. 1237. i++) 1275. pucData[i] = sChatStr[i].COM_POS_RESULT. HandleReturn().80). 1269.(CString)sChatStr). uint8 *pucData. } 1261. ppMsg = ppMsg. CHAR sChatStr[80].GetWindowText(sChatStr. uint16 iCount. 1247. . 1280. { 1257. 1289. 1274. return FALSE. tConnectInd->uiMaxFrameSize). 1283. 1238. } 1251. } 1278. 1281. 1246. void CRadioChatServerDlg::OnComDataInd(void **ppMsg) 1287.InsertString(index. 1248. uint8 *pucData. if (iCount > 0) 1272. } 1241. m_InputChat. 1258. 1279. } 1285.m_RFCommHandle. the command to read the incoming data from the client is issued.COM_POS_RESULT. 1300. &uiLength.(CString)sData). 1293. pucData = COM_DataExtract((MSG_TDataMsg *)*ppMsg. The response is sent to the client to indicate that the data has been received. i < uiLength. the function HandleReturn will be invoked to send the data to the remote device. the code of file transfer application has been reused for this example. } m_ChatArea. 1304. COM_RspData(tDataInd->tHdr. The screen has one edit box to enter messages and a list box to show the exchange of messages between the server and the clients. ♦ Lines 1286–1305: When COM DATA IND event is fired by the BLUETOOTH module. 1294. and HCI programming. packet sizes supported for ACL and SCO links. index++. uint16 uiLength. the screen in Figure 9-10 appears. Using Ericsson’s Bluetooth PC Reference Stack and Bluetooth module. . 1298. Summary In this chapter. &uiHandle). 1303. 1296. The data that has been read is added to the chat area in the dialog box.uiHandle). ♦ Lines 1265–1284: The data entered in the chat Input is retrieved and sent to the remote BLUETOOTH peer device. we studied how to create a full-fledged application for file transfer using RFCOMM. 1297. } CHAR sData[80]. ♦ Lines 1–1250: Explained in RadioFileServerDlg. version number.InsertString(index. Code Output When the application is built. how to do loopback testing and also how to obtain the remote Bluetooth device address.Chapter 9: Bluetooth Programming 323 1290. 1295. for (i=0.cpp file. two desktop PCs become Bluetooth enabled. ♦ Lines 1251–1263: As soon as the Enter key is pressed. int i. 1305. Then. 1299.ucSeqNr. The differences are explained below. The API calls provided in the Reference stack enable us to access the services of different layers. uint16 uiHandle. The data is displayed in the chat area list box. We also discussed how the file transfer application could be extended to create a chat application. which can be accessed by other devices in the piconet. 1302. Code Description To the greatest extent possible. SDP. 1292. we discussed the programming aspects of Bluetooth. 1291. 1301. i++) { sData[i] = pucData[i]. The SDP programming example has been used to demonstrate how to register services on a Bluetooth device. The HCI programming example illustrated how the API calls can be used for the stack to communicate with the Bluetooth module to obtain the Bluetooth device address. the protocol stack needs to be ported to that device. if the source code for the stack is available. All these applications are built using the API calls and the sample code given in this Bluetooth SDK. The code given here covers the most important API calls for creating data applications using the Ericsson’s PC Reference stack. For Bluetooth enabling of a device. Reusing the file transfer code to the maximum possible extent. we also presented chat application implementation. one can easily port the code on to any platform. With a thorough understanding of the protocol implementation discussed in this chapter.324 Chapter 9: Bluetooth Programming Figure 9-10: Output of the Server Module This application can be easily extended to demonstrate WAP with Bluetooth applications. . These traditional mobile systems can be called single cell systems. a city) catered to an area of about 50 km radius. A channel consists of two frequencies: one frequency for communication from the base station to the mobile terminal (called downlink) and one frequency for communication from the mobile terminal to the base station (called uplink). Development of sophisticated mobile devices and high data rate mobile networks are paving the way for exciting times — wireless network multi-media services that provide “anywhere. and tools for content development. one channel is used. . According to market projections. For communication by one mobile terminal. thus we won’t discuss any programming aspects of 3G. which are currently operational. Even though voice continues to be the killer application on mobile communication systems. we study the 2. The disadvantages of this type of system are: ♦ Very powerful transmitters are required at the base station and the mobile terminals — high power transmitters are costly.5G) and third generation (3G) networks. Then. We briefly review the underlying telecommunication technologies but focus more on content development to use the 3G technologies. which support higher data rates to provide multimedia applications. To provide the 3G services. and an antenna. The challenge is to develop systems that can support high data rates without throwing away the existing infrastructure. This chapter gives the basic theory of 3G technologies. there will be one billion wireless Internet Access Devices by the year 2003. advanced languages. To provide these services will be a technological challenge because the operators have already installed billions of dollars worth of equipment. we study the various “generations” of wireless networks. mobile systems were structured like TV broadcasting systems. The second generation systems.Chapter 10 An Overview of 3G The need to provide communication facilities for people on the move led to the development of cellular mobile communication systems. You must understand these technologies if you want to take up content development for 3G networks. are digital but support low data rates. We review these aspects in this chapter. Principles of Cellular Mobile Communications During the initial days of mobile communications. We study the architecture of the most popular second generation wireless system — Global System for Mobile Communications (GSM). The mobile terminals were generally carmounted with a transmitter. which was standardized in Europe but adapted by many other countries. The first generation wireless networks were analog systems. receiver. which presently supports only low data rates. anytime” communication will soon be a reality. based on the subscriber density in the region. A base station with a very powerful transmitter located at the highest point in a service locality (for example. In the next chapter we will study programming aspects to develop sophisticated applications over 3G networks. Each base station is assigned a number of channels. the demand for mobile data services is increasing rapidly. as the entire coverage area is only one cell.5 Generation (2. we need sophisticated mobile devices for subscribers to access the Internet content. In this chapter. the other option is chosen. use one of these channels for communication. but it has many advantages: ♦ Because of the low power required at each base station. To overcome all the above limitations. the service area is divided into “cells” as shown in Figure 10-1. if a mobile subscriber moves from one cell to another cell while the call is in progress. When the mobile terminal is at the edge of one cell. Figure 10-1: Multi-cell system with service area divided into cells (seven-cell cluster) In a multi-cell system.326 Chapter 10: An Overview of 3G ♦ The capacity of the system is very low. multi-cell systems have been developed. Each cell is represented by a hexagon. This process is called handover. A cell is the basic geographic unit in a mobile system. ♦ The number of subscribers who can make calls simultaneously is limited. and so on) or man-made terrain (such as buildings and such). there are two options: either the call has to be dropped or the mobile terminal has to switch to the one of the channels used in the new cell. The call will not be dropped. lakes. Because dropping a call is not acceptable. ♦ The size of the mobile terminal is large because of the high-power transmitter. In a multi-cell system. as well as the mobile terminals. as well as for the mobile phones. low cost systems can be developed. when they are in that cell. . but conversation can continue using the new channel. Multi-Cell Wireless Networks Bell Labs developed the concept of multi-cell systems in the early 1970s. depending on the terrain: natural terrain (such as mountains. Certainly. Each cell is allocated some channels and all the mobiles. The main attraction of this approach is that it requires of very low power transmitters at the base stations. as only a fixed number of channels are available for a service area (because of the limited radio spectrum). and the mobile terminal monitors the signal strengths of the channels in the adjacent cells and switches to the channel for which signal strength is high. the signal strength goes down. Each cell will have a base station. So. The size of the cell may vary. ♦ Expansion of the system to cater to a higher number of subscribers is very difficult. and the Nordic countries were the first to introduce commercial multi-cell mobile systems in 1981. with a low power transmitter. handover introduces complexity in cellular mobile communication. The size of the mobile terminals also are smaller. two adjacent cells cannot use the same channel because there will be interference. lakes. in practice. Cellular System Design Issues When we take on the complicated task of designing a cellular communications system. some areas may not have radio coverage. variable power levels can be used for communication. The cellular operator has to ensure that no shadow regions exist. Radio Engineering Based on the terrain of the service area (keeping in view the hills. high-rise buildings) and the likely subscriber density in different areas. no channels are reused within a cluster. each cell is assigned a group of radio channels and the same channels can be reused in another cluster of cells. The hexagonal cell is only a theoretical representation. cells denoted by “2” in all three clusters can use the same set of channels. the cells will be split. at the outset of development. the same channels can be reused provided there is a minimum separation distance between the cells using the same channels. such regions are called shadow regions. In Figure 10-1. and the frequency reuse pattern is reworked out. cells can be of different sizes. and as the subscriber capacity increases. Frequency Allocation and Frequency Reuse For each base station located in a cell.Chapter 10: An Overview of 3G 327 ♦ Depending on the distance between the mobile terminal and the base station. Shadow Regions Because of the terrain. or at least that their area is minimized. ♦ The cell size is not fixed. Cell Splitting For economic reasons. a seven-cell cluster is shown. mobile calls are dropped. A mobile operator has to obtain the frequency allocation from a national authority. thereby reducing the power requirements and hence. In urban areas with high subscriber density. In shadow regions. The trunk capacity between the mobile switching system and the PSTN switch has to be decided based on the traffic considerations. The number of channels is based on the subscriber capacity in that locality and the maximum number of simultaneous calls that should be supported. and in rural areas cell size can be large (as large as 30 kilometers). Though adjacent cells cannot use the same channels. a number of channels (pairs of frequencies) have to be assigned. a cell can be split and new base stations can be installed. the cellular service provider does not design the cellular system with small cells. The service provider may have large cells to start with. If the subscriber capacity or traffic increases in a cell over a period of time. The concept of clusters is of importance here. there is a limit on the number of simultaneous calls. we must address many issues. and so on. cell size can be small (as small as 500 meters). . Cluster is a group of cells. the service area has to be divided into different cells. Some important issues are discussed in this section. the battery requirements of the mobile terminals. there may be overlaps of the cells and some small regions may not be covered by the radio. A radio survey is carried out to find out the best location for installing the base stations and to ensure maximum possible coverage. PSTN Connectivity The mobile network is connected to the Public Switched Telephone Network (PSTN) to enable normal telephone subscribers to be contacted by the mobile subscribers and vice versa. Cells denoted by “1” in all the three clusters can use the same set of channels. In frequency reuse. more base stations will be installed. ♦ Based on the number of channels allocated for each cell. and Africa. The next (or third) generation (3G) systems evolve from the GSM systems in most of the countries. but a large bandwidth is required to transmit information and all users can transmit simultaneously. These wireless networks were based on proprietary protocols developed by various equipment manufacturers. which are presently operational. multiple subscribers share a radio channel. These systems were known as First Generation (1G) systems. which use CDMA technology. are known as second generation (2G) wireless networks. ♦ Personal Digital Cellular (PDC) system and Personal Handy System (PHS) are operational in Japan. which use TDMA technology. These systems. the operator has to monitor the traffic continuously to check whether calls do not materialize because of network congestion. ♦ Global System for Mobile Communication (GSM) systems. in which data is transmitted. limited spectrum.328 Chapter 10: An Overview of 3G Traffic Analysis As soon as the mobile communication system is operational. digital systems were developed. ♦ IS 95A-based systems operational in North America. . These systems were hardly used for data communication. in 1983 the European Telecommunications Standards Institute (ETSI) formed the Groupe Speciale Mobile (GSM). the entire system bandwidth is made available to each user. and Middle East in addition to Europe. the acronym GSM now means Global System for Mobile Communications. Out of all the previous systems. Second Generation Wireless Networks To overcome the problems associated with the 1G systems. Africa. First Generation Wireless Networks In the 1980s. In TDMA systems. poor data communication support. Global System for Mobile Communications To facilitate roaming from one country to another within Europe while using the same mobile terminal. To avoid interference between the data of the subscribers. GSM systems are operational in Europe. Each subscriber is allocated a time slot. In case of network congestion. The 2G networks can be broadly categorized as Time Division Multiple Access (TDMA) systems and Code Division Multiple Access (CDMA) systems. The 2G systems that are still operational are: ♦ Interim Standard (IS) 54/136-based systems operational in North America. which use TDMA technology. These systems are no longer operational in North America and Europe. and minimal privacy. Some of the 1G systems deployed in North America and Europe were: ♦ Nordic Mobile Telephony (NMT 450) system operating in 450 MHz band since 1981 ♦ Advanced Mobile Phone System (AMPS) operating in 800/900 MHz band since 1983 ♦ Total Access Communication System (TACS) operational since 1985 ♦ Nordic Mobile Telephony (NMT 900) operating in 900 MHz band since 1986 The drawbacks of these analog cellular systems are: low calling capacity (about 55 calls/cell). this body was formed to develop standards for mobile communication systems. wireless networks for mobile communications systems were deployed in various countries. the GSM system has the largest installation base. but are in operation in some developing countries in Africa and Asia. each subscriber transforms the data using a special code. Because the standard has been adapted widely by many countries in Asia. Asia. In CDMA systems. capacities have to be enhanced. which is exactly four times the RF frequency shift.833 Kbps. In this time slot he will send his data and then wait for the next time slot. ♦ Signaling: Unlike telephone networks. in GSM a separate signaling network is used for carrying signaling information.Chapter 10: An Overview of 3G 329 The Memorandum of Understanding for GSM was signed by 17 European operators and manufacturers in 1987.and so forth) is sent in the same channel as the voice. The subscriber gets the time slot again after the others finish their transmissions. which he will get after the seven others finish transmitting their data in their time slots. where the bit rate is exactly four times the frequency shift. the quality of the speech is low compared to the voice quality in a normal telephone network. ♦ A higher calling capacity per cell (about 125 calls per cell) as compared to analog systems (about 55 calls per cell) ♦ Support for international roaming ♦ In addition to voice services. 1s and 0s are represented by shifting the RF carrier plus or minus 67. Thanks to advances in microelectronics. the radio channels are . The GMSK is a special form of Frequency Shift Keying (FSK). GSM handsets now go into pockets. speech is not transmitted at 64 Kbps data rate (as in normal telephone networks) but at 13 Kbps. ♦ Speech coding: To conserve radio spectrum. 1800 MHz band has been allocated with 1710 – 1785 MHz for uplink and 1805 – 1880 MHz for downlink. Send Mobiles” because of the complexity involved in developing handsets. such as better noise immunity and better data capability. The systems operating in 1800 MHz band are referred to as DCS 1800 (Digital Cellular System 1800). each subscriber will transmit his data in bursts. In TDMA system.708 kHz. As the modulation spectrum is reduced by applying a Gaussian pre-modulation filter to avoid spreading of energy into adjacent channels. thereby paving way for competition. network elements manufactured by different equipment vendors can work with one another. data services are also supported. and the commercial systems were launched in 1992. ♦ Duplex distance (distance between uplink and downlink frequencies): 45 MHz ♦ Channel spacing (between adjacent carrier frequencies): 200 kHz ♦ Modulation: Gaussian Minimum Shift Keying (GMSK). thus security can be easily built into the system and GSM has all the advantages of the digital communication systems. both network operator and the subscriber benefit from this. various tones. In other words. in time slots which he gets periodically. ♦ Because the interfaces are standardized. The first trial version of GSM was developed in 1991. ♦ Transmit data rate (over the air bit rate): 270. ♦ Access method: Time Division Multiple Access (TDMA) with eight time slots. So. such as ring-back tone. Each subscriber is allocated a small time slot during which he can transmit his data. where the signaling information (digits dialed. As the 900 MHz band got congested. the modulation is called Gaussian MSK (GMSK). is called the Minimum Shift Keying (MSK). FSK modulation. Because of low data rate. During the initial days of GSM. Prominent features of GSM The most prominent features of GSM are: ♦ GSM is based on digital technology. the same frequency is shared by eight subscribers. GSM specifications The broad specifications of the GSM system are as follows: ♦ Frequency band: 900 MHz band (890 – 915 MHz for uplink and 935 – 960 MHz for downlink). The acronym GSM used to be jokingly referred to as “God. many were skeptical about its commercial viability because of the complex protocol architecture. to forward a call to another mobile handset or a land line ♦ Blocking outgoing calls ♦ Blocking incoming calls. In addition to the normal telephony services. which emulates the function of a Private Branch Exchange (PBX). which gives an estimate of the call charges based on time ♦ Call hold. GSM system architecture The GSM architecture is shown in Figure 10-2. the following services are also supported: ♦ Facsimile (fax) transmission through a special interface provided to the handsets. the message will be stored in a message center and sent to the handset after it is turned on or when it is within the coverage area. accident information. A pre-defined group of mobile handsets form the equivalent of PBX. and so forth. to notify an incoming call when a conversation is in progress ♦ Multi-party service to provide conferencing facility ♦ Calling Line Identification Presentation (CLIP) to display the telephone number of the calling party ♦ Closed User Group (CUG). hence the radio spectrum is used efficiently. ♦ Cell broadcast can transmit maximum of 93 characters to all the handsets in a particular cell. ♦ Short Message Service (SMS) to transmit a maximum of 160 alphanumeric characters. ♦ Voice mail ♦ Fax mail The GSM system also supports the following supplementary services: ♦ Call forwarding. .330 Chapter 10: An Overview of 3G used only for carrying out voice traffic. All incoming or only incoming calls when roaming outside an operator’s region can be blocked. The signaling used in GSM is called Signaling System 7 (SS7). ♦ Advice of charge. If the handset is turned off or is out of the coverage area. to interrupt a call and then reestablish it again ♦ Call waiting. This service is used to transmit information regarding traffic congestion. which is based on standards developed by the International Telecommunications Union-Telecommunications Sector (ITU-T). GSM services GSM services are divided into telephony services (referred to as teleservices) and data services (referred to as bearer services). SIM contains IMSI. The functions of each element of the GSM system are described in the following section. this is the subscriber terminal.Chapter 10: An Overview of 3G 331 Figure 10-2: GSM architecture A mobile communications service provider operates in a given geographic region. The PLMN is connected to the Public Switched Telephone Network (PSTN) or a Public Data Network (PDN). In addition to these elements. The service area is arranged into cells. To identify handset hardware uniquely. A Personal Identity Number (PIN) protects the SIM. known as mobile handset. The MS contains an SIM (Subscriber Identity Module). Nowadays. or hand phone. The SIM is a smart card inserted in the handset. Home Location Register (HLR). The BSS acts as a relay between the NSS and the mobile stations. manufacturers use IMEI (International Mobile Equipment Identity) to provide a number to the handset. The BSS consists of Base Station Controller (BSC) and Base Transceiver Subsystem (BTS). Each cell can vary from 350 meters to 35 . The MSC consists of Mobile Switching Center (MSC). and powerful batteries that provide at least six hours of talk time and four to five days of standby time. and Visitor Location Register (VLR). The MS can be hand-held or car-mounted. The mobile network of the entire region is known as Public Land Mobile Network (PLMN). such as the Internet. such as subscriber management. Authentication Center (AuC). such as voice dialing. mobile terminals come with many features. A unique mobile phone number identifies the MS. network management. and each cell has a BTS.8 watt – 20 watts. The BSS consists of BSC and BTSs. which provides the man-machine interface to carry out administrative functionality. The PLMN consists of mobile stations (MS). Equipment Identity Register (EIR). and so forth. whereby one can use his voice to dial a number. The PIN is checked locally and not transmitted over the radio link. and Network Switching Subsystem (NSS). Each MS is also uniquely identified by IMSI (International Mobile Subscriber Identity). The power transmitted by the MS is in the range 0. The PLMN is in the administrative control of one operator. the PDN is a data network. billing. Also. there is also Operation and Maintenance Center (OMC). The PSTN is the technical word for the telephone network that we all use. Base Station Subsystems (BSS). 332 Chapter 10: An Overview of 3G kilometers depending on the terrain and the subscriber density. Multiple BSSs can be controlled by one BSC. It is connected to the MSC through land lines.25 watt – 320 watts. It uses standard Pulse Code Modulation (PCM). The maximum power transmitted by the BTS is in the range 0. The BTS uses TDMA for multiple access with eight slots per channel. BSC does the transcoding — conversion of 13 Kbps speech to PCM and vice versa. a coding technique through which speech is coded at 64 Kbps data rate to carry voice in digital format between the BSC and MSC. The TDMA frame format is shown in Figure 10-4. The BTS is the radio interface between the MS and the BSC. If channel 2 is given to a particular cell. This is a very simplified format — TDMA slots are also used to carry out all the signaling between the BSC and MS. To reduce radio bandwidth. normally two Mbps links. Each BSC controls a number of BTSs. Carriers are separated by 200 kHz. two frequencies are allocated — one uplink frequency and one downlink frequency. The frequency allocation for GSM in the 900 MHz band is depicted in Figure 10-3. The BSC handles radio management functions. Figure 10-3: Frequency allocation for GSM . the GSM uses low bit rate coding of speech at 13 Kbps. Communication between the MS and the BTS occurs through one channel consisting of a pair of frequencies — one for uplink and one for downlink. typically up to 40. The BSC arranges new radio link connections to the mobile stations when handover is required. The TCH (Traffic channel) carries the bi-directional speech data between the mobile station and the base station. Each time slot has a time period equal to 156. and of course. which acts as a beacon signal to find service and decode network information. The VLR is generally integrated into MSC. If a cell has one ARFCN. It is a stand-alone system connected to the GSM network subsystems with Signaling System No. The HLR/AuC administered by the Man Machine Interface (MMI) is derived from the OMC. there will be one BCH and seven time slots for TCH. Twenty-six or 51 frames are grouped together to make a multi-frame.25 of the data bits.615 milliseconds. If there are two ARFCNs in one cell. When a mobile station roams into a new MSC service . The VLR contains information about all the mobile subscribers currently located in the MSC service area. The HLR reroutes incoming calls to the MSC target or another telephone number when call forwarding is requested. the HLR is consulted and the database translates the mobile phone number to an IMSI number. These complex frame and multiframe structures are used to transmit control information. encryption key. to carry out synchronization. thus each frame period is 4. The BCH occupies time slot zero. This database contains ♦ Subscriber information ♦ Subscriber rights and privileges (what types of calls are permitted) ♦ Location information ♦ Activity status The HLR retains permanently the location of any subscriber. to carry speech data. and an algorithm to be used for encryption. 7 (SS7) signaling. Each cell is given a number of frequency pairs (channels) denoted by ARFCN (Absolute Radio Frequency Channel Numbers).Chapter 10: An Overview of 3G 333 Figure 10-4: TDMA Frame Format in GSM Each data bit is of 3. When an MS receives a call. There are eight time slots per frame. A super-frame consists of 51 or 26 multiframes. The AuC contains security functions such as IMSI. Each base station produces a BCH (Broadcast Channel). The AuC provides the data to verify the identity of each user and to provide conversation/data confidentiality.692 microseconds duration. there will be one BCH and 15 time slots for the TCH. The HLR is a centralized database to manage the subscriber data. Each Location Area is served by one or more BSCs. The MSC/VLR checks if the mobile station is authorized to access the network. the VLR connected to that MSC gets the data about the mobile station from the HLR and stores it. a number that uniquely identifies the cell. Each cell is given a Cell Global Identity (CGI). the EIR will not permit the call. GSM operation The operation of the GSM system can be understood by studying the sequence of events that takes place when a call is initiated from the Mobile Station. and other network management functions can be carried out. The communication between the OMC and the MSC/BSC is through a packet-switching network based on X. traffic analysis. When a PLMN contains a number of MSCs. If so. which are connected to the MSC. and fax messaging. The MSC/VLR receives the message of a call request. ♦ MSC/VLR Service Area: The area covered by one MSC is called the MSC/VLR service area. GSM network areas In a GSM network. AuC) is through an SS7 network. 2. data. The EIR contains informaticontains information about the mobile equipment. Each Location Area is assigned a Location Area Identity (LAI). fax mail. The MSC is also connected to the OMC through which the configuration of the network. configuration management (such as adding a new BSC. billing. Public Data Networks (PDNs) can be connected to the MSC. cell splitting. If the lost mobile is used for making a call. the following sequence of events takes place: 1. The GSM system can contain the following network elements. Separate servers are required to handle these messaging systems. To facilitate normal telephone subscribers of PSTN to receive/make calls to the mobile subscribers. because only signaling information is exchanged between these entities. and e-mail messaging. one MSC is designated as a Gateway MSC to interconnect with other networks such as PSTN and PDN. entry. ♦ PLMN: The area covered by one network operator is called PLMN. The VLR is responsible for the information about the current location of the user. billing. the mobile station is activated. traffic analysis. The MSC provides the complete switching functionality for the entire network.25 standards. EIR. and so on). cell broadcast. the subscriber informs the customer-support center and this information is stored in the EIR. If the PLMN contains only one MSC. such as fault diagnosis of various network elements. the following areas are defined: ♦ Cell: Cell is the basic service area: one BTS covers one cell. When a mobile subscriber makes a call to a PSTN telephone subscriber. It handles the Short Messaging Service (SMS). The communication between the MSC and the databases (HLR. service will be denied. EIR and AuC can be combined into one machine. A PLMN can contain one or more MSCs. that MSC itself can act as a Gateway MSC. voice mail. . The OMC is used to carry out network management activities. As EIR and AuC both provide security. performance management. If the mobile station is not authorized.334 Chapter 10: An Overview of 3G area. Message Center is a node that provides voice. Similarly. Each MS is uniquely identified by IMEI. This is the area that is paged when a subscriber gets an incoming call. the MSC is connected to the PSTN through trunk lines. If a mobile handset is lost. as well as managing subscriber information. and modification of the subscriber data. hence all call control functions are built in the MSC. ♦ Location Area: A group of cells form a Location Area. The MS responds to the page request. the speech is received at 64 Kbps rate at the BSC and the BSC does the transcoding to 13 Kbps for radio transmission. Handover. if required.Chapter 10: An Overview of 3G 335 3. The MSC checks the VLR for the location area of the MS. 5. after the subscriber answers. it would be of immense value. fast file downloads. This market demand is paving the way for exciting developments in wireless Internet services and technologies. accessing the Internet is a lot of fun. 2. many enhancements were done to the GSM standards (GSM Phase 2 and GSM Phase 2+) to provide higher data rates for data applications. and secondary storage.5G systems. . such as Internet Explorer or Netscape Navigator. 4. Note. The Gateway MSC receives the call and queries the HLR for the information needed to route the call to the serving MSC/VLR. the GSM systems can evolve to 2. The only drawback of this access method is that we are restricted to being in one place — there is no mobility. In its original form. GSM supports 9. that is. The BSC allocates a traffic channel and sends a message to the MS to tune to the channel. The MSC then forwards the speech data to the PSTN. we face lots of challenges — the mobile phone has a small display and small memory. The mobile station keeps on taking measurements of the radio channels in the present cell and neighboring cells and passes the information to the BSC. MSC/VLR analyzes the number and initiates a call setup with the PSTN. If handover is not required. a new traffic channel is allocated to the mobile station and the handover is performed. and fast and easy navigation. 4. The MS generates a ringing signal and. as discussed in the earlier case. The BSC allocates the traffic channel and passes the information to the mobile station. the number of wireless devices will probably exceed the number of wired devices accessing the Internet. However.6 Kbps data. which requires huge resources. This enables us to run a browser. takes place. 7. such as mobile phones. In the reverse direction. Through these enhancements. to achieve this objective. the need for mobile access to the Internet is growing rapidly. anywhere between 64 Kbps to 2 Mbps. with a lot of multimedia content. laptops. the wired connection can support high data rates. Wireless Internet Access through 2G Systems At present. The GMSC routes the call to the MSC/VLR. In the future. the mobile station continues to transmit in the same frequency. The BSC decides if handover is required. and long delays are common. However. the sequence of events is as follows: 1. Call to a mobile station When a PSTN subscriber calls a mobile station. If we could access Internet services through wireless devices. The BSC converts (or transcodes) the speech to 64 Kbps and sends it over a land link or radio link to the MSC. Over the last few years. Also. The MSC contacts the MS via the BSC through a broadcast message. through a paging request. The monitors are capable of displaying high-resolution color graphics. that the MS codes the speech at 13 Kbps for transmission over the radio channel in the given time slot. 5. Hence. 6. 6. which we study later in the chapter. 3. if so. mobile networks support very low data rates. or palmtops. the speech connection is established. large primary storage (Random Access Memory). most of us access the Internet through our desktops or our corporate LANs through wired connections (dial-up or leased lines). Our desktops have high processing capability. The called party answers the call and the conversation takes place. MSC/VLR asks the corresponding BSC to allocate a traffic channel (a radio channel and a time slot). which can be transmitted in one TDMA time slot. 7. ♦ WAP is a connection-oriented protocol. unless the WAP service picks up. pagers. the Wireless Application Protocol (WAP) has been developed. users could have mobile access to the Internet anytime from anywhere. ranging from 300 bps to 14. So. The mobile device (the handset) has to run a small browser (micro-browser). providing Internet services over these mobile devices is a pretty challenging task. ♦ Wireless devices (mobile phones. the WAP protocol stack can be used on any type of digital wireless networks. Many critics of the WAP have already dismissed it as technology that makes you “Wait and Pay!” In its present form. accessing a Web page with multimedia components would take ages! As compared to the wired networks. ♦ WAP enabled mobile phones are costly at present. the protocols for wireless access to the Internet need to be independent of the underlying cellular network protocols. ♦ Present wireless networks support very low data rates. and then the data can be transferred in a session. the delay is higher in wirless networks. but it has since realized that lots of work needs to be done to enhance the speeds of wireless networks. develop efficient protocols. different memory sizes.336 Chapter 10: An Overview of 3G If widespread wireless access to the Internet becomes a reality. In the late 1990s. and so forth) have limited capabilities: • Small screen. The need for WAP arose because a “light-weight” protocol is needed — a protocol with less overhead as compared to the Transmission Control Protocol/Internet Protocol (TCP/IP) used in the Internet. CDMA. generally 4 lines with 8 to 12 characters per line • Screen with low resolution and no support for color • Low power • Keypad with a very limited functionality ♦ Wireless devices vary widely — different platform technologies. GSM. in particular) presents many problems at present. CDMA.4 Kbps. At present. the WAP service will not pick up. Thus. The time taken for a data packet to reach the server and be acknowledgement (known as the round trip delay) is very high in wireless networks. the number of mobile portals will not increase. GSM. portals with WAP content are very few. To provide wireless Internet access through 2G systems. Unless there is a good number of mobile portals. WAP limitations and future work WAP is the first step in the process of standardization for achieving wireless Internet access. developing applications and protocols for wireless access of Internet services is a real technical challenge. and so on. . ♦ WAP content needs to be developed in WML and WMLScript. and so on. PDC. whereas most of the Internet content presently is in HTML. As we have seen in earlier chapters. However. Due to these problems. These problems are: ♦ There are a variety of protocols for the wireless systems. the software industry created a lot of hype about wireless access to the Internet. The conversion from HTML to WML using automated tools is very inefficient as many tags supported in HTML are not available in WML. and also create useful and appealing applications. as we see in the next section Challenges in wireless access to the Internet Wireless access to the Internet (Web service. WAP does have some limitations: ♦ For WAP to be deployed on a large scale. such as the TDMA. PDC. which interprets the WML content and presents it to the user. WAP content needs to be available. ♦ WAP is still considered a heavy-weight protocol because of the overhead involved in sending packets of data. such as the TDMA. meaning that a connection must be established with the server. this has been made possible through the i-mode technology of Japan’s largest cellular operator — NTT DoCoMo. and WAP 2. The communication between the Internet and the i-mode server is through TCP/IP and HTTP protocols. XHTML (Extensible HyperText Markup Language) will be used for content development. i-mode As the rest of the world has been struggling to provide wireless Internet access through WAP on 2G networks. i-mode became an extremely popular service in a short span of time because of the content. and hence the existing WAP applications will continue to run without any changes. Figure 10-5: i-mode system architecture i-mode supports a number of services. efficient protocols used.0 specifications have been released in July 2001 to overcome these limitations. As XHTML is derived from the XML and is very similar to the HTML. and the tool kits are available with Japanese language support only. Information providers. the message length is limited to only 160 characters. wireless Internet access has become very popular. cHTML is derived from HTML to provide the content on the wireless network. The i-mode terminal has a micro-browser to access Internet services. such as mobile banking. i-mode is a proprietary protocol. in addition to the low price the subscribers pay for accessing the service. WAP has been revised by the WAP Forum. An i-mode server is connected to the Internet and to the DoCoMo packet network. and high data rates. In WAP 2. the content-related problems are likely to be solved. in Japan. such as banks can connect to the i-mode server to provide services. Compatibility with WML is provided.Chapter 10: An Overview of 3G 337 ♦ When Short Messaging Service (SMS) is used as the bearer for WAP. based on PDC (Personal Digital Cellular) standard of Japan. and the microbrowser interprets the cHTML content and presents it to the user. The system architecture for offering i-mode mobile Internet services is shown in Figure 10-5. such as: ♦ Short e-mail messages ♦ Weather information .0. Compact HTML (cHTML) is used to transfer the data from the i-mode server to the mobile terminal. and also because of the large content available to the users. because conversion from. Navigation is tough because only few soft keys are available on the handset. JavaScript to WMLScript is also extremely difficult. Composing a message on the handset is also time consuming because the keypad has limited functionality. With 17 million subscribers and 776 information providers as of January 2001. in terms of processing power (only 8-bit or 16-bit micro-controllers). High resolution graphics cannot be transmitted. most of the Internet content is in HTML format. say. content is also available in this language. Scripting languages. such as WMLScript present more difficulties. WAP and i-mode provide good utility in obtaining focused information from the mobile portals. 2G Internet content Today. The content has to be in WML in the case of WAP.338 Chapter 10: An Overview of 3G ♦ Mobile banking ♦ Travel information including traffic information and maps of tourist spots ♦ Shopping information ♦ Part-time job listings ♦ Games and horoscopes ♦ Navigation information for drivers ♦ Graphic and comic strip downloads Because i-mode works on the packet mode and not the circuit-switched mode. low tariff. or cHTML in the case of i-mode. Consequently. or news. sports information. and Europe as well. the services provided to the users also have limitations. The tariff is based on the number of packets (one packet = 128 bytes) transmitted. thus i-mode is now being considered for deployment in many other countries. as compared to WAP. The WAP Forum and NTT DoCoMo are to work jointly to provide efficient protocols and attractive content to the end users. Automatic tools. it is always connected and is also faster. and many tags supported in HTML are not supported by WML. . The precursor to WAP is Handheld Device Markup Language (HDML). but they don’t do a good job because WML supports very few tags. such as HTML-to-WML conversion utilities are available. Other limitations include small black and white displays (2 to 4 lines with 8 to 12 characters). many of these languages share the same predicament: content cannot be made available to everyone irrespective of the characteristics of the wireless device. But still. One of the main reasons for the delayed development of widespread wireless Internet access is this content-related problem. The protocols used in imode are lightweight. “content transcoding” is a big business — it involves transferring the content from one markup language to another. The popularity of i-mode service is due to its fast access. such as astrological predictions. Presently. or small text messages. Later in this chapter. thus the browser that runs on these devices also is of limited capability. such as stock quotes. There are also examples of proprietary content creation approaches. i-mode is the most popular wireless Internet access service in the world. and animation is not possible. However. we see how the next generation of wireless devices can overcome this problem. small keypads. NTT DoCoMo is now promoting i-mode in the U. 2G wireless devices The wireless devices that access the Internet content through 2G networks have limited capability. such as Palm’s webclipping. which makes typing text difficult. weather information.S. which cannot be accessed through 2G wireless devices. The content that can be downloaded on to the handsets should be text-based and very focused. will support data rates in the range 64 to 144 Kbps. Because the protocols used in the GSM network and the PSTN/Internet are different. This data rate is sufficient to support good resolution graphics. it is well suited for applications. In the GSM network. the quality of the video will not be very high because of the limitation of the data rate.5G wireless networks. it gives 8 x 9. which evolve from the 2G systems. . This is a connection-oriented service. where a data call has to be established for Internet access. such as video conferencing.5G are: ♦ High Speed Circuit Switched Data (HSCSD) based on GSM ♦ General Packet Radio Service (GPRS) based on GSM ♦ IS 95B Systems based on CDMA HSCSD The HSCSD system is shown in Figure 10-6.6 Kbps data.8 Kbps of theoretical data rate. that is. The HSCSD is based on multi-slotting — a user is allocated two to eight time slots. download speeds up to 43. The HSCSD is an add-on feature to the GSM network with software only for upgrades.6 Kbps.Chapter 10: An Overview of 3G 339 2. such as a normal telephone call. Using this approach. In one time slot. Because the HSCSD provides a connection-oriented service. and these networks will in evolve into 3G systems. The various standards for 2.2 Kbps have been achieved in practical systems. when a call is established. as shown in Figure 10-6. 76. Of course. one time slot is allocated to the subscriber. and low speed video.5G Wireless Networks The 2. Figure 10-6: High speed circuit switchboard data service The IWF carries out the necessary protocol translation between PSTN/Internet and the GSM. animation. an Inter Working Function (IWF) is required. If all eight time slots are allocated to one user. where a circuit has to be established before the conferencing takes place. we can push 9. Figure 10-7: GPRS architecture CDMA 95B The CDMA 95B networks will evolve from the networks based on the IS 95A standards. The mobile device is assigned an IP address whenever it is connected to the Internet for carrying out any data transfer. As in the case of the HSCSD. Location registers in the SGSN (HLR and VLR) store the location information. Qualcomm Corporation. A mobile device connected to the GPRS is like a node on the LAN. The IS 95Abased networks evolved from the AMPS networks and support data rates up to 14. Using efficient coding techniques. and managing the links for data communication between the Internet and the mobile devices.. The block diagram of the GPRS system is shown in Figure 10-7. we can push data up to 14.4 Kbps. and the data rates can be increased to 172 Kbps. . such as is needed for the Internet. Two network elements —Gateway GPRS Support Node (GGSN) and Serving GPRS Support Node (SGSN) — are added to an existing GSM infrastructure. Video transmission using MPEG-4 standard (a low bit rate video coding standard developed by Motion Picture Experts Group) has been demonstrated over the GPRS network. The GGSN also carries out the address conversion because the addressing formats of the mobile network and the data network will be different. multiple time slots are allotted to the user. The IS 95Bbased networks support 76. The Serving GPRS Support Node (SGSN) performs the authentication of the users and keeps track of the mobile users.8/115. It is responsible for mobility management. or a node connected to the Internet through the Digital Subscriber Line (DSL) — it is always online and there is no need to make a call. data rates up to 78. i. which pioneered the CDMA technology. such as the Internet. as well as user profiles of the subscribers registered with the GPRS. Similar to the HSCSD.2 Kbps using packet switching.8 Kbps can be achieved in the GPRS. Internet) and the GPRS network.4 Kbps in one slot. but the data is transmitted using the Internet Protocol (IP). attaching and detaching the mobile devices to the network. such as current cell. is the most prominent manufacturer of these CDMA-based systems. GGSN is the gateway between a GPRS wireless network and the IP-based data network. GGSN carries out the necessary protocol conversion between the packet network (for example.340 Chapter 10: An Overview of 3G General Packet Radio Service (GPRS) GPRS uses the GSM infrastructure to provide packet switching. The SGSN also routes the packets to/from the mobile device to the GGSN by establishing the links.e. high-resolution graphics.5G systems are only a stepping-stone to the 3G systems. such as telephony. such as video mail and video conferencing.Chapter 10: An Overview of 3G 341 All these 2. ♦ Asymmetric and symmetric services should be supported. 384 Kbps for walking mobile devices. Third Generation Wireless Networks The 3G wireless networks will be capable of supporting very high data rates in the range of 384 Kbps – 2. In asymmetric services. high quality audio (music) downloading. TV and radio broadcast. video and audio conferencing ♦ Audio/video on demand. The following services should be supported: ♦ Computer data with Internet access. mail. various proposals were submitted by the following organizations: ♦ ETSI Special Mobile Group (SMG) of Europe ♦ Research Institute of Telecommunications Transmission (RITT) of China ♦ Association of Radio Industry and Business (ARIB) and Telecommunications Technology Committee of Japan ♦ Telecommunication Technologies Association (TTA) of Korea ♦ Telecommunications Industries Association (TIA) and T1 of USA . huge infrastructures put in place by different operators. the uplink (from handset to base station) data rates can be lower and downlink (base station to handset) data rates can be higher. 3G Standardization Activities Based on a call for proposals by the ITU Radio Communications Standardization Sector (ITU-R) Task Group 8/1. and 144 Kbps for carborne mobile devices ♦ Support for global roaming ♦ The 3G systems should work in all radio environments: urban areas. lack of availability of spectrum in the same bands in different countries. no common spectrum is available worldwide for 3G systems. nor can a single technology be standardized. file transfer. The work was challenging considering the many different technologies (some of which are in vogue. Even today. With these data rates. the cell size may vary considerably. suburban areas. and animation can be supported. The broad objectives of 3G systems are: ♦ Support 2 Mbps for handheld devices. mobile computing ♦ Telecom services. and indoor environments. FPLMTS is now known as IMT 2000 (International Mobile Telecommunications in 2000). The Future Public Land Mobile Telecommunication Systems (FPLMTS) working group developed the initial set of standards. UMTS (Universal Mobile Telecommunications Systems) is the European version of IMT 2000. To achieve this. In addition to the regular cells in the GSM networks. The data rates supported by 2. and an increasing demand for higher and higher data rates by the end users. ITU initiated the standardization process in 1986.5G systems can be used for graphics and audio applications. these data rates are not sufficient.048 Mbps to provide multimedia services to mobile users. tele-shopping. such as two-way video conferencing. video telephony. hilly and mountainous regions. applications. some of which are not). but for high resolution video streaming applications. To develop high-speed wireless networks. the 3G systems should support micro-cells (cells of a few meters radius) and pico-cells (cells of a few feet radius). Figure 10-8: Evolution of 3G CDMA2000 The CDMA2000 network will evolve from the existing CDMA systems. 5.342 Chapter 10: An Overview of 3G The objective was to develop a single international standard IMT2000. Subsequently. The PDC system of Japan will be upgraded to the W-CDMA-based system for providing the 3G services. However. User data rates ranging from 9. One system is referred to as CDMA2000 and the other as the W-CDMA. The evolution of 3G is shown in Figure 10-8. the 3GPP (3G Partnership Program) and the 3GPP2 to harmonize and develop standards for 3G systems based on the above proposals. Though there is a backward compatibility to the GSM network. 5.6 Kbps to 2 Mbps are supported in this system. Harmonization is a tall order — the access scheme (TDMA versus CDMA). a dual-band handset will be needed because of the differences in the frequency of operation. if a user of the W-CDMA network roams into an old GSM network. which facilitates global roaming. the 3G standards have mainly two types of systems.25. and 2 Mbps for static users. The RF channel bandwidths required for this system are 1. The GSM network will be upgraded to the GPRS. W-CDMA This network will evolve from the GSM networks. such as IS 95A and IS 95B. The IS 95A network based on CDMA will be upgraded to IS 95B network.. IS 41. 10. a new spectrum is required for the 3G services. This system uses the same frequency band as the IS 95-based systems and thus. the existing spectrum is used. and 20 MHz. The RF channel bandwidths required for this system are 1. 10. both based on the CDMA technology. The signaling protocols used in the network are same as those used in the IS 95 standards viz. So instead of a single technology. Signaling protocols used in the GSM network are also used in W-CDMA networks. which are also based on CDMA. and such — all differ from system to system. However. spectrum. which in turn will be upgraded to the W-CDMA network. . 15 and 20 MHz. Both the systems meet the objective of 3G system data rates: 144 Kbps for high mobility users. which in turn will be upgraded to CDMA2000 network in 3G.25. 384 Kbps for limited mobility users. signaling protocols. The existing spectrum will be used for providing the 3G services. new frequency bands are proposed for this network and hence new spectrum needs to be allocated. two international bodies were established. The proposals submitted by the previously mentioned organizations were nowhere near achieving this objective — they were all based on different technologies. The KVM occupies very small memory (less than 256 KB) and. input device capability. Sun Microsystems developed J2ME (Java 2 Micro Edition). OS/9. Thus. To run various applications above the operating system. Better battery technologies are required to be incorporated in the 3G devices. 2010-2025 MHz. battery capacity. The input devices should be user-friendly. which has a virtual machine. Also a full-fledged keyboard must be integrated. In addition. ♦ Small size and weight: Size and weight continue to be the most important features. This will be the greatest challenge in developing 3G devices. Not all devices have full-fledged operating systems residing on them. The existing Personal Communication Services (PCS) bands in the region of 1850-1990 MHz will be used for 3G networks in the USA. handover from one type of network to another type of network. ideally all the 3G systems in different countries should use the same frequency bands. and for interfacing to the legacy wireless networks. hence. The Java compatible software applications can be downloaded from the Internet on to the mobile device just the way we download the applications from the Internet on to our desktops today. such as voice dialing through speech recognition. and Java OS will be ported on the mobile devices. the frequency bands 1900-1980 MHz. the battery drain also goes up. ♦ Low power consumption: As the processing power increases. For the European region. this is not possible because 3G systems evolve from the existing systems. Imagine a multi-media PC that can go into your pocket — that is the 3G mobile device! ♦ Operating system: To take care of input/output management. and 2100-2170 MHz have been allocated for IMT 2000. which are compatible only with the GPRS networks. The 3GPP and the 3GPP2 have been merged together to form the Global 3G (G3G) forum. A large mobile population continues to use the normal handsets — some will continue to have the WAP-enabled phones and some will have mobile phones. Mobile operating systems. This forum worked out the modalities to achieve international roaming by providing the necessary network elements for protocol conversions. As users would like to have the capabilities. a video camera needs to be integrated into the mobile device. it is naïve to assume that all 3G devices will have all the preceding characteristics. Unfortunately. the mechanism for accessing the content from the Internet also varies: . at least 10 times the processing capability of today’s mobile devices. primary and secondary storage capacity. and so on. Also. Palm OS. no common spectrum is available worldwide for 3G mobile services. and process management. The important point to be noted here is that each of these devices have different processing capabilities and have different platform technologies. called the KVM (Kilobytes Virtual Machine). ♦ Integrated peripherals: To support applications such as video. 3G Wireless Devices To support the applications making use of the high data rates. the processor should be capable of handling the input/output operations quickly. such as the existing 2G networks. All these devices vary in terms of processing power. an operating system needs to be running on the mobile device. which use different frequency bands in different countries. international roaming is still a problem. it is ideally suited for mobile devices. However. Because of the variety of the wireless access devices. wireless mobile devices should have the following characteristics: ♦ High performance: The mobile device should have high processing capability. such as Win CE. memory management. display size and resolution. Small size and less weight with high performance can be achieved only by large scale integration of the electronic circuitry using the system-on-a-chip concept. the devices should have high primary memory (RAM) and also secondary storage devices. a high resolution color graphics display is needed.Chapter 10: An Overview of 3G 343 3G Spectrum Needs To achieve global roaming. However. ♦ Entertainment services: To obtain sports information. However. e-mail address. such as WAP and the content has to be in a format. it is likely that the content creation will be based on languages derived from XML. to buy and sell shares. However. it needs to be mentioned that for 3G to succeed. such as the WML.344 Chapter 10: An Overview of 3G ♦ Mobile phones. ♦ Devices will be capable of handling multi-call services for simultaneous handling of both voice and data services. and the like. Content for 3G Devices Creating content that can be accessed by mobile devices of different capabilities is going to be the biggest challenge for 3G content developers. weather information. They need to access the content using protocols. and a color display with larger size. In the next section. 3G Applications In the present 2G networks. which is the electronic wallet. and very small displays. They can run a browser with better features than a micro-browser and interpret mark up languages. to convert content of one language to another. transcoding of content. will continue to be a big business. . a built-in camera. Web browsing is very constrained because of the limited capabilities of mobile devices. However. to book flight. reply to. Some applications that are now becoming popular are listed in the following section:. Creating content in many markup languages that cater to different devices will be a gigantic task. The end user is not as much interested in the CDMA or TDMA as in what applications are supported and how effectively the 3G networks can be used for daily routine — for shopping. For some time to come. two way pagers. but there is no need to give credit card information. limited memory. these devices can run a KVM that can download Java code. Alternatively. ♦ Handheld computers will have higher processing power. train tickets. and applications will be based on Java. such as XHTML. forward and create e-mails. for education.and so on). such as XHTML or XML. Thus. and. travel information. there is no need to exchange paper business cards. ♦ M-Commerce: To place orders for small items (books. and hence they can run Java-based applications. This service is an enhanced version of the Short Messaging Service (SMS) of the cellular mobile systems. and sports news. sports scores. One can carry out a mobile commerce transaction. for entertainment. and the like will have limited processing capability. Alternatively. such as WinCE. to carry out bank transactions. and video-transmitting functions to support video conferencing. With the advent of J2ME and Sun Microsystems’ Wireless Tool Kit. another smart card can be placed in the mobile phone. ♦ Electronic business cards: The information contained on a business card will be available in a mobile device (name. ♦ Mobile e-mail: To read. in the long run. designation. the key lies with content creation. for business. daily horoscope. ♦ Mobile devices that can support high data rates will have a large display. The bill amount can be a part of the telephone bill. phone numbers). we discuss the various applications supported by the 3G networks. bouquets. these applications continue to be popular as they provide very focused information and can be accessed quickly. political. of course. They can run a mobile operating system. more memory. ♦ Electronic wallet: The SIM card in the mobile device can act as a wallet. PalmOS or JavaOS. ♦ News: To obtain the latest business. ♦ Laptop computers will be Able to run a full-fledged desktop operating system and access Internet content just as we access the content from the desktops. the 3G programming roadmap isn’t so blurry. This information can be automatically transferred to another mobile device. a GPS receiver gives the longitude and latitude of the location of the mobile device. ♦ Telemedicine: Facilitating remote medical diagnostics. the Location Interoperability Forum (LIF) was founded by Ericsson. These services will be made available on both the 2G and the 3G systems and terminals. The architecture of the system is shown in Figure 10-9. one can get information about the hotels or hospitals in that locality from the server. Location-based services will be of immense use in public safety and emergency services. ♦ Mobile video player: Downloading a video (movie) while on the move ♦ Advanced car navigation: Downloading the digital maps while on the move and obtaining navigational information and location-based services To summarize. Some typical applications are listed here: ♦ Videophone: Facilitating seeing the video of the people in conversation ♦ Video conferencing: Point-to-point or point-to-multipoint conferencing through video and audio ♦ Video mail: Sending video clippings in the mail messages ♦ Web based learning: Participating in real-time Web casting of lectures. the 3G systems will be introduced only in 2002 or later. On entering a new city in a car. in May 2001. It also provides the capability to create virtual learning communities and discussion groups and provides bibliographic database access. whatever we are doing through our desktops. the names of the nearby hotels. New exciting personalized services can also be developed using this technology — you can find a friend in a specific locality as soon as you enter a particular location. In the future. multimedia services can be supported. Web-based learning provides an integrated solution for hearing lectures online or offline. A patient can send the diagnostic reports to a specialist and obtain second opinion. To exploit the potential of the location-based services and at the same time to ensure interoperability between mobile positioning systems developed by different organizations. Telemedicine can be effectively used in remote/rural areas where there might be only a paramedic staff available. Motorola. Japan was the first country to introduce 3G system on experimental basis. the BSC will forward the location information of the mobile device to the server. These location-based services are now catching up very fast. send the information pertaining to that location to the mobile device. The server will. The system is based on W-CDMA. in turn. and Nokia in September 2000. as the capability of mobile devices improves and the access speed increases. The system supports both packet-switching and . Information pertaining to that location can be transferred to the mobile device. Location-Based Services When a mobile device accesses a server to obtain the content. anytime. for instance. This can be achieved in two ways: ♦ By integrating a Global Positioning Satellite (GPS) receiver with the mobile device. These include features such as animation and real time video. A 3G Example: NTT DoCoMo’s FOMA In most countries. we will be able to do from anywhere. ♦ The mobile system (the BSC of the GSM network) can calculate the approximate distance between the mobile device and the base station. the server will know the approximate location of the mobile device. which can be transferred to the server to obtain the information pertaining to that location. This is a revenue generating source for the operators and service providers. Based on this distance.Chapter 10: An Overview of 3G 345 ♦ Advertisements: Advertisements can be sent to the mobile devices from the server. by the end the first decade of the 21st century. the GSM systems were the most widely deployed systems. such as e-mail. users can access a wide . the 3G system standardization activity has been initiated. For applications. an i-mode server will be connected to the W-CDMA network. highresolution graphics and limited multimedia applications can be supported.346 Chapter 10: An Overview of 3G circuit-switching operations.5G systems were proposed which are evolving from the 2G systems. content is generally limited to text and lowresolution graphics. anywhere — making the utopia of a global village a reality. just like a voice call.5G systems support data rates up to 144 Kbps and. For all these data services.5G systems are based on the TDMA technology and the GPRS and CDMA technology. image distribution servers.4 Kbps.048 Mbps to provide full-fledged multimedia applications. This service is known as FOMA (Freedom of Mobile Multimedia Access). such as video conferencing. and then carry out video conferencing and disconnect the call. To provide wireless Internet access over the 2G systems. Web content can be accessed through mobile phones at data rates up to 14. Various content providers will be connected to the network to provide content — such as normal Web servers. special protocols. Out of the various 2G systems. for video conferencing. the 2. file transfer. Hence. The 3G systems can be broadly categorized as the CDMA2000 systems and the W-CDMA systems. which in turn is connected to the Internet. The 2. To increase the speeds further. and text chat are carried out through the packet-switching operation. Because these services are similar to the i-mode services being offered today. circuit switching is used at a data rate of 64 Kbps. Using these protocols. To increase the data rates for Internet access. the speeds supported are 64 Kbps for uplink and 384 Kbps for downlink. Using 3G systems. which use packet switching. Summary This chapter gives an overview of the evolution of wireless networks. service such as FOMA will be available throughout the world and one will be able to communicate with anyone. a user has to make a call. Figure 10-9: NTT DoCoMo’s FOMA Hopefully. and the second-generation wireless networks were digital systems. such as Wireless Application Protocol and i-mode were developed. The first-generation wireless networks for mobile communications were analog. 3G systems support data rates in the range 384 Kbps to 2. So. music distribution servers. The normal data services. The 2. hence. location-based services are likely to become very popular with the advent of the 3G systems. Palm OS. In addition. 60 percent of the traffic is expected to be multimedia. in addition to the network technologies. multi-party audio.Chapter 10: An Overview of 3G 347 variety of services that include text. Handheld devices are also evolving rapidly. Therefore. The mobile handsets are no longer low power devices: handheld devices with mobile operating systems. anytime” communication a reality. graphics. These handheld devices can run small Java Virtual Machines called KVM and can interpret Java code. anytime at a very low cost. In order for the 3G systems to become popular. research needs to focus on wireless device technology and content development technology. More than that. By 2010. Wireless Internet access holds a great promise — the wireless subscribers are likely to grow form 400 million in 2000 to 1800 million by 2010. OS/9. the operators and equipment manufacturers can reap rich benefits. thereby making “anywhere. the users will benefit greatly — a wide variety of services will be available to them anywhere. . and so forth are available with higher memory and high-resolution color display to present the Internet content. what we can do today on desktops can soon be done through the handheld devices. and video conferencing. So. such as the Win CE. . ♦ Subscribers with mobile phones that support data rates up to 64 Kbps. These devices can also run a Kilobytes Virtual Machine (KVM) and can interpret the Java code. The subscribers can be divided into the following categories: ♦ Subscribers with mobile phones that support low data rates (up to 14. the thrust for operators is to develop the content that can provide appealing applications. These devices. First. ♦ Subscribers with laptops that can run a desktop operating system. ♦ Subscribers with high-end wireless devices that run a mobile operating system (such as Palm OS and Win CE) that can support high data rates (384 Kbps upwards). can run a sophisticated browser and interpret the content written in XHTML or XML. business. and Java. 3G Application Development Issues NTT DoCoMo was the first operator to introduce 3G services. These subscribers have WAP-enabled handsets that understand only WML content. Consequently these handsets are capable of handling both circuit-switched data and packet-switched data. which require high bandwidth. They also support. or leisure activities. As a consequence. These subscribers have handsets that support GPRS and WAP.0). the subscribers of wireless data services will have wireless devices of different capabilities. and video applications. but who would like to use the wireless network from fixed locations. the 3G services are likely to be introduced on a large scale between 2002 and 2004. These include: Wireless Markup Language (WML). The end user is not concerned with the underlying technologies. audio. 3G networks can support animation. So. which is the markup language standardized in the next version of Wireless Application Protocol (WAP 2. we focus on creating the content to provide multimedia applications. but he/she is interested in using the network for personal. which has some presence as a legacy language for a few more years. In this chapter. which is now more widely used for developing Internet content. We briefly review these languages and tools in the next section. audio and video streaming applications in addition to animation.Until the market for 3G services matures. in May 2001. In all other countries. we have different markup languages and different tools to develop 3G applications. we study the various issues involved in 3G programming. the network programming language that provides true platform independence and multimedia support. These devices are capable of handling data rates up to 2 Mbps and can support full-fledged multimedia with video conferencing. Extensible Markup Language (XML). We study 3G programming using different languages. and then we discuss the implementation of real-world examples. to some extent. Unlike the 2G networks.4 Kbps). . Extensible HyperText Markup Language (XHTML).Chapter 11 Advanced 3G Programming The objective of the 3G wireless networks is to provide to end users applications that support high data rates. which illustrate the ease with which content can be developed for 3G networks. To cater to all these categories of subscribers is the challenge of 3G programming. because of higher memory capacities. XML You may be wondering. In the next section. To access content from mobile devices with limited capability. the browser needs to be much simpler. Due to the limited capabilities of wireless devices. WAP-enabled phones will be cheaper than the other high-end 3G mobile devices. Also. utilities are available that convert images into the WBMP format. The same content needs to be made available through wireless devices. XML. the browsers that interpret HTML content create a lot of problems. However. and simple database access. why not use HTML for 3G programming? Though HTML has been standardized. In this section. Some of these problems are as follows: ♦ The HTML-content creators did not follow the syntax strictly (for example. Still. with backward compatibility for WML. wireless networks. . ♦ WML does not support tags for playing audio and video files directly. WML The revolution of wireless Internet access started with WAP. We need to create wireless bitmap (WBMP) images. we study the limitations of WML and the new languages for 3G application development namely. ♦ Because most of Internet content is in HTML. we need a markup language that has strict syntax. we need to follow a roundabout approach. These utilities reduce the data rate required to transmit the image and also reduce the resolution of the image. XHTML. will continue to be available. ♦ To create animation. which has already been developed. and WML content. ♦ Because WAP is meant for low-speed. the browser itself is a complex piece of software with high memory requirements. WAP 2. which can be displayed one at a time. and Java — the language for networked applications. to present the content properly on the browser. if most Internet content is available in HTML. WML for 3G-applications development is not an attractive choice. To enable an image to be transmitted over wireless networks with low data rates. news. WAP will continue to be present for some time. which specifies the time in milliseconds. particularly for obtaining focused information such as stock quotes. we need to create a WML deck that contains a number of WML cards. However. conversion of HTML to WML is not efficient. it needs to be mentioned here that WML is still a good choice for the legacy 2G networks. we see how animation can be achieved using this approach. Each card is displayed for a few milliseconds and is followed by the next one. ♦ Because the browser runs on a desktop with high processing power. A good number of sites are presently available that provide WML content. many markup languages have been proposed to develop content that can be presented through a browser that has minimal processing requirements. For these reasons.350 Chapter 11: Advanced 3G Programming The wired Internet provides access to information through wired devices at very high speeds. the browser developers use all the necessary processing power to interpret the content properly. Many tags supported in HTML are not available in WML. to provide content to mobile devices using WML is a considerable task. the WBMP files provide very lowresolution graphics. Hence. as discussed in the previous chapters. many HTML programmers do not use close tags). which used WML as the markup language.0 was released in July 2001 using XHTML as the markup language — of course. WML has the following limitations: ♦ The graphics capability of WML is very limited. The amount of time a card is displayed is controlled through the “ontimer” tag. If the browser has to be simpler. So. sun. ♦ There must be a single root element. can interpret XML documents. ♦ <head> and <body> elements should not be left out. A well-formed document has the following features: ♦ All elements must have opening and closing tags. Unless the card tag is closed with </card>. The tags are identical to HTML but as the syntax is that of XML.java. The computing power and memory requirements are fewer than those for HTML or XML. if we do not close the body tag (</body>). Because XML is a very powerful meta-language. The advantages of XHTML are: ♦ Because most Internet content is in HTML.0 Strict/EN” “ “> ♦ A reference to the XML namespace has to be included in the html element. To overcome these problems. they can also interpret XHTML. Omitting closing tags is not allowed. ♦ Developing browsers for wireless devices is not very complex because of the strict syntax of XHTML. For example. which contains all other elements. the root for a WML document is <wml> under which all other elements are used. XHTML uses the vocabulary of HTML and the syntax of XML. XML has been standardized — XML is a meta-language and hence we can define our own tags using XML. XHTML documents can be interpreted by any XML user agent (desktop. In HTML. For instance. <html xmlns=http://www. You only need to ensure that the syntax is followed strictly.com. palmtop. we need a special parser to parse XML documents. ♦ All attribute values must be enclosed in quotation marks. ♦ Tags must nest properly. Only the wireless devices with high processing capability can handle such parsers. The word “extensible” is mainly to indicate the following feature: New tags can be created as long as the documents are well-formed. ♦ Because most of today’s browsers interpret HTML. Popular parsers for Java are SAX and DOM. XHTML The advantages of XML and HTML are combined to form XHTML. so you don’t have to change or get new browser software. ♦ All tags have to be closed. <!DOCTYPE PUBLIC “~//W3C/DTD XHTML 1. ♦ Different browsers can display the content in the same fashion. The other good news is that you hardly need to expend much effort to learn XHTML if you know HTML. you can’t close the wml document with </wml>. such as Internet Explorer and Netscape Navigator. a <wml> tag can contain the <card> tag. which can be downloaded from Sun Microsystems’ Web site: www. but this is not allowed in XML.w3.Chapter 11: Advanced 3G Programming 351 ♦ As users wanted more and more features for accessing the vast amount of information on the Web. and browsers became proprietary. new tags were added for content creation. the most widely used browsers.0 and XHTML: ♦ A DTD declaration has to be provided at the top of the file. in WML. or mobile phone). The following are important differences between HTML 4. ♦ All elements must be nested properly. However.org/TR/xhtml1> ♦ Tag names and attribute names must be in small letters. some browsers (such as Internet Explorer) may not complain. . This resulted in the content not being displayed uniformly on all browsers. you don’t need to rewrite a large amount of code. WML is derived from XML. However. the Java code can move from machine to machine. All Rights Reserved 1. the animation will be much slower than on a phone emulator. Because WML does not support animated images to be given directly as attributes for the image tag.352 Chapter 11: Advanced 3G Programming ♦ The first element in the head must be the <title> element. 2. <img alt=" " src="IMG001. <timer value="1"/> 6. and the wireless device can download Java compatible code and execute it. So. you cannot simulate the speed of the network.wbmp. 3. The KVM can run on a wireless device. Listing 11-1: WML code for animated image using timer © 2001 Dreamtech Software India Inc. we create an animated image using WML that can be displayed on WAP-enabled devices. thereby providing the capability for network computing. This virtual machine is called KVM (K stands for Kilobytes). Using Java for Internet computing with desktop as the client is now taken for granted. IMG002. The Java programming language provides dynamic content creation capability through applets. it is likely to revolutionize Internet access through wireless devices in the first decade of the 21st century. <p align="center"> 7. In addition. we need to create a series of images and use the timer tag to display one image after another. which has a Virtual Machine that occupies only a few Kilobytes. 4. 3. We illustrate XHTML programming with examples in the next section. In this example. JVM can interpret the Java code that is downloaded from a server on the Internet. 1. These WBMP files are stored in different files with filenames IMG001. The details of the code follow. we discuss the implementation of 3G applications.1//EN" "http://www. and Java. Sun Microsystems developed J2ME (Java 2 Micro Edition). <wml> 4. 2. you first need to create six images and convert them into a WBMP format from a BMP format by using a tool for that purpose. and the applications that run on these devices are called MIDlets.wbmp. 4. Animation Using WML In this example. Just the way Java revolutionized Internet access through desktops in the 1990s.1.wapforum. Now for the problem: The JVM (for the Java Standard Edition that runs on the desktop) requires large memory and high processing capability. 6. XHTML. These mobile devices are referred to as Mobile Information Devices (MIDs). on an actual WAP-enabled mobile phone. The code is given in Listing 11-1. Implementation of Real-World 3G Applications In this section. The Java applet can be downloaded from the server and executed in a client. <?xml version="1. We will study how to create wireless applications using the wireless tool kit of Sun Microsystems later in this chapter. To overcome this problem.wbmp"/> . The main advantage of Java is its platform independence.org/DTD/wml_1. Note that the images are displayed in the following order: 1. 5. the Java Virtual Machine (JVM) must be running on the client. Java Java is the programming language for network computing. XML. These are the basic differences between HTML and XHTML. 5. <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1. and so on. <card id="card1" title="Animation" ontimer="#card2"> 5. We will discuss how the content can be created using WML.0"?> 2. These are available on desktops but not on mobile devices. If you are using a tool kit’s phone emulator.xml"> 3. 63. 46. 36. 51. 43. 38.wbmp"/> </p> </card> . 57. 19. 25. 47. 11. 45. 37. 33. 9. 14. 31. 15. 21. 40.wbmp"/> </p> </card> <card id="card9" title="Animation" ontimer="#card10"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG003.wbmp"/> </p> </card> <card id="card7" title="Animation" ontimer="#card8"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG005.wbmp"/> </p> </card> <card id="card5" title="Animation" ontimer="#card6"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG005. 35. 22. 41.wbmp"/> </p> </card> <card id="card10" title="Animation" ontimer="#card11"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG002. 12. 62.wbmp"/> </p> </card> <card id="card6" title="Animation" ontimer="#card7"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG006. 53. 27. 18.Chapter 11: Advanced 3G Programming 353 8. 30. 55. 60. 44. 58. 24. 59. 10. 13. 26.wbmp"/> </p> </card> <card id="card4" title="Animation" ontimer="#card5"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG004. 56. 49. 20. 32. 52. 61. 50. 54. 23. 16. 48. 29. 34.wbmp"/> </p> </card> <card id="card3" title="Animation" ontimer="#card4"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG003. 39. 17. </p> </card> <card id="card2" title="Animation" ontimer="#card3"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG002. 28. 42.wbmp"/> </p> </card> <card id="card8" title="Animation" ontimer="#card9"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG004. This tag has the src as an attribute to pass the image (IMG001. 69.wbmp. The ontimer event is used in this tag to perform a task when a stipulated amount of time is completed. ♦ Lines 34–39: Another card with card id as “card6”.wbmp. <card id="card11" title="Animation" ontimer="#card1"> <timer value="1"/> <p align="center"> <img alt=" " src="IMG001. The image to be displayed is IMG003. The image is IMG002.wbmp. The image to be displayed is IMG002. alt is another compulsory attribute.wbmp).wbmp. 66. The content of the card is same as the previous card with changes in the card id and the image passed. ♦ Line 8: Close of para tag ♦ Line 9: Close of card tag ♦ Lines 10–15: Another card with card id as “card2”. The output of the code is shown in the simulator. In this line only. The image is IMG004. The image is IMG006. card2 is displayed.wbmp.wbmp. the card1 will be displayed . ♦ Lines 40–45: Another card with card id as “card7”. 68. Click the Compile button and then the Show button.wbmp. ♦ Lines 58–63: Another card with card id as “card10”. 67. the alt tag says what the image is.wbmp. alt is blank. The time is in milliseconds. which contains the alternative text for the image. Note that on expiration of timer. It is useful because when the image is not displayed. the timer tag is closed.wbmp"/> </p> </card> </wml> Code description ♦ Line 1: Indicates the XML version being used by the tool kit ♦ Line 2: Indicates the document-type definition for creating the WML page ♦ Line 3: Start tag of the WML page ♦ Line 4: Start tag for the WML card. The content of this card is same as the above card with changes in the card id and the image passed. ♦ Lines 16–21: Another card with card id as “card3”. ♦ Line 70: Closing of the wml deck Code output After entering the code in the WML environment of the Nokia tool kit. When the timer expires. This card has the ID “card1” and title “Animation”. ♦ Lines 64–69: Another card with card id as “card11”. The image is IMG005.wml). The image is IMG003. ♦ Lines 46–51: Another card with card id as “card8”. The image is IMG005. ♦ Line 5: The timer tag — the tag for initiating the timer and setting the timer. Here. The image is IMG004. The image is IMG001.wbmp. Some screen shots are shown in Figure 11-1. save the file (animation. ♦ Lines 52–57: Another card with card id as “card9”. 70. the tag for inserting the image. ♦ Line 6: The para tag — the tag in which the actual content is put.wbmp. which aligns the content. . 65. ♦ Line 7: The image tag. It contains an attribute align. You will see a moving ball above the welcome message. ♦ Lines 22–27: Another card with card id as “card4”. ♦ Lines 28–33: Another card with card id as “card5”.354 Chapter 11: Advanced 3G Programming 64. you can still view animation well. we will see the power of XHTML to create content. Precisely for this reason. on a high-speed network. XHTML has the capability to create applications using a much simpler code. such as . In the next set of examples. However. To run this application. Animation Using XHTML The following example illustrates how to create animation in an XHTML document. XHTML is adapted as the standard for content creation in WAP version 2.Chapter 11: Advanced 3G Programming 355 Figure 11-1: Snapshots of the animated image displayed on the WAP phone Now you can appreciate the complexity involved in creating animation through WML. we had to create a series of images and use the timer to control the display. As you can see. Because of the support for display of only one low-resolution image at a time.0. However. you need to create an animated file in GIF format (you can use any popular software. content creation is pretty tough. save the file with the extension HTM or HTML. 5. Listing 11-2 gives the XHTML code for displaying an animated file. You can also open the file by doubleclicking the left mouse-button on the file.wav. You need to create a file myClip. Open the browser and call the file from the location where you saved it. 9. 11. Code output After typing the code using any text editor. Images. It specifies the border of the table.org/TR/xhtml1/DTD/xhtml1-transitional. 6. let’s assume that a file with the filename anim. this is a much simpler code because the animation files can be given as arguments to the img tag in XHTML. the DTD used for content development and the reference location of the DTD ♦ Line 4: Start tag with XML name spacing reference location ♦ Line 5: Head start tag ♦ Line 6: Title of the page with start and end tags for the title ♦ Line 7: Close tag for head ♦ Line 8: Body start tag. 12.w3. As compared to WML. 7.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 3. 4. This file can be created using an audio blaster card of your . <?xml version="1. ♦ Line 11: Table close tag ♦ Line 12: Body close tag ♦ Line 13: HTML close tag. 10. Play an Audio File Using XHTML Here is an example to play an audio file through an XHTML document. which closes the document. 8. which are static images. All Rights Reserved 1.w3.gif"/></td></tr> </table> </body> </html> Code description ♦ Line 1: Indicates the version of XML being used and the encoding format ♦ Lines 2-3: Indicate the document type. ♦ Line 10: Row tag with td (table data cell) tag which is a cell.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>This is Animation Example</title> </head> <body> <table border="1"> <tr><td width="75" height="75"><img src="anim.dtd"> <html xmlns="http://www.0 Transitional//EN" "http://www. The td tag contains the image (img) tag with src (source) as attribute for passing the source of the animated GIF image.gif is created. whereas WML allows only WBMP files. 2. which defines the body of the document ♦ Line 9: Table start tag with attribute border.356 Chapter 11: Advanced 3G Programming Adobe Photoshop). The code given in Listing 11-2 is explained below: Listing 11-2: Animation through XHTML © 2001 Dreamtech Software India Inc. In this example. 13. which contains a recorded file. as shown in Figure 11-2 are displayed — this animation is a falling drop. dtd"> <html xmlns="http://www.Chapter 11: Advanced 3G Programming 357 PC. 9. ♦ Line 4: HTML start tag with XML name spacing reference location ♦ Line 5: Head start tag . 4. Listing 11-3 shows the code for playing an audio file. Store the file in the WAV format.org/TR/xhtml1/DTD/xhtml1-transitional. 7.wav" autostart="false" width="200" height="45" /></td></tr> 11.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>This is Audio Example</title> </head> <body> <table border="1"> <tr><td><embed src="myClip. </body> 13. 8. 3. the reference location of the DTD. 6. </table> 12. 2. ♦ Lines 2–3: Indicate the document type and the DTD used for content development.0 Transitional//EN" "http://www. 5. Listing 11-3: XHTML code to play an audio file © 2001 Dreamtech Software India Inc. <?xml version="1.w3. Details of the code follow.w3. </html> Figure 11-2: Snapshot of the animated image displayed on the browser Code description ♦ Line 1: Indicates the version of XML being used and the encoding format. All Rights Reserved 1. 10.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. which specifies the border of the table. Open the browser and call the file from the location where you saved it. The details of the code follow. Downloading an audio file (say.htm or audio. height as attributes to embed the sound file into the document.w3.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. Alternatively. which will output the file to the speakers. Listing 11-4 gives the XHTML code for playing a video clipping.htm. the mobile devices have to pass the audio file to the voice processing module. If you don’t have an .mpg file in your system. you can also open the document by double-clicking the file. the width and height are to specify the height and width of the embedded file. autostart is to specify whether to start on load or not.com/shirley_holmes/ or mschockey. The td tag contains the embed tag with src (source). ♦ Line 11: Table close tag ♦ Line 12: Body close tag ♦ Line 13: HTML close tag. the audio file will not be played as soon as the document is loaded. autostart.org/1999/xhtml" xml:lang="en" lang="en"> .w3. which is a cell. which defines the body of the document ♦ Line 9: Table start tag with attribute border.wav). save the file with extension HTM or HTML (audio. You need to have a video clipping with the filename video. 2. After downloaded on to the mobile device. you can hear the sound. If the autostart is true. a music file) on to a mobile device is extremely simple.dtd"> <html xmlns="http://www.8m. You can now feel the power of XHTML. When you open the file. If autostart is false.org/TR/xhtml1/DTD/xhtml1-transitional. The file format is as per the standards defined by Moving Picture Experts Group (MPEG). Play a Video File Using XHTML This example illustrates how a video clipping can be played through an XHTML document. The src specifies the source of the file (myClip. 3. <?xml version="1. MPEG standard is used for transmitting video clippings and also for video conferencing. Note that the video file format is MPG as indicated by the extension of the filename.bobcam.html). width. it will be played immediately on loading the file on to the browser. ♦ Line 10: Row tag with td (table data cell) tag.mpg in your system. You have to explicitly start it. Listing 11-4: XHTML code to play video file © 2001 Dreamtech Software India Inc.358 Chapter 11: Advanced 3G Programming ♦ Line 6: Title with start and close tags for the title ♦ Line 7: Head close tag ♦ Line 8: Body start tag. 4. you can download from one of the following sites: www.0 Transitional//EN" "http://www.com/movies. Figure 11-3: Audio file control pad By clicking the arrow (the play button). the audio file control pad is displayed (Figure 11-3). which closes of the document. Code output After typing the code in any text editor. All rights Reserved 1. the width and height are to specify the width and height of the embedded file.mpg" type="video/quicktime" widht="200" height="200" /></td></tr> 11. which specifies the border of the table ♦ Line 10: Row tag with td (table data cell) tag. 6. After you open the file. you can see a screen (see Figure 11-4).Chapter 11: Advanced 3G Programming 359 5. ♦ Lines 2–3: Indicates the document type and the DTD used for content development. video. with start and close tags for the title ♦ Line 7: Head close tag ♦ Line 8: Body start tag. the reference location of the DTD. 8. The src is to give the source of the file (in our case. The td tag contains the embed tag with src (source).htm or video. the type is to specify the file type. which closes the document Code output After typing the code using any text editor. </body> 13. you can save the file with the extension HTM or HTML (video. 10. <head> <title>This is Audio Example</title> </head> <body> <table border="1"> <tr><td><embed src="video. ♦ Line 4: HTML start tag with XML name spacing reference location ♦ Line 5: Head start tag ♦ Line 6: Title of the document. </table> 12. width.mpg). Open the browser and call the file from the location where you saved it.html). ♦ Line 11: Table close tag ♦ Line 12: Body close tag ♦ Line 13: HTML close tag. which is a cell. which defines the body of the document ♦ Line 9: Table start tag with attribute border. 9. Then the actual video file starts playing. height as attributes to embed the video into the document. </html> Code description ♦ Line 1: Indicates the version of the XML being used and the encoding format. You can also open the document by double-clicking the file. 7. type. Figure 11-4: Video file control pad . the mobile device can automatically pass the longitude and latitude information of its present location to the server. and hospitals. restaurants. Otherwise. 19. 24. for example. “hospitals” is also a text field having hospital names. 23. 13. 4.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Location based services</title> </head> <body> <form action="location.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. this information has to be sent by the user to the server by inputting the data. hotels and hospitals of a location along with the longitude and latitude. Listing 11-5 gives the ASP code for gps. 18. the information on the hotels in that location is sent to the mobile device. 2. 11. You also need to write two programs — the first program (gps. 14. 12.w3. After the location information of a mobile device is received. <?xml version="1. Listing 11-5: XHTML code for giving latitude and longitude input © 2001 Dreamtech Software India Inc.asp.asp" method="post"> <table border="1"> <tr> <td width="25"><font face="arial" size="2">Latitude</font></td> <td width="5"><input type="text" name="latitude" size="2"><font face="arial" size="1">degrees</font></input></td> </tr> <tr> <td width="25"><font face="arial" size="2">Longitude</font></td> <td width="5"><input type="text" name="longitude" size="2"><font face="arial" size="1">degrees</font></input></td> </tr> <tr> <td align="center"> <input type="reset" value="refresh"></input> </td> <td align="center"> <input type="submit" value=" submit "></input> </td> </tr> . The fields in the table are latitude.360 Chapter 11: Advanced 3G Programming Location-Based Services Using XHTML and ASP In this example. All Rights Reserved 1. 15. we illustrate how location-based services can be provided to mobile users. The database has one table also named gps.dtd"> <html xmlns="http://www. 3.asp) processes the data and presents to the user the restaurants and hospitals in the locality based on the location given by the user. “restaurants” is a text field having the restaurant names. 7. Create a Database In MS Access or any other database available on your system. 9. 17. and the second program (location. 10. 26. longitude. 6. 25. 8.0 Transitional//EN" "http://www. 22. 5. The latitude is a text field consisting of various latitude values. 21. you need to create a database of.org/TR/xhtml1/DTD/xhtml1-transitional. 20.asp) presents a form to the user to input latitude and longitude. create a database named gps. The longitude is also a text field having longitude values. For this application. 16. If the mobile device is fitted with a GPS (Global Positioning System) receiver.w3. asp is given in Listing 11-6. which sets the style and size of the text in the font tag. The font is another attribute. ♦ Line 4: HTML start tag. The input type submit is to submit the form values. The input tag is used to put the form components in the page. The table tag is to insert the table in the page. You can make border=“0” if you do not want a border. The name of the component is latitude. and so forth. which places a text box. which makes the row into divisions. 28. ♦ Lines 2–3: Indicate the DTD used in which the tags used in the document are defined. The input type reset is used to clear all the values in the text boxes and the input type submit is used to clear all the values in the text boxes. </table> </form> </body> </html> Code description ♦ Line 1: Indicates the XML version that is used and the encoding format. the data in the form will be posted and location. which is used to send the values when the form is submitted. 30. The value input by the user is in the variable “longitude”. The width attribute fixes the width of the division. which is the tag to place the elements. which prompts the user to give the value of Longitude ♦ Line 17: Another division in the row with input type as text with the name longitude.asp is executed. ♦ Line 14: Closing of row tag ♦ Line 15: Opening of new row ♦ Line 16: New division in the row. form. ♦ Lines 5–7: Head portion of the document with title tag.Chapter 11: Advanced 3G Programming 361 27. ♦ Line 10: Table tag with border attribute. The variable name for the value input by the user is “latitude”. This row has two divisions each having an input type reset and submit. The input type specified here is text. after the Submit button is pressed after the form is filled. ♦ Line 13: Another division tag having the input tag. which also contains the XML name-spacing reference location. ♦ Line 8: Start of the body tag ♦ Line 9: Form tag. This line prompts the user to type in Latitude. ♦ Line 27–30: Closing tags for table. each division is called a cell. body and html The source code for location. . such as text boxes. The form tag method attribute is to specify the method to be used to perform the task. which is UTF-8. and the border attribute is used to add a border to the table. In this case. which specifies the title of the document. meaning ASCII text. respectively. buttons. ♦ Line 11: Table row tag to put a row in the table ♦ Line 12: Table data cell tag. 29. It also contains the reference location of the DTD. The form tag action attribute is used to perform some action when the form is submitted. ♦ Line 18: Closing of the row tag ♦ Line 19–26: Code for another row. execute("SELECT * from gps") 13.close 45. <% 18. <html xmlns="http://www. <tr><td widht="15"><font face="arial" size="2">resturants:</font></td> 30. </head> 8.362 Chapter 11: Advanced 3G Programming Listing 11-6: XHTML code for displaying the retrieved values from database © 2001 Dreamtech Software India Inc. <title>gps locations</title> 7. <td widht="5"><font face="arial" size="2"><%=gps1("hospitals")%></font></td> 35. <td widht="5"><font face="arial" size="2"><%=gps1("resturants")%></font></td> 31. %> 46.dtd"> 4. <tr> 22. <tr> 26.%> 17.MoveNext 40. <td widht="15"><font face="arial" size="2">longitude:</font></td> 27. </tr> 36. gps1. %> 20.Connection") 11. %> 42. <% 10. <body> 9. <td width="5"><font face="arial" size="2"><%=gps1("latitude")%></font></td> 24.0" encoding="UTF-8"?> 2. "http://www. gps1. end if 39. <head> 6.w3.eof 16. <td widht="15"><font face="arial" size="2">latitude:</font></td> 23. dbConn. </tr> 25. <% 15. dbConn. While not gps1. </tr> 32.CreateObject("ADODB.close 44.form("longitude") then 19. </body> 47. <td widht="5"><font face="arial" size="2"><%=gps1("longitude")%></font></td> 28. set dbConn=Server.org/TR/xhtml1/DTD/xhtml1-transitional. <td widht="15"><font face="arial" size="2">hospitals</font></td> 34. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. <?xml version="1. <table border="1"> 21. if gps1(0)=request.org/1999/xhtml" xml:lang="en" lang="en"> 5.Open("dsn=gps") 12. All Rights Reserved 1. Wend 41.0 Transitional//EN" 3.w3. </tr> 29. </html> . <tr> 33. <% 38. </table> 37. set gps1=dbConn. %> 14. <% 43.form("latitude") and gps1(1)=request. select the database driver (in this case Access. The conidition is whether the variables passed in the gps. ♦ Line 36: Closing of the table ♦ Lines 37–41: Closing of the if condition and moving the record set to next record within the while loop and closing of the while loop ♦ Lines 42–45: For closing of the record set and closing of the data object ♦ Lines 46–47: Closing of body and HTML tags Creation of Data Source Name (DSN)/Code output Creating a DSN will differ depending on your development environment. select the database there. or if you used another database engine. . It also contains the reference location of the DTD. which also contains the name spacing reference location ♦ Lines 5–7: The head portion of the document with the title tag. ♦ Lines 20–22: Table row and data cell tags ♦ Line 23: Another division tag with script to write a record retrieved from the database ♦ Line 24: Closing of row ♦ Lines 25–28: Another row with two divisions. go to StartSettingsControl Panel. The second division has a script in which to put a record retrieved from the database. ♦ Lines 17–19: Script if condition where the if condition is used to check whether a condition is satisfied or not. on the desktop. Figure 11-6 shows the display of restaurants and hospitals in that location. Enter the DSN name. As the Create a New Data Source Window prompt appears. to open the database using the DSN (Data Source Name). The variables passed contain the latitude and longitude values. ♦ Lines 14–16: The script while loop. The ODBC set up window opens. In the control panel. ♦ Line 4: HTML start tag. The second division has a script to display the information about restaurants retrieved from the database. Click the Add button. which is used to go through the records step-by-step until the end of the file. select the appropriate database driver) and click the Finish button. The second division has a script to display the information about hospitals retrieved from the database.asp are found or not. and click Finish. select the ODBC data sources. If the variables are found. ♦ Lines 10–13: To create a data object. further processing will continue. For Windows 95/98. and to declare a variable and assign the record sets retrieved from the database. The script is used to access the database and retrieve the records from the database. Note that you can connect to the database in different ways — here we will discuss ODBC connectivity. which specifies the title of the document ♦ Line 8: Start of the body tag ♦ Line 9: Start of the script tag. ♦ Lines 29–31: Another row with two data cells.Chapter 11: Advanced 3G Programming 363 Code description ♦ Line 1: Indicates the XML version number and the encoding format ♦ Lines 2–3: Indicates the DTD used in which the tags used in the document are defined. a new window is displayed where user DSN appears. To create a DSN. Figure 11-5 shows the display for the user to input the latitude and longitude values. the following description is valid. When the ODBC data sources are selected. ♦ Lines 32–35: Another row with two data cells. All Rights Reserved 1. 18. 16. 7.xsl and store it. create the file animation. 3. . 12. The header tag is also closed in this line. 21..gif"></IMG></td> <td width="100" ></td> </tr> </table> </body> </html> </xsl:template> </xsl:stylesheet> Code description ♦ Line 1: Indicates the XML version. Using a text editor. 5. <?xml version='1.\\New Folder\animation. 10. 4. 11. Note that XML processing instruction starts with <? and ends with ?>.364 Chapter 11: Advanced 3G Programming Display an Animated Image in XML Using XSL We can create the preceding applications using XML through style sheets as well. 19.html"> <xsl:template match="/"> <html> <head> <title>XML ANIMATION </title> </head> <body> <h1> <CENTER> XML ANIMATION </CENTER></H1> <table align="center" border="0" bgcolor="#ffffff" cellspacing="0" cellpadding="0" width="700"> <tr> <td width="250" ><IMG ALIGN="center" SRC="C:\WINDOWS\Desktop\graphics \balloons_confetti_lg_clr. represents the title of the page on title bar ♦ Line 7: Closing head tag ♦ Line 8: Opening body tag ♦ Line 9: Header tag to specify the heading ♦ Line 10: Tag to align the text at the center of the HTML page ♦ Line 11: Heading followed by closing of center tag. 13. 17.0'?> <xsl:stylesheet xmlns:xsl=". 9. 14. 8. ♦ Line 2: Opening tag of the XSL style sheet with XML name spacing ♦ Line 3: Style sheet template declaration start tag and setting the root node through the match attribute ♦ Line 4: Opening HTML tag ♦ Line 5: Opening head tag ♦ Line 6: Title tag. The procedure is to create a style sheet and then link it to an XML document. The details of the code follow. 15. 20. and video — are presented here. Listing 11-7: Animation through XSL © 2001 Dreamtech Software India Inc. 22. 2. audio. 6. the same examples — animation. Listing 11-7 gives the style sheet for displaying the animated image. For illustration. Chapter 11: Advanced 3G Programming 365 ♦ Line 12: Tag to open a table. The attributes are to set the border (in this case, no border as the value is 0), background color, cell spacing, padding, and the width. ♦ Line 13: Tag to open table row ♦ Lines 14–15: Tag td is for opening the table data. The animated image location is specified by src. The full path where the animated image is located has to be specified. ♦ Line 16: Closing tag for table data ♦ Line 17: Closing tag for table row ♦ Line 18: Closing tag for table ♦ Line 19: Closing tag for body ♦ Line 20: Closing tag for HTML document ♦ Line 21: Closing tag for template ♦ Line 22: Closing XSL tag Figure 11-5: Screen to input latitude and longitude 366 Chapter 11: Advanced 3G Programming Figure 11-6: Display of restaurants and hospitals in the locality Listing 11-8 gives the XML code that links the XML file with the style sheet animation.xsl. Listing 11-8: XML code for animation © 2001 Dreamtech Software India Inc. All Rights Reserved 1. 2. 3. 4. <?xml version='1.0'?> <xml-stylesheet type="text/xsl" href="animation.xsl"?> <animation> </animation> Code description ♦ Line 1: Indicates the XML version number ♦ Line 2: This code links the animated file with the xsl style sheet through href attribute. ♦ Line 3: This code indicates the opening of the root element. ♦ Line 4: This code indicates the closing of the root element. Code output Save the file as animation.xml. After you run the XML code in Internet Explorer, you can see the animated object as in Figure 11-7. Chapter 11: Advanced 3G Programming 367 Figure 11-7: Animation display in the browser Play an Audio File Using XSL The listing for playing an audio file using XSL is done on similar lines as the animation. The code is provided in Listing 11-9. Listing 11-9: Audio through XSL © 2001 Dreamtech Software India Inc. All Rights Reserved 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. <?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="..\\New Folder\audio.html"> <xsl:template match="/"> <html> <head> <title>XML AUDIO </title> </head> <body> <h1> <center> XML AUDIO </center></h1> <table align="center" border="0" bgcolor="#ffffff" cellspacing="0" cellpadding="0" width="700"> <tr> <td width="250" ><bgsound src = “file///c:/windows/desktop/trial_xml/0.5.wav” loop=”-1”></bgsound></td> <td width="100" ></td> </tr> 368 Chapter 11: Advanced 3G Programming 16. 17. 18. 19. 20. </table> </body> </html> </xsl:template> </xsl:stylesheet> Code description ♦ Line 1: Indicates the XML version ♦ Line 2: Opening tag of the XSL style sheet with XML name spacing ♦ Line 3: Style sheet template declaration start tag and setting the root node through the match attribute ♦ Line 4: Opening HTML tag ♦ Line 5: Opening head tag ♦ Line 6: Opening title tag, represents the title of the HTML page on the title bar. The title tag is also closed in the same line. ♦ Line 7: Closing head tag ♦ Line 8: Opening body tag ♦ Line 9: Opening heading tag ♦ Line 10: To align the text at center of the HTML page. The heading is also specified here, and the center tag and the heading tag are closed. ♦ Line 11: Tag for creating a new table. The attributes are alignment, border, background color, cell spacing and padding as well as the width. ♦ Line 12: Tag for opening table row ♦ Line 13: Tag for opening table data. The tag bgsnd is to play the sound in background. The source of the sound is specified by src whose value is the complete pathname of the file. The bgsnd tag is also closed in this line. ♦ Line 14: Closing table data tag ♦ Line 15: Closing table row tag ♦ Line 16: Closing table tag ♦ Line 17: Closing body tag ♦ Line 18: Closing HTML tag ♦ Line 19: Closing template tag ♦ Line 20: Closing XSL tag Save this file with the filename audio.xsl. Create an XML document with Listing 11-10. Listing 11-10: XML code for audio © 2001 Dreamtech Software India Inc. All Rights Reserved 1. <?xml version='1.0'?> 2. <xml-stylesheet type="text/xsl" href="audio.xsl"?> 3. <audio> 4. </audio> Code description ♦ Line 1: Indicates XML version number Chapter 11: Advanced 3G Programming 369 ♦ Line 2: To link the animated file with xsl sheet ♦ Line 3: Opening of the root element ♦ Line 4: Closing of the root element Save the file with extension .xml. Code output Run the XML code in Internet Explorer. You can hear the audio through the speakers on your multimedia PC. Play a Video Using XSL To play video with XSL, you follow the same procedure as for animation. You need to have a video clipping in MPG format to test this application. Listing 11-11 gives the XSL code for creating a style sheet. Listing 11-11: Playing video through XSL © 2001 Dreamtech Software India Inc. All Rights Reserved 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. <?xml version='1.0'?> <xsl:stylesheet xmlns:xsl="..\\New Folder\video.html"> <xsl:template match="/"> <html> <head> <title> XML VIDEO </title> </head> <body> <h1> <center> XML VIDEO </center></h1> <table align="center" border="0" bgcolor="#ffffff" cellspacing="0" cellpadding="0" width="700"> <tr> <td width="250" ><img border="0" dynsrc="..\\trial_xml\Chellva_Wash.mpg" start="fileopen"></img> </td> <td width="100" ></td> </tr> </table> </body> </html> </xsl:template> </xsl:stylesheet> Code description ♦ Line 1: Indicates the XML version number. ♦ Line 2: Opening tag of the XSL style sheet with XML name spacing ♦ Line 3: Style sheet template declaration start tag and setting the root node through a match attribute ♦ Line 4: Opening HTML tag ♦ Line 5: Opening head tag ♦ Line 6: Opening title tag, which represents the title of the page on the title bar. After the opening tag, the title is given followed by closing tag for title. 370 Chapter 11: Advanced 3G Programming ♦ Line 7: Closing head tag ♦ Line 8: Opening body tag ♦ Line 9: Opening tag for heading ♦ Line 10: Tag to center align the text of the HTML page ♦ Line 11: The heading is followed by closing center tag and closing heading tag. ♦ Line 12: Opening tag for table row ♦ Line 13: Opening tag for table row ♦ Line 14: Opening table data and the image tag. The image tag contains the attribute dynsrc, which specifies the source of the video by the complete path name. The image and table data tags are also closed in this line. ♦ Line 15: Closing table data tag ♦ Line 16: Closing table row tag ♦ Line 17: Closing table tag ♦ Line 18: Closing body tag ♦ Line 19: Closing HTML tag ♦ Line 20: Closing template tag ♦ Line 21: Closing XSL tag Save the code with extension XSL. The style sheet has to be linked to an XML document, which is shown in Listing 11-12. Listing 11-12: XML code for video © 2001 Dreamtech Software India Inc. All Rights Reserved 1. <?xml version='1.0'?> 2. <xml-stylesheet type="text/xsl" href="video.xsl"?> 3. <video> 4. </video> Code description ♦ Line 1: Indicates the version number of XML ♦ Line 2: To link the file with the XSL sheet ♦ Line 3: Opening of the root element ♦ Line 4: Closing of the root element Code output Save the file with a XML extension. Run the XML code in Internet Explorer, and you can now see the video file. Development of a Mobile Advertising Application Using the Wireless Tool Kit As discussed in an earlier chapter, you can use the wireless tool kit to create applications for mobile devices by writing Java programs. Recall that a Java application created for running on Mobile Information Devices (MIDs) is called a MIDlet. You can run the MIDlets either through the KtoolBar or through Forte for Java Development environment. Forte for Java is an Integrated Development Chapter 11: Advanced 3G Programming 371 environment, which provides facilities to edit, compile, build, and execute MIDlets. Recall that to run a MIDlet, invoke the Forte for Java and then right-click on the MIDlet Suite icon RunAll and click the Execute menu item, as shown in Figure 11-8. The tool kit provides four types of phone emulators; you can use the DefaultColorPhone or DefaultGrayPhone to test the applications. Figure 11-8: Running a MIDlet Listing 11-13 gives the listing of the MIDlet to create a mobile advertising application. The application has to display a set of items (cosmetics, jewelry, books, clothing). When the user selects an item, it has to display the new products that have arrived (such as earrings, necklaces, and bracelets if the user selects jewelry). The code details follows. Listing 11-13: MIDlet for mobile advertising © 2001 Dreamtech Software India Inc. All Rights Reserved 1. 2. 3. 4. 5. 6. 7. 8. 9. import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class MAdvertising extends MIDlet implements CommandListener { Display display = null; List menu = null; List choose = null; List choose1 = null; List choose2 = null; 372 Chapter 11: Advanced 3G Programming 10. List choose3 = null; 11. Ticker ticker = new Ticker("Mobile Components"); 12. static final Command backCommand = new Command("Back", 13. Command.BACK, 0); 14. static final Command mainMenuCommand = new Command("Main", 15. Command.SCREEN, 1); 16. static final Command exitCommand = new Command("Exit", 17. Command.STOP, 2); 18. String currentMenu = null; 19. public MAdvertising() { } 20. public void startApp() 21. throws MIDletStateChangeException { 22. display = Display.getDisplay(this); 23. menu = new List("Advertising Products", Choice.IMPLICIT); 24. menu.append("Cosmetics", null); 25. menu.append("Jewelry", null); 26. menu.append("Books", null); 27. menu.append("Clothing", null); 28. menu.addCommand(exitCommand); 29. menu.setCommandListener(this); 30. menu.setTicker(ticker); 31. mainMenu(); 32. } 33. public void pauseApp() { 34. display = null; 35. choose = null; 36. choose1 = null; 37. choose2 = null; 38. choose3 = null; 39. menu = null; 40. ticker = null; 41. } 42. public void destroyApp(boolean unconditional) { 43. notifyDestroyed(); 44. } 45. //Main menu 46. void mainMenu() { 47. display.setCurrent(menu); 48. currentMenu = "Main"; 49. } 50. public void testCosmetics() { 51. choose = new List("Cosmetic Products", Choice.MULTIPLE); 52. choose.setTicker(new Ticker("Cosmetics...")); 53. choose.addCommand(backCommand); 54. choose.setCommandListener(this); 55. choose.append("Nail Polish", null); 56. choose.append("Body Lotion", null); 57. choose.append("Body Spray", null); 58. display.setCurrent(choose); 59. currentMenu = "Cosmetics"; 60. } 61. public void testJewelry() { 62. choose1 = new List("Jewelry", Choice.MULTIPLE); 63. choose1.setTicker(new Ticker("Jewelry...")); 64. choose1.addCommand(backCommand); Chapter 11: Advanced 3G Programming 373 65. choose1.setCommandListener(this); 66. choose1.append("Earrings", null); 67. choose1.append("Necklace", null); 68. choose1.append("Bracelets", null); 69. display.setCurrent(choose1); 70. currentMenu = "Jewelry"; 71. } 72. public void testBooks() { 73. choose2 = new List("Books", Choice.MULTIPLE); 74. choose2.setTicker(new Ticker("Books...")); 75. choose2.addCommand(backCommand); 76. choose2.setCommandListener(this); 77. choose2.append("Java", null); 78. choose2.append("VB", null); 79. choose2.append("VC", null); 80. display.setCurrent(choose2); 81. currentMenu = "Books"; 82. } 83. public void testFashion() { 84. choose3 = new List("Clothing", Choice.MULTIPLE); 85. choose3.setTicker(new Ticker("Clothing...")); 86. choose3.addCommand(backCommand); 87. choose3.setCommandListener(this); 88. choose3.append("Trousers", null); 89. choose3.append("T-Shirts", null); 90. choose3.append("Jeans", null); 91. display.setCurrent(choose3); 92. currentMenu = "Clothing"; 93. } 94. public void commandAction(Command c, Displayable d) { 95. String label = c.getLabel(); 96. if(label.equals("Exit")) { 97. destroyApp(true); 98. } else if (label.equals("Back")) { 99. if(currentMenu.equals("Cosmetics") || 100. currentMenu.equals("Jewelry") || 101. currentMenu.equals("Books") || 102 currentMenu.equals("Clothing")) { 103. // go back to menu 104. mainMenu(); 105. } 106. } else { 107. List down = (List)display.getCurrent(); 108. switch(down.getSelectedIndex()) { 109. case 0: testCosmetics();break; 110. case 1: testJewelry();break; 111. case 2: testBooks();break; 112. case 3: testFashion();break; 113. } 114. } 115. } 116. } Code Description ♦ Lines 1–2: This code is to import the necessary class libraries. 374 Chapter 11: Advanced 3G Programming ♦ Lines 3–4: To create a class MAdvertising, which extends the MIDlet ♦ Lines 5–10: Initialization of menu and the choice list ♦ Line 11: Ticker class which displays a horizontal scrolling message “Mobile components” ♦ Lines 12–17: Creation of soft keys Back, Main, and Exit ♦ Line 18: Initialization of current Menu object ♦ Lines 19–32: This code creates the list items for “Advertising Products” namely, Cosmetics, Jewelry, Books, and Clothing ♦ Lines 33–41: Re-initialization of the list items ♦ Lines 42–44: Code to call the destroyApp object ♦ Lines 45–49: To display the main menu items ♦ Lines 50–60: If cosmetics are chosen, the various subitems are displayed here. Note that the horizontal scrolling is now changed to “Cosmetics”. ♦ Lines 61–71:If Jewelry is chosen, the various sub-items are displayed and horizontal scrolling is changed to “Jewelery”. ♦ Lines 72–82: If the item books is chosen in the main menu, the subitems are displayed using this code. The horizontal scrolling changes to “Books”. ♦ Lines 83–93: If the item Clothing is chosen, the sub-items are displayed using this code. The horizontal scrolling changes to “Clothing”. ♦ Lines 94–97: This code is to check if the soft key Exit is pressed and if so, to exit the application. ♦ Lines 98–115: This code keeps track of the various soft keys pressed by the user on the phone emulator. This code checks whether the back button is pressed and, if so, based on the previous actions, the previous screen is displayed. Internally, the history of the various keys pressed is stored in a history stack, and if the back button is pressed, the last entry on the stack is displayed. Otherwise, main menu is displayed. Code Output When this MIDlet is executed using the Forte for Java, you will see the screens in Figure 11-9. Chapter 11: Advanced 3G Programming 375 Figure 11-9: Mobile adverting displayed on the Wireless tool kit emulator You can compare the power of MIDlet with that of a WML-based application using this example. The look and feel of the application will be much better using the MIDlet approach because of the power of Java programming language. Summary In this chapter, we studied the programming aspects of 3G content development. We illustrated the complexity involved in creating simple animation using WML. For example, in order to animate images with WML, we need to create a number of static, low-resolution images in WMBP format and use a timer to display the images one after the other. Using XHTML, we can obtain animation by downloading an animated GIF file directly through simple code. We also illustrated how the audio and video clippings can be played using XHTML as well as XML and XSL. Using the wireless tool kit of Sun Microsystems, we illustrated the capability of creating applications on wireless devices that run the Java Virtual Machine. Chapter 12 3G Programming Using BREW The two main systems for wireless Internet access are the CDMA-based systems and the GSM-based systems. The GSM systems have been widely deployed in Europe and CDMA-based systems have a wide installation base in North America. On other continents, both types of systems are used. Qualcomm Corporation, which pioneered the CDMA technology, has released Binary Runtime Environment for Wireless (BREW) to develop applications that which can be ported on to any mobile device. In this chapter, we will discuss implementation of applications using BREW. An overview of BREW capabilities is given followed by the implementation of applications along with the source code. BREW Overview BREW provides the necessary tools to develop applications for deployment on CDMA-based wireless networks. The applications can be developed on the standard PC environment and tested before actual deployment on the network. For deployment on a commercial basis, a development organization has to obtain the necessary certification from Qualcomm. BREW SDK 1.0 supports images, graphics, and sound files in MIDI (Musical Instrument Digital Interface) and MP3 (MPEG Audio Layer 3) formats. BREW SDK 1.0.1, released in August 2001, has support for position location and application messaging as well as improved emulation capabilities. BREW SDK can be used for developing wireless applications not only for 3G networks but for the existing wireless networks as well. BREW applications are independent of the underlying air interface. As the data rates supported by the wireless networks become higher and higher, the user experience in running the applications become better due to faster response. The BREW development environment consists of a Graphical User Interface (GUI) to develop the applications and a BREW Emulator to emulate the mobile device. A number of predefined mobile device emulators with options to change the configuration parameters are available. The advantage of this is that the portability of the application for devices with different capabilities can be checked. Applications developed using BREW are called applets. Modules can also be developed, which can be used by several applets. Applets and modules are developed in C or C++ as stand-alone DLLs and are loaded into BREW Emulator at runtime. In this chapter, we use the words applets and applications interchangeably. The BREW development kit can be downloaded from https://brewx.qualcomm.com/developer/sdk/ and installed on your system. The system requirements are Windows NT 4.0 or higher or Windows 2000 with 128 MB RAM. To develop applications, Microsoft Visual Studio 6.0 or higher should also be installed. While developing applications, note that floating-point operations cannot be used. Although the application using floatingpoint operations may run on the Emulator, the target mobile devices do not support floating-point operations and should be avoided. After the BREW tool kit is loaded onto your system, you can run the sample applications provided in the kit by launching the Emulator. The BREW Emulator automatically launches the Application Manager showing the icons and applet names on the screen. To run the applications involving sound files, you Chapter 12: 3G Programming Using BREW 377 need to have a sound card installed along with the necessary driver software. You can check the functionality of the sound card by playing a stored MIDI file. All the sound files are kept in the Music folder in the Application folder. The graphics files are in the Animation folder with a BMP extension and with one-bit-per-pixel resolution. In the following sections, we will discuss how to create applications using the BREW tool kit. To start with, we will demonstrate how to create a simple application through a step-by-step procedure. After that, we will discuss the code for the following applications: ♦ Creating animation ♦ Downloading a music file onto a mobile device ♦ Mobile advertising ♦ Creating a database application. Using BREW to Develop a New Application In this section, we discuss how to create a small application that displays a welcome message on the mobile device. This example illustrates the step-by-step procedure to create the application; after you’re familiar with the procedure, creating applications more complicated than those discussed in this chapter will be quite an easy task. To develop a new application by using BREW, the steps are: 1. Create the ClassID file, meaning, BID (Binary Identification), and module information file, MIF, for the module. 2. Place the MIF in the applet directory or in a separate MIF directory. 3. Copy the workspace for one of the sample applications into your work area. 4. Write your application. 5. Place the Module DLLs in a corresponding subdirectory within the applet directory. 6. Launch the BREW Emulator and execute the application. Each of these steps is explained in detail in the following sections; here you will create a small application to display a welcome message. Create BID and MIF files To create a new application in a BREW environment, first a BID file has to be created. A BID file contains the applet or application identification. Every application must have a unique identification. The BID file is used to pass the ClassID information to the application. The BID file is created using the MIF editor. The MIF editor is launched through StartProgramsBREWMIF Editor. When you click the menu, the window in Figure 12-1 appears. If a new application is being created, a new ClassID has to be generated or an existing BID file can also be used. To select the existing BID file, click the Browse for BID file button. To create a new ClassID, click the New Applet button at the bottom of the window. The window in Figure 12-2 appears after the New Applet button is clicked. 378 Chapter 12: 3G Programming Using BREW Figure 12-1: The MIF Editor window Figure 12-2: The ClassID Generation window Enter the name of the ClassID in the Name text box and a hexadecimal number in the ClassID text box. By default the option, “From the BREW Web Site” is on. However, to create and test an applet or application locally, select the Locally option. Fill in the details and click the Generate button. A window appears asking where to save the BID file. Save the file in the Applet folder or in the Application folder. When the BID file is saved the window in Figure 12-3 appears. Chapter 12: 3G Programming Using BREW 379 Figure 12-3: The Brew MIF Editor window after entering the ClassID Enter the Name, Applet Type, Icon, and Icon Type fields. The Name field is compulsory. Click the File Save button and save the file in the Applet directory or in a separate MIF folder. The application manager processes each MIF to obtain the list of applications whose information is present within that MIF. Using the information available from the MIF, the Application Manager loads the applications. By default, a MIF folder is provided along with the BREW SDK. The folder is in the Examples folder. All the applications of MIF files are saved in that MIF folder. Note that the name of the MIF file and the BID file and the name that is provided in the ClassID generation window should be the same. Resource Editor If the application uses some resources, such as string, bitmap, or dialog controls, the Resource Editor has to be used to build the resources. Open the Resource Editor StartProgramsBREWResource Editor. If you click the menu, the window in Figure 12-4 appears. Depending on the requirement of the application, string, bitmap, or dialog control resources can be built. To create a string resource, click the menu ResourceNew String or right-click the String in the window. The window in Figure12-5 appears. Now select New String, and the window in Figure 12-6 appears. Enter the Resource ID, Resource Name, String Type, and Value and then click the OK button at the bottom of the window. A String resource is created. To create a Bitmap resource, click the menu ResourceNew Bitmap or directly right-click on the Bitmap in the BREW Resource Editor window. The window in Figure 12-7 appears. 380 Chapter 12: 3G Programming Using BREW Figure 12-4: The Resource Editor window Figure 12-5: The Options window Figure 12-6: The String Resource window Chapter 12: 3G Programming Using BREW 381 Figure 12-7: The Bitmap Resource window Enter the Resource ID, Resource Name, Path To File, and Image Type and then click the OK button at the bottom of the window. A Bitmap resource is created. To create a Dialog resource (we use it in the later examples), click the menu ResourceNew Dialog or directly right-click on the Dialog in the window. The window in Figure 12-8 appears. Figure 12-8: The Dialog Resource window 382 Chapter 12: 3G Programming Using BREW Enter the Resource ID, Resource Name, Dialog Title, Dialog Flags, Initial Focus ID, Initial Position X, Y, and Initial Size W, H and then select the type of control to use. Click the OK button at the bottom of the window after completing the above procedure. A Dialog resource is created. After creating the resources, the main Resource Editor window appears. After all the Resources are created, click the Build menu. The Build command creates the resource files, the Resource header file and a BAR file. The header file has to be included in the application, and the BAR file is defined as a resource file in the application. Copy the workspace of a sample application and write a new application. The application is written in the C language, so open the workspace that you copied and modify the C file in the workspace. (See Listing 12-1.) Listing 12-1: Welcome.c © 2001 Dreamtech Software India Inc. All Rights Reserved 1. #include "AEEModGen.h" 2. #include "AEEAppGen.h" 3. #include "AEEShell.h" 4. #include "AEEDisp.h" 5. #include "welcome.bid" 6. static boolean eventHandle(IApplet * pi, AEEEvent aee, uint16 ui, uint32 dui); 7. int AEEClsCreateInstance(AEECLSID ClsId,IShell * ish,IModule * po,void ** obj) 8.{ 9.*obj = NULL; 10.if(ClsId == AEECLSID_WELCOME){ 11.if(AEEApplet_New(sizeof(AEEApplet), ClsId, ish,po,(IApplet**)obj, 12.(AEEHANDLER)eventHandle,NULL) 13.== TRUE) 14.{ 15.return (AEE_SUCCESS); 16. 17. 18.return (EFAILED); 19.} 20.static boolean eventHandle(IApplet * pi, AEEEvent aee, uint16 ui, uint32 dui) 21.{ 22.AEEDeviceInfo di; 23.AECHAR szBuf[] = {'W','e','l','c','o','m','e','\0'}; 24.AEEApplet * app = (AEEApplet*)pi; 25.switch (aee) 26.{ 27.case EVT_APP_START: 28.ISHELL_GetDeviceInfo (app->m_pIShell, &di); 29.IDISPLAY_ClearScreen (app->m_pIDisplay); 30.IDISPLAY_DrawText(app->m_pIDisplay, AEE_FONT_BOLD, szBuf, -1, 0, 0, 31.0, IDF_ALIGN_CENTER | IDF_ALIGN_MIDDLE); 32.IDISPLAY_Update (app->m_pIDisplay); return(TRUE); 33.case EVT_APP_STOP: 34.return TRUE; Code Output Run the BREW Emulator. which is an applet ClassID.} Code Description ♦ Line 1: Header file. In this case. The event type is passed to the aee parameter.break. The method verifies the ClassID and then invokes the AEEApplet_New() function provided in the AEEAppletGen. ♦ Line 3: Header file. . the IDISPLAY_ClearScreen() function clears the screen. The handle event is used to handle all kinds of events generated in the application. To run the Emulator. select the application and run it. ♦ Line 2: Header file. use the Build command to build the application. This file contains the AEECLSID_WELCOME ClassID for the applet. ♦ Line 4: Header file. which contains the module interface definitions. the applet receives the EVT_APP_STOP event. which contains the string data. 39. ♦ Line 5: BID file. To change the Applet directory. go to FileChange applet directory or go to the ToolsSettings menu.} 38. ♦ Line 23: A character array is declared. After the Emulator launches. ♦ Line 6: Declaration of the function prototype of HandleEvent. which contains the idisplay interface definitions. After writing the application code in the visual studio environment. Figure 12-9 shows the display. change the default applet directory or MIF directory. ♦ Lines 20–39: Code for the handle event method. When the user presses the end key. place the DLL in the application sub-directory in the Applet folder. After the applet receives this event. it releases the memory occupied by the application. the string is ‘welcome’. The application produces a DLL.Chapter 12: 3G Programming Using BREW 383 35. 37.return FALSE. which contains the ishell interface definitions. The create instance method returns the AEE_SUCCESS status upon successful loading of the applet and EFAILED status upon failure.default: 36. The IDISPLAY_DrawText() function is used to draw the text in the screen. The header files are included at the beginning of the application program. which contains the applet interface definitions. ♦ Line 32: IDISPLAY_Update() function is used to update the screen. This method is invoked after the application begins. All these header files are provided along with the BREW SDK. go to StartProgramsBREWBREW Emulator. If the application is saved in a separate Applet directory or the MIF file is in a separate MIF directory. whichever is needed.c. If the EVT_APP_START receives the START event. The header files provide the definitions of the functions and of the interfaces provided. ♦ Lines 7–19: Code for create instance method. 384 Chapter 12: 3G Programming Using BREW Figure 12-9: The Welcome application on the Emulator Application: Developing Animation In this example. we create an application that displays an animated image. The first step to develop the animation application is to create the BID file. The MIF Editor is used to create the BID file. The animation example is a new application. . The window in Figure 12-11 appears after the New Applet button is clicked. so click the New Applet button at the bottom of the window. The window in Figure 12-10 appears after the MIF Editor menu is clicked. To create the BID file go to StartProgramsBREWMIF Editor. and MIF filename should be the same. The ClassID name. The window in Figure 12-12 appears after you click the Generate button. .Chapter 12: 3G Programming Using BREW 385 Figure 12-10: MIF Editor window Figure 12-11: The New Applet ClassID Generation window Enter the name and unique ClassID of the applet. Save the BID file in the application-specific folder or in the Applet directory. Click the Generate button at the bottom of the window. BID filename. Icon. Applet Type. Figure 12-13: The BREW Resource Editor window . When you click the menu.386 Chapter 12: 3G Programming Using BREW Figure 12-12: The MIF Editor window after entering the ClassID Enter the Name. the window in Figure 12-13 appears. Go to FileSave as and save the file in the Applet directory or in a separate MIF folder. and Icon Type fields. Resource Editor The application uses bitmap resources. Resource editor has to be used to build the resources. To open the resource editor go to StartProgramsBREWResource Editor. Path To File. and click the OK button at the bottom of the window. go to ResourceNew Bitmap or directly right-click on the Bitmap in the window.C © 2001 Dreamtech Software India Inc.#include 2. Resource Name. Figure 12-15: The Bitmap Resource window Enter the Resource ID. After you create the resources.h" "AEEDisp.#include 3.#include 5. Click the Build menu.h" "AEEShell. the main Resource Editor window appears. The header file has to be included in the application and the BAR file is defined as a resource file in the application. All Rights Reserved 1. The animation application code is given in Listing 12-2. Figure 12-14: The Option window Select New Bitmap.#include "AEEAppGen. Listing 12-2: Animation.Chapter 12: 3G Programming Using BREW 387 To create a Bitmap resource.#include 4. and a BAR (animation. and Image Type. The Build command creates the resource files.h). the Resource header file (animation_res.h" "AEE. You can enter the path of the bit-mapped image given in the tool kit. Copy the workspace of a sample application and write a new application.h" .h" "AEEStdLib. The window in Figure 12-14 appears. The window in Figure 12-15 appears.bar) file.h" "AEEUsageAppIDs. A Bitmap resource is created.#include 6. Open the workspace you copied and modify the C file in the workspace. po.} 49.#include "animation_res.#include "AEEFile.m_pIShell. 44. 23. 28. 43.ClsId.388 Chapter 12: 3G Programming Using BREW 7.} 55.static void freeApp(IApplet* app).h" 10.AEEApplet a.void mainMenu(ima*app).#define IDS_IMAGETITLE 0 25.typedef struct CIImageApp { 14.m_pIShell == NULL) 37.IMENUCTL_Release(app->ime).uint16 ui. 30.IIMAGE_Release (app->iim). 58.app->iim = NULL. 22.(AEEHANDLER)eventHandle.if(AEEApplet_New(sizeof(CIImageApp).return TRUE.#include "animation.} . 41. 32.if(ClsId == AEECLSID_ANIMATION){ 29. void** obj){ 27. uint16 20.(PFNFREEAPPDATA)freeApp)) 31.return(TRUE).h" 11.if ((ui == AVK_UP || ui == AVK_DOWN) && 56.#include "AEEStdLib.IImage * iim.return(TRUE).static boolean eventHandle(IApplet * pi. 16.IIMAGE_Stop (app->iim). IModule* po.app->iim != NULL){ 57.} 17. 51.*obj = NULL. 36. 18.return (EFAILED).case EVT_APP_STOP: 46.return(AEE_SUCCESS).int AEEClsCreateInstance(AEECLSID ClsId.{ initApp((IApplet*)*obj).(IApplet**)obj. 38.#define APP_RES_FILE "animation.switch (aee) { 39.IIMAGE_Release (app->iim).static boolean initApp(IApplet* app).AEECLSID_MENUCTL.boolean imageUse (ima*app.#define ANIMATION 100 26. 21. 15.CIImageApp. uint32 dui){ 35.} 34. aee.case EVT_KEY: 52.if(ISHELL_CreateInstance(app->a.if (app->iim != NULL){ 47.bar" 24.#include "AEEMenu.IMenuCtl * ime. AEEEvent aee. uint32 dui). uint16 ui).h" 9. 19.IShell.bid" 13.h" 12. 54. 48.return FALSE. 45.static boolean eventHandle(IApplet * pi. AEEEvent ui. (void **)&app->ime)) 42.case EVT_APP_START: 40.app->iim = NULL.}} 33.mainMenu(app). 50.ima* app = (CIImageApp*)pi. IShell* ish.h" 8.#include "AEEGraphics.if (ui == AVK_STAR && app->iim != NULL){ 53.return TRUE.if (app == NULL || app->a. 83.ima* app = (CIImageApp*)pi.return FALSE.EVT_KEY.void mainMenu(ima*app){ .IMENUCTL_SetActive(app->ime.IDISPLAY_UpdateEx(app->a.IMENUCTL_SetActive(app->ime.} 72.break.IDISPLAY_EraseRect(app->a.app->iim = NULL.if (app == NULL || app->a.else return FALSE.Chapter 12: 3G Programming Using BREW 389 59.cxScreen .case ANIMATION:{ 102. 100. 106. 95.} 74. 96.return FALSE.} 109.break. 107.rect. IPARM_NFRAMES.return FALSE.app->iim = NULL. 60. 86.IDB_BROWSER_ICON_ANIM).case EVT_COMMAND: 65.IMENUCTL_Release(app->ime). FALSE).app->iim=ISHELL_LoadResImage(app->a.return TRUE. 77.} 112.char szResFile[] = APP_RES_FILE.boolean imageUse (CIImageApp* app.switch (ui){ 101.case ANIMATION: 67.Param. ui). 91. 104. 64. 78. 97. 99.&rect).dy = di. 103. 61. 89.AEEImageInfo aii. 60.} 75.IIMAGE_GetInfo(app->iim. TRUE).if (app->iim != NULL){ 82.AEERect rect.switch(ui){ 66.static void freeApp(IApplet* pi){ 80.60). 70. 110. 94.&di). 92.static boolean initApp(IApplet* pi){ 76.} 84.imageUse (app.TRUE).m_pIDisplay == NULL) 93.if(app->iim){ 105.return TRUE.y = 0 .cyScreen. 81. uint16 ui){ 88.rect.if (app->ime != NULL){ 85. 0)) 62.IIMAGE_SetParm(app->iim.default: 73.return TRUE.} 108. 98. 4.x = 0.return TRUE.default: 71.m_pIShell.m_pIDisplay.} 113.IIMAGE_Release (app->iim).app->iim = NULL.m_pIShell == NULL || app->a.rect. &aii).AEEDeviceInfo di.default: 111. 69. 63. 90.ima* app = (CIImageApp*)pi.m_pIShell.szResFile.m_pIDisplay.return TRUE.dx = di. 68.} 79.}} 87.if(IMENUCTL_HandleEvent(app->ime.IIMAGE_Start(app->iim.ISHELL_GetDeviceInfo(app->a. 0).rect. ANIMATION. 123. This structure holds the data members of the applet throughout the life of the applet. ♦ Lines 75–78: The InitAppData method. ♦ Line 3: Header file. 89.STR_TO_WSTR("Animation Example".h file is created by using the resource editor.if(app == NULL || app->a. ♦ Line 11: animation_res.h contains AEEFile Services. The AEEAppGen.IMENUCTL_AddItem(app->ime. In line 94.&di). szBuf.IMENUCTL_SetTitle(app->ime. AEEStdLib. The module must verify the ClassID and then invoke the AEEApplet_New() function that has been provided in AEEAppGen. 0. ♦ Lines 4 –10: Header files. all the events are handled using the switch.cyScreen. rectangle. szBuf. ♦ Lines 34–74: Code for the handle event method.qrc. ♦ Lines 24–25: Defines the application-specific constants.h file consists of the AEEApplet declaration.y = 0. ♦ Lines 13–17: Code for the data structure IImageApp. The parameter pi is pointer to the AEEApplet structure. and image information. 121.return. This file contains the ClassID of the applet or application. The AEE. szBuf. In line 88. 117.STR_TO_WSTR("1.AECHAR szBuf[100].c. This file contains the resources used by the application.AEEDeviceInfo di. sizeof(szBuf)). 115. ♦ Line 2: Header file. After invoking AEEApplet_New().TRUE). and 90 variables are declared for device information.AEERect qrc. 125. 116. ♦ Lines 19–22: Code for the application-specific functions.cxScreen.h contains AEE StdLib Services. this function can do application specific initialization. The AEEUsageAppIDs.dy = di. 128. . AEEFile.x = 0. szBuf). 120. 127.h contains AEE Shell Services.qrc. The AEEShell. 126. AEEMenu. ♦ Lines 26–33: Code for creating the instance method. 0.qrc. This function is invoked while the application is being loaded. AEEStdLib. This function initializes application-specific data and allocates memory for the data.bid file. &qrc).m_pIShell == NULL || app->ime == NULL) 118. ♦ Line 23: Defines the resource file.IMENUCTL_SetActive(app->ime. device-specific information is loaded. This method frees data contained in application data and memory for the application data. ♦ Line 18: The handle event function declaration. Animation".dx = di. 124.h file contains ClassIDs of usage applications.m_pIShell.390 Chapter 12: 3G Programming Using BREW 114. This method handles all the events of the application. 129.IMENUCTL_SetRect(app->ime.qrc. ♦ Lines 79–86: Code for the FreeAppData method.h contains AEE stdlib services. In this. AEEDisp. ♦ Line 12: animation. 119.h contains Graphics Routines.} Code Description ♦ Line 1: Header file.h file contains the Standard AEE Declarations. sizeof(szBuf)).ISHELL_GetDeviceInfo(app->a. 122.h contains Menu Services. ♦ Lines 87–112: Code for the imageUse method. Character array is declared in line 91. The parameter aee specifies the Event sent to this applet.h contains AEE Display Services. 0). The application resource file is passed to the array. 0. NULL. AEEGraphics. when you select the text the animation is displayed. Figure 12-18 displays the animation screenshot. Lines 120–123 define the coordinates for drawing the initial rectangle. Line 102 is for loading the image resource. Figure 12-16: Emulator with Animation application . Code Output Figure 12-16 shows the initial screen of the Emulator when the animation example is chosen. Figure 1217 shows the animation applet is loaded on the Emulator. Lines 114–115 are the declaration of variables. Line 105 is for setting the image parameters. ♦ Lines 113–129: Code for the build main menu method. Line 108 is for displaying the image. Line 127 is for putting a text option. Line 125 sets a title for the display.Chapter 12: 3G Programming Using BREW 391 Lines 95-98 gives the coordinates for the rectangle. 392 Chapter 12: 3G Programming Using BREW Figure 12-17: Emulator loaded with the Animation displaying the option Figure 12-18: The Animation display . the first step is to create the BID file. we illustrate how a music file can be downloaded onto a mobile device. you can use your mobile phone to download music from a content provider and listen to it while waiting at an airport lounge. The window in Figure 12-19 appears after the MIF Editor menu is clicked. As soon as the 3G services are up and running. As usual. To create the BID file go to StartProgramsBREWMIF Editor. The MIF Editor is used to create the BID file. so click the New Applet button at the bottom of the window. Figure 12-19: The MIF Editor window Figure 12-20: The New Applet ClassID Generation window . The window in Figure 12-20 appears after the New Applet button is clicked. This application demonstrates how to accomplish this. This application is a new one.Chapter 12: 3G Programming Using BREW 393 Application: Downloading Music onto a Mobile Device In this example. #include 9. and Icon Type in the appropriate fields.h" "AEEMenu.#define 13.#include 10. All Rights Reserved 1. Icon. Click the File Save menu option and save the file in the applet directory or in a separate MIF folder.h" "AEEUsageAppIDs.#define 16.h" "AEEFile. Applet Type.#include 5.bid” PLAY 103 STOP 104 REWIND 105 FASTFORWARD 106 PAUSE 107 RESUME 108 MIDI_MAX_FILES 10 TIME_INMILLISECONDS TEMPFACTOR DIRECTORY_CHAR 5000 300 // 5000 ms .#include 3.#define 15.#define 11. Listing 12-3: Sound.#include 6. Figure 12-21: The MIF Editor Window after entering the ClassID Enter the Name.#define 17.#include 8.#define 19.#include 7. The sound application code is given in Listing 12-3.#define 14.#include 4.h" "AEESoundPlayer. we will write the new code by opening the workspace and modifyin the C file.#define 18.#ifndef "AEEModGen. The window in Figure 12-21 appears after you click the Generate button.h" “sound.394 Chapter 12: 3G Programming Using BREW Enter the name and a unique ClassID of the applet.#define 12.h" "AEEAppGen.h" "AEESound.h" "AEEStdLib.#include 2.C © 2001 Dreamtech Software India Inc. As we are creating a new application. static boolean eventHandle(IApplet * pi.#endif 27. 45.IModule * po.if (initApp((IApplet*)*obj) == TRUE){ 49. 34. uint16 ui.static boolean eventHandle(IApplet * pi. AEECLSID_MENUCTL.if(AEEApplet_New(sizeof(spa).#define DIRECTORY_STR "\\" 23.return TRUE.return FALSE. uint32 dui){ 52.m_pIShell == NULL || app->a.{*obj = NULL.(AEEHANDLER)eventHandle. 40. AEEEvent aee.} 51.case EVT_COMMAND: .IMenuCtl * ime. 30.}}} 50. EVT_KEY.case EVT_APP_START: 57. ish. 60. uint32 dui).#else 24.case EVT_APP_STOP: 62. 38.static void mainMenu(spa *app).#define DIRECTORY_CHAR '\\' 22.static boolean initApp(IApplet* app). 39.void ** obj) 44.return(TRUE). 31.po.AEEDeviceInfo info.int AEEClsCreateInstance(AEECLSID ClsId. 68.return(AEE_SUCCESS). ui.case EVT_KEY: 64.boolean flag. AEEEvent aee.return (EFAILED).uint32 ptm. 61.spa * app = (spa*)pi.static void playerUsage (spa * app. 37. 32.static void freeApp(IApplet* app). ClsId.else 67.mainMenu (app).int lh.m_pIShell. (void **) &app->ime) != SUCCESS){ 58. 55. 41.(IApplet**)obj. uint16 ui).return(TRUE).ISoundPlayer * iso.Chapter 12: 3G Programming Using BREW 395 20.#endif 28. uint16 ui.{AEEApplet a. 43.#ifdef AEE_SIMULATOR 21.if(app->ime != NULL && IMENUCTL_HandleEvent(app->ime.switch (aee) { 56.if(ClsId == AEECLSID_SOUND){ 46.return FALSE. 0)) 65.char * fname. 35.typedef struct CISoundPlayerApp 29.return FALSE.if (app == NULL || app->a.IShell * ish.#define DIRECTORY_STR "/" 26. 53. 47. 42. 63. 66.if(ISHELL_CreateInstance(app->a.m_pIDisplay == NULL) 54. 33. 36.} 59.#define DIRECTORY_CHAR '/' 25.(PFNFREEAPPDATA)freeApp) == TRUE) { 48.}spa. app->ptm = 0. (int)DIRECTORY_CHAR) + 1. (void **)&pIFileMgr)) 100.IFILEMGR_EnumNext(pIFileMgr.} 114.m_pIShell == NULL || app->a.AEEDeviceInfo *di = NULL. 98. ui). AEECLSID_FILEMGR.szName.static void playerUsage (spa * app. 87.app->fname = MALLOC(STRLEN(szStart) + 1). &pnDescent). 88. 95.case FASTFORWARD: 74.return FALSE.} 83. 108.app->fname = NULL.spa * app = (spa*)pi.case STOP: 72.IFileMgr * pIFileMgr = NULL. &fi). 94. 96.app->flag = FALSE.int pnAscent = 0.return. 77.IFILEMGR_EnumInit(pIFileMgr.IDISPLAY_ClearScreen (app->a.} 80. 120.int pnDescent = 0. 121. 113.static void freeApp(IApplet* pi){ 110.app->iso = NULL.m_pIDisplay).app->lh=IDISPLAY_GetFontMetrics(app->a.if (app->fname) 115. 90.return FALSE.di = &app->info. 89.if (!app) 91.default: 81.if ( szStart ){ 105.&app->info).} 109.ISHELL_GetDeviceInfo(app->a. 86. AEE_FONT_NORMAL. 102.return FALSE. 97. &pnAscent.} 116.switch(ui){ 70.return FALSE.} 107.app->ime = NULL. FALSE).STRCPY(app->fname.return TRUE.FileInfo fi.char * szStart. 92. 104.playerUsage (app.m_pIShell.396 Chapter 12: 3G Programming Using BREW 69. 85.app->ime = NULL.m_pIDisplay. uint16 ui){ 117.szStart = fi. 111.szName. 99.case REWIND: 73. 118.case RESUME: 76.IMENUCTL_Release (app->ime). 78.FREE (app->fname). 101.if (app->ime != NULL){ 112.m_pIDisplay == NULL) 119.} 82. szStart). "Music". // STRCHR(fi.m_pIShell.case PLAY: 71. 106.spa * app = (spa*)pi. . 93. 103.if (app == NULL || app->a.case PAUSE: 75.return TRUE.default: 79.if ( ISHELL_CreateInstance(app->a.break.static boolean initApp(IApplet* pi){ 84.IFILEMGR_Release(pIFileMgr). STR_TO_WSTR("Pause". PLAU.uint32 dwTime.ISHELL_CreateInstance(app->a.uint32 dwTime. 129.AECHAR szBuf[50]. 0). // in milliseconds 135. 170.case PLAY:{ 124. sizeof(szBuf)). 167.Chapter 12: 3G Programming Using BREW 397 122. 0). } 150. szBuf.case FASTFORWARD: { 138. 0. 0.cyScreen). } } 147.IMENUCTL_AddItem(app->ime. } } 131.&di). szBuf. 161.IMENUCTL_SetTitle(app->ime. } 141. 137.switch (ui){ 123. 132. 0). } } 144.return. REWIND.int pnAscent = 0.return. sizeof(szBuf)). 153. // in milliseconds 140. 0.static void mainMenu(spa *app){ 152. szBuf.m_pIShell. app->fname).ISOUNDPLAYER_Pause (app->iso).ISHELL_GetDeviceInfo(app->a.STR_TO_WSTR("FastForward (5 secs)".AEEDeviceInfo di. NULL.return. di.IMENUCTL_AddItem(app->ime.STR_TO_WSTR("SoundPlayer Menu:".dwTime = TIME_INMILLISECONDS.dwTime = TIME_INMILLISECONDS. } 128. { 139. 173. } } 136.return.return.m_pIShell. PUSE. STOP. . 165. SDT_FILE. szBuf. 168. di. szBuf. 0.case STOP:{ { 130. szBuf.if (app == NULL || app->ime == NULL || app->a.ISOUNDPLAYER_Play (app->iso).IMENUCTL_AddItem(app->ime.return.ISOUNDPLAYER_Stop (app->iso).default: 149. 148. &qrc).IMENUCTL_AddItem(app->ime. 171. 0.return. 0). dwTime).case REWIND: { 133. szBuf.ISOUNDPLAYER_Set(app->iso. 166. sizeof(szBuf)).STR_TO_WSTR("Play". szBuf. FASTFORWARD. 155. { 134. 127. 172. szBuf.int pnDescent = 0.IMENUCTL_AddItem(app->ime. 0.int charHeight = 0. 145.STR_TO_WSTR("Stop".ISOUNDPLAYER_Rewind (app->iso.SETAEERECT (&qrc. 142.if (app->iso == NULL){ 125. 0).AEERect qrc. 174. (void **)&app->iso). 0. 162.cxScreen. AEECLSID_SOUNDPLAYER. szBuf. 154. 0.m_pIShell == NULL) 159.STR_TO_WSTR("Rewind (5 secs)".IMENUCTL_SetRect(app->ime. 0. } 126. 157.case PAUSE: { { 143. 0. 156. 0. 164. sizeof(szBuf)).return. szBuf.return. sizeof(szBuf)). sizeof(szBuf)). 0. 169. dwTime). 160.ISOUNDPLAYER_FastForward (app->iso. 0. 158. szBuf). 163.case RESUME:{ { 146.} 151.ISOUNDPLAYER_Resume (app->iso). ♦ Lines 43–50: The create instance method. The module must verify the ClassID and then invoke the AEEApplet_New() function that has been provided in AEEAppGen. 171.398 Chapter 12: 3G Programming Using BREW 175. This method frees data contained in applet and memory for the data. The MIDI file will be played when the play option is selected. 169. This structure contains information specific to this applet. Code Output Figure 12-22 shows the display when the applet is loaded in the Emulator. The AEEAppGen.IMENUCTL_AddItem(app->ime.bid. The AEEModGen. ♦ Lines 116–150: The playerUsage method. allocates memory for the data. ♦ Line 109–115: The FreeAppData method. szBuf. ♦ Lines 19–27: Declaration statements. ♦ Lines 39–42: Code for the application-specific functions.} Code Description ♦ Line 1: Header file. ♦ Lines 28–37: Code for the IsoundPlayerApp data structure.h file consists of AEEModule declaration. Lines 165. ♦ Line 9: The BID file. ♦ Lines 10–18: Defines the constants used in the application. 0). 173. ♦ Line 38: The handle event function declaration.h file contains AEEApplet declaration.TRUE). sizeof(szBuf)). 176. rewind. this function can do applet specific initialization. szBuf. 0. RESUME. or fast forward the music file using the given options. 167. ♦ Lines 83–108: The InitAppData method. ♦ Lines 51–82: The handle event method.IMENUCTL_SetActive(app->ime. This structure holds the data members of the applet throughout the life of the applet. ♦ Line 2: Header file.STR_TO_WSTR("Resume". This function is invoked while the applet is being loaded. Line 163 displays the text as a title of the screen. sound. After invoking AEEApplet_New(). This method handles all the events of the application. You can pause. ♦ Lines 151–177: The build player menu function. The options are called using the switch case. ♦ Lines 3–8: Header files as in the earlier examples.c. This function encompasses all the usage examples of all the functions in code blocks switched using the BREW API function Id passed into this function. This function initially displays some text on the screen. This function initializes applet-specific data. 0. 177. . It is initialized during the AEEClsCreateInstance() function and code specifies the event sent to this applet. the attached functionality will be performed. and 175 display the options on the screen. The pi parameter is Pointer to the AEEApplet structure. After the option is selected. we create an application that displays a list of businesses.Chapter 12: 3G Programming Using BREW 399 Figure 12-22: Display in the Emulator when Sound Application is loaded Application: Mobile Advertisements In this example. however. When a business is selected. The first step is to create the BID file. here we will use the Dialogue Resources to create the dialogues required for our application. Figure 12-23: The MIF Editor window . We follow the same steps as discussed in the earlier examples. Go to StartProgramsBREWMIF Editor. The window in Figure 12-23 appears after the MIF Editor menu is clicked. The MIF editor is used to create the BID file. the product range of that business is displayed. Click the File Save button and save the file in the Applet directory or in a separate MIF folder. The window in Figure 12-25 appears after you click the Generate button. . and Icon Type in the appropriate fields. Figure 12-25: The MIF Editor window after entering the ClassID Enter the Name. Figure 12-24: The new applet ClassID Generation window Enter the name and ClassID of the applet and ensure that the ClassID name. Applet Type. Click the Generate button at the bottom of the window and save the BID file. BID filename. so click the New Applet button at the bottom of the window.400 Chapter 12: 3G Programming Using BREW The advertisement example is a new applet. and MIF filename are the same. Icon. The window in Figure 12-24 appears after the New Applet button is clicked. The Resource Editor has to be used to build the resources. The window in Figure 12-27 appears. To open the Resource Editor go to StartProgramsBREWResource Editor.Chapter 12: 3G Programming Using BREW 401 Resource Editor The application uses string and dialog resources. The window in Figure 12-28 appears. Figure 12-27: The Option window Select New String. go to ResourceNew String or directly right-click on the string in the window. Figure 12-28: The String Resource window . Figure 12-26: The BREW Resource Editor window To create a string resource. By clicking the menu the window in Figure 12-26 appears. String Type. Resource Name. After you create the resources. A Dialog Resource is created.h). Resource Name.#include 3.h" "AEE. The Build command creates the resource files. Listing 12-4: Advertise. the main Resource Editor window appears.h" . The header file has to be included in the application and the BAR file is defined as a resource file in the application. the Resource Header file (advertise_res. Dialog Title. Initial Focus ID.h" "AEEShell. Y. After creating the resources. To create a Dialog Resource. After all the Resources are created.#include "AEEAppGen.402 Chapter 12: 3G Programming Using BREW Enter the Resource ID. and Value and click the OK button at the bottom of the window. and a BAR file (advertise.C © 2001 Dreamtech Software India Inc.#include 2.h" "AEEDisp. The window in Figure 12-29 appears. the main Resource Editor window appears. and Initial Size W. H and then select the type of control to use. Initial Position X.#include 4.bar).#include 5. go to ResourceNew Dialog or directly right-click on Dialog in the window. Click the OK button at the bottom of the window after completing the previous procedure. Figure 12-29: The Dialog Resource window Copy the workspace of a sample application and write a new application using the code is given in Listing 12-4. All Rights Reserved 1. Enter the Resource ID. click the Build button. Dialog Flags.h" "AEEUsageAppIDs. A String resource is created. #define PANASONIC 105 27.static void freeApp(IApplet* app).{ida * app = (ida*)pi.(PFNFREEAPPDATA)freeApp) == TRUE){ initApp((IApplet*)*obj).IMenuCtl * ime.} 39. AEEEvent aee.h" 10.h" 9. IModule* po. AEECLSID_MENUCTL.} ida.} 52.#define SONY 102 25. 36. uint16 ui.{ *obj = NULL. 46.(IApplet**)obj.AEEApplet a. 34.IMENUCTL_Release(app->ime). ish.Chapter 12: 3G Programming Using BREW 403 6. uint32 dui) 40.h" 7.#define APP_RES_FILE "advertise.if(app->ime != NULL){ 50. 44.(void **)&app->ime) != SUCCESS) 45.int AEEClsCreateInstance(AEECLSID ClsId. 23.static boolean eventHandle(IApplet * pi. 20.#include "AEEFile.switch (aee) { 42. 38.if(ClsId == AEECLSID_ADVERTISE){ 33.h" 12.return (EFAILED). 51.#include "advertise_res.#define BORDER_WIDTH 5 30.return(TRUE).return(TRUE).(AEEHANDLER)eventHandle.} } 37.case EVT_KEY: 54.#include "AEEGraphics.case AVK_DOWN: . 15. 47. 53.#define PHILIPS 109 29. 16.h" 11.#include "advertise.case EVT_APP_START: 43.static boolean initApp(IApplet* app). 22.void mainMenu(ida *app).if(AEEApplet_New(sizeof(ida). 19. 18. 32.bar" 24.if(ISHELL_CreateInstance(app->a.boolean dailogUsage(ida *app.m_pIShell. 48.app->ime = NULL.switch (ui){ 55. uint16 ui. uint16 ui). 35.case AVK_UP: 56.case EVT_APP_STOP: 49.#define MERCEDES 107 28. uint32 dui).AEERect rc. void** obj) 31. IShell* ish. 21.bid" 13.static boolean eventHandle(IApplet * pi.#define KENWOOD 104 26.return(AEE_SUCCESS).#include "AEEStdLib.typedef struct CIDialogApp { 14.h" 8.return TRUE.#include "AEEMenu. 41. AEEEvent aee. 17.po.#include "AEEStdLib.mainMenu(app). ClsId. 'S'.&di).if (ISHELL_GetActiveDialog(app->a.dialogUsage (app.return TRUE.m_pIShell) != 0) 60.TRUE). 94.case KENWOOD: 76.app->ime = NULL.'A'.m_pIShell.m_pIShell) != 0){ 59.}} 72.'T'. 65.'D'.AEERect qrc. 103.y = BORDER_WIDTH. 63.'\0'}.case PHILIPS: 79.} 87.AECHAR mbuf1[] = {'E'.app->rc.'Z'.TRUE). EVT_KEY.cyScreen .case MERCEDES: 78.app->rc.default: 67.return TRUE. ui.AEEDeviceInfo di.'S'.case PANASONIC: 77.char szResFile[] = APP_RES_FILE. 112.'Z'. 101.'O'.switch(ui){ 74.ida * app = (ida*)pi. 71.m_pIShell == NULL) 91.(2 * BORDER_WIDTH).'A'.IDISPLAY_EraseRect(app->a. ui).ISHELL_GetDeviceInfo(app->a.case EVT_COMMAND: 73.'E'. uint16 ui){ 105.default: 83.'B'.(2 * BORDER_WIDTH). 89. 106. 66.}} 104. 82. 93.app->rc.'A'. 98. 108 109 110. 61.static boolean initApp(IApplet* pi){ 88.AECHAR probuf[] = {'P'.dy = di. 80.'L'. 0)) 70. 81. FALSE).IMENUCTL_SetActive(app->ime.if(IMENUCTL_HandleEvent(app->ime.return FALSE.return TRUE.404 Chapter 12: 3G Programming Using BREW 57. ui.else return FALSE.'\0'}. 0)) 64.'C'. EVT_KEY.if(app->ime != NULL){ 102. 92.AEEDeviceInfo di.} 99.m_pIShell).case SONY: 75.} 84.'S'.'T'.if (IMENUCTL_HandleEvent(app->ime.app->rc. 97.m_pIDisplay.'N'.x = BORDER_WIDTH.static void freeApp(IApplet* pi){ 100.case AVK_SELECT: 58.} 62.if(!ISHELL_GetActiveDialog(app->a. 111.while (ISHELL_GetActiveDialog(app->a.app->ime = NULL.ISHELL_EndDialog(app->a.'E'. 90.IMENUCTL_SetActive(app->ime.'R'. 95.else return FALSE.'U'. 69. 96. &app->rc).return TRUE.boolean dialogUsage (ida * app.'B'.return TRUE.dx = di.return FALSE.ida * app = (ida*)pi. .'\0'}.'C'.IMENUCTL_Release(app->ime).if (app == NULL || app->a.AECHAR mbuf[] = {'T'.cxScreen .default: 85.} 86.break.'N'.m_pIShell)){ 68. 107.IMENUCTL_SetActive(app->ime. IDISPLAY_DrawText(app->a.50. -1.m_pIShell.cyScreen.&qrc).'I'. sizeof(title)). title. sbuf1. 139.'I'.'\0'}. 122.case SONY:{ 127.50.ISHELL_EndDialog(app->a.IDISPLAY_Update (app->a.STR_TO_WSTR("KENWOOD".50. 154.IDISPLAY_DrawText(app->a. 133.50.x = 0.'V'.return FALSE.m_pIDisplay). 137.0. title. sizeof(text)). 152.case MERCEDES:{ 158. text). THE LIFE IN ELECTRONICS". sizeof(title)). -1.break. 132.'M'.m_pIShell.m_pIShell.case PANASONIC:{ 150.'I'.switch (ui){ 126.'N'. 129. THE MUSIC OF THE WORLD". 134. AEE_FONT_BOLD. IDF_TEXT_TRANSPARENT).". text[100].'U'. IDF_TEXT_TRANSPARENT).50.IDISPLAY_DrawText(app->a. text[100]. IDF_TEXT_TRANSPARENT).'S'.70.'I'.'A'. 160. title.'O'.'D'. 144. title.50.cxScreen.STR_TO_WSTR("WELCOME TO KENWOOD. text[100].STR_TO_WSTR("PANASONIC". 124.m_pIShell. sizeof(title)).&di).'T'. title.'D'.'M'.ISHELL_GetDeviceInfo(app->a.0. } 148.m_pIDisplay == NULL) 118.m_pIDisplay. text). sbuf3.90. 161.'Y'. sizeof(text)).'E'.break. 116.'T'. 119. title.STR_TO_WSTR("WELCOME TO PANASONIC.AECHAR title[20].text. sbuf. text[100].IDISPLAY_DrawText(app->a.m_pIShell.AECHAR sbuf1[] = {'A'. 159.} 140. 138. 117. 145.ISHELL_EndDialog(app->a.'I'.0. 115.'S'. 130.'I'.AECHAR sbuf3[] = {'H'.qrc.AECHAR sbuf[] = {'T'. 143.STR_TO_WSTR("WELCOME TO MERCEDES. 125.ISHELL_MessageBoxText(app->a. -1.'M'.100.'S'.m_pIDisplay.SHELL_MessageBoxText(app->a. title.text. IDF_TEXT_TRANSPARENT).'\0'}.IDISPLAY_DrawText(app->a. sizeof(text)).qrc. sizeof(text)). text).'\0'}. 141.'F'.ISHELL_EndDialog(app->a.m_pIShell).Chapter 12: 3G Programming Using BREW 405 113. 151.m_pIShell). AEE_FONT_BOLD. -1. 120.qrc. 136.m_pIDisplay.text.IDISPLAY_EraseRect(app->a. 128. 149.AECHAR title[20].ISHELL_EndDialog(app->a.ISHELL_MessageBoxText(app->a.'Y'. 131.m_pIDisplay.AECHAR title[20]. 146.'O'. AEE_FONT_BOLD. sbuf2.'A'. 157. AEE_FONT_BOLD.'\0'}.'E'.case KENWOOD:{ 142.'N'. AEE_FONT_BOLD.'S'.AECHAR title[20].STR_TO_WSTR("SONY".m_pIDisplay.'E'.'S'. . 163.dy = di.AECHAR sbuf2[] = {'H'.m_pIDisplay.'S'.if (app == NULL || app->a.0.'I'.STR_TO_WSTR("WELCOME TO THE WORLD OF SONY. 114. probuf. } 156.qrc.STR_TO_WSTR("MERCEDES".m_pIShell == NULL || app->a. text).'L'.m_pIShell). 147. IDF_TEXT_TRANSPARENT).ISHELL_MessageBoxText(app->a.y = 0. 123.dx = di.break.text.'C'. 121. title.m_pIShell). sizeof(title)).ISHELL_EndDialog(app->a. 162. 153.80.m_pIShell). -1. 155. THE DEFINITION OF CAR".0. 135. dy = di. 0. sizeof(buf)). sizeof(buf)). 196.STR_TO_WSTR("MERCEDES". AEEStdLib.0. 0.case PHILIPS:{ 170. 199.TRUE).IMENUCTL_AddItem(app->ime. 0. 192. 0.m_pIDisplay.m_pIDisplay). buf.STR_TO_WSTR("PANASONIC".qrc.STR_TO_WSTR("Advertisements : press and Select the one you want".406 Chapter 12: 3G Programming Using BREW 164. AEEDisp. 0). ♦ Line 2: Header file.STR_TO_WSTR("WELCOME TO PHILIPS .STR_TO_WSTR("PHILIPS". &qrc).60. KENWOOD.50. 169.&di). buf.h file contains the Standard AEE Declarations. 0.IMENUCTL_AddItem(app->ime.AEEDeviceInfo di.return FALSE.h contains AEE StdLib Services.IMENUCTL_AddItem(app->ime. buf.m_pIDisplay. 191. 0. 182. 200.y = 0. sizeof(buf)). 186. buf).50.m_pIShell). 173.IMENUCTL_SetActive(app->ime. .h contains Menu Services.ISHELL_EndDialog(app->a.break. 0). 0.IDISPLAY_DrawText(app->a.} 179. NULL. 0. 174.qrc. AEE_FONT_BOLD. AEE_FONT_BOLD. 0). 0. The AEEShell. 197. 184. AEEMenu. MERCEDES.x = 0. 198.IDISPLAY_DrawText(app->a. ♦ Line 3: Header file. PANASONIC. PHILIPS.50.h file contains ClassIDs of applet.ISHELL_MessageBoxText(app->a. The AEEAppGen. 172.m_pIShell). SONY. buf. IDF_TEXT_TRANSPARENT).IMENUCTL_SetRect(app->ime. buf.return TRUE. The AEE.STR_TO_WSTR("PHILIPS". AEEStdLib. 187.h file consists of AEEApplet declaration. 188. 177. 194.IMENUCTL_SetTitle(app->ime. buf. sizeof(buf)). buf. 189. text). -1. 0). 193. 195.h contains AEE Display Services.cyScreen. 167.STR_TO_WSTR("KENWOOD". 0).161. text.m_pIShell. IDF_TEXT_TRANSPARENT). text[100]. mbuf1.AECHAR buf[100]. 175.h contains AEEFile Services. 166. 0.m_pIShell == NULL || app->ime == NULL) 185. sizeof(buf)). 165. sizeof(buf)).break.IDISPLAY_Update (app->a.return.161.h contains Graphics Routines.ISHELL_GetDeviceInfo(app->a.dx = di.IMENUCTL_AddItem(app->ime.ISHELL_EndDialog(app->a. mbuf. The AEEUsageAppIDs. -1. 204.STR_TO_WSTR("SONY".default: 178. title. buf.AEERect qrc.h contains AEE stdlib services. } 168.cxScreen.} Code Description ♦ Line 1: Header file. } 176. 201. title.h contains AEE Shell Services.} 180.0. buf. LETS MAKES THINGS BETTER". 183.qrc.if (app == NULL || app->a. buf. sizeof(title)). buf.m_pIShell. 0.qrc. 190. AEEGraphics. 171.AECHAR title[20]. AEEFile.void mainMenu(ida *app){ 181. 203. ♦ Lines 4–10: Header files. sizeof(text)).IMENUCTL_AddItem(app->ime. 202. Lines 108-116 are for declaring the character buffers to store some data. This method frees data contained in the applet and memory for the data. After invoking AEEApplet_New(). This function is invoked while the applet is being loaded.bid file. all the events are handled using the switch statement. This method is the first to display some text options on the screen in this application. followed by the lines 133–137 for displaying text on the screen. In this case. The parameter code specifies the Event sent to this applet. This file contains the ClassID of the applet. ♦ Lines 180–204: Code for the build main menu method. Line 183 is to declare a character array of size 100. and 202 put text on the screen. ♦ Lines 19–22: Code for applet-specific functions.c. Lines 194. ♦ Lines 39–86: The handle event method. The parameter pi is pointer to the AEEApplet structure. Lines 189–192 are for defining coordinates. The switch case starts from line 125. Code Output Figure 12-30 shows the initial display with the menu items when the applet is loaded on to the Emulator.Chapter 12: 3G Programming Using BREW 407 ♦ Line 11: animation_res. This file contains the resources used by the applet. Line 129 displays text as body. this function can do appletspecific initialization. This structure holds the data members of the applet throughout the life of the applet. ♦ Lines 87–98: Code for the InitAppData method. ♦ Lines 13–17: Code for the data structure IDialogApp. 200. Figure 12-31 shows the display when SONY menu item is selected. . ♦ Line 23: Defines the resource file ♦ Lines 24–29: Defines the application-specific constants. Lines 120–123 are for declaring the coordinates to draw a rectangle. ♦ Line 99–103: Code for the FreeAppData method.h file is created by using the Resource Editor. Line 128 displays text as a title. Line 186 puts some text on to the screen. ♦ Lines 30–38: Create instance method. This function initializes applet-specific data and allocates memory for the data. The module must verify the ClassID and then invoke the AEEApplet_New() function that has been provided in AEEAppGen. 198. This method handles all the events of the applet. 196. ♦ Line 104–179: Code for the dialogUsage method. ♦ Line 18: Handle event function declaration. ♦ Line 12: Animation. 408 Chapter 12: 3G Programming Using BREW Figure 12-30: Initial display in the screen when the applet is loaded Figure 12-31: The display in the Emulator when the Sony option is selected . { 40.static void dbUsage (dbap * app.static void mainMenu(dbap *app). The code in Listing 12-5 creates an internal database and also provides the dialogues required for accessing the database. uint16 ui). Listing 12-5: Code for database application © 2001 Dreamtech Software India Inc.{ 17. 20.h" 8.IShell * ish. #include "AEEMenu. .AEEDeviceInfo dinfo. { 31. 18. uint16 ui. This internal database provides faster access to the data as compared to having an external database and accessing the data through the standards SQL commands.static void freeApp(IApplet* app).int AEEClsCreateInstance(AEECLSID ClsId.#include "AEEStdLib. 35.void ** obj) 30. #define APP_RES_FILE "idbusage.IMenuCtl * ime. return(AEE_SUCCESS). The basic code given here can be enhanced to create applications such as mobile commerce or accessing corporate databases.#define SOFTKEY_MENU_HEIGHT 20 15. (AEEHANDLER)eventHandle. uint32 dui). 21.IModule * po.h" 3.h" 6.(PFNFREEAPPDATA)freeApp) 36. AEEEvent aee. if (initApp((IApplet*)*obj) == TRUE) 39.#define REMOVE 111 14. 22.h" 7. 24. ClsId. All Rights Reserved 1. we create a database and a user interface on the mobile device to retrieve the information from the database. 19. #include "AEEAppGen. int nline. { 38.}dbap.AEEApplet a. if(AEEApplet_New(sizeof(dbap). 23.typedef struct CIDBApp 16. if(ClsId == AEECLSID_DATABASE_APP) 33.bar" 9.int lh.h" 4. ish.static boolean initApp(IApplet* app).#define RETRIEVERECORD 107 12.static void display(dbap * app. #define OPENDATABASE 101 10. #include "AEEDB. 32. char *pszStr).Chapter 12: 3G Programming Using BREW 409 Application: Database In this application. == TRUE) 37. 26. #include "AEEUsageAppIDs. *ibj = NULL.h" 5.(IApplet**)ppObj. 28. 27. 25.h" 2. 29. #include "AEEModGen.po.#define ADDRECORD 104 11.static boolean eventHandle(IApplet * pi. #include "idbusage_res.#define UPDATE 110 13. { 34. (void **) &app->ime) 53. { 55. 79. return FALSE.else 65. 59. != SUCCESS) 54. int pnDescent.case EVT_APP_STOP: 60. ui. default: 78. ui). switch (aee) 50. 91.case ADDRECORD: 72.case UPDATE: 74. } 42. return TRUE. 61.return(TRUE). 89. { 48.return (EFAILED). int pnAscent.} 43. } 57. 58.m_pIShell.} 83. if(app->ime != NULL && IMENUCTL_HandleEvent(app->ime.return TRUE.410 Chapter 12: 3G Programming Using BREW 41. dbap * app = (dbap*)pi.dbUsage(app. return FALSE. dbap * app = (dbap*)pi.case REMOVE: 75. 66. app->ime = NULL. } 80. 0)) 63.switch(ui) 68.{ 69.m_pIDisplay. 77.return FALSE. 56. uint16 ui. 76. default: 81. break. uint32 dui) 47. AEE_FONT_NORMAL.static boolean initApp(IApplet* pi) 86.return(TRUE). 82.case EVT_COMMAND: 67.mainMenu(app). if(ISHELL_CreateInstance(app->a. . 84. 70. AEEEvent aee.static boolean eventHandle(IApplet * pi. case EVT_APP_START: 52. 88. { 51.case RETRIEVERECORD: 73. AEECLSID_MENUCTL. 90.case EVT_KEY: 62.case OPENDATABASE: 71. 64. return FALSE.} 46. app->lh = IDISPLAY_GetFontMetrics (app->a. 45.} 44.{ 87. EVT_ KEY.} 85. 49. IDISPLAY_ClearScreen (app->a. -1.if (idb == NULL) 118. 94. "db1".display (app.m_pIDisplay). &pnDescent).switch (ui) 110.IShell *ish = app->a.IDatabase * ida = NULL.static void freeApp(IApplet* pi) 97. 127.break.if (app->ime != NULL) 100. ISHELL_GetDeviceInfo(app->a. 103. 140.} 96. 132.else 130. uint16 ui) 106.{ 111.static void dbUsage (dbap * app. 109. case OPENDATABASE: 112.} 105. 137. -1.IDBRecord *idbr = NULL. } 134. &pnAscent. "Database open failed"). 102. flag = TRUE.!= NULL) 125.} 129. -1.ISHELL_CreateInstance(ish.IDATABASE_Release (ida).display (app. return. IDBMgr *idb = NULL. flag)) 120.IMENUCTL_Release (app->ime).{ 144. 115. 116.m_pIShell.} 133. == NULL) 121. return TRUE. 146.m_pIShell.{ 107. { 122. (void **)&idb).{ 113. 128. 119. *ifbr1= NULL.IDBMgr *idb = NULL. 117. "db1". 93. "Opened an already existing Database. 95.{ 101.else 135.{ 136.{ 126. 99.} 139.{ 131. "Database open successful").} 141. .IDBMGR_Release (idb). 108. flag)) 124.case ADDRECORD: 143.dbap * app = (dbap*)pi.{ 98.} 104.boolean flag = FALSE. display (app.Chapter 12: 3G Programming Using BREW 411 92. 145.if ((ida = IDBMGR_OpenDatabase (idb.").if ((ida = IDBMGR_OpenDatabase (idb. 142. 138. AEECLSID_DBMGR.IDATABASE_Release (ida). 114.&app->dinfo). 123.app->ime = NULL.IDatabase * ida = NULL. 167. 177.} 192.412 Chapter 12: 3G Programming Using BREW 147. field11[1].field[0].} 196. field11[1].!= NULL) 198. nfields)) 197. 160. 151. FALSE)) != NULL) 184. field. 159. 168.{ 188. 190.fName = AEEDBFIELD_HOME_PHONE.!= NULL) 187. field [2].fName = AEEDBFIELD_ADDRESS. field [1]. field1. field11[0]. 170. field11[2]. 175. -1.if ((idbr1 = IDATABASE_CreateRecord (ida.return.fType = AEEDB_FT_DWORD. (void **)&idb).pBuffer = (void *)name1. 181. field11[0].display (app.wDataLen = STRLEN (address). field [1]. 172. field11[2]. 179.const char address[] = "123 First Street.uint32 phno1 = 1234568. 156.wDataLen = STRLEN (name).wDataLen = sizeof (uint32).fType = AEEDB_FT_STRING.fName = AEEDBFIELD_FULLNAME. field [2]. 166.fType = AEEDB_FT_STRING. 189. field [0]. 195. 152. 154.if ((idbr = IDATABASE_CreateRecord (ida.field[0].fType = AEEDB_FT_STRING. "Create DB: successful").else 193. 176. field11[1]. 150.if (idb == NULL) 182.uint32 phno = 1234567.pBuffer = (void *)&phno1. "Create DB: successful"). 191. USA". 165. 164. field [1]. "Create DB: Failed").IDBRECORD_Release (idbr).pBuffer = (void *)name. . field [0]. 155.{ 194.int nfields = 3. field11[0]. 173.pBuffer = (void *)&phno.fName = AEEDBFIELD_HOME_PHONE. -1. field [1]. 174. 148. field11[2]. 157. field11[2].fType = AEEDB_FT_STRING.{ 199. 162.wDataLen = STRLEN (name). 153. 149.pBuffer = (void *)address1.ISHELL_CreateInstance(ish.pBuffer = (void *)address. -1. "db1". field11[0]. 171.if ((ida = IDBMGR_OpenDatabase (idb.{ 185.wDataLen = sizeof (uint32). 180. 178. 183. field [2].AEEDBField field[3]. AEECLSID_DBMGR. nfields)) 186.const char name [] = "Saidev". 163. field1[3]. 169. field [2]. INDIA".fName = AEEDBFIELD_FULLNAME. 158.const char address1[] = "124 Second Street.fName = AEEDBFIELD_ADDRESS.wDataLen = STRLEN (address).display (app.fType = AEEDB_FT_DWORD. 161.const char name1 [] = "hanuma".display (app. field11[1]. } 202. "db1". 243. 253.case RETRIEVERECORD: 212.} 208. 230.if (data != NULL) 240.AEEDBFieldName fname. ftype = IDBRECORD_NextField (idbr1.IDBRecord * idbr1 = NULL.for(i=0.IDBRecord * idbr2 = NULL.else 203.{ 213.break. "Create DB: Failed").display (app.SPRINTF (szBuf. &ftype. IDBMGR_Release (idb).if ((ida = IDBMGR_OpenDatabase (idb.data = IDBRECORD_GetField (idbr1. &fname. (char *)data). 215. ++j. 231.if (idb == NULL) 226.data = IDBRECORD_GetField (idbr1.if (idbr1 != NULL) 236.uint32 rcount=0. &flen).AEEDBFieldType ftype.i++){ 234. 235. (char *)data). ++j. 209. szBuf). IDBMGR_Release (idb). (void **)&idb). 222.} 244. &fname.IDBRECORD_Release (idbr1).j=0.IDATABASE_Release (ida).if (data != NULL) . 227. 217. &flen). 214.} 232. &fname. 211.Chapter 12: 3G Programming Using BREW 413 200.} 251. "field 2: %s". 249. rcount =IDATABASE_GetRecordCount(ida). 216. 239. & fname. &flen). 233. 221. 218. ftype = IDBRECORD_NextField (idbr1.} 206. 246. 219. &ftype.{ 241.int i.SPRINTF (szBuf. 205. AEECLSID_DBMGR.char szBuf[50] = {0}. &fname. ftype = IDBRECORD_NextField (idbr1.i< rcount.return. return.if (data != NULL) 247. &flen).data = IDBRECORD_GetField (idbr1. 201. szBuf).{ 248. &fname.ISHELL_CreateInstance(ish. FALSE)) == NULL) 228.IDBMgr * idb = NULL. idbr1 = IDATABASE_GetNextRecord (ida).{ 229. 242. 220.uint16 flen. 224.} 210. &flen).{ 237. 223. &ftype. display (app.byte * data = NULL. 225. 252. 245. -1. "field 1: %s".IDatabase * ida = NULL.{ 204.display (app. 238. &flen). 207. 250. data = IDBRECORD_GetField (idbr. 280.{ 305. 277. 306. szBuf). 294. (char *)data).{ 292. 285. 274.uint16 flen.IDBMGR_Release (idb).SPRINTF (szBuf. 299. 269. if (data != NULL) 291.byte * data = NULL. &flen). 2. 1). szBuf).ISHELL_CreateInstance(ish.return. &flen). 303. &fname.IDBMgr * idb = NULL.int nfields = 1. (void **)&idb). field [0]. 268.SPRINTF (szBuf. 275.const char lastName [] = "SaiDev".fName = AEEDBFIELD_LASTNAME.if ((ida = IDBMGR_OpenDatabase (idb.} 287. 263. &fname. "Updated Val: %s".if (data != NULL) 304. 272.return. "db1". &fname.{ 267.{ 255. "Field Val: %s".wDataLen = STRLEN (lastName).display (app.} 308. 296. 273. 297. 289.char szBuf[30] = {0}. 4.IDBRecord * idbr = NULL. &fname. 278. 279.case UPDATE: 266.data = IDBRECORD_GetField (idbr. 293. 286.if ((nRetVal = IDBRECORD_Update (idbr.(char *)data). 282. &flen).int nRetVal = AEE_DB_EBADREC.} 295.display (app. (char *)data). &ftype.IDATABASE_Release (ida).SPRINTF (szBuf. field [0]. 290.IDatabase * ida = NULL.break. 256. 265.} 358.{ 284. 270. 288.} 259. FALSE)) == NULL) 283. 260. field [0].AEEDBFieldType ftype.fType = AEEDB_FT_STRING. 302.pBuffer = (void *)lastName. field [0].display (app. 271.} 264.{ 301.AEEDBFieldName fname. AEECLSID_DBMGR. szBuf).} . field. ftype = IDBRECORD_NextField(idbr.414 Chapter 12: 3G Programming Using BREW 254. 307.IDBMGR_Release (idb). ftype = IDBRECORD_NextField(idbr.if (idb == NULL) 281. "field 3: %d". &ftype.} 261. &flen). 276.IDBRECORD_Release(idbr1).idbr = IDATABASE_GetRecordByID (ida.AEEDBField field [1]. 298. ++j. 1)) == SUCCESS) 300. 262. 257. szBuf).IDATABASE_Release (ida). } 313. 322. 346. } 357. display (app."). 350. 316. display (app. break. of Records: %u". 338. if ((ida = IDBMGR_OpenDatabase (idb.m_pIShell == NULL) . 342. "Failed removing record 1"). if (app->ime == NULL || app->a. 312.else 310. 329. } 347. return. 1). "Update Failed. 2. idbr1 = IDATABASE_GetRecordByID (ida. 333. { 332.} 335. 362. 315. AEECLSID_DBMGR. "No. 334.{ 361. (void **)&idb).{ 345. IDBMGR_Release (idb).IDBMGR_Release (idb).uint32 rcount = 0. 1. } 317. int nRetVal = AEE_DB_EBADREC. 4. rcount). IDATABASE_Release (ida).{ 311. ISHELL_CreateInstance(ish. rcount).IDBRecord * idbr1 = NULL.display (app. szBuf). break. 356. if (idb == NULL) 328. display (app. 363. 327. 324.return. } 343. display (app. return. else 344. 314. 348. 351.default: 355. TRUE)) == NULL) 331. { 320. 354.Chapter 12: 3G Programming Using BREW 415 309.IDBMgr * idb = NULL. return. 326. 352.IDatabase * ida = NULL. 325. 2. of Records: %u". 339. "No.SPRINTF (szBuf.case REMOVE: 319. 321. "db1". 337.} 359. 323. 330. 358. } 353.char szBuf[30] = {0}. 349.AECHAR szBuf[40].AEERect rc.static void mainMenu(dbap *app) 360. IDBMGR_Release (idb). 5. SPRINTF (szBuf. { 341. 336.rcount = IDATABASE_GetRecordCount (ida).if ((idbr1 != NULL) && ((nRetVal = IDBRECORD_Remove (idbr1)) == SUCCESS)) 340. "Removed Record 1"). rcounr = IDATABASE_GetRecordCount (ida). IDBRECORD_Release (idbr). 318. szBuf. 200). UpdateRecord".else{ 398.if (app == NULL) 390. 393. app->dinfo. SETAEERECT (&rc. 0.IDISPLAY_DrawText(app->a. szBuf. 365. 386. 380.{ 383. AddRecord".IMENUCTL_SetRect(app->ime. szBuf.cxScreen. 371. buff. sizeof(szBuf)). 384. 402. AEEFont font = AEE_FONT_NORMAL. NULL.STR_TO_WSTR ((char *)pszStr. AECHAR * buff = NULL.&pnFits). 0). 0.TRUE).psz = buff. 0. 0).} 415. 374. 0. .416 Chapter 12: 3G Programming Using BREW 364. &rc).int totalCh = 0. szBuf. 0. 5 . sizeof(szBuf)). AEE_FONT_NORMAL. szBuf. 406. pnFits.while ((totalCh > 0) && (*psz != NULL)) 403. 387. int nline. 0. 414. 389. szBuf.STR_TO_WSTR("12. 368.STR_TO_WSTR("IDB Functions:".if ((buff = (AECHAR *)MALLOC(200)) == NULL) 392. REMOVE. szBuf. 0).return.cyScreen). RETRIEVERECORD.IMENUCTL_SetTitle(app->ime.static void display(dbap * app.STR_TO_WSTR("8. char *pszStr) 382.5. szBuf.{ 412. RetrieveRecords". 375. 0). 410. sizeof(szBuf)). OpenDatabase". sizeof(szBuf)).IMENUCTL_AddItem(app->ime. 366. 376.IMENUCTL_AddItem(app->ime. sizeof(szBuf)). 0.if (pnFits == 0) 411. 0).STR_TO_WSTR("2.STR_TO_WSTR("5.dy. szBuf.font.IMENUCTL_SetActive(app->ime. 369.} 381. 0). szBuf).AECHAR * psz = NULL. psz.IMENUCTL_AddItem(app->ime.m_pIDisplay. 0. 405.cxScreen . 391. 401. 379. return.IMENUCTL_AddItem(app->ime.cyScreen*2/5.FREE (buff).IMENUCTL_AddItem(app->ime. szBuf. 378. return. } 397. 396. 409. 407. dy. 377. dy = app->dinfo. 394. ADDRECORD. 0. 388. 399. 408. RemoveRecord". szBuf.-1. 373. if (nline < 0) { 395. 0.m_pIDisplay. OPENDATABASE. 0 . 417. 416.app->dinfo. UPDATE. 0.return.(AECHAR *) psz. 367. 385. 370. app->dinfo. } 400.STR_TO_WSTR("11.int pwidth. dy = nline * app->lh. 413.{ 404. 0. sizeof(szBuf)). 0. int pnFits = 0. 418. 372.psz += pnFits.totalCh = STRLEN ((char *)pszStr).pwidth = IDISPLAY_MeasureTextEx(app->a. ♦ Lines 265–317: Explaining the functionality of updating an existing record. ♦ Lines 142–209: Explaining the functionality of adding records to the database.m_pIDisplay). 422. When the user presses the End key. The EFAILED is returned when loading is not successful. database interface definition. the applet receives EVT_APP_STOP event. IDBMGR_Release () is invoked to release IDatabase object. the applet receives EVT_KEY. 425. If it is true. 428. ♦ Lines 29–45: CreateInstance() method. Line 32 verifies the ClassID. the applet receives EVT_COMMAND. ♦ Lines 15–21: Defines Database applet structure.IDISPLAY_Update(app->a.dy += app->lh. which frees data and memory. Update) the dbUsage() method is invoked in line 75.pnFits = totalCh. allocates memory for app data (AppletData) and sets it to pAppData of AEEApplet. In line 139.FREE (buff). Remove.} 426. ♦ Lines 105–359: dbUsage()method. in line 57 mainMenu() function is invoked. 427.totalCh -= pnFits. ♦ Lines 46–84: The HandleEvent() method. This section returns AEE SUCCESS status upon loading the applet.Chapter 12: 3G Programming Using BREW 417 419. ♦ Lines 8–14: Code for defining macros and constants. This function initializes appletspecific data.if (totalCh < pnFits) 424. ♦ Lines 85–95: InitAppData() method. and menu interface definition. retrieverecords. 420. line 34 invokes the AEEApplet_New() function and then InitAppData() is called to initialize AppletData . applet interface definition. 421. otherwise it returns FALSE. When the user presses a key. ♦ Lines 22–27: Declarations of the function prototypes. otherwise it returns FALSE. IDatabase object is created in line 114. if database does not exist.return. It returns TRUE if the applet has processed the event. Line 89 initializes the MenuCtl pointer to NULL. This function is invoked while the applet is being loaded.} Code Description ♦ Lines 1–4: Header files for interface definition. ♦ Lines 211–264: Eexplaining the functionality to retrieve the records. ♦ Lines 96–104: freeApp() method. Line 90–92 gets the font metrics information. ♦ Line 7: Resource header file. This will hold all the data members that needs to be remembered throughout the life cycle of the applet. it creates Imenu interface object in lines 52-56. The first data member of this structure must be an AEEApplet OBJECT. in lines123-124 new database db1 is created and opened. In lines 116–118 ISHELL_CreateInstance() method is invoked to create IDBMgr object. If it receives EVT_APP_START. ♦ Lines 5–6: Header files for variable definitions. All events to this applet are handled in this function. If the user selects any one of the menu items (Opendatabase. Line 93 gets the device information. Line 137 IDBMGR Release() is invoked to release IDBmgr object. If it successful. This is the main structure for this applet. Addrecord. In lines 119–121 IDBMGR Open Database() method is invoked to open existing database db1. IDBmgr object is created in line 113. When the user selects a menu item. This method is called when the user click any of the menu items and the menu ID is passed to this function as a parameter. . This method returns TRUE if the allocation and initialization is successful. 423. Code Output When the previous application is run on the Emulator. the display is a menu list with options to Open Database. Add Record. and Remote Record. This function displays an output string at a given line number on the screen. IMENUCTL_SetTitle() is invoked to set the title to the menu. This method builds the main menu when this applet is started. to decide whether wrapping is required. If the string cannot be accommodated in one line. Figure 12-32: Display on the Emulator when ‘Retrieve Records’ menu item is selected . In line 367. the display is as shown in Figure 12-32. Line 400 psz keeps track of the point from where the next line should start. IMENUCTL_AddItem() methods are invoked to set the menu items to the menu. ♦ Lines 381–428: Explaining display() method. Update Record. If you select Open Database. ♦ Lines 359–380: mainMenu() method. ♦ Lines 402–425: Keep displaying text string in multiple lines until the condition ((totalCh > 0) && (*psz != NULL)) is true. ♦ Line 401: For calculating the total string length. and line 393 is to convert the string into Unicode. the display shows “Opened an already existing database. In line 368. the string will be split into two or more lines. Line 391 is to allocate buffer to hold the string. Lines 394–399 determines the starting location of the string on the screen. In lines 370–378. Retrieve Records.418 Chapter 12: 3G Programming Using BREW ♦ Lines 318–358: Explaining the functionality of removing an existing record.” If the Retrieve Records option is selected. IMENUCTL_SetRect() method is invoked to set size for menu. with lines being 15 pixels apart from each other. .Chapter 12: 3G Programming Using BREW 419 Summary In this chapter. DLLs are created and loaded onto the Emulator to test the application before actual deployment in the field. called applets. music downloading. mobile advertising. We discussed the step-by-step procedure for creating a small application followed by applications for animation. Irrespective of the underlying interface. The applications. are created using C/C++ in Visual Studio environment. we discussed the implementation of wireless applications using BREW tool kit of Qualcomm. BREW can be used to develop applications on existing as well as future wireless networks. and a database application. BREW tool kit provides a good development environment for creating and testing wireless applications. The clients can run the normal TCP/IP as in the wired Internet. corporate presentations over the network. Two-way and multi-party audio/video conferencing is also possible. the set of Application Programming Interfaces (APIs) released by Sun Microsystems for developing these applications. in addition to ISP subscription charges. the Web basically provides a one-way communication — the content stored in the Web server is transferred to the client. special protocols are required for realtime transmission of audio and video over IP networks. we are witnessing a revolution — to be able to transmit voice and video in real-time over the Internet and corporate Intranets. which was mostly in text format. However. voice is transferred between the two terminals. a circuit is set up between the calling party and the called party. we only pay for the connection charges for accessing the server of the Internet Service Provider (ISP). the Internet was extensively used for accessing information. audio. multimedia content access has become the norm. such as virtual class rooms. graphics. such as virtual class rooms for online lectures. . when we use the Internet. and then the circuit is disconnected.Chapter 13 Voice and Video Communication over IP and Mobile IP Networks In its early years. and live video program broadcasting ♦ Two-way and multi-party audio and video conferencing All these services can be provided at a fraction of the cost of a normal telephone network. The various applications of voice/video over IP networks (Internet and Intranets) are ♦ Audio/voice mail ♦ Video mail for transmitting video clippings. For the implementation. Major corporations that have Intranets spread over the country or across the continents can also drastically reduce their telecommunication costs by using voice/video communication over IP networks. With the advent of the Web. Application of Voice and Video over IP When we make telephone calls using a telephone network. for example. the charges we incur vary according to the distance between the calling party and the called party because telephone networks use circuit switching. or they can run Mobile IP in the wireless Internet. On the other hand. Making a long-distance call at the rate of a local call is economical by anyone’s standards. this “flat rate” charge is one of the major selling points for voice/video communication over the Internet. However. and video. we use the Java Media Framework (JMF). Web content can be a combination of text. The charges for using the Internet are not based on the distance between the client (the user terminal) and the server from which we are accessing the information. In this chapter. and broadcasting audio programs for the general public ♦ Video broadcasting for applications. In circuit switching. This is paving way for the convergence. corporate presentations. for offline lectures ♦ Audio broadcasting for applications. we will briefly discuss the protocols and focus on implementation of real-time voice and video transmission over the IP networks. Now. meaning that we no longer need to use separate audio and video broadcasting networks — the Internet can be used for both audio and video broadcasting. Thus. Above UDP. Similarly. low bit rate coding suffices. Above UDP. two special protocols. for video applications. To reduce the processing requirements. the IP can be IP version 4 or IP version 6.3 Kbps. and so on. a 64 Kbps low data rate video-coding technique is used.3 Kbps/6. there will be breaks in speech. it is not possible to ensure a required Quality of Service (QoS). the quality is good enough. ♦ To overcome unreliable transmission. which reduce the data rates to 5. If there is variable delay. this is an important requirement — the delay should be constant and packet loss should be minimal. RTP provides the features for real-time transmission of voice/video along with RTCP. both of which run on fixed terminals connected to the Internet or a Mobile IP that runs on the mobile devices. Although QoS parameters can be specified in the TCP/IP network. Low Bit Rate Coding of Voice and Video In the normal telephone network. UDP (User Datagram Protocol) is used instead of TCP. In this figure. . and packets may arrive at the destination with different delays. Some packets may be lost and some packets may be duplicated (received more than once). Above the IP. This is a very high data rate for present IP networks. to transmit voice over IP networks. For voice/video transmission. for voice/video transmission over the IP networks. it is better suited for real-time communication. for business meetings where the image activity is less. you have no guarantee that these requests will be honored. speech 64 Kilobits are required. So. and discard the packets which are duplicated. Above this layer. the TCP layer has to do lot of processing and processing requirements are very high. RTP (Real Time Transport Protocol) and RTCP (Real Time Control Protocol) are used. the audio and video quality is not very good compared to broadcast quality audio or video. using low bit rate video transmission for transmitting a dance program is not appealing to users as the user will feel many “jerks”. ♦ For these reasons. Tp store one second of. the TCP layer has to take care of the previously mentioned problems. low bit rate coding techniques are used. The TCP layer may ask for retransmission if the packets are lost. rearrange the packets if they are not received in sequence. As a result. the important requirement is that when packets are transmitted. for normal business applications.Chapter 13: Voice and Video Communication 421 Protocols Overview TCP/IP networks are not suitable for real-time transmission of audio or video because of the following: ♦ The IP does not provide a reliable transmission of the packets. which means that we cannot specify that the packets have to be delivered within a specified delay or the number of packets lost should be below a threshold. So. Because UDP has less protocol overhead. however. which involves transmitting one second of speech. The protocol suite for realtime transmission of voice/video over the IP networks is shown in Figure 13-1. meaning that the packets may not be received in the same order in which they were transmitted. For real-time transmission of voice/video. the audio/video application programs run. UDP is used to take care of transport layer functionality. speech is coded at 64 Kbps data rate using a technique called Pulse Code Modulation (PCM). For instance. in addition to PCM. they should be received at the destination with a constant delay. The TCP layer cannot do anything if all the packets do not have the same delay. and the devices have the Java Virtual Machine (JVM) running on them. and so forth. G. signaling is done through Q. the IP address will be the home IP address.323 support will provide killer applications to mobile subscribers: Subscribers will have access to voice and video services at a very low cost as compared to the fixed network services and existing mobile network services.1. integrated video cameras are already available. Voice coding .323 recommendations.323 terminals.323 protocol stack.323 standards specify the communication protocols and the low bit rate coding techniques to be used for voice and video communication over the IP networks. called H. Presently. The examples given in this chapter illustrate how to provide the H. This protocol stack is shown in Figure 13-2.323 protocol stack on fixed terminals such as PCs and H. A number of vendors are incorporating a Mobile IP layer as a part of the network protocol suite that is bundled with the mobile Operating Systems. These standards do not guarantee the desired QoS. that address will. Mobile H.261 and H.323 capability to mobile devices. namely. which provides an embedded solution of the H.711 and G. However. Mobile devices with small. the mobile device will have two addresses. a “home” address and a “care of” address. products are available that implement the H. The other requirement of the mobile device is that it should have the capability for voice and video support.422 Chapter 13: Voice and Video Communication Figure 13-1: Protocol suite for voice and video over IP H. which can be PCs. it should be noted that in Mobile IP.323 telephones.931. be forwarded to the mobile device to its point of attachment (the Mobile IP is discussed in Chapter 14). namely. With the support for Java Media Framework (JMF). H.323 recommendations also specify the standards for audio coding. In addition to RTP and RTCP (mentioned earlier). So. and for video coding. Mobile devices with H. which specify the standard protocols used for multimedia communication over IP networks. To set up and disconnect calls over the IP networks. which is the standard signaling used in ISDN (Integrated Services Digital Network).263. in the code given in this chapter. This protocol stack runs on the end terminals. and video coding is done through software. We assume here that the Mobile IP software will be running on these devices.723. The network will send the packets to the home address. H. the applications can be run directly on the mobile devices. The IP can be either the fixed IP (IP version 4 or version 6) or the Mobile IP that runs on the mobile devices. The H.323 Standards International Telecommunications Union (ITU) has released the H. laptops. in turn.323 devices are on the anvil. . ♦ The codes provide low bit rate coding of voice and video signals. The architecture of JMF is shown in Figure 13-3.323 series of standards. JMF provides the necessary classes and methods to develop applications using the H. the best application of the code given here is to develop mobile H. So we need to choose the appropriate coding mechanism in the JMF based on the coding technique used in the mobile device. dividing the audio and video to send them to the different devices for playback — audio to the sound card and video to the monitor. The implementation examples discussed in this chapter can be tested on a LAN with the desktops as nodes or with laptops that provide wireless connectivity to the LAN. Because the implementation is in Java. ♦ Java applications or applets can be created through the JMF presentation and processing APIs. Figure 13-2: H. the JVM has to be run on the nodes along with JMF.323 Terminal-side protocol stack Java Media Framework Sun Microsystems provides a set of Application Programming Interface (API) calls through Java Media Framework (JMF). ♦ Users can write their own APIs or use third party APIs through the JMF plug-in APIs.323 terminals and to obtain the audio and video services over wireless 3G networks. ♦ Renderers and effects allow for playback and manipulation of signals. JMF supports a number of coding techniques including the 13 Kbps coding technique used in GSM.Chapter 13: Voice and Video Communication 423 is the other issue. ♦ The multiplexers facilitate combining the voice and video signals for transmission over the channel. ♦ The de-multiplexers do the reverse of multiplexers. However. In the following sections. We need to develop two Java programs for this application: one is AudioCapture. and much more. Figure 13-3: Architecture of JMF Application Setup To try the code given in the following examples. Through implementation of this application. Development of the audio broadcasting application 3. Application: Voice Messaging This application is used to develop voice mail. and while explaining the code. which is for capturing the audio. for sending e-mails with voice file attachments. we discuss the implementation of three applications: 1. and the other is UserInter. Development of the audio and video broadcasting application These applications can be used for a variety of scenarios: for developing e-learning modules.java. the following set-up is required: ♦ A Local Area Network with a Windows NT server and 95/98 clients. we demonstrate how interesting applications can be created using JMF. for corporate presentations (live as well as offline).1 or Later . ♦ A few of the nodes on the LAN with multimedia capabilities: • A sound card with microphone and speakers • A desk-top video camera Ensure that the corresponding drivers are installed and check the audio and video capabilities of the nodes before testing the code. a user can create a voice message and transmit it over the network to another user just like a normal text mail.424 Chapter 13: Voice and Video Communication That is JMF in a nutshell. which is to create the necessary user interface. In the following sections. we study the various classes and methods used for creating multimedia applications.java. The complete code listings are given. Development of the voice messaging application 2. The hardware and software requirements are as follows: Client side Development platform JDK1. Type the command java JMFRegistry at the command prompt. 5. 5.audio".util. wdexecute. Click User Settings 3. 9.io. From the Permissions (first list box). Click the Add Permissions button.*".misc". and give a name for this policy file (for example c:\mypro\vmail\mypolicy).RuntimePermission "accessClassInPackage. permission java. Click the Commit button.lang. Type the command policytool at your command prompt. Policy Entry.lang. choose ird. 7. you need the swing jar file in the CLASSPATH. 3.path". which opens another window. but if you are running JDK 1.home". From the Actions (third list box). "read". "read".dir".RuntimePermission "accessClassInPackage.home". permission java. To generate a policy file automatically.FilePermission "<<ALL FILES>>".util.” This can be done by using the JMFRegistry application and needs the swing library to run.lang. Enter the values for CodeBase and SignedBy fields as follows: CodeBase: file://c:/mypro/vmail/ SignedBy: XXXXXX (Your Name) (“vmail” is my current working directory). 6. permission java. which opens another window.lang.RuntimePermission "loadLibrary. Exit from the Policy tool. Click the Allow File Writing for Applets toggle. 10. permission java.sun.sun.Chapter 13: Voice and Video Communication 425 JMF API 2. The policy tool automatically generates the following code by doing the previous procedure: /* AUTOMATICALLY GENERATED ON Sat Jun 02 15:13:47 GMT+05:30 2001*/ /* DO NOT EDIT */ grant { permission java.2 or greater. 6. perform the following procedure: 1. Choose FileSave as. choose <<ALL FILES>>. Invoke JMFRegistry and execute the followings steps: 1. you don’t have to do anything. From the Target Name (second list box). Click OK. To give the security permissions for your current working directory files.RuntimePermission "modifyThreadGroup". choose File Permissions.util.util. "read". . you have to generate a policy file. "read". Permissions. permission java. permission java. permission java. browse your folder. permission java. permission java.PropertyPermission "user. you need to enable “capture from applets.x.1.lang.PropertyPermission "java.name". 2. Quit JMFRegistry. To run the application.util.1 or Later Server side Web Server Personal Web Server (PWS) The code for the two programs is given in Listings 13-1 and 13-2.1. "read".PropertyPermission "java. 8. "read". 4.class.RuntimePermission "modifyThread".PropertyPermission "user. Click the Add Policy Entry button. 4. If you are using JDK 1.PropertyPermission "user. permission java. Click the Allow Capture for Applets toggle. 2. Create six folders in “\inetpub\mailboxes\”.io.sound. delete.sampled. }. permission java. 2.FilePermission "<<ALL FILES>>". The Webserver IIS (comes by default with Win2000) and other similar servers also support this program.io.java and UserInter. write. 1. Now perform the following steps.SocketPermission "*". AudioCapture. with the names that are mentioned in the choice box of UserInter. Enter the source code of previous two files after making the changes in Step 3 and save them. "delete".io. (All these are user’s mailboxes).AWTPermission "showWindowWithoutWarningBanner". execute". grant codeBase "file://c:/mypro/vmail/" { permission java.FilePermission "${user. write.log".accept".io. delete. permission java. You have to change the line numbers 104 and 109 in AudioCapture.java.java program (Listing 131)from "john1" to your server name or IP address.java (using javac) 6.FilePermission "<<ALL FILES>>". For example. Here "john1" is the server name to store the voice mail in the following code. "connect. "write". 5.dir}${/}jmf. "read. 4.FilePermission "C:WINDOWSTEMP*". "write". “Donald” folder is in \inetpub\mailboxes\.net. Compile two files. }. which is a mailbox for the user Donald.FilePermission "${user.JMStudioCfg". grant codeBase "file://c:/mypro" { permission java. permission java.FilePermission "C:WINDOWSTEMP*". Figure 13-4: Applet Viewer window . Run the UserInter file using appletviewer with the following command: appletviewer.awt. 3. }. This command displays the screen in Figure 13-4. "read.426 Chapter 13: Voice and Video Communication permission java. permission java.home}${/}. Run the Personal Web Server (PWS) on your server and create a folder “mailboxes” in the personal Web server folder “Inetpub”. execute". "write".AudioPermission "record". permission java.io.io. permission javax. media.getDeviceList(format). Now you can speak into the microphone. 13. 16. boolean realized. 20. 29. 6.media.wav. javax. 36. The subject is Help and the count is the number of files in the receiver’s folder. 34. boolean closed.*. entered Help in Subject field. java. 35.*.start().size()>0) . the samp.*. enter “Subject” in the Subject field. Here the sender’s name is taken as the client’s system name. javax.44100. 9. javax. 27.wav at the URL provided in line 65 (file://mypro/vmail/samp. 11.*. 12. 14.media.*.LINEAR. 3. 30. if Donald’s mail box already contains 6 messages. javax. 22. 8.wav will be copied to the server user’s mailbox that you have selected from the Directory list box.awt.format. Therefore. format=new AudioFormat(AudioFormat. import import import import import import import import import import import import java. 23. 1. 2.rtp. as samp.*.rtp.java © 2001 Dreamtech Software India Inc. 33. 7. public AudioCapture() { t1=new Thread(this).prefetched.eom. 26. 5.*. CaptureDeviceInfo di=null.1). The voice message is stored in a file at the server in Donald’s mailbox with the filename <sender’s name> <subject> <filecount+1>.Chapter 13: Voice and Video Communication 427 The procedure for sending a voice mail is as follows: Select a name from the Directory list box. Susan. javax. Listing 13-1: AudioCapture. and composed the voice message.wav. 21. 24.stoped. the filename becomes Susan_Help_7. t1. 19.configured=true. 18.*. Thread t1. for example.io. } // end of constructor public void run() { waitObject=new Object().net. public class AudioCapture implements Runnable. All Rights Reserved.util. 31. Object waitObject. java. DataSource source.event.wav). 15. AudioFormat format.awt. 32. devices=CaptureDeviceManager.*.control. If you click the Stop button. javax. assume that you have selected the user name Donald from the Directory. DataSink filewriter. Vector devices. 28. 17. and click the Start button.java. di=null. java.media.media. For example.event. 10. 4. ControllerListener { Processor p=null. 37.util.media.*.media. javax. java. if(devices. Listing 13-1 presents the code for AudioCapture.16. 25. If you click the Send button.*.protocol.*.failed. a temp file will be created. 65.println("configured= "+configured). filewriter. System. 90.start(). } 62. 67. source=p.out. p.} 49.setContentDescriptor(new FileTypeDescriptor(FileTypeDescriptor. waitObject. }catch(NoProcessorException ie){System. } catch (Exception e) {} 83. di=(CaptureDeviceInfo)devices. 88. 74.close(). p. 56.out. 57.out. if(!waitForState(p.out. else 42. try { 69. else 55. 40.getLocator()). MediaLocator dest = new MediaLocator(url). p=Manager. if(!waitForState(p. 43.wait(1).println("p noprocessorexception"). { 60.printStackTrace(). 47. System.428 Chapter 13: Voice and Video Communication 38. System. p. 70.out. 77.Configured)) 51. filewriter = Manager. public void stop() .out. try{ 46. { 52. p.out.Realized)) 59. dest).elementAt(0). 86. 53. 84. 50. System. } catch (IOException e) { e.println("Device not found").createDataSink(source. System. } 54. 78.WAVE)). 48.start(). try { 73.exit(0).println("started").println("Realized= "+configured). j++.configure().realize().printStackTrace().createProcessor(di. 61. filewriter. 64. filewriter. } 41. catch (SecurityException e) { e. String url = "file://mypro/vmail/samp.getDataOutput().} 72. 75. 66. 44. 82.open(). { 80. 68. try{ 81. DataSink filewriter = null.wav".out. p. System. while(!stoped) 79.close(). 87. int j=0. 58.println("Realized= "+configured). } catch (NoDataSinkException e) { e.println("p ioexception").println("no configured= "+configured). } 76.} 71. { System. } // end of run 89. } 45.printStackTrace(). else 63. }catch(IOException ie){System. } 85. { 39. 100. public synchronized void controllerUpdate(ControllerEvent ce) 136. 103. { 142. 119. { 123.Chapter 13: Voice and Video Communication 429 91.substring(0. s=s.available()].toString(). { 137. 133. 101. while (p. 105.out.notifyAll(). System. byte b[]=new byte[ii.read(b). waitObject. } 132.username+"'s mailbox "+count). int i=ii.println("Sender: "+s). stoped=true.wav"). 107. 106. System. synchronized (waitObject) 122.list(). try{ . 130. } // end of waitForState 134. int count=files. { 97.out.username+"/"+s+"_"+UserInter. { 139. 109. s=s. String files[]=filecount.getLocalHost(). System. waitObject. } // end of stop 94. 104.indexOf("/")). } 117. FileOutputStream fout = new FileOutputStream(remotefile). return configured. try 124. synchronized (waitObject) 141. { 121. { 125. 99. } 129. public boolean waitForState(int state) 120. fout. 95.wav"). 116.out.println("Your mail has been sent").subject+"_"+cou nt+". 113. 114. File filecount=new File("//john1/mailboxes/"+UserInter. public void sendMail() 96. 93. }catch(Exception e){ e. { 127. InetAddress localhost=InetAddress. 140.username). configured = true.write (b). File remotefile=new File("//john1/mailboxes/"+UserInter. { 92. } // end of sendMail 118. 110. 135.trim().getState() < state && configured) 126. FileInputStream ii=new FileInputStream ("c://mypro//vmail//samp. if (ce instanceof RealizeCompleteEvent) 138. try{ 98. 128. } catch (Exception e) {} 131.printStackTrace().println("Total number of mails in "+UserInter. 112. 115. 108. 102. 111.s.length. String s=localhost.wait(1). new AudioCapture(). 162. 163. 159. 160. 156. waitObject. Note: A collection is a group of objects. 153.io package. 164. 157.notifyAll(). 147. } 169. 148. } // end of AudioCapture Code Description ♦ Line 1: java. { 194. else 178. { 179. }catch (Exception e) {} } } else if (ce instanceof ConfigureCompleteEvent) { configured = true. 180. . } else if (ce instanceof ControllerErrorEvent) { failed = true. closed = true. 146. 165. } 177. public static void main(String args[]) 193. } // end of controllerUpdate 191. 161. 166. 151. { 175. 144.net package. 158. 167.430 Chapter 13: Voice and Video Communication 143. 176. synchronized (waitObject) { try{ waitObject. else if (ce instanceof ResourceUnavailableEvent) 174. 190. 145. else if (ce instanceof ControllerClosedEvent) 170. waitObject. } 173. 172.util package contains enhancements added by Java 2 collections. 149. 154. 192. ♦ Line 3: java.notifyAll(). } else if (ce instanceof EndOfMediaEvent) { eom = true. configured=false. which provides support for networking. which provides support for I/O operations. 168. } 181. { 171. 152. } catch (Exception e) {} } } else if (ce instanceof PrefetchCompleteEvent) { prefetched = true. ♦ Line 2: java.notifyAll(). return. 150. 155. } // end of main method 196. 195. ♦ Line 66: Create a destination media locator with the URL specified in line 65. the keyboard. which is of type CaptureDeviceInfo. It can also convert an AWT Image object to a JMF Buffer object. Send Streams. such as a push button. Player and classes. Sessions. by passing the MediaLocator. ControllerListener. ♦ Line 11: javax. ♦ Line 14: User-defined Class AudioCapture starts at line 14 and ends at line196. manage fonts. ♦ Line 5: java..media. which is in Manager class. output text. and MediaLocator. ♦ Line 9: javax. ♦ Line 39: CaptureDeviceInfo object contains information about a particular capture device and returns this information to variable di. ♦ Line 13: Empty line. using the method createDataSink. ♦ Line 10: javax. ♦ Line 7: javax. ♦ Line 69: Create a data sink. These are in the javax. ♦ Lines 16–25: Variables declaration. such as Controller. ♦ Line 85: To close the processor. and quality of media.event package contains the classes to handle events generated by the mouse. with the source and destinations. contains the classes to handle events generated by Receive Streams. and Time out.media package.media. ♦ Lines 31–88: run() method. Format. Manager. and utilize graphics.format package contains classes for JMF-supported media formats. content descriptor. ♦ Line 6: javax. Processor.media. ♦ Line 86: To close the data sink.media. ♦ Line 12: javax.awt.protocol package contains interfaces and classes for file type descriptor. ♦ Line 46: To create a processor for the specified media using createProcessor method. which implements the Runnable interface for using threads and the ControllerListener interface for handling asynchronous events generated by controllers. CaptureDeviceManager.media package contains interfaces. ♦ Line 8: javax.rtp. ♦ Line 35: Gets a list of CaptureDeviceInfo objects that correspond to devices that can capture data in the specified format. such as CaptureDeviceInfo. line 28 creates a thread and invokes run method by calling the start method in line 29. ♦ Lines 72–76: Open data sink to write the data from the data source. ♦ Line 64: To get the output DataSource from the processor ♦ Line 65: Create a URL for storing the temp file in the local system.event package. ♦ Lines 49–63: To configure and realize the processor.Chapter 13: Voice and Video Communication 431 ♦ Line 4: java. buffers. and creating the data source from which you have to capture the data. which is in Manager class.util package contains classes to convert a video Buffer object to an AWT Image object that you can render using AWT methods. tracks. ♦ Line 34: For creating an audio format instance with the AudioFormat class. frame rate. ♦ Lines 26–30: Constructor of AudioCapture.control package contains classes for controlling the bit rate. These are all related to the RTP protocol. and various controls.awt package contains classes and methods that allow you to create and manage windows.rtp package contains interfaces and classes for data transmission through real-time transport protocol.media. .media. 29. ♦ Lines 119–133: waitForState() method to configure the processor.event. tfsubject=new TextField(12). 19. .awt. To run this file use the following command: 8. capturing. 24. All Rights Reserved 1. 13. 31. AudioCapture as. { 23. Label labeldirectory. TextField tfsubject. /* <applet code="UserInter" width=200 height=180> </applet> */ 12. public void init() 22. static String username. ♦ Lines 109–114: Copy the samp. 16. 6. import java. 20.labelsubject. 2. 4. 28.security. 18.java © 2001 Dreamtech Software India Inc. 5. appletviewer UserInter–Jplease correct this statement Djava. chdirectory=new Choice(). 11.io. import java.policy = c:\mypro\vamil\mypolicy 9.addItem("John"). chdirectory. ****/ 10. 17.stop. stop=new Button("stop"). ♦ Lines 104–107: To count the total number of files (e-mails) in the receiver’s mailbox. header= new Label("Voice Mail").java. start=new Button("Start").432 Chapter 13: Voice and Video Communication ♦ Lines 90–93: stop() method to stop the process.header.awt. ♦ Lines 98–102: To get the sender’s system name from the InetAddress. 3.*. and writing to the data sink. 32.wav file from sender’s system to server system’s receiver’s mailbox.subject. Button start. public class UserInter extends Applet implements ActionListener 14. which is method in ControllerListener interface.applet. ♦ Lines 192–195: main() method to create an instance of class AudioCapture. chdirectory.*.*. Listing 13-2: UserInter. 30.*. 26. ♦ Lines 135–190: controllerUpdate() method. { 15. 25. import java. /***** 7. labelsubject =new Label("Subject"). ♦ Lines 95–117: sendMail() method to send the temporary file from the local system to receiver’s mail box. send=new Button("Send"). 21. Choice chdirectory. labeldirectory =new Label("Directory").send. Listing 13-2 presents the code for UserInter.addItem("Donald"). import java.This method is called when an event is generated by a controller that this listener is registered with. 27. 80. stop. 35. 47. add(p1). 81.addActionListener(this). add(p0). 73. 65. } // end of if for send button if(ae.getSelectedItem(). 52. 58.trim(). setSize(200. Panel p3 = new Panel(). p0.addActionListener(this).setEnabled(false).add(header).add(chdirectory). p3. } public void actionPerformed(ActionEvent ae) { if (ae. Panel p0 = new Panel(). setVisible(true). 48.getSource()==stop) { stop.setEnabled(false).addItem("Mary"). p2.setEnabled(true).add(labeldirectory). as. 83.setEnabled(false). 66. 56. 49. p2. 53. p3. 44.add(tfsubject). 70. 76. 55. 54. 40. 74. 50. start. 84.addActionListener(this). 72. subject = tfsubject. send. 67. . 42.setEnabled(true).getSource()==start) { as=new AudioCapture(). 59. 68. 79.io package that provides support of I/O operations.stop(). 39. } // end of if for start button if (ae.add(labelsubject). 61.trim(). 45.200). 75. 41. 57.getText(). 82. chdirectory. 38. p1. 37. add(p2). start. 62. send. 77. 46.sendMail().addItem("Henry"). send. p3. start. chdirectory.getSource()==send) { username = chdirectory.addItem("Susan"). 51.add(start). Panel p2 = new Panel().addItem("Bill"). stop. 64. chdirectory. p1. stop.setEnabled(true). 60. add(p3). 43.add(send). 36. as. 69. 71.Chapter 13: Voice and Video Communication 433 33. 78. } // end of if for stop button } // end of actionPerformed() } // end of UserInter Code Description ♦ Line 1: java.add(stop). 63. chdirectory. Panel p1 = new Panel(). 34.setEnabled(false). and add action listener to the buttons. buttons (Start. ♦ Lines 62–83: actionPerformed() method that is invoked when an action occurs. java.java for transmitting audio and Professor. Application: Audio Broadcasting In this application. Stop. javax. The server module consists of two programs: AudioSendStreams. java. Enter each of these programs and compile them. contains the Applet class and three interfaces AppletContext. respectively. The source code of these programs is given in Listings 13-3. com. 2. output text. you will hear the audio broadcast. The client module also consists of two programs: AudioReceiveStreams. AudioClip.awt. ♦ Lines 13–84: User-defined class UserInter that extends java.434 Chapter 13: Voice and Video Communication ♦ Line 2: java. ♦ Line 4: java. import 4. A screen will appear that has Start.awt package contains classes and methods to create and manage windows.*.util. we add the components choice box (directory). import java.awt. At the client-side. ♦ Lines 15–20: Variables declaration.*.rtp.media. java. A screen will appear with Start and Exit buttons.awt. 4. manage fonts. Run the Professor program at the server using the command java Professor. 6. the keyboard. when you compile the code.class file is created. the audio is captured by the microphone and is transmitted to whomever is logged on to the server.java to receive the audio and Student. 5.*.sun.applet.ui. Stop. The application consists of one module that runs on the server where audio broadcasting is done and one module that runs on the clients that receive the broadcast.*. ♦ Line 11: <applet> tag. import 8.java © 2001 Dreamtech Software India Inc.media. import 7.*. import 2. Send). import 9.*.java that creates the user interface. and various controls.net.*. java.media. and a text box (Subject) to the applet.class file is created. we develop programs to do audio broadcasting over a network.event. .io. the Professor. These applet methods provide detailed control over the execution of the applet.event package contains the classes to handle events generated by the mouse. After you click the Start button. Listing 13-3: AudioSendStreams. com. All Rights Reserved 1. The procedure for executing this application is as follows: 1. import 6. and 13-6.media. and AppletStub. and utilize graphics.java to create the user interface. Execute the Student program using the command: java Student. ♦ Lines 21–60: Applet life cycle invokes the init() method when applet starts. and Exit buttons.applet package. 13-5. javax. When you click the Start button. for executing this class file using appletviewer. 3.sun. In this init()method. Student.*.rtp.Applet class and implements the interface ActionListener. 13-4.*. such as a push button. import 5. import 3. ♦ Line 3: java. *. 18. AudioFormat format. 34.println("p ioexception"). if(!waitForState(p. 61. System. 26. javax.Chapter 13: Voice and Video Communication 435 10.rtcp.protocol. javax.elementAt(0). 35. 59. 36. boolean realized.1). 62. 44.out. { p=Manager. 48. 25. 42. Vector devices. 43.Configured)) 58. 41.exit(-1).media. try 50. 14. }catch(NoProcessorException ie) 54.rtp. int port=49150. 20. System. {System. boolean encodingOk.closed.*.media.*. } public void run() { waitObject=new Object(). javax.failed.media.out. String HostName. 29.out.RAW_RTP)). 11.*. format=new AudioFormat(AudioFormat. 15. 21. public AudioSendStreams(String Name) { HostName=Name.16. 23. 38.println("AudioSendStream-Name="+Name).start(). } 60.out.44100.Device not found"). } 49. 17.getLocator()).length. 55.i<track. 51. 22.println("AudioSendStream-no configured= "+configured). 33. playerlist=new Vector().event. } catch(IOException ie) 52. TrackControl track[] = p.prefetched. 47. 28. Thread t1. boolean encodingOK=false.out. javax. 46.setContentDescriptor(new ContentDescriptor(ContentDescriptor.configure(). 57. devices=CaptureDeviceManager.playerlist.stoped. Object waitObject. CaptureDeviceInfo di=null. 40.println("AudioSendStream. } 56. { if(!encodingOk && track[i] instanceof FormatControl) .media. 30. di=null.*. 19. 31. 13.i++) 64.getTrackControls(). 12. 53.configured=true. 16. for(int i=0.createProcessor(di. if(devices. import import import import import javax. } else {System. p.LINEAR. 37. p. 63. ControllerListener { Processor p=null.format.println("p noprocessorexception").media. public class AudioSendStreams implements Runnable. { System.size()>0) { di=(CaptureDeviceInfo)devices.control.getDeviceList(format). t1=new Thread(this).eom. 45. 32. 39. 24. t1. 27. { System.rtp. RTPSessionMgr().println("AudioSendStream-Realized= "+configured).5. 111.GSM_RTP. } catch (UnsupportedFormatException upe) . new SourceDescription(SourceDescription.username+ “@company. } 100.initSession(localaddr.out.sun.0”. 112. mgr. 123.”JMF RTP Player v2. new SourceDescription(SourceDescription.getDataOutput(). 94. 120.436 Chapter 13: Voice and Video Communication 65.8000.cname. 115.1))==null) { track[i].25).18). { p. 66.destaddr. String username = null.Realized)) 87. }. { new SourceDescription(SourceDescription.0). 92. 82. } 83.getMessage()).println(e. 116. 78. if(encodingOk) 85. SessionAddress localaddr = new SessionAddress(). try 96. 84. 97. 93. 86.SOURCE_DESC_EMAIL. 88.1. 114. } else { encodingOk=true. String cname = mgr. {System. } }else track[i].realize(). SessionManager mgr=new com. } catch (Exception e) { System. 95.1.userdesclist. } DataSource source=p.setFormat(new AudioFormat(AudioFormat.getProperty("user. 105. } 89. 117.8. s.GSM_RTP. { username = "user".0.exit(-1).SOURCE_DESC_TOOL. mgr.media. } catch (IOException ie) { ie.1.addFormat(new AudioFormat(AudioFormat. 103.rtp. 91.printStackTrace(). try 104.com”.8.SOURCE_DESC_CNAME.1.createSendStream(source. 76.startSession(sessaddr.setEnabled(false). p. 90.start(). 77. 113. 99.generateCNAME(). SourceDescription[] userdesclist= new SourceDescription[] 107.null). 118.err.port + 1).0.1). mgr. { if(((FormatControl)track[i]).name"). 79. } catch (SecurityException e) 98. 101 102.false). 108. 106.setEnabled(false). 81.port. SessionAddress sessaddr = new SessionAddress(destaddr.false) 110.start().false). 119.8000. 109. 121. { InetAddress destaddr = InetAddress. if(!waitForState(p.getByName(HostName). 122. { username = System. if (mgr == null) System. 80. try { SendStream s= mgr. 141. 136. } /* End of controllerUpdate */ 175. } } public boolean waitForState(int state) { synchronized (waitObject) { try { while (p. 125. 169.getState() < state && configured) { waitObject. } 174. } else if (ce instanceof ResourceUnavailableEvent) { configured=false. 179. 154. 159. 178. } catch (Exception e) {} } return configured. 132. 135. int j=0. 177. 165. 149.notifyAll(). 127. 130. 170. String title) { super(player). 139. 161. 134. 137.printStackTrace(). 129. 143. } else if (ce instanceof ControllerErrorEvent) { failed = true. 133. 173. 168. public void stop() { stoped=true. } catch (Exception e) {} } } else if (ce instanceof ConfigureCompleteEvent) { configured = true. synchronized (waitObject) { try { waitObject. } /* End of IF Condition */ } /* End of Run Method */ public synchronized void controllerUpdate(ControllerEvent ce) { if (ce instanceof RealizeCompleteEvent) { configured = true. 126. 162.Chapter 13: Voice and Video Communication 437 124. 150. 148. 131. 160. 152.notifyAll(). 147. 163. class RTPPlayerWindow extends PlayerWindow { public RTPPlayerWindow(Player player. } catch (Exception e) {} } } else if (ce instanceof PrefetchCompleteEvent) { prefetched = true. 151.notifyAll(). 166 167. 156. 172. { upe. 128. 176. } . 164. } else if (ce instanceof ControllerClosedEvent) { closed = true. 146. setTitle(title). 138. } waitObject. 158. 140. 153. synchronized (waitObject) { try { waitObject. 145. 144. 157. } else { return. 142. 171.wait(1). } else if (ce instanceof EndOfMediaEvent) { eom = true. ♦ Lines 49–55: Try block for creating a processor for the specified media.rtp. ♦ Line 17: The Processor interface defines a module for processing and controlling time-based media data.255.255.* at compilation time.session are now in javax. { setTitle(title).rtp. ♦ Line 19: Indicates port number as 49150 for transmitting audio streams ♦ Lines 20–28: The necessary variables are declared in this code.438 Chapter 13: Voice and Video Communication 180. ♦ Line 14: This package is the reorganized RTP package.RTPSessionMgr.rtcp provides support for RTP.rtp. ♦ Lines 37–127: This code is the Run method to send audio streams to the clients. Otherwise. ♦ Lines 42–48: Checking for Capturing Device. ♦ Line 10: This package provides all audio and video format classes available in JMF. RTPSessionMgr is an implementation of SessionManager provided with the JMF reference implementation. } 186.media. ♦ Line 13: javax.ui. } 184. ♦ Line 4: This is an automatic-imported package. and related classes. panels. ♦ Line 6: Package for event handlers. . at compile time. all the streams go to CaptureDeviceInfo. it returns “AudioSendStream-Device not found” and exits from the loop.media. public void Name(String title) 182. Processor extends the Player interface. { new AudioSendStreams("255. ♦ Line 16: Beginning of AudioSendStreams class. } 183. ♦ Lines 29–36: Creation of the constructor for AudioSendStreams.rtp. This createProcessor method returns a string value. ♦ Line 2: Package for networking-related classes. ♦ Line 11: This package provides the all Controller interfaces in JMF.event. public static void main(String args[]) 185. If the device is not found. ♦ Line 12: This package is a Type-Import-on-Demand declaration (it extracts the classes from this application at compile time).getSupportedFormats to only valid RTP formats.sun.sun.255"). ♦ Line 5: This package is for time-based media. this package extracts all related classes belonging to this package. ♦ Line 3: Package for the frames. this line will limit the supported formats reported from Track.media. ♦ Line 7: Package that provides APIs for playback and transmission of RTP streams. output stream classes. ♦ Line 8: This package constructs all instances of com.media. ♦ Line 60: To set the output content descriptor to RAW RTP. } Code Description ♦ Line 1: Package for the input.media. } 181. ♦ Line 9: This package constructs an instance of com. The reorganization consists of the following changes: The RTP event classes that were in javax. add(stop). import java. This is description of the actual source and frequency. 22. ♦ Lines 103–115: Try block for the InetAddress class represents an IP Address. p3. start.stop.setEnabled(false). 20. All Rights Reserved 1. AudioSendStreams as. the controllerUpdate for different types of events.addActionListener(this). 29. 16. ♦ Lines 106–110: Here the SourceDescriptor constructs the type of source description. setVisible(true).exit. 3. 14. 6.Chapter 13: Voice and Video Communication 439 ♦ Line 61: To get the tracks from the Processor. exit. Panel p2= new Panel(). add(p2).awt. which extends the PlayerWindow class. 17. reaching of end of media. stop. This method can only be called once after Processor interface has been configured. 9.event. State of the processor. Listing 13-4: Professor. add(p3). by using the getTrackControls method and a TrackControl interface for each track in the media stream. stop=new Button("stop"). { Button start. 19. start=new Button("Start"). 11. stop. 15. This waitForState method returns a Boolean value. 23. ♦ Lines 129–130:For stopping the transmission.*. public Professor() 8.100). } public void actionPerformed(ActionEvent ae) . 10. ♦ Lines 132–142: Synchronization method for waitForState with one parameter. 2.add(start).java © 2001 Dreamtech Software India Inc. exit=new Button("Exit"). In this application. ♦ Lines 144–174: Synchronization method. { setLayout(new FlowLayout()). Panel p3= new Panel(). ♦ Lines 176–183: Creates a class for RTPPlayerWindow.addActionListener(this).*. public class Professor extends Frame implements ActionListener 5. 24. 7. 4.add(exit). such as completion of configuration of the processor. ♦ Lines 184–186: Creating an instance of AudioSendStreams. p1. 18.awt.addActionListener(this). 25. 13. add(p1). p2. ♦ Lines 63–82: Program for setting the track lengths ♦ Line 102: Creation of instance of the local session address (assigned to variable name called “localaddr”). 21. setSize(100. import java. 27. 12. we used the method getByName to create a new InetAddress instance. Panel p1= new Panel(). 28. and so on. 7.*. and Exit buttons. 38. ♦ Line 2: Package for event handlers. { as=new AudioSendStreams("255. { new Professor().getSource()==exit) 35. } Code Description ♦ Line 1: Package for frames. } 44. import javax.java © 2001 Dreamtech Software India Inc.media.setEnabled(false).*. import 2.setEnabled(true).255"). and related classes. start. java.event. ♦ Lines 16–18: Initialization of the panels. { if (ae. import java. } 41. ♦ Lines 19–21: Adding the buttons to the panels.255. java.*.control. java. ♦ Lines 29–41: This is an actionPerformed method to write the event handling for Start.*. we use the addactionListener method provided in ActionListener interface.io.util. 9. panels. .protocol. java. Listing 13-5: AudioReceiveStreams.*.*. and Exit variables through a button class. 34. { stop. 39. All Rights Reserved 1.awt.exit(0). Stop.*. 40. }else 37.*.getSource()==start) 31. ♦ Lines 9–11: Initializing the Start. 8. 33.media. start. as.*. Stop. we can directly register the components into ActionListener interface. javax. import 6. ♦ Lines 22–24: Adding panels to a frame. ♦ Lines 13–15: Registering the buttons to the Listener interface through addActionListener method. ♦ Line 4: Beginning of the main Professor class.awt. }else if (ae. ♦ Lines 25: Setting size of the frame. Through addActionListener method. import javax. import 5. import 3.net.media.440 Chapter 13: Voice and Video Communication 30.stop(). public static void main(String[] args) 43. 36. { System.setEnabled(true). To write event handlers on the buttons. 32.format. } 42.setEnabled(false). import 4.255. buttons are initialized. ♦ Line 44: End of the Professor class. ♦ Lines 7–28: In this constructor. import javax. stop.media. ♦ Lines 42–43: Creation of an instance of the Professor class. ControllerListener.println("Device not found"). import javax.media. 55. 35.eom.closed. boolean encodingOk. 48. Vector devices. for(int i=0. if(!waitForState(p. 24. format=new AudioFormat(AudioFormat. 19. 25. CaptureDeviceInfo di=null. 58. 53. 11. 26. } p.getDeviceList(format). TrackControl track[] = p. System. 28.length.ReceiveStreamListener { Processor p=null. 15.setContentDescriptor(new ContentDescriptor(ContentDescriptor. } p. } catch(NoProcessorException ie) { System.out. 62. 57. 36. 32.rtcp.16. playerlist=new Vector().rtp.elementAt(0).configure(). 41.rtp. 17. devices=CaptureDeviceManager.media.sun. 13. 63.*. 37. int port=49150. 45.getTrackControls(). boolean encodingOK=false. 47. t1=new Thread(this).RAW_RTP)). import javax.println("p noprocessorexception").failed. 12.*.Configured)) { System. 22.*. } else { System.*. Thread t1.println("AudioTransmitStream-no configured= "+configured).media. 49. 39. public AudioReceiveStreams(String Name) { HostName=Name. t1.stoped. 29.println("AudioReceiveStream-Name="+Name). } try { p=Manager. } catch(IOException ie) { System. String HostName. public class AudioReceiveStreams implements Runnable.event.out. AudioFormat format. 34.i<track.out. 16.println("p ioexception"). 59. 60. import javax. 30. Object waitObject.setFormat(new . System. 52. 33.getLocator()). 21. DataSink filewriter. 18. 20.media. 38. } public void run() { waitObject=new Object().LINEAR. 51. 56. di=null. 27.ui.Chapter 13: Voice and Video Communication 441 10.start(). 14. 23.1). DataSource source. boolean realized.exit(-1). 44. 46.playerlist.out. 31. 64. 50.rtp. import com. 61.44100.sun. 42.i++) {if(!encodingOk && track[i] instanceof FormatControl) {if(((FormatControl)track[i]). 40.createProcessor(di. import com.size()>0) { di=(CaptureDeviceInfo)devices.*. if(devices.prefetched.out. 43.media. 54.configured=true. sun.err. 80. 77. 96. AudioFormat(AudioFormat. 66.null).port.25). 106.0”. new SourceDescription(SourceDescription.Realized)) 74. public boolean waitForState(int state) 112.RTPSessionMgr(). 83.1. { username = "user". mgr. source=p.GSM_RTP. 100. }.”JMF RTP Player v2.startSession(sessaddr. } 103.getMessage()). { System. }else 107 System. {System.getByName(HostName). 69. SessionAddress localaddr = new SessionAddress(). 73.8000.Realized= "+configured).1.0.1.false). 75.println(e. { stoped=true. SessionManager mgr= rtpsm.destaddr.addFormat(new AudioFormat(AudioFormat. 92.start(). 70. } 71. try 91. 88. } catch (SecurityException e) 87.SOURCE_DESC_EMAIL. {new SourceDescription(SourceDescription.println("AudioTransmitStream-zdZd"). public void stop() 110. { while (p. mgr.false) 97.out. 82. if(!waitForState(p. SessionManager rtpsm=new com.out.exit(-1). }else encodingOk=true.SOURCE_DESC_TOOL. { synchronized (waitObject) 113.8000. 93.getDataOutput(). SourceDescription[] userdesclist= new SourceDescription[] 94. }else track[i].println("AudioTransmitStream. 95.0. 105.8.SOURCE_DESC_CNAME.generateCNAME(). 78. } catch (Exception e) 101. if(encodingOk) 72.initSession(localaddr. SessionAddress sessaddr = new SessionAddress(destaddr. try 85. int j=0. 67.getProperty("user.cname.8.GSM_RTP.1. { InetAddress destaddr = InetAddress. { try 114.rtp. 99. } .port + 1).wait(1).442 Chapter 13: Voice and Video Communication 65. } 89. 84.userdesclist.com”. { p. 104. System. 90. 108. { username = System.out. String cname = mgr. if (mgr == null) System. 81.false). 98.name").getState() < state && configured) 115. } 111.username+ “@company.setEnabled(false).println("AudioTransmitStream-started"). 102.18). String username = null. 68. 86. new SourceDescription(SourceDescription. mgr.setEnabled(false). } 76.1))==null) { track[i]. 79.realize(). { waitObject. p.media.5.addReceiveStreamListener(this). mgr.1). } /* End of Run Method */ 109. 162. 124. } catch (Exception e) {} return configured. 126. 147. } } /* End of synchronized void controllerUpdate(ControllerEvent ce) */ public void update(ReceiveStreamEvent event) { Player player = null. 154. 166. try 167. 149. 131. 128./* create a player by passing datasource to the Media Manager */ 163. 121. 130. 161. 165. waitObject. DataSource dsource = stream. 141. 129. 158. 144. 168. 146. } else if (ce instanceof EndOfMediaEvent) { eom = true. } else if (ce instanceof ControllerClosedEvent) { closed = true.println("in ReceiveStreamEvent1"). 156. try { stream =((NewReceiveStreamEvent)event). } } public synchronized void controllerUpdate(ControllerEvent ce) { if (ce instanceof RealizeCompleteEvent) { configured = true. 143.Chapter 13: Voice and Video Communication 443 116. 159.getReceiveStream(). } else if (ce instanceof ControllerErrorEvent) { failed = true.getSource(). 157. } catch (Exception e) {} } }else if (ce instanceof PrefetchCompleteEvent) { prefetched = true. 151. 145. ReceiverPlayerWindow playerWindow = null. SessionManager source = (SessionManager)event. 123.out. 139.println("created player " + player).out. 122. 119.sleep(500). player = Manager. 138. 125.notifyAll().currentThread(). Participant participant = stream. ReceiveStream stream = null. } catch (Exception e) {} } }else if (ce instanceof ConfigureCompleteEvent) { configured = true. System. if (event instanceof NewReceiveStreamEvent) { String cname = "Java Media Player". 160. } else { return. 150. 152. 148. 118. 136.notifyAll().createPlayer(dsource). 164. 137.getDataSource(). 134. 155. 132. 153.getParticipant(). 133. System. 140. 120. 142. { Thread. if (participant != null) cname = participant. 127. } catch(Exception e){} . synchronized (waitObject) { try { waitObject. synchronized (waitObject) { try { waitObject. 117.notifyAll().getCNAME(). } else if (ce instanceof ResourceUnavailableEvent) { configured=false. 135. { new AudioReceiveStreams("131. cname).err. String title) 182. { super(player).rtp. 177.44100. otherwise it returns “Device not found” and exits from the loop. } catch (Exception e) 170.sun.200. playerWindow = new ReceiverPlayerWindow( player.println("NewReceiveStreamEvent exception "+ e. } /* update(ReceiveStreamEvent event) */ 179.2.1) as mentioned at line 39. } 178.16. ♦ Lines 90–102: Try block for the InetAddress class that represents an Internet Protocol (IP) address. public void Name(String title) { setTitle(title). ♦ Lines 48–54: Try block for creating a processor for the specified media. ♦ Line 77: Here an instance of com. If the device is not found. we used the method getByName to create a new InetAddress instance./* send this player to player GUI */ 176.RTPSessionMgr. ♦ Line 60: To get the tracks from the processor by using the getTrackControls method and a TrackControl interface for each track in the media stream. public static void main(String args[]) 189. 173. } 172. class ReceiverPlayerWindow extends PlayerWindow 181.addControllerListener(this).LINEAR. ♦ Lines 30–36: Creation of the constructor for AudioReceiveStreams. playerlist. ♦ Lines 62–70: Program for setting the track lengths. In this application. } 190. This method can only be called after the Processor interface has been configured. is created. } } 188. 185. . { public ReceiverPlayerWindow( Player player. player.addElement(player). } setTitle(title). 175.444 Chapter 13: Voice and Video Communication 169. 171. ♦ Line 19: Port number is defined as 49150 for Receiving Audio Streams. all the streams will go to CaptureDeviceInfo. } Code Description ♦ Lines 1–14: Importing of packages as in the previous code. ♦ Line 18: Blank line. if (player == null) return. ♦ Lines 20–28: Necessary variables are declared. 186. 180. 184. ♦ Lines 42–47: Checking for Capturing Device. ♦ Line 16: Beginning of AudioReceiveStreams class.25"). 183. { System. ♦ Line 17: The Processor interface defines a module for processing and controlling time-based media data.media. 174.getMessage()). ♦ Line 59: Set the output content descriptor to RAW_RTP. 187. This createProcessor method returns a String value. ♦ Lines 37–108: This is the Run method to Receive Audio Streams to the clients in the format (AudioFormat. ♦ Lines 111–119: Synchronization method for waitForState with one parameter: the state of the processor. 14. public class Student extends Frame implements ActionListener 5.getSource()==start) 25.stop(). 9.event. } . setVisible(true). { as=new AudioReceiveStreams("131. 6. 29. start=new Button("Start"). public Student() 8. { setLayout(new FlowLayout()). controllerupdate for different types of events.getSource()==exit) 28.exit(0). setTitle("Student"). 27. } 23. p2.setEnabled(false). 31. setSize(100.addActionListener(this).add(start). ♦ Lines 109–110: For stopping the received streams. ♦ Lines 180–187: Creates a class for RTPPlayerWindow.75). exit. 2. import java. 20. Panel p1= new Panel(). 4. ♦ Lines 120–147: Synchronization method. 26. This RTPPlayerWindow extends the PlayerWindow class. add(p2). start. 3. public static void main(String[] args) 34. 15. 12. 13. start. { start.*. This allows the user to get details on all the ReceiveStreams as they transition through various states.java © 2001 Dreamtech Software India Inc. } 35.200.setEnabled(true). All Rights Reserved 1. exit=new Button("Exit").2. Panel p2= new Panel(). 18.awt. }else if (ae.*. } 32. 17.Chapter 13: Voice and Video Communication 445 ♦ Lines 93–97: Here the SourceDescriptor is for specifying the description of the source. 10. public void actionPerformed(ActionEvent ae) 24. } 33. { if (ae. 7. import java. Listing 13-6: Student. 19. 30.25").add(exit). AudioReceiveStreams as. add(p1). 11. 16. p1. as. exit. 21. System. { Button start. { new Student(). ♦ Lines 188–190: Creating an instance of AudioReceiveStreams. 22.awt.addActionListener(this). ♦ Lines 148–178: ReceiveStreamEvent notifies a listener of all events that are received on a particular ReceiveStream. *. Stop. and Exit Buttons. On all the machines.java are provided in Listings 13-7.java. and Exit variables through a Button class.media.io. there will be two programs: AudioVideoTransmit. 13-8.net. On the server. and 13-9.format. the broadcast originates here. Listing 13-7: AudioVideoTransmit. To write event handlers on the buttons. or clients. 4. we need JDK 1. On each client are two programs: AudioVideoReceive. import javax. import java. which is a batch file.media.*.rtp.media.InetAddress. we had the addactionListener method provided in the ActionListener interface. ♦ Lines 11 and 12: Registering the buttons to the Listener interface through addActionListener method.awt. ♦ Lines 7–22: In this constructor. import javax. we can directly register the components into ActionListener Interface. All Rights Reserved 1. 6. import com. 9. 3.1 or later to be able to run. import javax.*.bat.*.*.rtcp. and AudioVideoReceive. 11. ♦ Line 4: The beginning of the main Student class.media. ♦ Lines 15 and 16: Adding the buttons to the panels.*. The code for AudioVideoTransmit. ♦ Lines 9 and 10: Initializing the Start. Application: Audio–Video Broadcasting In this application. Professor. ♦ Lines 23–32: This is an actionPerformed method to write the event handling for Start.*. 7.sun. 5.java. Through this addActionListener method. ♦ Line 19: Setting the size of the frame.1 or later version and JMF 2. On the server.media.java.java. which is for reception of audio and video and Student.1. ♦ Lines 17 and 18: Adding the panels to a frame.media.rtp. Each client should have the sound card to receive the audio. which is for the transmitting. ♦ Line 35: End of the Student class. 10.*.protocol. import javax. One node is on the network that is designated as server. import java. Stop. we develop the code for broadcasting of audio and video over a network using JMF. we have initialized buttons.control. respectively.media.java © 2001 Dreamtech Software India Inc. There can be a number of nodes.java. a video camera is required to transmit the video in addition to the sound card. import javax. import javax.rtp.446 Chapter 13: Voice and Video Communication Code Description ♦ Line 1–2: Code for importing of packages.*. 2. ♦ Lines 33 and 34: Creation of an instance of the Student class. which provides the user interface. 8. ♦ Lines 13 and 14: Initializing the panels. which can receive the broadcast. . and Professor. import java. rm[i]. 64. 37. 33. portNumber = port.close(). 17. 23. 41. 61. MediaLocator medialocator. } status = createRTPSession().dispose(). if (status != null) { p. 57. 34. } public void stopTransmitter() { synchronized (this) { if (p != null) { p. 38. i++) { rm[i]. DataSource datasource = null. status = startProcessor().255. p = null. 49. 18. 54. 56. 39. int portNumber. 29. 60.removeTargets("Session ended. Processor p = null. 22. 16. 20. 43. 42.255. } p. 30. 31.length. 19. } public synchronized String startTransmitter() { String status. 51. 36. 52. 50. 26. 45. if (status != null) { return status. p. } } } } String startProcessor() { DataSource datasourceProcess. 28. 25. return null. for (int i = 0. 59. 66. 27. 53.255". return status. . boolean failed = false. public class AudioVideoTransmit implements ControllerListener 13. RTPManager rm[]. 63. 32. 35. 21. 47. String broadcastAddress = "255. p = null. public AudioVideoTransmit(int port) { medialocator= new MediaLocator("vfw://0&javasound://44100").close(). 24."). 65. 48. { 14. 62.start(). 46. 15. i < rm.Chapter 13: Voice and Video Communication 447 12. 58.stop(). 44. 55. 40. 121.RAW_RTP). if (status == false) return "Error in configuring processor". i++) { Format format = trackcontrol[i]. 116. 71. SessionAddress localAddress.createDataSource(medialocator).448 Chapter 13: Voice and Video Communication 67.} 80.getSupportedFormats(). rm = new RTPManager[pbs. } catch (Exception e) {return "Error in creating DataSource".length < 1) return "No tracks in processor". 84. catch (IOException ie) {return "Error in creating processor". 85. 92. } else trackcontrol[i]. 108.setContentDescriptor(cdesc). trackcontrol = p. return null. 98. 79. Controller. Processor. } catch (NoProcessorException pe) {return "Error in creating processor". cdesc = new ContentDescriptor(ContentDescriptor. 68. } else trackcontrol[i]. 103. i < trackcontrol. for (int i = 0. 82. if (trackcontrol[i]. 74. if (supportedFormats. . 94. trackForSupport = true. datasource = p. 70. boolean status.println("Track " + i + " is transmitting ").getDataOutput().} status = wait(p.createProcessor(datasourceProcess).length]. 114. 95. PushBufferStream pbs[] = pbd. 87. destAddress. 90. } if (!trackForSupport) return "No Supported tracks for valid RTP format". 111. 91.setFormat(selectedFormat). SendStream sendStream.getTrackControls(). 115. 99. Format supportedFormats[].Configured). p. 97. 104.out. datasourceProcess = Manager. if (trackcontrol == null || trackcontrol. 105. Format selectedFormat. ContentDescriptor cdesc. 69. System.setEnabled(false). 100.} try { p = Manager. 113.getStreams().length > 0) { selectedFormat = supportedFormats[0]. 88. 117. 112. 109.Realized). 78. 75. 101.isEnabled()) { supportedFormats = trackcontrol[i]. 107. 93. 76. trackcontrol[i]. } String createRTPSession() { PushBufferDataSource pbd = (PushBufferDataSource)datasource. 102. 119. 86. try { 73. 118. 72. 110. 96.getFormat(). status = wait(p. 83. 81. 89. 120. 106. if (status == false) return "Not realized the processor". TrackControl [] trackcontrol.setEnabled(false).trackForSupport = false.length. InetAddress ipAddress. 77. getByName(broadcastAddress). } 170.addTarget( destAddress). port). 124. ipAddress = InetAddress. while (p. p.} 138. } 171.Realized) 151. synchronized (this) 157.initialize( localAddress). } 141. for (int i = 0. } 163. } . else if (state == Processor.getLocalHost(). 128.realize(). { 144. } 150. port = portNumber + 2*i. int port. failed = false. private synchronized boolean wait(Processor p. } catch (Exception e) { return e. this. { 165. System. else 168. int state) 143. rm[i].start(). 131. } 167. { 148. port). { 158. localAddress = new SessionAddress( InetAddress. rm[i]. 125. i++) { try { rm[i] = RTPManager. 176. 129. 153. 142. sendStream = rm[i]. 140.} 161.out. 166. 145.getState() < state && !failed) 155. 130. failed = true. if (failed) 164. i). { return true. 160. public synchronized void controllerUpdate(ControllerEvent ce) 172. 137.println("RTP session: "+broadcastAddress +" "+ port). } 162. destAddress = new SessionAddress( ipAddress.newInstance(). p. 169. { 152. return false. { 175. 146. p. 149. 136. } catch (InterruptedException ie) { return false.configure(). try { 159. } 154.length.createSendStream(datasource.addControllerListener(this). 134. 123. 132. sendStream. if (ce instanceof ControllerClosedEvent) 174.Chapter 13: Voice and Video Communication 449 122. SourceDescription srcDesList[].getMessage(). 127. 135.Configured) 147. } 139. { 173. 126. 133. { 156. i < pbs. return null. if (state == Processor.wait(). 179. If you want to transmit a prerecorded file. ♦ Line 14: The MediaLocator class provides the way to identify the location of a media stream. it returns null. ♦ Line 19: Variable declaration for RTPManager. TrackControl. ♦ Lines 46–62: Method stopTransmitter() to stop the transmission.notifyAll(). ContentDescriptor. . ♦ Lines 76–80: Try block to create a processor to handle the input medialocator . ♦ Lines 21–25: This code is for the AudioVideoTransmit constructor with parameter port. ♦ Lines 72–75: Try block for creating the DataSource using createDataSource method for the specified medialocator.mov”). ♦ Lines 64–113: Method startProcessor() for creating a processor for the specified media. ♦ Line 15: Variable declaration for broadcast address with name "broadcastAddress". waiting to configure. the port number on which the track will transmit. SupportedFormats. replace line 23 with the following line: medialocator= new MediaLocator(“file://c:/media/samp. ♦ Lines 66–71: Variable declarations for DataSource. } 181. closing the processor and disposing of the RTP manager. } if (ce instanceof ControllerEvent) { this. Processor extends the Player interface. 180. trackForSupport. ♦ Line 20: The DataSource is an abstraction for media protocol handlers. it returns “Error in configuring processor”. ♦ Line 42: Starts the processor if both the above methods are successful and returns null. If the RTP session is created successfully. ♦ Line 18: The Processor interface defines a module for processing and controlling time-based media data. ♦ Line 35: Creating an RTP session by calling the method reateRTPSession(). and selectedFormat. Lines 31-34 are for checking whether the processor is created. ♦ Line 16: Variable declaration for port to transmit data. it returns null. status. meaning. ♦ Line 17: Variable declaration for checking processor failure. This DataSource is available in the javax. DataSource manages the life cycle of the media source by providing a simple connection protocol. 178.450 Chapter 13: Voice and Video Communication 177. that is. Code Description ♦ Lines 1–10: Importing of the packages. RTPManager API creates sessions for each media track of the processor. returns true if successful ♦ Lines 82 and 83: To check whether the processor is configured. If the processor is created.media. It can be file or capture device source. If the processor is not configured. ♦ Lines 27–44: Method startTransmitter() for starting the transmission. ♦ Line 30: Start a processor for the specified media locator by calling method startProcessor(). } 182. ♦ Line 12: Class for AudioVideoTransmit starts here. ♦ Line 81: Calls the method wait().protocol package. 20.20. 11. ♦ Line 107: If no track is detected. 2. panel. setBounds(350.setBounds(80.awt.60.70).setLayout(null). setVisible(true). public Professor() 9. { 10.10. import java.10. exit. 8. ♦ Line 111: Gets the output data source of the processor. Panel panel. ♦ Line 88: Sets the content descriptor to Processor. exit=new Button("Exit"). 26.20).20). 23.setBounds(10. setTitle("Professor"). This method can only be called after the Processor Interface has been configured and after checking for at least one track. } . 22.awt. ♦ Lines 89–105: Checking for the tracks to supported formats. 3. import java. Note that at line 116 the PushBufferDataSource class abstracts a data source that manages data in the form of push streams. public class Professor extends Frame implements ActionListener 4.50). 17. which creates sessions for each media track of the processor.add(exit). 15.addActionListener(this). panel. 21. add(panel).setBounds(10. ♦ Lines 114–140: Method createRTPSession(). 16. it returns "No Supported tracks for valid RTP format". 7. { 5.170. 12.60.addActionListener(this).*. All Rights Reserved.Chapter 13: Voice and Video Communication 451 ♦ Lines 84–86: To get the tracks from the processor by using the getTrackControls method and a TrackControl interface for each track in the media stream. ♦ Lines 171–182: Method controllerUpdate() for ControllerListener to catch the controller events.*. panel = new Panel(). 24.200.java © 2001 Dreamtech Software India Inc. start. setLayout(null). start=new Button("Start").add(start). meaning PushBufferStreams.setEnabled(false). 6. ♦ Lines 142–170: Synchronization method for wait with two parameters. Listing 13-8: Professor. panel. start. 19. Button start. The streams from this data source contain Buffer objects. 27.exit. 1. ♦ Line 108: Calls the wait() method to realize the processor ♦ Lines 109 and 110: Checks whether the status of the process is false. exit.170.event. exit. 13. 25. AudioVideoTransmit avt. 18. This method is used for configuring and realizing the Processor. panel. ♦ Line 87: Create the content descriptor to RAW_RTP. Processor and State of the processor. 14. 33. import java. 11.exit(0). 49.media.*.*. 46.*. 39. 41. Panel. 42.util. using addActionListener method provided in ActionListener Interface. System. 31. start.*. 35. 30. 5.*.rtcp. and AudioVideoTransmit classes. 48.media. import javax. import javax. import javax. Listing 13-9: AudioVideoReceive.exit(0). event handlers are written on the Buttons. 2.rtp. } else if (ae. 3.format.event.out.stopTransmitter(). 4.net. 7. System.event.media.452 Chapter 13: Voice and Video Communication 28. if (result != null) { System. } exit. import java. 8. and the boundaries are set. 50.rtp.awt.io. import javax. 9. ♦ Lines 5–7: Variable declaration of Buttons. 38.awt. 36. ♦ Line 48–52: Main method to call the Professor class.getSource()==exit) { avt.startTransmitter(). 43. 37. import java.setEnabled(true). .*. ♦ Lines 28–47: This is an actionPerformed method to write the event handling for Start and Exit buttons.protocol. ♦ Lines 3–52: The main Professor class starts. } public void actionPerformed(ActionEvent ae) { if (ae. 52. 34.media.*. import javax. 32. ♦ Lines 8–27: In this constructor Buttons and Panel are initialized and added to the Frame. 29. 10.media. 45. 6. 40. } } public static void main(String[] args) { new Professor(). String result=avt.*.rtp. import java.getSource()==start) { avt=new AudioVideoTransmit(49250).println("Error : " + result).*. 44. } Code Description ♦ Lines 1 and 2: Importing of packages. import javax. import java. 47. All Rights Reserved 1.media. 51.Vector.*.setEnabled(false).java © 2001 Dreamtech Software India Inc. 30.out. 42. RTPManager managers[] = null. 16. } 48. ipAddress = InetAddress.ControllerListener 14. { 15.isMulticastAddress()) 44.control. 27. localAddress= new SessionAddress( ipAddress.println("RTP session for : "+ sessions[0] +" port: "+ port[i] +" ttl: "+ ttl). managers = new RTPManager[lengthOfSessions]. .addTarget(destAddress). 36.getMessage()).setBufferLength(350). destAddress = new SessionAddress( ipAddress. managers[i]. 52. 58. return false. 19. localAddress= new SessionAddress( InetAddress.getByName(sessions[0]). managers[i]. port[i]. SessionAddress localAddress = new SessionAddress(). 20. managers[i] = (RTPManager) RTPManager.initialize( localAddress). } 63. for (int i = 0. ttl). destAddress = new SessionAddress( ipAddress.Chapter 13: Voice and Video Communication 453 12. { 45. SessionListener. 62. managers[i]. 35. { 26. 18. try { 28. 31. } catch (Exception e){ 60.currentTimeMillis(). port[i]). 34. 57.waitingtime.addReceiveStreamListener(this). 49252}. import javax.newInstance(). receiverWindows = new Vector(). 55. 61. this. bc. BufferControl bc = (BufferControl)managers[i]. i++) 37. 29. 54. System.port[i]). else 49. 17. long currenttime.media.sessions = sessionsAddress. System. 32. { 22. 33. { 38. protected boolean initialize() 25. 40. 13. public AudioVideoReceive(String sessionsAddress[]) 21. int lengthOfSessions = 2. Object waitObject = new Object().out. 47. 43.BufferControl.println("Not creating the RTP Session: " + e. if( ipAddress. i < lengthOfSessions. } 59. managers[i]. currenttime = System. String sessions[] = null. } 53.getLocalHost(). { 50.addSessionListener(this). int ttl = 1. if (bc != null) 56. 23. int port[] = {49250. public class AudioVideoReceive implements ReceiveStreamListener. 46. boolean dataObtained = false. ttl). Vector receiverWindows = null. SessionAddress destAddress. InetAddress ipAddress. port[i]. 39.getControl("BufferControl"). 41. 51. } 24. size(). 103. 96. return true. } 74. 72. System. protected void close() 89. ((Receiver)receiverWindows.player == p) return rf.size() == 0. managers[i] = null. i++) 91. public boolean isExecute() 85. 65. waitingtime = 30000. 73.454 Chapter 13: Voice and Video Communication 64. i++) { if (managers[i] != null) { managers[i]. 101. if (rf. } 75. 113.println("No RTP data was received. { 70. } } } Receiver findPorS(Player p) { for (int i = 0. try{ 66. i < receiverWindows. 117.println("Waiting for the RTP data").elementAt(i).out.removeAllElements(). { 86. 110. } catch (Exception e) {} 95. { 68.wait(1000). 109. 102.length. } 82. 116. while (!dataObtained && System. i < managers. } receiverWindows.elementAt(i)).dispose(). 107. i++) { Receiver rf = (Receiver)receiverWindows. System. 97."). 99. for (int i = 0. return false. managers[i]. 104. { 92. 112. if (!dataObtained) 77. 108. } Receiver findPorS(ReceiveStream rstrm) . { 90. synchronized (waitObject) 67. 111. } 84. 79. 98.removeTargets("Closing this session. 114. try { 93.size(). } 88. } catch (Exception e) {} 76. i < receiverWindows. return receiverWindows. 115."). 80.currentTimeMillis() . waitObject. close(). } return null.out. 83. 100. { 78. 81.currenttime < waitingtime) 69. 87. if (!dataObtained) 71. for (int i = 0.close(). 105. 106. 94. 141. p. 134. 150. 144.size().getParticipant(). if (p == null) return. 149. } } catch (Exception e) { System. 140.addControllerListener(this).getDataSource(). 164. 148. 160. 167. 156. 139. 125. 170. 128. 169. 130. 132. 123. 147. 119.println("Exception " + e.stream == rstrm) return rf. 154.exit(0). 152.err.elementAt(i). stream).out.getMessage()). 171. 155. 151. 121. 157. 137. 146. } } public synchronized void update( ReceiveStreamEvent revt) { Participant prse = revt. 172. synchronized (waitObject) { dataObtained = true. p. 161. } public synchronized void update(SessionEvent sevt) { if (sevt instanceof NewParticipantEvent) { Participant pse = ((NewParticipantEvent)sevt).addElement(rf). 120. RTPControl rtpctl = (RTPControl)ds. 135. 165. receiverWindows.println("New participant joined: " + pse.getControl("RTPControl"). DataSource ds = stream. i++) { Receiver rf = (Receiver)receiverWindows. 142. System.getReceiveStream(). 122. if (rf. return. } else if (revt instanceof NewReceiveStreamEvent) { try { stream = ((NewReceiveStreamEvent)revt). 127.getDataSource() != null) { DataSource ds = stream.getCNAME()). 145.getReceiveStream(). 131. 163. { for (int i = 0.createPlayer(ds). Player p = Manager. . 129. if (revt instanceof RemotePayloadChangeEvent) { System. 166.notifyAll(). 158.Chapter 13: Voice and Video Communication 455 118.getDataSource(). 168. 138.realize(). 159. 143. Receiver rf = new Receiver(p. } return null. waitObject.getParticipant(). ReceiveStream stream = revt. 124. } } else if (revt instanceof StreamMappedEvent) { if (stream != null && stream. 133. 126. i < receiverWindows. 136. 162. 153. 209. 180. } } } 217. 198. 191. if (rtpctl != null) { System.setVisible(true). receiverWindows. 194. stream = strm. if (rf== null) { System. 203. if (rf != null) { rf. 189. controlcomponent. 216. 195. 202. Panel viewpanel. 175. 192.out. 177.removeElement(rf). 188. 221. 176. 206. 224. 182. 220.getSourceController(). 225. } } } else if (revt instanceof ByeEvent) { Receiver rf = findPorS(stream). } . if (p == null) return. 179. 174. } rf. 190. 184. 219.close(). Receiver rf = findPorS(p). 201. 199. 183. ReceiveStream stream. 185. 223.exit(0). 212. 181. 207.removeElement(rf). if (rf != null) { rf. 204. 197.println(" " + rtpctl. 214. 211. 218. Receiver(Player p.start().initialize(). if (ce instanceof RealizeCompleteEvent) { Receiver rf = findPorS(p). 186. 222.removeControllerListener(this). 213. class Receiver extends Frame { Player player. 227. 187. 226. Component visualcomponent. 200.close(). receiverWindows. p.getControl("RTPControl"). 208. 205. ReceiveStream strm) { player = p. } if (ce instanceof ControllerErrorEvent) { p. rf. } } } public synchronized void controllerUpdate(ControllerEvent ce) { Player p = (Player)ce. 193.getFormat()). 178. 196. 210.456 Chapter 13: Voice and Video Communication 173. 215. RTPControl rtpctl = (RTPControl)ds. } 255. ♦ Lines 15–19: Variables Declaration for RTPManager. 266. } 237. pack().getControlPanelComponent()) != null) 234. { 230. } Code Description ♦ Lines 1–12: Importing of necessary packages. { 251. 262. if (args. . 247. } 243.out. } 263.out. ♦ Lines 28–30: Variable declaration of InetAddress and SessionAddress.println(e).close().println("Failed to initialize. } 249.println("Usage : java AudioVideoReceive ipAdress"). { 239. 241.length == 0) 252. 231. } catch (Exception e) {System. System. controlcomponent). 242. viewpanel = new Panel(new BorderLayout()). } 248.sleep(1000). { 253. AudioVideoReceive avr = new AudioVideoReceive(args). try { 264. } 268. 261. 240. if ((controlcomponent = player. dispose().add("South". public void addNotify() 244. if ((visualcomponent = player. ♦ Line 34: Creating the RTPManagers for sessions. 246.exit(0). super. This RTPManager creates sessions for each media track of the processor. player. public static void main(String args[]) 250. viewpanel. 233.initialize()) 259. ♦ Lines 24–83: Method initialize() is for receiving audio video streams.out.add("Center". System. { 257.} 267. ♦ Lines 13 and 14: Starting of the AudioVideoReceive class to receive RTP Transmission. 258. add(viewpanel).addNotify(). while (!avr. viewpanel. 236. { 245.getVisualComponent()) != null) 232. 235. System."). { 260.Chapter 13: Voice and Video Communication 457 228. if (!avr. } 269. else 256. Thread. visualcomponent). 254. setVisible(false). ♦ Lines 20–23: The constructor of the AudioVideoReceive. public void close() 238. public void initialize() 229.isExecute()) 265. To run the AudioVideoReceive.java and Student. ♦ Lines 54–56: Trying with some other buffer size for better smoothness. 2. The H. This section waits for 30 seconds to get the RTP data from transmitter. To run the AudioVideoTransmit. You can see the image of the Professor (meaning.200. Run the Student. Professor. the Transmitter image) and hear audio through the headphone.java programs at the server: 1. ♦ Lines 217–248: Creating a GUI for receiver for a player.255.java and Professor. Enter the source code and compile the files. It then transmits audio and video to whomever is logged on to the server. In addition. You can create a file Student.class file is created.323 standards using JMF. ♦ Lines 107–126: Methods findPorS() for finding Player or ReceiveStream.bat file with the following line: java AudioVideoReceive 255.255. ♦ Lines 63– 81: Getting the current time and setting the wait time for 30 seconds.2. Run the Professor.bat file to the Professor’s system IP address. the AudioVideoTransmit class captures the video of the Professor from the video camera and sound from the microphone. ♦ Lines 249–269: Main method for creating an instance of AudioVideoReceive class and initializing it. 2. ♦ Lines 88–106: This is a method to close the players and the session managers.class file on the server system by giving the command java Professor. it returns true. Enter the code and compile the JAVA file. If data is received. these standards do not guarantee a desired quality of service.323 standards specify the protocols and coding techniques used for voice and video communication over IP networks. ♦ Lines 135–189: Method update(ReceiveStreamEvent revt) for ReceiveStreamListener. ♦ Line 57: Pass destAddress to RTPManager using the addTarget method. otherwise false. special protocols — RTP and RTCP — are defined by which we can achieve real-time transmission of voice and video over IP networks.2. Summary This chapter presented the implementation of audio and video applications based on H. For example: java AudioVideoReceive 131. after initialization of audio-video receiver.bat file (see the following section) on the client’s system.200. ♦ Lines 84–87: Method isExecute() is used for checking whether the data is received or not.java programs on the client: 1. After you click the Start Button. ♦ Lines 190–216: Method controllerUpdate(ControllerEvent ce) for ControllerListener. A screen display contains the Start and Exit buttons. low bit rate coding standards are specified for both .25 Here 131.bat file. ♦ Lines 127–134: Method update(SessionEvent sevt) for SessionListener.458 Chapter 13: Voice and Video Communication ♦ Lines 36–58: Creating the new instance of RTPManagers and adding the SessionListener and ReceiveStreamListener and initializing the RTPManagers.255 If you have any problem running the Student. change the IP addresses in Student.25 is the IP address of Professor’s system. However. So. Chapter 13: Voice and Video Communication 459 voice and video. The examples discussed in this chapter can be effectively used for developing applications.323 standards. Implementation of H.323 protocol stack. Voice and video communication over IP networks will be widely available in the future because of the savings in cost it provides. such as m-learning (mobile learning) — you can listen to a professor while relaxing in a garden rather than sitting at your desktop in a brick-andmortar classroom. JMF provides the necessary class libraries for implementation of H.323 over mobile devices is much more attractive because we can have very low cost voice and video communication using mobile devices. For 3G services to take off on a grand scale in the near future. the key lies with the content development through 3G programming for devices that run a full-fledged Java Virtual Machine and H. . these systems will be upgraded to 3G networks. a single mailbox for all types of mail — e-mails or voice mails). Certainly. To make life simpler for the end user. so that the user is not concerned with the underlying network technologies and protocols but can obtain the desired service using a terminal of his choice. which calls for the resolution of many administrative issues. we are now witnessing a revolution in telecommunications in the form of convergence.Chapter 14 The Future of Wireless Networks The 2G wireless networks of yesteryear are slowly being upgraded to 2. The main objective of convergence is to provide the end user with a simple and efficient means of accessing the services. In the next few years. we use different networks for accessing different services. a number of networks provide different services. which support higher data rates. which support much higher data rates to provide full-fledged audio. we use the paging network to page a person on the move. all these services together provide us the power to communicate and to be in touch with our office. and to access these networks. . ♦ The operators and service providers have to upgrade their networks continually to provide higher bandwidths as the subscriber capacity and the demand for high bandwidth services grow. Convergence Technologies Today. has to keep track of a number of mailboxes. The main drawbacks of this telecommunication architecture are ♦ The user has to maintain a number of terminals to access different services through different networks. each operator has to come to an understanding with other operators. such as instant messaging and unified messaging. ♦ To provide value-added services to the users (for instance. and mobile telephone service providers. we use the Public Land Mobile Network (PLMN) to make calls from a mobile telephone. and our friends. content development. voice mailboxes located at servers of fixed telephone service providers. We use the Public Switched Telephone Network (PSTN) for making calls from a land-line telephone and for sending fax messages. We will discuss the emergence of convergence — convergence of networks and convergence of services.and video-streaming applications over mobile devices. We also keep a number of mailboxes to receive messages — the e-mail boxes at our ISP.5G networks. As shown in Figure 14-1. we will outline the new developments taking place in the wireless arena. and we use the radio to receive audio from audio broadcasting stations. or mailboxes at Web-based e-mail service providers (such as Hotmail or Yahoo!). We will highlight the developments taking place in the field of mobile devices. which are also discussed. and also has to keep track of the multiple bills from different service providers. Still. In this chapter. we use the desktop to access the Internet through an Internet Service Provider (ISP). our home. users have a number of terminals. and protocols. the end user’s demand for much higher bandwidths and value-added services are forcing the network operators and infrastructure providers to develop new technologies to support broadband services. we use the cable TV network to receive TV programs. which will facilitate new services. The content providers and the applications providers connect the servers to the backbone network. and listen to the music through the headset — all that without the need for wires. and video applications. The architecture shown in Figure 14-2 clearly demonstrates how Bluetooth and 3G technologies can work together to provide services to the end users. This link. takes away nearly 50 percent of the total cost of the providing telephone. Here we have a backbone network. voice. known as the subscriber loop or local loop. a mobile device. which is a very high-speed optical-fiber network. In remote/rural areas. The wireless local loop is now the best solution because we can avoid wires. this cost is much higher. . cable TV network. and so forth. simultaneously download MP3 music from a Web site onto the mobile device. However. one can access the Internet through the desktop PC. The installation and maintenance costs are very high for wired local loops. and so on. and video services using a terminal of his choice — it can be a desktop PC. For instance. download files. The end user can also have a Personal Area Network (PAN). very high data rates are supported. a WebTV. voice. transfer them to the laptop. which is the ad-hoc network of the devices of the user. The end user gets connected to the backbone network through the access network to obtain various data.5G and 3G systems. The last mile problem is solved through these wireless networks.” The link from the telephone exchange (or switch or end office) to the home/office is the costliest element in the whole network. in the earlier days. because the population is geographically dispersed. The backbone network is connected to various access networks — these networks provide access to the end users. The access network can be a fixed telephone network. Wireless last mile The traditional wired telecommunication systems provided a great challenge only in the “last mile.Chapter 14: The Future of Wireless Networks 461 Figure 14-1: Architecture of telecommunications networks Convergence of Networks The first step in convergence is to redefine the telecommunications architecture. This results in a drastic cost reduction. The backbone network can support very high data rates for data. mobile network. With the advent of 2. the wireless local loop supported only low data rates. a laptop. Laying cables in mountain/hilly regions is a Herculean task. as shown in Figure 14-2. note that the data rates are not to scale. The service spectrum shown in Figure 14-3 depicts the various service categories: data. Convergence of services The architecture shown in Figure 14-3 provides high data rate services to the end users. however. one-way video. one-way audio. The Convergence paradigm beautifully arranges the marriage between 3G technology and Bluetooth technology. This “wireless last inch” attains significance mainly because it provides mobility to the users — the user need not be glued to a desktop or a land-line telephone.462 Chapter 14: The Future of Wireless Networks Figure 14-2: Convergence of networks Wireless last inch Technologies such as Bluetooth network connect the devices in a small area. This network in turn can get connected to the access network. interactive audio. such as home or office cabin. Bluetooth-enabled devices will have the intelligence to decide which access network to connect for the desired services. In the future. This figure also represents the data rates requirements. . the tariffs on different networks will be different. and two-way video services. over the Internet. which can then be accessed by the end user from a desktop PC. an Internet-enabled TV set. One-way video services include video mail. This calls for large file transfers. and so forth. and so forth. graphics and collaborative working. “wireless Web radios” will be a consumer item that can be used to tune the desktop or a mobile device to a Web site to download audio programs. The interactive audio applications include voice chat between two persons and multi-party audio conferencing with white board facility to share graphics.” One can transmit the patient data (such as ECG. The quality of speech. In regard to education. wherein video clippings can be attached to the e-mail messages. high-resolution graphics. The one-way audio applications include voice mail. TV programs can be distributed over the Internet backbone to the cable TV access network. groups of persons working on different corners of the earth can form a virtual group to carry out. lessons can be taught through virtual classrooms so that one can sit in the comfort of his/her home and participate in lectures and interact with the teacher. Audio broadcasting over the Internet is an important paradigm shift — the broadcasting networks will “merge” with the Internet.Chapter 14: The Future of Wireless Networks 463 Figure 14-3: The service spectrum Data services include e-mail. or from a mobile device. This service has potential applications in many areas. and the Internet itself can be used for listening to audio programs. is not very good. Another area where this service is of great benefit is in telemedicine. and x-ray) over the Internet to specialists located in distant places to obtain . of course. With the high-speed wireless networks of 2. In collaborative working. this is another important aspect of convergence — the convergence of cable TV and Internet. the interactive audio applications use low bit rate coding of voice. mobile commerce. the two most important being education and medicine. text chat. graphics. The teacher and the students can share the data. At present. which.5G and 3G. and high fidelity audio can be used for voice applications. and video broadcasting. require high bandwidths. or “medicine from a distance. During the next few years. EEG. and audio broadcast. Interactive video services include two-way video conferencing or multi-party video conferencing. voice quality can be improved substantially. for example. downloading of video clippings. software development. downloading of music. Again. therefore. or say “3G programming” and all the books on 3G programming will be displayed. Nowadays. and computer-telephony integration. Or. Of course. you can still use your mobile phone to make a call through the PSTN. it will recognize the word and connect the user to his or her home number by looking up the corresponding phone number in the database within the mobile device. Using the text-to-speech conversion technology. one must “train” the mobile phone to recognize his or her voice. Of course.464 Chapter 14: The Future of Wireless Networks medical help. A new set of applications is now being made available based on three emerging technologies: speech recognition. Text-to-Speech Conversion Just the way we want computers and mobile devices to recognize our speech. we will see how these functions can be achieved through a new mark-up language called VoiceXML. This is of great significance. you can use your mobile phone to access any of the mailboxes. an accident. The Bluetooth-enabled mobile phone will automatically detect the presence of the PSTN connection availability and establish the call over the PSTN because the call from the PSTN would be a cheaper choice. If you are at home. communication will be really effective. the mobile phone can serve as a . particularly for providing emergency services from ambulances: paramedic staff can send diagnostic information to the hospital within minutes after. From an end-user point of view. the letter “u” is pronounced differently in the words “put” and “but”). speech is the most convenient and effective means of communication among human beings. and the paramedic staff can have a doctor in the nearest city analyze the information. Text-to-speech conversion enables us to get Web content through speech. the choice would be a mobile device. Conversion of text into speech is not straightforward because of the pronunciation idiosyncrasies of languages (for example. WAP. For example.com” and the corresponding Web site will be displayed. Emerging Technologies Although we use text as the medium of communication. Special software for text-to-speech conversion is required. Later in the chapter. text to speech conversion. for example. some mobile phones support a “voice dialing” feature. and computer telephony integration technologies help in achieving this objective. when a user speaks the word “home” into the mobile phone. Providing telemedicine service through the wireless networks is also of great importance in rural and remote areas where there are no medical facilities. say. Another interesting possibility is to browse the Web through voice commands. Speech Recognition Automatic speech recognition technology has now matured to a stage where it is commercially viable. as the mobile device is considered “the most personal gadget” one has. For example. you can say “hungryminds. Note that the transmission of high-resolution diagnostic data such as x-rays requires high bandwidths that can be supported only by 3G networks. If we combine text-to-speech and speech recognition. such services will reduce the “digital divide” between the different sections of the society. one still has to rely on the desktop PC for obtaining large-screen. Certainly. Mobile hospitals can carry the diagnostic equipment. the main advantage of the convergence of networks is that the user can use a terminal of his choice to access the service. You can visualize the advantages of accessing a converged network from any device. Using this technology. high-resolution graphics or to compose a large document and send it over the network. we can obtain the stock quotes in speech form through a server. computers can be made to convert text into speech. Speech recognition. facilitates obtaining focused information through text messages (such as stock quotes). If we are able to communicate with computers in speech form. Or you can say “Search” and the search engine will appear. It takes the text as input and produces the output. Invariably. text-to-speech conversion. computers or mobile devices can be made to understand the words we speak. Instant Messaging Today. fax. In IVR systems. the device typically can be a mobile device that one always carries. For example. With the convergence of networks. whenever a new e-mail message arrives in your mailbox. data. and Interactive Voice Response (IVR) systems. such as ♦ One mailbox for all types of media. the IVR system will ask you to dial the account number. if we can provide the information through speech. you can retrieve the message. mobile devices can be “always connected” to the network. Instant messaging can also be used for informing you when your friends or relatives have logged on to a Web server when you are also logged on. the server can push the information to the user. call different numbers depending on the location of the called person. The instant message can be sent to a device of your choice — your obvious choice is your mobile phone. Because the penetration of PCs is low as compared to penetration of telephones (mobile and fixed). It also provides a single mailbox to access messages of different types. anytime using different media: voice. data. or a desktop.” During the next few years. anywhere. the user has to use different devices to access different networks. Unified Messaging Technology has made it possible to communicate with anyone. which you can input through the keypad. a pager. unified messaging. For instance. and so forth ♦ Access to different services from one device of their choice. However. The driving factor for this unified messaging is users’ demands for simple and easy-to-use interfaces for meeting their communication needs. if you want to find out the status of your bank balance in your bank account. Unified messaging aims at solving this problem by providing the ability to access different networks using a device of one’s choice.Chapter 14: The Future of Wireless Networks 465 very user-friendly mechanism to obtain information from the Web. “What is the stock price of Microsoft?” The server will recognize the speech. it is ideal. and video. The new services emerging can be categorized into instant messaging. With increased use of communication facilities. you can dial the bank IVR system. text-to-speech conversion. and such. is 100 dollars as at eleven hours. and informs you “Your bank balance is five hundred and sixty dollars. and receives multiple bills for the different services. and deliver the stock price in speech format: “The stock quote of ABC Inc. convert it into speech format. does text-to-speech conversion. a user can dial a stock trading portal through voice dialing and say. databases. .” Computer Telephony Integration (CTI) A lot of information is presently available on computers in the form of text files. such as voice. we spend lot of time finding out whether we have received new e-mails by connecting to the Internet and logging into our mailboxes. e-mail. you will receive a notification to that effect. the instant message can be delivered to any of the devices — a mobile phone. and precise location-based services. For instance. Another value addition of instant messaging is that you can combine it with location-based services. or video. retrieve the information from the database. the computer will prompt the user to give the input through the keypad on the telephone. and instead of pulling the information from the servers. The IVR system retrieves the information from the database. With packet-based wireless networks. Based on the urgency. instant messaging informs you immediately. Whenever a person in your database or address book is near you (or your mobile phone). subscribers are demanding a number of services. these technologies will be integrated into the services being provided on mobile devices to make the interaction between humans and the Internet servers much more effective. CTI technology facilitates this by a combination of speech recognition. not different mailboxes for voice. This facilitates chat or sharing other information. a few of these applications are being made available. E-mail To access text messages. or through a PC. A person can program his mobile device for forwarding all the calls to a fixed line or vice versa. with the present technology. Fax messages can be retrieved from the mailbox using a normal fax machine or they can be read through a telephone (of course. fax mail. voice mail. The voice mailbox can be accessed from the telephone. fixed or mobile. presently. with the limitation that the pictures cannot be read). . and interactive voice response systems. the voice mailboxes are many — at the PSTN service provider. bank account or credit cards. say. Voice messaging If a called party does not want to be reached or is not available. easy-to-use interface for accessing different services ♦ A single. text-tospeech conversion. a single voice mailbox can be provided that can be used for voice mails from the PSTN or a mobile phone. or on the PC. the user has to train the device for his voice to obtain good recognition accuracy. After one accesses the mailbox. Voice dialing Voice dialing presents real advantages when it comes to easily accessing mailboxes or other telephones. at the mobile service provider. voice mail is left in the voice mailbox. Applications of Unified Messaging The following are some of the applications of unified messaging that use speech recognition. all these will be possible. However. the text is converted into speech through text-to-speech conversion software and then played to the user.466 Chapter 14: The Future of Wireless Networks ♦ Simple. The fax message can be routed to a normal fax machine or a message box. or at the subscriber premises. The user can program to receive the short message on his mobile phone. and the calling party is saved the bother of trying different numbers. Short messaging service Whenever mail (e-mail. call forwarding is supported on many networks. At present. However. the user can be alerted through a short message. Interactive voice response systems Users can access information available in databases using IVR from mobile phones in speech form. The user can interact with the database (without operator intervention) and obtain the information regarding. or video mail) arrives in one’s mailbox. pager. In addition. Instead of so many boxes. consolidated bill for all the services. This allows a person to be in touch with office/home all the time. Advanced IVR systems also facilitate receiving fax messages on demand. however. Call forwarding Nowadays. This calls for special software that converts the fax text into normal text and then converts the text into speech. The voice mailbox can also be used for storing e-mails. e-mail (mail in text form) can be retrieved through a telephone (fixed or mobile). not different bills for different networks ♦ A single directory number to call a person irrespective of the location of the called person In due course. Fax mail Fax messages can also be stored in the same mailbox as e-mails. We discuss these in the following sections. there is a separate mailbox (or multiple mailboxes if one has multiple mail addresses). Certainly. so we need to watch how location-based services will be received by the public. with good video-streaming technologies presently in development. video messaging will be extensively used. restaurants. Also. devices with and without operating . the MSC of your mobile network will know that you are at home (as the MSC keeps track of your mobile phone). the mobile device needs to run an Operating System (OS). Precise Location-Based Services We discussed various location-based services earlier in the chapter. and so forth. anywhere. and the incoming calls to your mobile device can be routed to your home telephone number. which is the optimized version of Win CE for mobile devices. To provide all these exciting services. According to one school of thought. a shift from low processing power to high processing power. which is the mobile version of Outlook Express and Mobile Internet Explorer. location-specific services can be provided such as information about hotels. The Java programs can be downloaded from the server to the mobile device. Exciting times are ahead due to the unified messaging.) The issues related to privacy will be of paramount importance in providing location-specific services. When you are at home. The 2G mobile devices were mostly voice-only devices that supported two-way voice communication. we next need to address the issue of the capabilities of the mobile devices. it can be automatically forwarded by the MSC to the home telephone. the location of your Bluetooth-enabled mobile device is known to the mobile operator’s MSC. and it will be an integral part of unified messaging. and Microsoft’s Stinger. With it you can communicate with anyone. Your location information can also be used by a network operator to route the calls. and content can be presented to the user. Stinger has Outlook companion. video messaging is not widespread because video occupies a large bandwidth. The OSs that have been developed for the mobile device market include Palm OS. According to the second school of thought. Those who believe that “the network is the computer” (a slogan popularized by Sun Microsystems) feel that it is enough if the mobile device runs a browser. there are two schools of thought and. Mobile Devices During the last few years. For instance. desktop video conferencing is becoming popular. when a call is made to your mobile phone. The Asian market demands mobile devices that are capable of handling text content in different languages. if the capability of the device is small) and any application or content can be downloaded from the network servers.Chapter 14: The Future of Wireless Networks 467 Video messaging Presently. (Note that the user must use the call-forwarding feature for this to work. there is a shift from Europe and North America to Asia where the mobile phone market growth rate is very high. hospitals. Java phones are based on this concept. Providing content in regional languages is a challenge particularly for content providers. In the arena of mobile devices. Location-based services have yet to emerge on a large-scale commercial level. accordingly. two types of devices. which can interpret WML and HTML. Another possibility is to use Bluetooth technology for location identification. a shift from black-and-white monitors to color monitors. anytime by using just one number and with any device of your choice. Location-based services also help in navigation. Now there is a shift from voice to voice and data. the mobile device needs just a browser (a micro-browser. Based on the location of the mobile device. if you are at home. Symbian’s EPOC. the resulting quality is poor. As soon as the Internet backbone can support higher data rates. However. and if low bit rates are used. a lot of research has gone into making more “intelligent” mobile devices. 468 Chapter 14: The Future of Wireless Networks systems will be in use, because the cost considerations will ultimately contribute to the decision of the end users. Tools for Content Development As we have seen in the earlier chapters, the content for the wireless networks is available in different forms — WML, HTML, XHTML, XML/XSL, Java programs, and so on. Making content available to different mobile devices based on the characteristics of the device is a great challenge. At present, Internet content access through mobile devices has not been a big success, mainly because the content is not presented in a very user-friendly manner due to varying device characteristics. Ideally, the server at the content provider should obtain the capabilities of the mobile device. Based on these capabilities (display size, monochrome or color display, graphics capability in terms of pixels, whether the device is Java-enabled, the browser running on the device, the protocols supported by the device, and so forth), the content has to be presented to the user in an appealing way. This calls for a database at the server that stores the mobile subscribers’ device capabilities. When the user tries to access the data, the server will consult the database, obtain the capabilities, and format content in a suitable format and send it to the device. Many people still dislike accessing Internet content and seeing text messages on the mobile device display. For such people, presenting information through voice is a good option. With the use of text-tospeech conversion and speech recognition; such systems are already in use. To provide such services, content creation requires a new markup language, which is VoiceXML. VoiceXML The VoiceXML forum (www.voicexmlforum.org) was founded by AT&T, IBM, Lucent Technologies, and Motorola to promote Voice Extensible Markup Language (VoiceXML). VoiceXML has been designed to make Internet content available through voice from telephones (both mobile and fixed telephones). VoiceXML, in short, makes it possible to achieve a “voice-enabled Web.” VoiceXML version 1.0 was released in March 2000. Access to the Web is normally achieved through a desktop PC. The information obtained is rich in content and graphics. But the PC penetration is very low in many areas of the world, particularly in developing countries; computer literacy is also a must in order to access Web services. Accessing the Web through the mobile phone using WAP protocols is another alternative, but WAP-enabled mobile phones are costly. Because of the limited display on the mobile phones, WAP services are not userfriendly. If Web services were accessible through normal telephones or mobile phones, with the output in voice form, Web reach could be much more extensive, and the services would still be user-friendly because speech is a very natural way of communication among humans. VoiceXML provides this possibility. Consider a simple example of obtaining weather information form an Internet Web server. The dialogue between the computer (C) and the human (H) can take one of the two forms: directed dialogue and mixed initiative dialogue. ♦ Directed dialogue: In this approach, the interaction between C and H can be as follows: • C: Please tell the state for which you want the weather information. • H: Illinois. • C: Please tell the city. • H: Chicago. • C: The maximum temperature in Chicago is 40 degrees. ♦ Mixed initiative dialogue: In this approach, the interaction between C and H can be as follows: Chapter 14: The Future of Wireless Networks 469 • C: Please tell the city and state for which you want the weather information. • H: Chicago, Illinois. • C: The maximum temperature in Chicago is forty degrees. This kind of interaction is possible (completely through speech) for obtaining information available on the Web. This calls for interfacing a text-to-speech conversion system, speech recognition system, and also, if required, an IVR system to the Web servers. It is possible to provide voice-enabled Web service without VoiceXML as well, but because all these components are built around proprietary hardware and software, it is difficult to port the application for different platforms. VoiceXML has been designed with the following goals: ♦ To integrates voice services and data services. ♦ To separates the service logic (CGI scripts) to access the databases, interfaces with legacy databases, and so on, from the user interaction code (VoiceXML). ♦ To promotes service portability across implementation platforms because VoiceXML is a common language for content providers, tool providers, and platform providers. ♦ To shield the application developers from low-level platform-dependent details, such as hardware and software for text-to-speech conversion, IVR digit recognition, and speech recognition. The operation of voice-enabled Web is shown in Figure 14-4. The VoiceXML server contains the necessary hardware and software for telephone interface, speech recognition, text-to-speech conversion, and audio play/record. The Web server contains the information required for the specific application in the form of VoiceXML documents along with the service logic in the form of CGI scripts and necessary database interfaces. When a user calls an assigned telephone number to access, say, the weather information through PSTN or PLMN, the call reaches the VoiceXML server and this server converts the telephone number to a Uniform Resource Locator (URL). This server obtains the information corresponding to the URL from the Web server, which is in the format of VoiceXML. VoiceXML server converts the content into speech format and plays it to the user. When the user utters some words (for example, the city and the state for obtaining the weather information), the VoiceXML server recognizes these words and, based on the information available in the database, plays the information to the user. Figure 14-4: Architecture of voice-enabled Web The VoiceXML server is capable of doing the following functions to provide information in speech form: ♦ Recognition of the digits dialed by the user from the fixed or mobile phone 470 Chapter 14: The Future of Wireless Networks ♦ Recognition of the words spoken by the user ♦ Conversion of the text obtained from the Web server into speech form using text-to-speech conversion software and playing the speech to the user ♦ Recording of the speech input by the user (if the user wants to leave a message) VoiceXML has been developed so that content can be written by a content developer and can be interfaced to any hardware/software used for text-to-speech conversion and speech recognition. VoiceXML provides the means of interaction with the user through forms and menus. Forms collect values for a set of variables (for instance, city and state for weather information) and menus provide the users with a set of choices (for instance, selection of cosmetics, fashion-wear, or jewelry in an mcommerce application). VoiceXML provides a simple yet efficient method of providing content for developing voice-enabled Web applications. In the next decade, these services will catch up, allowing for very user-friendly Web browsing through telephones. SyncML A person using multiple devices (desktop, laptop, mobile phone, and so forth) encounters a very serious problem: The information in the various devices may not be the same. For instance, the appointments stored in the mobile handset and laptop may be different, but they need to be synchronized with each other. Similarly, the contact information (addresses) stored in the desktop and laptop need to be synchronized periodically so that both the devices contain the same data. The same goes for “to do” lists that are stored on different devices. Similarly, the files on different devices need to be in synchronization (contain the same data). Synchronizing information and updating applications between the information on the network and the devices themselves is generally done manually, or in some cases through proprietary solutions developed by different vendors. Synchronization Markup Language (SyncML) is an industry initiative to develop a data synchronization protocol. SyncML standardization activity has been initiated by IBM, Lotus, Motorola, Nokia, Palm Inc, Psion, and Starfish Software. SyncML defines the protocols to locate and update information on the fly. Exchanging information about the updates and resolving the conflicts between the data on the network and the device is known as data synchronization. SyncML defines the data formats and the protocols to synchronize the data. The data can be personal data, such as contact information (called vCard) or calendar information (called vCalendar), or e-mails, network news, XML, HTML documents, and so forth. The protocol stack for SyncML is shown in Figure 14-5. SyncML is designed to run on different protocol stacks, such as TCP/IP and HTTP, WAP (WSP), and Bluetooth on the client (the mobile device). When a mobile device has to synchronize the data with a server (say, a desktop), the user invokes the Sync client application, and the Sync client agent software communicates with the Sync server software through SyncML protocols to carry out the synchronization and, if necessary, update the information. Go to www.SyncML.org for the latest information on SyncML. Protocols The present protocol stack that is running on the mobile devices for wireless Internet access is not very efficient and is designed for only low-speed networks. In the future, mobile devices, because of their higher processing capability, can run protocols with better functionality and also can be more heavy weight. The WAP protocol stack has been developed mainly because the TCP/IP protocol stack requires lot of processing to be done on the mobile devices. However, because mobile devices are now capable of higher processing power with more memory, running the TCP/IP stack on a mobile device will not be difficult. Embedding networking protocols in mobile devices is now a distinct possibility. With this, IP Chapter 14: The Future of Wireless Networks 471 can run on mobile devices to provide IP-based services, such as Voice over IP, fax over IP, and video over IP, which allow low-cost voice, fax, and video communication over the Internet through mobile devices. However, with the unprecedented growth of the Internet and mobile devices capable of accessing the Internet, two important changes are required in the IP: the new version of IP (which has been introduced) and mobile IP. Figure 14-5: SyncML Protocol stack IP version 6 The IP that is currently running on the Internet is IP version 4 (abbreviated IPv4). IPv4 supports 32-bit address, meaning, each device connected to the Internet is assigned a 32-bit unique address. With this addressing capability, at most 4 billion addresses can be given. Now we want every mobile device, every TV, every laptop, and so on to be connected to the Internet, and this addressing capability is not sufficient any more. IP version 4 has the following limitations: ♦ Limited addressing capability. Thus, if we want every mobile device to also have an IP address, the 32-bit address format is not sufficient, and we need to enhance the address length. ♦ The IP in its present form has a header field which is fixed, and the routers need to do lot of processing to route the packets to the correct destination. So, fast packet transmission is not guaranteed, and there will also be a delay. Hence, in the present form, IP is not well suited for real time audio and video transmission. ♦ Applications (such as e-commerce and mobile commerce) require high security, which is not provided in the present version. To overcome these problems, IP version 6 has been released (IP version 5 is used only at a few Internet sites). In IPv6, each device is given a 128-bit address. In addition, the IPv6 provides a number of additional advantages: ♦ Increased security features through authentication and encryption ♦ Modified header format to reduce the processing at the routers so that delay can be minimized ♦ Support for resource allocation to facilitate real-time audio and video transmission ♦ Support of unicast, multicast, and anycast addressing formats. Unicast implies sending a packet to a specific address, muticast implies sending a packet to multiple addresses (which is required in 472 Chapter 14: The Future of Wireless Networks applications, such as audio/video conferencing) and anycast implies sending a packet to any address. Presently, software on hosts and routers is being upgraded for supporting IPv6. However, this is a big job because millions of hosts and routers are to be upgraded. Compatibility with IPv4 is provided — an address with 96 zero bits followed by 32-bits of IPv4 address. However, a translator software is required for conversion of IPv4 packets (called datagrams in IP documents) into IP6 packets. Mobile IP In the wired Internet, when two systems have to exchange data, first a TCP connection is established between the two systems and packets are exchanged. The IP addresses of the source and destination, together with the TCP port numbers on the two systems, help in the routing of the packets from the source to the destination. The IP address contains the network address as a part of it. A router analyzes the incoming packet for the destination address, takes out the network address, and routes the packet to that network. The network to which the system is attached is called the home network. In the wireless Internet, this scheme does not work because the mobile device keeps changing the location, and, hence, the point of attachment changes. Thus, the packets cannot be routed properly to the mobile device. Hence the need for a new protocol at IP level arises, which is called the Mobile IP. The Mobile IP is defined in the RFC 2002 of Internet Engineering Task Force (IETF). A mobile node is given two addresses: a fixed (or static) IP address called the home address and a care of address that changes at each point of attachment. The static address is to identify the TCP connection and the care of address is to identify the point of attachment (the present network to which it is connected). So, mobile IP requires the existence of a network node called Home Agent (HA), which is the permanent address. When the mobile device is not attached to its Home Network, Home Agent gets all the packets addressed to the mobile node and then forwards them to the present point of attachment, which is known as the Foreign Agent (FA). Whenever the mobile device changes its point of attachment, it registers its care of address with the home agent. The packets are then forwarded to the care of address by the Home Agent. The Mobile IP mechanism is depicted in Figure 14-6. Initially, the Mobile Device (MD) is attached to the HA. When it is on the move, it reaches an FA locality. The FA keeps advertising its service. The MD requests the service to the FA. FA relays the request to the HA, and the HA can either reject or accept the request. If the HA accepts the request, the care of address is used to redirect all the packets received to the MD through the FA to the MD. The functions of the Mobile IP functions are ♦ Discovering the care of address ♦ Registering the care of address ♦ Redirection to the care of address Mobile IP has been implemented by a number of vendors, but presently security is a concern. IPv6 and Mobile IP together will provide the required features to carry out secure transactions over mobile devices. Because of IP, the Internet is a very powerful tool; the same power will now be available on mobile devices through Mobile IP. 4G Systems Now that the 3G technologies are standardized and the data rates are fixed, we will have access to multimedia services over mobile devices. Now, the equipment manufacturers and the operators are focusing on the fourth-generation (4G) wireless networks. 4G is still at a conceptual stage as far as network architecture and protocols definitions are concerned, but the present focus is on the kind of services that can be provided to the users. Certainly the data rates will be in the range of 2 Mbps to 8 Mbps. This allows very high-resolution graphics, high-fidelity audio, and broadcast quality video services to be provided to mobile users. Chapter 14: The Future of Wireless Networks 473 Figure 14-6: Mobile IP Summary In this chapter, we discussed the technology trends to provide value-added services for the end users through the mobile networks. The convergence of telecommunication networks and services is paving the way for many value-added services to be available to the users, such as instant messaging, unified messaging, precise location-based services, and accessing the Web through telephones in voice format. The IP version 6 and Mobile IP will provide the protocol infrastructure for IP services to be made available on mobile devices with the necessary security. Applications of the high bandwidth services will be in many areas, such as collaborative working, multi-party audio and video conferencing, virtual classrooms, telemedicine, and much more. Appendix A What’s on the CD-ROM This appendix provides information about this book’s companion CD-ROM, found on the inside back cover of the book. For the latest information, please refer to the ReadMe file located at the root of the CD. System Requirements This book’s CD-ROM runs on Microsoft Windows 95, 98, 2000. Your computer must be equipped with a CD-ROM drive that is double-speed (2x) or faster. If your computer doesn’t match up to these requirements, you may have a problem using the contents of the CD. CD Contents The CD-ROM contains source code examples, applications, and an electronic version of the book. The following is the summary of the contents of the CD-ROM: Source Code The folder named “Source Code” is categorized into different folders named according to the chapter numbers. The source code of the case studies and the programs are contained in their respective folders. Following is the list of the folders in the source code folder: ♦ Chapter 2: This folder contains the two folders: “Information Master Application” and “Restaurant Application.” These folders contain the source code of the application. These case studies are built using WML and WMLScript. ♦ Chapter 3: This folder contains the source code for Question Quiz Application. This project is built using Cold Fusion with WAP. ♦ Chapter 4: This folder contains the source code for the WTA program, which illustrates WTAI function call. This example is built using WML. ♦ Chapter 5: This folder contains the source code of the Weather Application. This application is built using the Servlet, JDBC and WML. ♦ Chapter 6: This folder contains the two folders: “Pushing the stock quotes” and “Shopping cart with advertisement push.” These folders contain the source code of the application. These case studies are built using WML, HTML and Java. ♦ Chapter 8: This folder contains the two folders: “Airport Kiosk” and “Shopping Mall Kiosk.” These folders contain the source code of the applications. These case studies are built using ASP, WML, and WML Script. ♦ Chapter 9: This folder contains the following folders, which contain the source code of their respective projects. All these projects are built using the Bluetooth Development Kit. This is using VC++ programming style. 475 Appendix A: What's on the CD-ROM • HCI Programming. • SDP Programming • File Transfer Application • Chat Application ♦ Chapter 11: This folder contains the source code of all the programs explained in this chapter. All these programs are developed by using XML, XHTML, WML, ASP, XSL, and Java. ♦ Chapter 12: This folder contains the following folders, which contain the source code of their respective Projects. All these projects are built using the Brew toolkit provided by Qualcomm. • A New Application using Brew • Developing Animation Application • Application for music Downloading onto a Mobile • Mobile Advertisement Application • Database Application ♦ Chapter 13: This folder contains the following folders, which contain the source code of their respective projects. All these projects are built using JMF (Java Media Framework) • Voice Messaging Application • Audio Broadcasting Application • Audio-Video Broadcasting Application Applications The following applications are on the CD-ROM: ♦ Nokia WAP Software folder contains the following: • Nokia WAP Toolkit 2.1: This toolkit Provides developers, the PC environment required for developing and testing WAP applications. It offers the tools needed for developing WML and WMLScript content, adding graphics etc. there by equipping them fully to avail the push functionality. • Nokia Activ Server 2.0 Professional Edition: This is an open software platform that offers secure mobile connectivity to a company’s current information systems, both intranet and internet. WAP-Enabled services may be connected to the Nokia Activ Server using Circuit Switched Data (CSD) and also Short Message Services (SMS). ♦ Tomcat Server folder contains the Tomcat Server: • Tomcat Server 3.0: With the tomcat environment, development of Javaservlets and JSP are possible without having to install a full-fledged web server as entailed by ASP, CGI, Perl etc. In the tomcat environment all classes are available, as suited to the server side Java programming environment. ♦ Macromedia folder contains the following: • Macromedia Cold Fusion Studio 4.5 Enterprise Edition: Cold Fusion Studio provides an integrated development environment for Cold Fusion applications. The studio is optimized to suit development of Cold Fusion- based web sites and applications. Some of the prominent features of this studio are: Project management, Code Snippets, Expression Builder, Visual database tools, Validation tools, Code debugging, Design layout and page preview. • Macromedia Homesite 4.5: Homesite is an HTML editor with an award to its credit. It makes for creating websites better and at the expense of lesser time. By Virtue of this HTML editor you can integrate money lending web technologies such as JSP,CFML and WML. Appendix A: What’s on the CD-ROM 476 ♦ Java Developers Kit folder contains the following: • Forte for Java release 2.0- The Forte for Java release 2.0 software is an integrated development environment used for devloping Java application. It is an IDE provided by Sun microsystem. • Java 2 SDK- This is a software development kit for Java standard edition required for developing Java applications. ♦ Acrobat Reader folder contains the Acrobat Reader 5.0 • Acrobat Reader 5.0- This software enables you to view the Adobe PDF files over a liberal range of hardware and operating systems. You can avail the Acrobat reader 5.0 for adding digital signature to files even while remaining connected to your web browser or for converting your office documents to Adobe PDF file for the Acrobat Reader for Palm OS. E-Book Those readers, who desire an electronic copy of the contents in the book, can avail the CD-ROM, which accompanies this book. This CD-ROM contains the PDF files of all the chapters as well as the appendices in the book. These files can be viewed through the Acrobat Reader 5.0 software, which has been incorporated in the CD-ROM. Troubleshooting If you have trouble installing or using the CD-ROM programs, then try the following solutions: ♦ Turn off any anti-virus software that you may have running. Installers sometimes mimic virus activity and can make your computer incorrectly believe that it is attacked by a virus. (Be sure to turn the anti-virus software back on later.) ♦ Close all running programs. The more programs you’re running, the less memory is available to the other programs. Installers also typically update files and programs; if you keep other programs running, installation may not work properly. If you are still having trouble with the CD, please call Hungry Minds Customer Service at (800) 7622974. If you are not in the United States, call (317) 572-3994. You can also contact Hungry Minds Customer Service by e-mail at [email protected]. Please note that Hungry Minds will provide only technical support for installation and other general quality control items. For technical support on the applications themselves, please consult the program’s vendor or author. Appendix B Tomcat Installation and Configuration Introduction to a Web Server Web servers allow you to serve content over the Internet using the HyperText Markup Language (HTML). In this process, the Web server responds to a request made by the browser in the appropriate HTML document. The Web server can accept requests from various browsers, such as Netscape and Internet Explorer and then respond to the appropriate HTML documents. A number of server-side technologies can be used to increase the power of the server to deliver standard HTML pages; these include CGI Scripts, Server-Side Includes, Java Server Pages (JSP), Servlets, SSL, and Active Server Pages (ASP). How a Web Server Works: An Overview When a browser sends a request for a Web page, such as http://www.yahoo.com/index.html, to the Web server, it maps the index.html from the computer. After mapping it, the server sends the response to the user. The communication done between the user and the server, that is, the request and the response are handled by the HTTP (HyperText Transfer Protocol), which isalso known as the request response protocol. This workflow is shown in the Figure B-1. Figure B-1: Web server handling HTML request This process in Figure B-1 works as follows: 1. User requests the document (index.html). 2. Web server looks for the document on the file system. 3. Web server maps the file from the file system. 4. Web server returns the data document to the Web browser. This simple arrangement was the initial concept behind the World Wide Web, which allows the handling of static content such as HTML. The exchange of complex and vital information between browsers and Web servers at the global level became possible by virtue of the WWW. But the most important part of the Web is dynamic content. The Common Gateway Interface (CGI) is the oldest and the most popular standard for dynamic content. It basically works as an interface for the user’s request for dynamic pages. The request is converted into an HTML response by the Web server, which sends it back to the user browser. Nowadays, various technologies are emerging that handle the user requests, which are to be processed by the Web server and sent back to the browser in the minimum possible time. We can the interface between the HTTP server and Tomcat is a published standard that can be implemented by components outside the Tomcat project. 2. You can download the different versions of Tomcat server from this site You can also check for the latest version of Tomcat server on http://jakarta. 3. while TOMCAT actually serves the JSP pages and runs the servlets that your site contains.apache. To install Tomcat on Windows.1 technologies. TOMCAT is an extension of the Apache-server.1.478 Appendix B: Tomcat Installation and Configuration implement ASP. You can also use the Tomcat server as an extension of the IIS Server. User requests a servlet or JSP Program (hello. Web server passes the output from hello.jsp).3 Standard Edition. 5. It is a servlet container.org/builds/jakarta-tomcat/release/. Web server sends its parameters to the browser requested. you must download the zip file. Web server launches and processes hello. and so on. Tomcat server can be downloaded from: http://jakarta. This means it is possible to make Tomcat work with any HTTP Web server. Introduction to the Tomcat Web Server Tomcat is used as the Web server for implementing Java Servlet 2. You can download JDK 1.1 and the JDK 1. 4.3 Standard Edition from: http://java.com/products. it actually runs on your machine as a process separate from the APACHE.html.jsp program.jsp. servlets. 6. which is a runtime shell that manages and invokes servlets on behalf of users. instead of CGI.apache.org/site/binindex. such as TAR. Figure B-2: Web server handling JSP or servlet request The process in Figure B-2 works as follows: 1. HQX. when you use TOMCAT 3. Step 1: Download To configure Tomcat as a stand-alone server you need to download the Tomcat 3.2 and Java Server Pages 1. but it runs independently of it. Install the Tomcat Web Server The Tomcat Web server installation is explained as follows.2. and so forth. Web server retrieves the output from the hello.jsp program to the browser. Tomcat includes a small HTTP server front end that can be used instead of APACHE. When configured correctly APACHE will continue serving HTML pages.sun. . Thus.When you visit the Tomcat site you will find the files in different formats. JSP. Web server receives the request. Figure B-2 shows how the Web server works with these technologies. Additionally. To do this under NT/2000.Appendix B: Tomcat Installation and Configuration 479 Step 2: Installing on Windows NT/2000 Unzip the file onto the hard disk (say D:). Figure B-4: Windows 2000 System Properties . you have to put your JDK into Tomcat's CLASSPATH and set the TOMCAT HOME environment variable. After you have extracted Tomcat. Figure B-3: NT/2000 Control Panel Using Windows 2000 Go to StartSystem Properties and select the Advanced tab (see Figure B-4). This should create a new subdirectory named “"tomcat”. (See Figure B-3). you must open the Control Panel. as shown in Figure B-7. You will then see the screen in Figure B-5. but this time add TOMCAT_HOME as the Variable Name and set the Variable Value as D:\jakarta-tomcat-3. Using Windows NT Go to StartSystem Properties and select the Environment tab.2.480 Appendix B: Tomcat Installation and Configuration Click the Environment Variables button on the System Properties dialog box. Type JAVA_HOME as the Variable Name and set the path of the JDK in the Variable Value field (see Figure B-6). Figure B-5: The Environment Variables dialog box of Windows 2000 Now click the New button under System variables. Figure B-6: JAVA HOME Environment Settings for Windows 2000 Repeat the previous step.1. . Appendix B: Tomcat Installation and Configuration 481 Figure B-7: Windows NT System Properties Type JAVA_HOME in the Variable field and set the location of your JDK in the Value field (see Figure B-8). Figure B-8: JAVA HOME Environment Settings for Windows NT . bat TOMCAT_HOME\bin\shutdown.”at the end of TOMCAT HOME and JAVA HOME ♦ Also include the classpath of the tools. Note: Do not use “.com /p /e:4096 This command changes the size of environment space from 1024 bytes to 4096 bytes.3 Set TOMCAT_HOME=d:\ jakarta-tomcat-3. open the file in Notepad and write the following below the line rem ---. You can also set these environment variables in the file tomcat. you will see the screen in Figure B-9. To do this. .c:\jdk122\bin.sys) and make the following changes: shell=c:\command.sys file (c:/>edit config.sys file. After a few seconds. Go to your command prompt and open the config.2.1 folder.1 in the Value field.bat You can start the Tomcat server by clicking the startup.2. Additional environment variables Some changes need to be made to the autoexec.2.482 Appendix B: Tomcat Installation and Configuration Repeat the previous step by typing TOMCAT_HOME in the variable field and D:\jakarta-tomcat-3. TOMCAT_HOME=c:\TOMCAT JAVA_HOME=c:\jdk122 CLASSPATH=c:\jdk122\lib\tools.bat file.Save Environment Variables That May Change ------------------------: Set JAVA_HOME=c:\jdk1. as shown here: SET SET SET SET PATH=C:\PERL\BIN.1 Using Windows 98 The value for the DOS environment space is 1024 bytes.jar file. Table B-1: Tomcat Startup/Shutdown Commands Startup Shutdown TOMCAT_HOME\bin\startup. you have to make changes in the config. If you receive a message.bat file.jar ♦ Include the path of JDK ♦ Set the path TOMCAT HOME and JAVA HOME environment variables to the directories where Tomcat and the JDK are installed.bat. You will get this file in the link folder of the JDK Table B-1 shows the Tomcat startup and shutdown commands. Restart your computer after making this change. such as “out of environment space” on your command prompt when you are running the tomcat.bat located in the Jakarta-tomcattomcat-3. http://localhost: 8080/ You then see the screen in Figure B-10. Figure B-10: Home page for Tomcat Web server .Appendix B: Tomcat Installation and Configuration 483 Figure B-9: The starting window for Tomcat Web server After starting Tomcat. enter the following in the URL of your browser. 484 Appendix B: Tomcat Installation and Configuration To verify the installation of JDK. for example. As shown in Figure B-10. You get the results shown in Figure B-12. Figure B-12: The JSP Date page . choose JSP Examples. Figure B-11: The JSP Samples page Now click any of the execute links. you may execute any of the examples given in the home page of the Tomcat server. You get a page similar to that shown in Figure B-11. Date. You can stop the Tomcat server by clicking on the shutdown.HttpConnectionHandler"/> <Parameter name="port" value="80"/> </Connector> To use the new setting of Tomcat.tomcat.PoolTcpConnector"> <Parameter name="handler" value="org.http.tomcat. Change <Connector className="org. Check the value of JAVA HOME and the location of the JDK. You then see the screen in Figure B-13 within a few seconds.tomcat. For example.HttpConnectionHandler"/> <Parameter name="port" value="8080"/> </Connector> to <Connector className="org.xml file and then restarting the Tomcat server. it means that the path of JAVA HOME has not been set properly.service.apache.apache.bat file and restart by clicking startup. Figure B-13: Stopping window for Tomcat Web server The default port to run the Tomcat server is 8080 and can be changed.service.service.Appendix B: Tomcat Installation and Configuration 485 If you get an error message instead of Figure B-12.bat file.service. you can change the HTTP port to 80.bat.tomcat.apache.apache.http. shut down the server first by clicking shutdown. .PoolTcpConnector"> <Parameter name="handler" value="org. Now type the following in the URL: http://localhost/ You will see results similar to those in Figure B-7. from port 8080 by making the following changes in TOMCAT_HOME/conf/server. To avoid clashing between two Web applications. a Web application can have JSP pages. such as server. html pages. It is not part of the public document. these directories can change without notice. we can deploy a Web application to it. Tomcat is dependent upon these Java Archive files. which will probably contain only interfaces and abstract classes at the time of Tomcat’s release /webapps Contains all Web applications and the WAR file /work After you execute the JSP file the first time. Table B-3: The Web Application Directory Structure Directory Explanation /web The root directory of the Web application and contains all JSP and XHTML files /web/WEB-INF Contains all resources related to the application that are not in the document root of the application. Besides servlets. first understand the directory structure of Tomcat. Directory structure To create a Web application.486 Appendix B: Tomcat Installation and Configuration Deploy Web Applications to Tomcat After Tomcat is installed and is running. a Web application is anything that resides in the Web layer of an application. Table B-2 describes the directories that make up a Tomcat installation. The Web contains each and every component as discussed in Table B-3.xml /server Contains the Tomcat Java Archive files /lib Contains Java Archive files. The main feature of a Web application is the relationship with ServletContext. and so forth). you have to first create the directory structure in which it exists. /logs Contains log files of Tomcat /src Contains the source code used by the Tomcat server. and other resources that can be bundled and run on multiple containers from multiple vendors. Table B-2: The Tomcat Directory Structure Directory Explanation /bin Contains the startup and shutdown files for Windows as well as Linux OS /conf Contains the main configuration files for Tomcat. It contains your Web application deployment descriptor. In other words. and other meta information describing the Web application. For example. the servlet generated by the JSP is placed in this directory Web Application A Web application is defined as a collection of servlets. images. different ServletContext are used for different Web applications. static documents (such as HTML. classes. Because we are using a beta release of Tomcat.xml and web. so the files of this directory can be served directly to a client. It is assumed that the value of TOMCAT HOME precedes each of these directories. The servlet container controls this relationship. we are creating the Web application by the name of the Web. utility classes. . To deploy a Web application. client-side classes. It is an XML file by the name web. If both the folders have the class file with the same name. <web-app> <display-name>The web App</display-name> <session-timeout>45</session-timeout> <servlet> <servlet-name>TryServlet</servlet-name> <servlet-class>com. For example.xml file. Deployment descriptor of Web application Deployment descriptor is the heart of all Web applications. You can store the classes either in /WEB-INF/classes or in /WEB-INF/lib directories. web. ♦ <session-timeout>: The second Web application level element. then classes of the \classes will be used.xml stored in the /<SERVER_ROOT>/applicationname/WEB-INF/ directory. it describes the name of the Web application and is functionally inoperative.web. The class loader loads the classes of /classes directory first followed by the JARs in the /lib directory. ♦ <servlet>: The last application level element that we have defined and this element defines a servlet and its properties. For our application the location of the web. it controls the lifetime of the application’s HttpSession object. The <session-timeout> value that we have used in the previous code tells the JSP/Servlet container that the HttpSession object will become invalid after 30 minutes of inactivity. .TryServlet</servlet-class> <load-on-startup>1</load-on-startup> <init-param> <param-name>name</param-name> <param-value>value</param-value> </init-param> </servlet> </web-app> where ♦ <display-name>: The first of the application level elements.xml file is in the /<SERVER_ROOT>/web /WEB-INF/ directory. You can edit or modify the configuration of a web.Appendix B: Tomcat Installation and Configuration 487 /web/WEBINF/classes Contains servlet and utility classes /web/WEB-INF/lib Contains Java Archive files. The deployment descriptor contains information about the following elements: ♦ ServletContext Init Parameters ♦ Session Configuration ♦ Localized Content ♦ Servlet / JSP Definitions and Mapping ♦ Mime Type Mappings ♦ Welcome File list ♦ Security ♦ Error Pages The following code has some of the elements of a Web application deployment descriptor. Tomcat is dependent upon these Java Archive files.xml carries information for the entire Web application. you can place a JAR file that contains a JDBC driver. Inc. is the root of our directory structure. and so on).3//EN" "http://java. Your application should now be running. At this point you will be creating a default web. JSP. as discussed in Table B-3.dtd"> <web-app> </web-app> Now copy this file to the TOMCAT HOME/web/WEB-INF/ directory. describing the web. setting the values for the path and docBase to the name of your Web application.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems. Listing B-1: web. The previously described application can be accessed by pointing your browser at: http://localhost/web Figure B-14 does not show any contents. you can package your Web application into a WAR file and go though the production deployment process. .xml file.xml file that contains only the DTD. <Context path="/web" docBase="webapps/web" debug="0" reloadable="true" /> Restart Tomcat after completing these steps. We will begin adding web application components to it in the following sections.com/j2ee/dtds/web-app_2_3. web. When it comes for deployment.488 Appendix B: Tomcat Installation and Configuration Create the Web application directory structure The name of our Web application. as the web folder does not carry any file (such as HTML.xml file. Create the directory directly in the Tomcat /webapps directory while in development.xml file.sun. The last step in creating the Web application directory structure is adding a deployment descriptor. and an empty element.//DTD Web Application 2. Listing B-1 contains the source for a default web. It contains all the files and subdirectories.xml <?xml version="1. Deploy a Web Application to Tomcat First create the web folder in the TOMCAT HOME/webapps folder and then add a new context entry to the TOMCAT_HOME/conf/server. Appendix B: Tomcat Installation and Configuration 489 Figure B-14: Tomcat Web server on default port 80 . Developer Edition Programmers use the Developer Edition to develop applications that use SQL Server 2000 as a database. Standard Edition This edition is used as a database server for smaller businesses with smaller databases (as compared to large corporations). SQL Server 2000 runs on Windows NT (with Service Pack 5 or above). It is not used as a production server. About MS SQL Server 2000 SQL Server 2000 is the database engine product by Microsoft. and so forth. . and Windows 2000. It can replicate data pertaining to any edition of SQL Server 2000 to synchronize Windows CE data with the primary database. factories. It is called SQL 2000 CE. we will explain how to install SQL Server 2000 and XML support configuration. It is capable of running a stand-alone application that requires a local database at a client computer.Appendix C SQL Server 2000 Installation and XML Support Configuration In this appendix. This edition is also good for small work groups and individual departments of larger businesses. Microsoft has also launched SQL 2000 on Windows CE. we give a brief introduction of SQL Server 2000. Before this. Windows CE Edition This edition is used to store data on Windows CE devices. and it is only licensed for testing and development purposes for the programmers. Window 98. Different editions of SQL Server 2000 SQL Server is available in the following editions: Enterprise Edition SQL Server 2000 Enterprise Edition can be used as a production database server for big plants. corporations. It is equipped with the power of Relational Database Management System (RDBMS). as well as the very good performance required in large Web sites. It supports all features that are available in SQL Server 2000. It also supports the OLTP (Online transaction processing) feature and data warehousing systems. Personal Edition This edition is meant for users who spend more time disconnected from their network of computers. It contains all the features of the Enterprise Edition. Now large queries can be divided into different processes that make the server performance faster.Appendix C: SQL Server 2000 Installation 491 SQL Server 2000 Enterprise Evaluation Edition You can download the full-featured version of SQL 2000 from the Microsoft site for the evaluation purpose. Platform Choice SQL Server 2000 runs on Microsoft Windows NT because Microsoft Windows NT (the operating system required for SQL Server) is capable of running on different platforms.0 platform independent so that it can run on an Intel x86 based processor as well as a Digital Alpha Server. Minimum Installation Requirements The minimum requirements for installing Microsoft SQL Server 2000 are as follows: Hardware requirements Following are the minimum hardware requirements for installing Microsoft SQL Server 2000 or SQL Server client management tools and libraries: ♦ Computer: Intel Pentium 166 or higher. The evaluation period for this edition is 120 days. DEC Alpha and compatible systems ♦ Memory (RAM) • Enterprise Edition: 64MB minimum but 128MB is highly recommended • Standard Edition: 64MB minimum • Personal Edition: 64MB minimum on Windows 2000 and a minimum of 32MB on all other operating systems • Developer Edition: 64MB minimum • Desktop Engine: 64MB minimum on Windows 2000 and a minimum of 32MB minimum on all other operating systems ♦ Hard disk space • SQL Server database components: 95 to 270MB although 250MB is generally used • Analysis Services: 50MB minimum although 130MB is generally used • English Query: 80MB • Desktop Engine only: 44MB ♦ Monitor: VGA or higher resolution of 800 x 600 because a higher resolution is required for the SQL Server graphical tools ♦ Pointing device: Microsoft mouse or compatible ♦ CD-ROM drive: Required . Windows NT can support 32 processors in a single server. SQL server 2000 can run on the following platforms: ♦ Intel x86 based processor ♦ Digital Alpha processor HAL (Hardware Abstraction Layer) makes Window NT 4. 0 • Windows 2000 Professional • All other Windows NT and Windows 2000 operating systems ♦ Client Tools Only • Microsoft Windows NT 4.492 Appendix C: SQL Server 2000 Installation Operating system requirements The various editions or components of Microsoft SQL Server 2000 runs on the computer installed with following operating systems: ♦ Enterprise Edition • Microsoft Windows NT Server 4.0 • Windows 2000 Server • Windows 2000 Advanced Server • Windows 2000 Data Center Server ♦ Standard Edition • Microsoft Windows NT Server 4.0 • Windows 2000 Professional • Microsoft Windows NT Server 4.0 • Windows 2000 (all versions) • Windows Me and Windows 98 ♦ Connectivity Only • Microsoft Windows NT 4.0 • Windows 2000 (all versions) • Windows Me • Windows 98 .0 • Windows 2000 Server • All the more advanced Windows operating systems • Developer Edition • Microsoft Windows NT Workstation 4.0 • Windows 2000 Server • Microsoft Windows NT Server Enterprise Edition • Windows 2000 Advanced Server • Windows 2000 Data Center Server ♦ Personal Edition • Microsoft Windows Me • Windows 98 • Windows NT Workstation 4.0 • Microsoft Windows NT Server Enterprise Edition 4. 2. which starts the installation wizard for the installation of SQL Server 2000. you can file the AUTORUN.Appendix C: SQL Server 2000 Installation 493 • Windows 95 Complete Installation of SQL Server 2000 (Setup) 1. (See Figure C-1). which helps in Online Analytical Processing (OLAP) and data mining applications. The CD that contains SQL Server 2000automatically starts up after you put it in. You may also execute this file by doubleclicking on it. provided you are connected to the Internet. ♦ Visit Our Web Site takes you to the Microsoft site. Thus. SQL Server 2000 Components installs the SQL 2000 on your server. ♦ Read the Release Notes opens the release notes. Figure C-1: Auto run menu for SQL 2000 The elements in Figure C-1 are explained as follows: ♦ SQL Server 2000 Components installs the SQL 2000 on your server. Install components. ♦ If you are running Microsoft Windows 95. Insert the SQL Server 2000 CD in CD-ROM. . Consequently. click SQL Server 2000 Prerequisites and then click Install Common Controls Library Update. ♦ The Browse Setup/Upgrade Help opens the books available online with SQL 2000. Insert the SQL Server 2000 compact disc into your CD-ROM drive. After you’re there. you can choose SQL Server 2000 Components. They are explained as follows: ♦ Install Database Server installs the SQL 2000 database. ♦ Install Analysis Services installs the analysis server. The Install Components screen is shown in Figure C-2.exe file in the root directory of SQL Server 2000. If the CD ROM doesn’t start automatically. it could mean that the auto start functionality of your CD ROM is disabled. In the Welcome screen. Select Install Database Server and setup prepares the SQL Server Installation Wizard at the Welcome screen. Then click Next. Figure C-2: Install Component for SQL 2000 3. Figure C-3 shows the Welcome dialog box. Figure C-3: Welcome screen of SQL 2000 .494 Appendix C: SQL Server 2000 Installation ♦ Install English Query allows the developer to build the application that provides the end-user with the ability to pose questions in English rather than asking questions with SQL statements. click Next. accept the default and click Next. ♦ Advanced options: This option is used for unattended setup. or install Client Tools. Installation selection. remove. After you’ve finished. or install Client Tools: This option is used to create a new installation of SQL 2000 and creates a new instance for SQL 2000 server. The options are as follows: ♦ Create a new instance of SQL Server.. The individual options are explained as follows: ♦ Local Computer: The default option is the name of the computer on which the setup is running. For a local installation. and registry rebuild.Appendix C: SQL Server 2000 Installation 495 4. Figure C-4 shows the Computer Name dialog box. or click Browse to locate the remote computer. . Choose the computer name. ♦ Remote Computer: If you are installing the SQL server 2000 in a network. enter the name of the computer for a remote installation. and then click Next. cluster maintenance. ♦ Upgrade. You can enter the name of a new Virtual SQL Server or that of the existing one. In the Installation Selection dialog box. remove.0) as well as instances of SQL Server 2000. or add components to an existing instance of SQL 2000. or add components to an existing instance of SQL Server: This option allows you to upgrade. You can upgrade. or add components in the earlier versions (SQL Server version 6. click Next. click Create a new instance of SQL Server. remove. Figure C-5 shows the Installation Selection dialog box. Figure C-4: Choosing the computer name for SQL 2000 5.5 and SQL Server version 7. ♦ Virtual Server: This option is available in case MSCS (Microsoft Cluster Service) is detected on a Windows 2000 Enterprise or the Windows NT operating system. Software license agreement for SQL Server 2000. Figure C-6 shows the User Information dialog box. . Enter your name and the name of your company. Then click Next. Here we are using the name techno campus and the company name techno campus ltd. Figure C-7 shows the Software License Agreement dialog box. Read the agreement and then click Yes.496 Appendix C: SQL Server 2000 Installation Figure C-5: Installation selection for SQL Server 2000 6. Figure C-6: User Information for SQL Server 2000 7. Gather user information. The options are as follows: ♦ Client Tools Only: This option installs the data access components. click Server and Client Tools and then click Next. you cannot use your computer as a server or for other management purposes. In the Installation Definition dialog box. If you make this selection. You may use this selection if you want the computer you are installing on to participate in SQL Server communication.Appendix C: SQL Server 2000 Installation 497 Figure C-7: Software License agreement for SQL Server 2000 8. and management tools for SQL Server. network libraries. ♦ Connectivity Only: This option installs the Microsoft data access components and network libraries but not the management tools. You should choose the option Client Tools Only if you intend to use this computer to manage an existing SQL Server remotely. Select the Installation type. Figure C-8: Installation Type for SQL 2000 . ♦ Server and Client Tools: This is the default option and performs a complete installation of SQL Server. Figure C-8 shows the Installation Definition screen. To install the default instance. . click Custom and then click Next. or other settings. The options are as follows: ♦ Typical: This is the default option for installation. service accounts. and you can install only a named instance. If you know all the components and subcomponents with their features and application. or network libraries. Figure C-9 shows the Instance Name dialog box. In the Setup Type dialog box. you can install either the default or a named instance. Select the instance name. click Typical or Minimum and then click Next. If the Default check box is not available. ♦ Minimum: This option installs the minimum components required in a computer to run SQL Server 2000. authentication. It is generally recommended for users at all levels. it means that a default instance has already been installed. clear the Default check box and type a new named instance in the Instance name edit box. then this particular option is recommended for you. ♦ Custom: This option allows you to choose components and subcomponents or to change settings for collations. If you want to select the components and subcomponents. select the Default check box and click Next. If your computer doesn’t have much space. Figure C-10 shows the Setup Type dialog box. Select setup type.498 Appendix C: SQL Server 2000 Installation 9. Click Next. you can choose this option. To install a named instance. If the Default check box is available. The default location for the installation of SQL Server 2000 is C:\Program Files\Microsoft SQL Server\. Figure C-9: The Instance Name dialog box for SQL Server 2000 10. network libraries. change character set. for both program as well as data files. You can change the destination for the program and data files by clicking the Browse button. This is the default option. ♦ Service Settings: Under this option. ♦ Customize the settings for each service: This option allows you to use different settings for the two services. The options are as follows: ♦ Use the same account for each service. . a service starts automatically when you start your computer. ♦ Username: You can either accept or change the username for the domain. and may restrict your SQL Server installation from interacting with other servers for the local system. Auto start SQL Server Service: This option uses one account for both the SQL Server and the SQL Server Agent. Microsoft SQL Server Agent. ♦ Domain: Here you can either accept or change the name of the domain. does not have network access rights in Windows NT 4. By default this option is unavailable and is only available when customizing the settings for each service. you have two sub-options: • Use the Local System account: This option does not require a password. Microsoft SQL Server. ♦ Password: Allows you to enter the password for the domain. By default. • SQL Server Agent: This option selects customize settings for the service. • SQL Server: This option allows you to select customize settings for the service. • Use a Domain User account: This option uses Windows Authentication to set up and connect to SQL Server for domain user.0. The two options available here are SQL Server and SQL Server Agent. These services start automatically when the operating system starts. Figure C-11 shows the Services Accounts dialog box. Select the services accounts. It contains the options Username. you can select a service for customize settings. ♦ Services: If you want. ♦ Auto Start Service: If you choose this option. and Domain. Password. it provides for the currently logged on user.Appendix C: SQL Server 2000 Installation 499 Figure C-10: Selecting the Setup Type dialog box 11. The options are as follows: ♦ Windows Authentication Mode: This is the default option and allows a user to connect using a Windows 2000 or Windows NT 4. 12. and then click Next.500 Appendix C: SQL Server 2000 Installation Figure C-11: The Services Accounts dialog box The SQL Server Agent Service is dependent on the SQL Server service. So you can only autostart the SQL Server Agent Service if you autostart the SQL Server service as well. SQL Server validates the account name and password by using the Windows NT 2000 or Windows 4. Figure C-12: Dialog box for selecting the Authentication Mode for connection with SQL 2000 . In the Service Accounts dialog box. Select the authentication mode.0 user account. In this option. It allows the user to connect if the information matches the previously recorded login account set information in the server.0 for the information. ♦ Mixed Mode: When a user connects with a specified login and password. it sends the error message to the user. SQL Server authenticates the login name and password. otherwise. Figure C-12 shows the Authentication Mode dialog box. In the Authentication Mode dialog box. accept the default settings. enter your domain Password. You can choose the Windows Authentication Mode or the Mixed Mode. accept the default setting and click Next. In XML. click Next in the Start Copying Files dialog box. Start copying the files for the installation of SQL Server 2000. and so on. click Yes. We can describe the data using XML and display it with the help of HTML using style sheets. Figure C-14: Setup Complete dialog box for SQL Server 2000 XML Support in SQL Server 2000 XML stands for the Extensible Markup Language that describes data. So you have no restriction in . Figure C-13 shows the Start Copying Files dialog box. After you have finished specifying the options. Figure C-13: Start copying the files for installation 14.Appendix C: SQL Server 2000 Installation 501 13. XSL. Here. we can create our own tags instead of using predefined tags. I want to restart my computer now and then click Finish. such as those used in HTML. Installation complete Figure C-14 shows the Setup Complete dialog box. <book> </book>. name. The following are a few facts regarding XML: ♦ XML was developed in 1996 by an XML Working Group (W3C) chaired by Jon Bosak of Sun Microsystems. You can locate this file in the %windir%\System32 folder of the Windows 2000 Server editions. Examples of HTML tags are <p> </p>. and so forth whereas examples of XML tags are <user> </user>.0. we may save the file as .xml (as in emp. For example. ♦ XML is used to transfer the data over the Internet and is supported by various other applications. and phone in SQL. if we create a table exm emp containing the empcode. ♦ A schema (in an XML document) is a description of the way in which a document is marked up. Steps for Creating a Virtual Directory 1.msi) is required. The description can be on its grammar.0 or Microsoft Windows 2000. DTD defines the document structure with a list of legal elements. For computers running Windows NT 4. address. Using IIS (Internet Information Server) for Accessing SQL Server 2000 The first step for accessing the SQL Server is installing the Virtual Directory for SQL Server.2 For computers running Microsoft Windows 2000 Professional. System Requirement for IIS Virtual Directory Management You can run the IIS Virtual Directory Management for SQL Server utility on any computer running Microsoft Windows NT 4. the following are the essential requirements: ♦ Microsoft Internet Information Server 4. the Administrative Tools pack (Adminpak. Figure C-15: Setting IIS Virtual Directory Management for SQL 2000 . the XML group was known as the SGML Editorial Review Board. vocabulary structure. and so on. Go to Start  Programs  Microsoft SQL Server program group and click Configure SQL XML Support in IIS (see Figure C-15).0 or higher ♦ Microsoft Management Console 1.xml) and view it in the browser. In the beginning. datatypes. ♦ The Document Type Definition (DTD) acts as a rulebook that defines the legal elements of an XML document. and so forth.502 Appendix C: SQL Server 2000 Installation creating the tags. For example. Here. You can either give the login name and a password or use the same name that you use to access the SQL Server 2000. we have entered the name pubs. For example. 5. point to New and then click Virtual Directory. Now type the local path or your physical directory or click the Browse button to locate it. such as local or the name of an instance of SQL Server 2000 if more than one instance is installed on the specified computer.Appendix C: SQL Server 2000 Installation 503 2. Click the General tab of the New Virtual Directory Properties dialog box and enter the name of the virtual directory. You get the New Virtual Directory Properties. In Figure C-17. You can either enter the name of a server. as shown in Figure C-16. On the Action button. In the Database box. Click the Data Source tab (Figure C-18). we select the Windows Integrated Authentication Option. enter pubs as the name of the default database. Click the Security tab (Figure C-17) and select the authentication method to access the data. 4. so you can enter \Inetpub\Wwwroot\pub in the Local Path. . we have created a sub-directory with the name pub in the C:\Inetpub\Wwwroot\. Click the plus (+) sign of the server (TECH SOFT) and then click the Web site that you want. here we are creating a virtual directory on the default Web site. Figure C-16: General Properties Tab IIS Virtual Directory Management 3. 504 Appendix C: SQL Server 2000 Installation Figure C-17: Security Properties Tab for IIS Virtual Directory Management Figure C-18: Data Source for IIS Virtual Directory Management . Schema mapping occurs between the XML queries and the SQL server databases. For example. Click the Settings tab (Figure C-19). you can select any or all of the following options: Allow URL queries allows the user to execute the SQL statement to run directly in the URL. It specifies the maximum size of the data passed through the post method. Figure C-19: Settings Tab IIS Virtual Directory Management 7. For example: http://tech_soft/pubs/cust/custlist Allow POST allows the user to create an HTML form and then send the data of the form to the server by the post method.Appendix C: SQL Server 2000 Installation 505 6.xml Allow XPath allows the user to use the Xpath query language to submit queries that user SQL Server views. . Click the Virtual Names tab (Figure C-20) and then click New to create the virtual name for the template type. http://tech_soft/pubs/myqery. such as http://tech_soft/pubs?SQL=select+*+from+authors+for+xml+auto Allow template queries allows the use and execution of the queries defined in the template file. You can also define any other name of the template. enter the name of the template in the Virtual name box. Click Save to save the virtual name. Enter the path (for example. the existence of the path is not checked). In the Type list. C:\Inetpub\Wwwroot\pubs\template. however.506 Appendix C: SQL Server 2000 Installation Figure C-20: Virtual Names IIS Virtual Directory Management In the Virtual Name Configuration dialog box (Figure C-21). We use the name template. select template. assuming that there is a subdirectory template in the physical directory associated with the virtual directory. Figure C-21: Creating a template by using Virtual Name Configuration IIS Virtual Directory Management . Appendix C: SQL Server 2000 Installation 507 8. Figure C-22: Advanced Properties tab for the IIS Virtual Directory Management . the user can set the advanced option for the virtual directory. By clicking the Advanced tab (Figure C-22). Do not make any changes and click OK to finish creating and configuring the virtual directory. philips.mecel. the distributor of Ericsson’s Bluetooth Application Tool Kit. Sweden based firm specializing in Bluetooth pre-qualification testing .com/bluetooth Site provides latest information on wireless technologies including product information.palowireless.motorola.irda. www.developer.anywhereyougo.com/bluetooth Bluetooth information area of Ericsson www.sigma.cstack.nokia.asp Bluetooth resource center www. URL Description www. supplier of Bluetooth protocol stack for embedded systems www.ericsson.axis.ivtcorporation.com The site of Telelogic.lesswire.Appendix D Bluetooth Reference and Resources The following table lists the various site addresses furnishing information related to Bluetooth.telelogic.com Web site of International Validation and Testing Corporation www.html Bluetooth information area of Nokia www.com/bluetooth Bluetooth information area of Motorola www. resources for developers including online testing.com/bluetooth/index. a leading supplier of Bluetooth modules www.se Site of Sigma ComTec AB. with a brief statement of what each one provides.comtec.lucent.org Web site of Infrared Data Association www.com/bluetooth/devtools.de German firm specializing in location-aware services using Bluetooth www.com Official site of Bluetooth Special Interest Group (SIG) www.com An open source implementation of Bluetooth protocol stack www. and a free newsletter www.org Web site for Home RF standards and products www.semiconductors.homerf.com/micro/bluetooth Bluetooth information area of Lucent Technologies www.com/bluetooth Site of Philips Semiconductors. Sweden.com “The Bluetooth site by engineers for engineers” www.se Web site of Mecel.bluetooth. Also see the Bluetooth PC Reference Stack User’s Manual by Ericsson. January 2001.topsitelists. .Appendix D: Bluetooth Reference and Resources 509 www. Release R1C.com/bestsites/bluetooth Provides links to the top 25 commercial and noncommercial Bluetooth sites. the3gportal.Appendix E 3G Reference and Resources The following table lists the various site addresses furnishing information related to 3G.rutgers.com NTTDoCoMo’s site gives information on I-mode and FOMA www.org Web site of CDMA development group www.openwap.org Web site of Universal Wireless Communications Consortium www.uwcc.org/standards/sfg/imt2K IMT2000 standards and other resources from Telecommuncations Industry Association www. with a brief explanation of what each one provides.locationforum.ipn.cdg.infowin.org Technology and standards of WAP http://winweb.acm. URL Description www.de.org Web site of Association for Computing Machinery . seminars.html Articles and resources on CDMA www.com/w-cdma1.wapforum.tiaonline.org The official site of 3G partnership program. online seminars and news of wireless Internet General technology sites URL Description www.edu/pub/ Information about Wireless Information Network Laboratory. which participates in the “precompetitive stage of technology creation” for wireless Internet. You can find a wealth of information on 3G technologies based on W-CDMA and GSM standards.org Web site for interplanetary Internet www. Offers information on workshops.org Web site provides links to downloads of WAP tool kits and discussion lists www.org/ACTS Web site of Advanced Communications Technologies and Services (ACTS) gives information about the pan-European research projects on advanced wireless communications technologies www.com Web site with rich information on 3G resources www.3gpp.nttdocomo. www.sss-mag.org Web site of Location interoperability forum www. 2001. Artech House.techonline. . Prasad (Ed). WCDMA: Towards IP Mobility and Mobile Internet. T. Ojanpera.511 Appendix E: 3G Reference and Resources www. Introduction to 3G Mobile Communications.ieee. Artech House. R.com Education portal with online and off-line lectures and virtual laboratories Books J. 2001.org Web site of Institute of Electrical and Electronics Engineers (IEEE) www. Korhonen. 350-352 3G partnership program Web site. 334 overview. 343 content development. 330 specifications. requirements for. 331 principles of operation. 510 ACTS (Advanced Communications Technologies and Services) Web site. 358-359 XML and. 334 MXE. 329 Gateway MSC. 334 network areas. 1 applications. 334 features. 153-154 advertisements. 367-369 video files. 349-350 animation example. 352 WML and. XSL and. 349-352 animation example. 139-140 WAP with Bluetooth. 332 base station subsystems. 343-344 4G systems. 340-341 GSM wireless systems architecture. 138 ACM (Association for Computing Machinery Web site. 333 VLR. 334 HSCSD. 360-363 video files example. 1 2G wireless networks. 510 3G programming ASP. 356-358 location-based services. 349 languages. 156 testing. 138 access networks. 336-337 Internet content. 346-347 global roaming. 350-351 animation display. 89 3G wireless networks and. 355-356 audio files example. 331 MSC. 59 addresses Bluetooth. 472 802. 132 A access code. 330-334 AuC (Authentication Center). location-based services. 343 Internet access. 328 2. 341-342 W-CDMA. 344 location-based services and. 328 animation . problems with. 130 ACL links. 333 mobile station. Bluetooth and. 345 example architecture. 510 addPBEntry function. 328 analog cellular systems. subsystems.11 wireless LAN. 345 BREW application. 328 PLMN. 369-370 3G wireless networks. 407 airport kiosk application. 338-339 3G application development.Index Numbers & Symbols 1G wireless networks. 333 base station controller. 332 EIR. 334 OMC. 339-340 Internet access difficulties of. 337-338 overview. WTA. WML Script file. 360-363 Java and. disadvantages of. 339 overview. 329-330 TDMA format. 399-402. 334 HLR. 346 overview. requirements for. 154-155 creating the DSN. 335 services. 461 ACL (Asynchronous Connection Less). 510-511 wireless devices. 336 i-mode. 156-157 AMPS (Advanced Mobile Phone System). 335-336 WAP limitations. link controllers (Bluetooth). 341 GPRS. 345-346 CDMA2000. 364-366 XSL audio files. 332 base transceiver. 352-355 XHTML and. 1 CDMA 95B. 328-339 wireless devices.5G wireless networks. 343 Web sites. link controllers (Bluetooth). Bluetooth devices. declaring (HCI programming). voice communication and. 352-355 XHTML 3G. 332 base transceiver subsystems. BREW. 15-24 SMS. 332 Baseband/Link Manager Protocol. 139-140 APIs. 358-359 Web. 129 chat application. 351 AuC (Authentication Center). 486 WTA. WBMP. See LMP batteries. 7 ASP (Active Server Pages) 3G programming. 130 classes. 51 automobile uses for Bluetooth devices. 417-418 deploying to Tomcat Web server. WML Script. 352-355 XHTML. 272-295 chat application server module. 50-51 arithmetic operators. 29-47 Restaurant Application. 148 BID files (BREW). 85-86 airport kiosk example. 508 API (Application Programming Interface) Bluetooth. 88 using WAP with Bluetooth. 3G programming.com Web site. 52 Bluetooth. 399-402.asp (shopping mall kiosk application). 370-375 push technology. 384WML 3G programming. 295-323 classes. 212-271 mobile advertisements. 355-356 audio. 355 WML and. 90 Service Indication. 384-391 GIF format.Index BREW application.asp (shopping mall kiosk application). 355-356 XML and. 350 XHTML. 147 JMF and. 181-183 classes. declaring (HCI programming). 350-352 applications 3G wireless networks. 49-50 architecture. 158-162 shopping cart with advertisement. GSM wireless systems.11 wireless LAN and. 177 . location-based services. 127. 407 mobile advertising. 346 B base station controller. 360363 airport application. 148 802. 345-346 animation BREW. 488 file transfer (Bluetooth). 3G programming. 160 asynchronous channels. 367-369 audio broadcasting application. 154-157 development. WTA. 3G programming. BREW. 350 bitwise operators. 9. WML Script. 384 binary encoding. 393-394 chat (Bluetooth). 434-440 audio-video broadcasting application. 8 blanket permission. programming. 3G wireless networks and. WTA. 105-106 Quiz. 93 XHTML. Java BREW. XHTML 3G programming. 154 shop. 379 bitmaps. 129 automobiles navigation services. 364-366 anywhereyougo. Tomcat Web server and. 409. 376 downloading. XSL. 158 513 shopnew. client. 3G programming. 332 base station subsystems. 271-323 database. BREW. 271 chat application client module. 356-358 XSL. GSM wireless systems. 423-424 applets. 127 bearers. 356-358 BREW. 3 application development. XHTML 3G programming. 377-379 animation application. 183-194 command to discover nearby devices. 132 addressing. 333 audio WML. 194-204 COM components. 377-383 downloading music. 94 bitmap resources. wireless toolkit. Cold Fusion. 148-150 video. declaring (SDP programming). 107-113. WML Script. 147 car uses. 131 attributes PAP. 96-101. GSM wireless systems and. 140 WTA server. 349 languages. GSM wireless systems. 350 WML. PPG. 120-124 stock quotes. 95 shopping mall kiosk example. 446-458 authentication LMP. 148 sending through mobile phone and laptop computer setup. 164-166 defining constants (HCI programming). 3. 163 devices that can be enabled. 213216 file transfer application server module. WTA. 135-146 TCS. 148-150 Bluetooth Application Tool Kit (Ericsson) Web site. 128 e-mail browsing with mobile phone. 510 CDMA development group Web site. 140-142 office uses. 130 PANs and. 150-153 implementation. 379 database application. 153 typical applications. 343 cell phones. WTA. 510 cdma2000 systems. 327 . 131 kiosks and. 135 services. 393-394 GUI. 377 Resource Editor. 466 call log model. 127 Personal Operating Space and. 138-139 LMP. 379-382 animation application. 376 MIF files. 3 CDMA 95B. 148 event handlers. 376. 132-134 data rates. 508 Bluetooth protocol stack (opensource) Web site. classes. 376 advertisement application. 129 CDMA. 203. 133 radio transmission. 134 WAP addressing. 149 link controllers data connections. 138-139 device states. 153 importing files (SDP programming). 508-509 RS232 variables. 181-183 development kit. 376 application development. 134 declaring constants. 153-154 client/server protocol stack. 377-379 overview. 386-387 string controls. 204208 voice services. 72-76 callback binding. 377-379 bitmap resources. 53 Call. 341 CDMA articles and resources Web site. and methods (HCI programming). 245-271 HCI programming overview. 212 file transfer application client module. 381 downloading music. 130 SIG. 239270 file transfer application. 384-391 applets. 208-212 SDP programming overview. 176 event handlers (SDP programming). 131 data services. 216-245 file transfer application common module. 128 operating frequency. 136-137 voice connections. 136 resources. 377-383 BID files. 376 BREW SDK. 379 BREW Emulator. 417-418 dialog controls. See mobile phones cell splitting (mobile communications design issues). 399-407 animation application. declaring (SDP programming). 127 system architecture. 376 C call forwarding. 150 profiles. 60 car uses for Bluetooth devices. 128 Host Control Interface. declaring (SDP programming). 129 piconets and. 144 variables. 130 operating range. 163-164 home uses. 166-181 commercial solutions. 137-138 time slots. 194 security.514 Index commands and messages (HCI programming). Web sites. 1 CDMA2000 wireless network. 194-204 IrDA comparison. 379 dialog resources. 127 radio transmission hardware. 508 BREW (Binary Runtime Environment for Wireless).java listing. 149-150 server initiation. 134 client initiation. 409. 153 interoperability. 26-29 Quiz application. 88 SMS-C. 91 connectionless push. 491 configuration engine. 327 . 5-7 WML Script. Bluetooth. Bluetooth. 181-183 SDP programming. 326 single cell wireless networks. 327 Cold Fusion. 141 constants declaring (HCI). 28-29 Cold Fusion Server. 295. LMP. 7-8 commericial uses of Bluetooth. 208-212 variables (SDP programming). 272-295 server module. 239 declarations classes (SDP programming). 91 client/server. 465 CVSD (Continuously Variable Slope Delta Modulation). 143-144 compatibility. 98 DDX Control functions HCI programming. 28-29 CGI (Common Gateway Interface). 130-134 databases BREW application. declaring (HCI programming).323 classes. startup and shutdown. GSM. BID files. 26 COM (Component Object Model) components. 132-134 communications. 194-204 COM components (HCI programming). PAP. 26 Cold Fusion Studio. 271 client module. 462 of services. 417-418 GPS. 460-464 converting HTML to WML. 360-363 location-based systems. 462-464 convergence technologies. early years. link controllers (Bluetooth). WSP. 94 content type. 29-47 tags. 3. 325-328 cellular networks. 1 CFCONTENT tag. 164-166. 464 cordless phones. 460-462 of networks. 327 cell splitting. 26. 204-208 deployment descriptor file. 149-150 clock offset request. 91 connections Bluetooth module to PC. 52 control structures. 28 cfm file extension. 28 context permission. WTA. 53 frequencu allocation and reuse. declaring HCI programming. 164-166 RS232 variables (SDP programming). 91 WAP/Bluetooth piconets initiation. cellular systems. 183194 command button functions. 133 Cordless telephony profile. Cold Fusion. PPG.Index cellular mobile communications. 461. 164-166 defining (HCI programming). 477 channel spacing. platforms (SQL Server 2000). 150-153 clients sessions. WML servlets. 176 commands HCI. 131 data services. 327 multi-cell wireless networks. 138139 data rates. 95 handsets. 28 CFML (Cold Fusion Markup Language). 8 convergence. 325 chat application (Bluetooth). 88 515 confirmed data push. 135 D data connections. 327 geographical cells and radio surveys. Bluetooth. frequency allocation and reuse within. 26 content type specification. 350 converting text to speech. RFCOMM. 377 client capability negotiation. 166-181 Tomcat Web server. 133 cstack. 26 CFOUTPUT tag. 409. creating. 468 content transmission. 28 WAP browser text display.com Web site. 163 LMP. 28 overview. Bluetooth. WML Script. 351 HCI programming. 175 SDP programming. 140 clusters. 360-363 stock quote push technology application. 487 design issues. 183-194 DTD. HCI programming. 508 CTI (computer technology integration). specifying WAP. protocol stack. 329 channels. 181-183 content development tools. serial. 194-204 ClassID. 482 WML. 327 frequency allocation and reuse. SMS. 6 frequency allocation and reuse. mobile communications design issues. Bluetooth enabled. 176 SDP programming. 477 dynamic WML content JSP. BREW. 133 files. 88 sending through mobile phone and laptop computer setup. 95 entertainment services. BREW application. 90 DTD declarations. 148 emerging technologies CTI. 485 European systems. content development tools. 245-271 File transfer profile. WTA. WML Script. 334 electronic business cards. Java. 7-9 Dial-up networking profile. 329 dynamic content technologies. LMP. 329 functions addPBEntry. 8 formatting commands. 351 duplex distance. 3 BREW SDK. 7-8 for statements. 1 event binding. 194-204 first generation wireless networks. 502-507 structure. 203 HCI programming. WTA. 508 Ericsson's PC reference stack (Bluetooth development kit). 84 downloading applets. 163 dialog controls. 68 servlets (Java). 133 destroy( ) method. 59 . 466 3G wireless networks and. See 1G wireless networks fixed devices’ obsolesence. 468 development kit (Bluetooth). WML commands. 132 frequency of operationg. HomeRF. Bluetooth. GSM. Bluetooth. Tomcat Web server. 328 desktop PCs. 60 Event model. WTA WML Script file. WML Script. 60 event handlers Bluetooth (SDP programming). 164 SDP application module. 6 F FA (Foreign Agent). 4 flight. 154-155 Float library. 3G wireless networks and. WML Script. 464 encryption. 327 frequency band. 213-216 server module. 6 forms.asp code (airport kiosk application. Tomcat Web server. 486 DNS (Domain Name Server). 133 digital mobile communication networks. 381 Dialogs library. 345 browsing with mobile phone. 65 developer. 465 speech recognition. 148 handset to PC. creation. 5. Bluetooth. GSM. 194 WML commands. 393-394 Tomcat Web server. 212 client module. 28 file transfer. WTA. BREW.com Web site. 345 electronic wallets. 376 music. 464 text-to-speech conversion. 379 dialog resources. 131 file transfer application (Bluetooth). Tomcat Web server.axis. 130 FSK (Frequency Shift Keying). 3G wireless networks and. 140 engine configuration. 363 DTD (Document Type Definition). 67-68 E EIR (Equipment Identity Register) GSM wireless systems. 345 environment variables. 466 Fax profile. WML servlets. See 2G wireless networks directories application directory structure. 486-488 IIS Virtual Directory Management. cfm. 327 traffic analysis. 508 development. 216-245 common module. WML. 88 PCs to mobile. 478 DSN (Data Source Name). 482 Ericsson Web site. 56 callback binding. 329 frequency of operation. WWW. 472 fax mail. 3G wireless networks and. 133 file extensions. Java servlets. 60 temporary. 163 error messages. 60 global. 239-241. importing (SDP programming). 327 shadow regions. 268-270 event management. 345 e-mail. HomeRF. 54-56 events HCI application module.516 Index PSTN trunk capacity. Bluetooth. GMSC (Gateway MSC). 334 overview. 131-132 hop frequency. 60 global roaming. 57 home uses for Bluetooth devices. 2 converting to WML. See GSM. 88 SMS messages. 133 headset. 3 Web servers. 329-330 TDMA format. 131 horoscopes. 360 Bluetooth and. 334 features. 334 GUI (graphical user interface) BREW. Bluetooth. 333 base station controller. 328 PLMN. 1 HLR (Home Location Register) GSM wireless systems. voice/video. 181-183 events module. 351 . 335 services. 333 SMS. 327 mobile communications design issues. WTA. 334 network areas. 153 Host Controller Interface. 166-181 declaring constants. 128 HomeRF. WTA WML Script file. Bluetooth. 140 hold( ) function. 334 Generic access profile. masters and. 376 517 HCI application module. 422-423 HA (Home Agent). 327 GFSK (Gaussian Frequency Shift Keying). GSM wireless systems. 334 HLR. 331 MSC (Mobile Switching Center). 129 graphics WBMP. 164 programming overview. 328 architecture. 2 WML. handling requests. 333 mobile station. 92 SMS configuration. 181-183 COM components. 340-341 GPS. 58 Network common WTAI library. 327 shadow regions. 339340 HTML (HyperText Markup Language).5G networks and. 332 EIR. 1. 332 base station subsystems. Bluetooth. 333 VLR. 350 XHTML comparison. 331 principles of operation. 88 SI messages. 58 WML Script. 133 geographical cells cell splitting. 148 high-speed data services. 136 SQL Server 2000 system requirements. 164 SDP application module. 334 OMC. SMS. 87 GPRS (General Packet Radio Service). 332 base transceiver subsystems. 164 GUI module. 145-146 Bluetooth event handlers. 56 sendDTMF. 330 specifications. problems with.Index makeCall. 343 Global System for Mobile Communication. declaring. Bluetooth. See HCI HSCSD (High Speed Curcuit Switched Data). WTA WML Script file. 8 WTAI functin call example. 2. 360-363 GPS (Global Positioning System). and methods. 334 MXE (Message Center). 183-194 commands and messages. 164166 defining constants. declaring. 87 hold mode. 136 global binding. 194 H H. 164 Headset profile. 491 HCI (Host Controller Interface). 330-334 AuC (Authentication Center). 85 Host Control Interface (Bluetooth). 133 hidden computing scenario. 477 WML conversion. LMP. 60-62 G Gateway MSC. 163-164 remote device module. 86 hardware radio transmission. 350 GSM (Global System for Mobile Communication) wireless systems. 176 classes. network specific WTAI library.323 standards. 472 handsets e-mail to PC. classes. 329 Gateway MSC. Information Master. downloading. 510 intrusion levels. 131 IrDA (InfraRed Data Association) standards. Information Master. 151 Mobile IP. 68-83 JVM (Java Virtual Machine). 336-337 Internet. 6 sun. 84 push technology and. 66 dynamic WML content. 65 Java technologies. 3. 2 importing. 508 Internet. WAP with Bluetooth. See IP interoperability. 337-338 I-Mode. Bluetooth. 344 difficulties of. 1 ISDN (Integrated Services Digital Network) H. 68 servlets. 471. 344. 153 Inter-planetary Internet Web site. 131 Bluetooth comparison. 3. 84 Internet Protocol. content 2G wireless networks. requirements for. 1 IS 95A based wireless systems. WML Script. WML Script. 52 Interim Standard (IS) 54/136 based wireless systems. 511 if-else statements. 93 IP (Internet Protocol). push messages. 3 L L2CAP (Logical Link Control and Adaptation Protocol).ico file. 131 SIR (Serial IR). Internet access. Bluetooth. 194-204 IMT2000 standards and resources Web site. 352 Java code.servlet. 422-423 ITU-R (ITU Radio Communications Standardization Sector Task Group 8/1).http. 465 interactive voice response systems. WML Script. 66 WAP application. 15 i-mode. 466 Intercom profile. 131 Web site. files (SDP programming). 65 JMF (Java Media Framework) voice/video. 142 client/server setups.323 standards. 1 IS 95B systems. 9-15 Information. 510 Information Master.servlet. compiling to. 422 ISP (Internet Service Provider). 328 IS 95A standards. 352 H. 149 KVM (Kilobyte Virtual Machine).323 standards. 460 ITU (International Telecommunications Union). 2 IEEE (Institute of Electrical and Electronics Engineers) standards. 8 IIS (Internet Information Server) Virtual Directory Management. 7-8 . 3. 133 Lang library. 420 IP version 6. 336 i-mode. 3 3G programming and. 508 initialization. WTA libraries. 65 javax. 352 Java. 493-501 Tomcat Web server. 472 IP networks video. accessing 2G wireless networks. WMLScript and. 131 IS (Interim Standard). 133 interfaces. 342 IVR (Interactive Voice Response). 510 LAN access profile.wml file. 1 IS 136 standards. 465 J J2ME (Java 2 Micro Edition). 472 IR (infrared) communication. 63 JavaScript. 478-485 instant messaging. 328 International Validation and Testing Corporation Web site. 9-11 Infrared Data Association Web site. 335-336 3G wireless networks. 502-507 images inserting in WML commands.518 Index I IE (Internet Explorer). 2 client/server setups. 420 voice communications. 339 pull technology and. 422 K kiosks. Java servlets. 2 javax. 65 installation SQL Server 2000. 150 Lacation interoperability forum Web site. WAP and Bluetooth enabled. 337-338 WAP limitations. 423-424 JSP (Java Server Pages). 352 servlets. Quiz application (Cold Fusion).h. Bluetooth device states. 216-218 RadioFileServerDlg.c (BREW). 59 ASP code (flight.h. 40-42 RadioChatClientDlg. Bluetooth. 158-159 LMASP code (shopnew. 133 laptop computers/mobile phones.h. 356 Animation through XSL. 409.asp) for Airport Kiosk.cfm. Quiz application (Cold Fusion). 248. 219.h (file transfer application). 36-37 MIDlet for mobile advertising.java. validating and displaying on browser (shopping cart). 98 Java program.asp) for Shopping Mall Kiosk.java.h (file transfer application). 294 RadioChatClientDlg. 136-137 voice/data connections. 417-418 Events. 181 Report. 148 last inch. 23 Restaurant. 457-458 AudioVideoTransmit. wireless communications. voice messaging. 38-39 CommandDlg. 133 lesswire Web site. 245-248 readallvalue. 214-215 Database application code (BREW). WTA. Quiz application (Cold Fusion). push messages. 350 XHTML. 11-12 PrintProfile. 427-432 AudioReceiveStreams. 96 Index. 213 . 184-187 Events.java. 205-207 PrintProfile. 352 WML. 451-452 questiondisplay. push technology. 440-445 AudioVideoReceive. 351-352 XML. 239 RadioFileClientDlg. 39-40 RemoteDevice. supervision (LMP). 58 link controllers.java.cpp. 164-166 HTML registration code shopping cart application. 72-76 checkvalue.cpp (file transfer application). 32. audio broadcasting application.cpp. 138-139 links.cpp. 10-11 Java program. Quiz application (Cold Fusion).h. 166. 157 Service Indication generated by Tool Kit for Shopping Mall Push Message.cfm. 371-375 Movie. preferences storage in database (shopping cart).h. 213-214 Service.java. 137-138 time slot. 387-391 answer.wml file (Information Master). 77-78 ResScripts. 44 appl. 3G application development. 154-155 ASP code (shop.h (chat application). 274 RadioFileClientDlg. 204-205 Professor. 350-351 LAN access point.h.asp) for Shopping Mall Kiosk. 267 RadioFileServerDlg. 140 listings Accessing emergency services through WTAI (WML code). 111 Java program. 462 last mile.cpp (file transfer application).cpp. 350 Java. communicating between. Quiz application (Cold Fusion). Cold Fusion.Index languages. 446-451 bingo. 402-407 Animation through XHTML. 16-17 RS232. 367-368 AudioCapture. 161 Service. 61 action.cfm. 7-9 WTAGSM.wml file (Restaurant App). 208-209 Service Indication generated by the Tool Kit for Airport Kiosk Push Message.java. 93 libraries function libraries (WTAI). 33 Information.cpp (file transfer application). Quiz application (Cold Fusion). 452. 34-35 Advertise.h (file transfer application). 113 login. 160 Audio through XSL. Bluetooth. Quiz application (Cold Fusion). saving order in database (shopping cart). 183 HCI Information CommandsDlg. 508 levels of intrusion. 109 stock quote application. 274.cfm. push technology. 196-202 CommandsDlg. 215 519 ConnectionInfo. 56-59 interfaces.h (file transfer application).cfm.cfm.cfm.wmls WML Script file (WTA). 121 Java program.wml file (Information Master). 461 LCD projector. 272.wmls file (Restaurant App).java. 364-365 Animation.cpp (chat application). preferences storage in database (stock quote).c (BREW). 194-196 ConnectionInfo. 52 WML Script.cpp (file transfer application). 45 Call. 209-210 RS232. 182 RemoteDevice.cfm. wireless communications. Quiz application. 175 HCI Information CommandsDlg.cpp.cpp. 370 MIF files (BREW).wml file (Restaurant App). 352. 3 methods.Java.xml. Quiz application (Cold Fusion). 369-370 Weather. 366 XML code for audio. push technology. 85 makeCall function. 86 mail notification. WTA. 3G wireless networks and. 352-354 WML code for calling servlet/placing order (shopping cart). 368-369 XML code for video.cfm. 360-363 3G wireless networks and. 467 voice dialing. Quiz application (Cold Fusion). 488 Welcome. network specific WTAI library. 424-434 messaging instant messaging. 42-43 TestWML. 508 medical services. 370-375 mobile banking.c (BREW). voice/video. 466 voice messaging.520 Index Servlet to push stock quote information. 2 mobile advertising application. 298-323 Source Code for RadioChatServerDlg. 445-446 submit. 394-398 Source Code for RadioChatServerDlg.java. 346 messages HCI. 131 PAN. 58 masters hop frequency. 360-363 XHTML. 360 Mobile IP. 89 push. communicating between.wml file (Information Master). 2 Lucent Technologies Web site. 131 piconet.cfm. 79-81 Sound. 21-22 Soft.wml file (Restaurant App). 357 XHTML code to play video files. 472 mobile phones/laptop comuters. 352. 466 short messaging service. 432-434 video play. 14-15 web. 7-8 low bit rate coding. WTA. 466 fax mail. 123-124 XHTML code for displaying retrieved values from database. LMP. 140-142 location. 166-181 length. 346 logical indicator model. 358-359 XML code for animation. 86 mobile-terminated SMS. 18-19 Student. 46-47 UserInter. 87 . 467 location( ) function. SMS and. WML Script. audio broadcasting application. 466 interactive voice response system.java. WML Script file. 150 LMP (Link Manager Protocol). 68 TrialServlet. 467 GPS. SMS and. precise location-based services. 140 m-commerce. 164-166 MIDlets. 89-90 voice messaging application. 53 Logical Link Control and Adaptation Protocol. 370 P (Baseband/Link Manager Protocol) client/server setups. 88 mobile communications cellular deisgn issues. principles of operation. 466 video messaging. 345 MD (Mobile Device). 360-361 XHTML code to play audio file. declaring (HCI). 148 mobile stations.wml file (Restaurant App). 57 location-based services 3G programming ASP. 326-327 principles of operation. 13-14 Weather. 472 Mecel Web site.JSP. See L2CAP logical operators. 20-21 Solution. XSL. 370 MIDs (Mobile Information Devices). 508 M m advertising. 3G wireless networks and. 67-68 tryagain.h (chat application). 465-466 call forwarding. 361-363 XHTML code for latitude/longitude input. 134 switching roles. 466 e-mail. WAP and. 465 unified messaging. 325-326 mobile devices. 89 PI and. 382-383 WML code for animation using timer.java.cpp (chat application). 466 meta languages. 421 low-speed networks. 331 mobile-originated SMS. 377-379 MIP (Mobile IP). 295-298 South. processing. 101 Snacks. voice messaging. 327-328 multi-cell wireless networks.wmls file (Information Master).c (BREW). GSM wireless systems.java. 69-70 TrialJsp. 7. 129 Philips Semiconductors Web site. 149-150 platform compatibility.wml file. 345 NN (Netscape Navigator). 460 Point to Point Protocol. 89-91 overloading SMS. Tomcat Web server. 2 nodes. 508 non-confirmed data push. See PPP. 425 WTA. 140 parsing. 131. 425 ports. Bluetooth enabled. 351 XML. 344 permissions policy files.Index 521 modulation. 344 SQL Server 2000. 140 namespaces. 52. 8 Originating Call model. 376 convergence of. 344 peripherals. 127 O Object push profile. 87 multi-cell wireless networks. downloading (BREW application). 88 performance. WML commands. 351 XML. 53 PI (Push Initiator). 12 listing. PANs. 334 mobile-originated SMS and. 89 N P name request. LMP. 6 navigation services for automobiles. Bluetooth. 900 North American systems. 326-327 music. 127 slaves. 52 Network common WTAI library functions. 491 PLMN (Public Land Mobile Network). WTA. policy files. 53 network specific WTAI library. 9 code output. 130 HomeRF. 329 Motorola Web site. 331. 91 Nordic Mobile Telephony (NMT). principles of operation. 128 OMC (Operation and Maintenance Center) . 328. 134 WAP and Bluetooth enabled. 163 PCM (Pulse Code Modulation). 508 Movie. XML. Bluetooth and. 131 news services. 57-58 networks access networks. system requirements. 131 topology. 133 ODBC connectivity. 86 mobile-terminated SMS and. push technology. 358 MSC (Mobile Switching Center) GSM wireless systems. 510 palowireless. 508 PANs (Personal Area Networks) Bluetooth. 89-91 park mode. 56 network message model. 131 PAP (Push Access Protocol). WTA Event model. LMP. 127 masters. 346 nested tags XHTML. 421 PCs e-mail to wireless. 328 Personal operating space. 135. 351 operating frequency Bluetooth. 3G wireless network requirements. 12 MPEG (Moving Picture Experts Group) files.com Web site. 450. 393-394 MXE (Message Center) GSM wireless systems. 508 phone book model. 3G wireless networks and. WSP. XML references. 351 network common WTAI library. 11. 133 NTTDoCoMo Web site. 131 overview. SQL Server 2000. 54 OTA (Over The Air) protocol. 130 operating systems 3G wireless networks. requirements for. GMSK. 461 BREW and. 351 PC reference stack (Bluetooth development kit). 363 office uses for Bluetooth devices. Information Master. 334 opening/closing tags XHTML. 351 navigation. 88 SMS and. 89 piconets. 3G wireless networks and. 86. 51 Personal Digital Cellular (PDC) wireless system. 3G wireless network requirements. 492-493 operators. 461-462 piconets. 132 operating range. WTA. WML Script. 485 power Bluetooth devices. 334 GSM wireless systems. 1 notebook PCs. Bluetooth. 127 Nokia Web site. 156 testing. 94 Push Message Simulator. 89-90 non-confirmed data push. PAP. 86-95 PPP (Point to Point Protocol). 89-94 pros/cons. 90-91 PAP protocol. 421 SDP. Public WTAI. 91 OTA protocol. 150 multiplexing. PAP. 29-30 action. 151 IP version 6. client/server setups. 136 power consumption. 90 push technology. 421 RTP. 183-194 commands and messages (HCI). L2CAP. 92 push submission. 2. 142 parameters exchange. 151 RTCP. 91 Q QoS L2CAP. 160 testing. 96-98. 344 power of transmission. 68 Quiz application. 2. 91 content transmission. 166-181 declaring constants. 92-94 shopping cart with advertisement. SDP application module. radio transmission. 84 message processing. 422 IP. 151 PQR. 470 client/server stack. 95 applications for. 45 . 163-164 protocol conversion. 91 stock quote application. 3G wireless network requirements. 133 programming classes. 335 Public Land Mobile Network. 151 push messages. 151 video. 94 service indication. 160-162 push cancellation. 156 push messages levels of intrusion. 84-85 PAP. 84 push applications airport kiosk example. 85 Service Loading. 91 connectionless push. PPG. 94 Internet content access and. 194 profiles. 152 WTLS. development.cfm listing. 85-86 binary encoding.522 Index LMP. 151 WSP. 101. 91 WSP. PPG. 94 protocols. See PLMN. 467 PRINTSERVICE. 94 SI. 421 voice communications. 52 pull technology. 471-472 L2CAP. 125 push initiation messages. 84 application. 140 power classes. and methods (HCI). 105-106 WDP. 158-160 creating the DSN.cfm listing. 89 push initiation messages. 2 UDP. 421 WAP bearers. 58 public WTAI library. 149-150 SMS. 154-155 creating the DSN. Bluetooth. 120-124 SIA. declaring (HCI). 460 mobile communications design issues. 91 PPP. 88 precise location-based services. HomeRF. 89 protocol conversion. 152 PSTN (Public Switched Telephone Network). 89 RFCOMM. 93 PPG and. 94 confirmed data push. 91 push framework. LMP. 89-91 overview. 181-183 HCI overview. 34-35 answer. 164-166 defining constants (HCI). Internet content access and. Cold Fusion. banking.cfm listing. 148 WDP. 327 principles of operation. 142 OTA.232 standards. 152 TCP. 107-113. 181-183 COM components. classes. 140 Question of the Day WAP page. declaring (HCI). 132 PPG (Push Proxy Gateway). 150-153 H. 150 LMP. 156-157 shopping mall kiosk example. 151 WTP. 89 protocols. 44 bingo. 38-39 function. 149 PRINTSERVICE module. 194 programming overview. 42-43 tryagain. 194-204 GUI module. sports. 40-42 readallvalue. 208-212 SDP application module. 26 WAP/Bluetooth piconets initiation. 386-387 resources. 142 sendDTMF function.Index checkvalue.java listing.cfm listing. 194-212 reject( ) function. See also Web servers Service discovery application profile. 142-143 classes. network specific WTAI library. declaring. 65 services convergence of. 343 root element. 36-37 questiondisplay. 9. 194 Report. defining (SDP programming). 65-83 .cfm listing. 144 scores. 131 range of operation and. 477. Bluetooth. 143-144 serial ports defining parameters (HCI programming). 462-464 registering (SDP programming). 151 roaming globally. 133 serial communications. 140 resolution. 136 HomeRF. 65 servers Cold Fusion. WTA. 164 SDP application module. 32-33 login. 7-8 remote devices HCI application module. 56-59 SDP (Service Discovery Protocol). 51 servers. 90 RF standards and products Web site. Bluetooth. 127 hardware. 239 SerlvetRequest object. 508 RFCOMM protocol.cfm listing. 135 permissions. 194 RS232 variables. 39-40 submit. 327 radio transmission Bluetooth. 239 events module. push technology. importing.cfm listing. 351 R radio surveys. XHTML. 77. 31-47 Index. 175 firing success/failure messages (HCI programming). graphics (WBMP). 178 interface constants. 194 remote device module. 150 WTA. 130 range of operation Bluetooth. Bluetooth.cfm listing. 351 RS232 variables declaring (SDP programming). WTAI interface. 421 RTP (Real Time Transport Protocol). 57 relational operators. 150 DDX Control functions.cfm listing. 85 scripting. 194-212 Servlet Response object. 204-208 second generation wireless networks. WML Script file. PAP. 421 S SCO (Synchronous Connection Oriented). services (SDP programming). 401-402 animation application. 194 piconets and. declaring. 130 HomeRF.cfm listing. 85 service( ) method. L2CAP. Java servlets. problems with. mobile communications design issues. WML Script. 78 request and response features of LMP. 143-144 client/server setups. RFCOMM and. 194 RS232 module. 138 TCS. declaring. See 2G wireless networks security Bluetooth. See SDP service indication. 51-52 segmentation. 194 files. 65 servlets Java. 132 registration. 208-212 variables. policy files. XML. 425 WTA. 2. 350 Resource Editor (BREW). 53 Restaurant Application. 15-24 result notification. WML Script. 194-204 client/server setups. 130 SCO links 523 link controllers. 379-382 advertisement application. 57 Serial communication profile. 58 sendUSSD( ) function network specific WTAI library. 46-47 quotation marks. 194 RTCP (Real Time Control Protocol). 133 Service Discovery Protocol. 491 Standard Edition. 493-501 overview. 508 signaling. 85 SQL Server 2000 Developer Edition. 491-493 Windows CE Edition. 490 XML support. 107-113. LMP. SMS and. push technology. 1 IS 95A. 26-28 WML. 330 SIGs (Special Interest Groups). 15 code output. 21-22 Soft. 351 TCP (Transmission Control Protocol). 491 operating systems. 87 Snacks. See SMS shutdown command. 152. 88 mobile-originated SMS and. 6 tags CFCONTENT. 92 SIA (Service Initiation Application). 9 code output.ico file. 5-7 WML Script. PAP. 19 listing. 158-160 creating the DSN.wml file. 470 syntax WML. GSM.wml file. 89 string controls. Restaurant App. voice/video. 501-502 standards IS 136.wml file. 15 code output. 86 mobile-terminated SMS and. 1 startup command. 329 speech recognition. 490 Enterprise Evaluation Edition. 91 shadow regions (mobile communications design issues). 15 code output. 86-89. 7-8 sun. 490 Personal Edition. Bluetooth. 53-54 store-and forward mechanism. Information Master. 91 stock quote application. devices.asp (shopping mall kiosk application). 18-19 speakers. BREW. 28 CFOUTPUT. 94 slaves PANs. 351 XML. 137-138 status codes. 160 shopping cart with advertisement application. 131 piconet. 327 shop. 91 SIG (Bluetooth Special Interest Group) Web site. 508 Sigma ComTec AB Web site. 90 status query.java listing. WTA. 466 SMS-C (SMS Center) configuration. 351 system architecture. 482 state management. Bluetooth. 95 sessions. 52 SIR (Serial IR). client creating. 79-81 South.asp (shopping mall kiosk application). 132 synchronization. 21 listing. 502 SQL Server 2000 hardware. PAP. 5 XHTML. 160 testing. Bluetooth. Tomcat Web server. 2 TCP layer. 491 installation. 135-146 system requirements IIS Virtual Directory Management. 379 String library. 482 SI (Service Indication) messages. 133 speech coding. 490 Enterprise Edition. 160-162 Short Messaging Service. 7-8 XHTML. push technology. 92. 23 listing. 421 . 158-159 shopnew. 134 switching roles. 464 sports scores. 120-124 shopping mall kiosk application. GSM. 28-29 Cold Fusion. commands (WML). 490 system requirements. 492-493 T tables. WTA.524 Index WML content. 85 storage. 20-21 Solution. Restaurant App. 127 single action permission. Restaurant App. 96-106 stock quotes. 140 SMS (Short Messaging Service). 490 platform compatibility. WTA. 133 SyncML (Synchronization Markup Language). 15 SWAP (Shared Wireless Access Protocol). 60 states. Tomcat Web server. 131 SL (Service Loading). WML Script. 88 handset configuration. 3. Bluetooth. 329 Signaling System 7 (SS7). 4 Synchronization profile. 509 Total Access Communication System (TACS). interface constants. 350 XHTML. 329 TrialJsp. 153-154 USB (Universal Serial Bus). 466 . 446-458 H. See UDP user permissions. 51 U UDP (User Datagram Protocol).Java listing. WTA Event model. 467 voice dialing. 422-423 IP network applications. deploying. 333 technoline. 3G wireless networks and. 478 startup and shutdown commands.JSP. 3G programming. WTA. LMP. 421 PCM. mobile communications design issues. 466 Universal Wireless Communications Consortium Web site.com Web site. 6 video. 423-424 low bit-rate coding. 466 video messaging. 60 Terminating Call model. 420 asynchronous channels. 329. 420 JMF. link controllers (Bluetooth). 345 video messaging. 327 trusted services. 204-208 environment. 345 video mail.com Web site. 420 JMF. 466 voice messaging. 3G wireless networks and. 131 audio broadcasting application. 51 V variables declaring (SDP programming). 421 client/server setups. 86 text-to-speech conversion. 488 directory structure. 136-137 timing accuracy information request. 160-162 TestWML. 486-487 topology PAN. WTA. addressing with Bluetooth. 358-359 XSL. 163 Telelogic Web site. defining (SDP programming). 464 the3gportal. 466 fax mail. 421 protocols. SMS. link controllers (Bluetooth). WTA.com Web site. 369-370 video conferencing. 466 e-mail. 144 TDMA (Time Division Multiple Access) GSM. 67-68 trunk capacity (PSTN). 434. 345 Virtual Directory Management (IIS). 486. 420 H. network specific WTAI library. 68 TrialServlet. 486 installation. 28-29 text messages. 422-423 IP network applications. WML Script. 464. 467 video players.java. 51. 423-424 low bit rate coding. 510 URL library. 53 voice communication. 54 testing airport kiosk example. 421 WML. 510 time slots. 3G wireless networks and. 421 protocols. WTA. 511 Teleca ComtecWeb site. 478-485 overview. 488 applications. 482 Web applications. 482 WML commands. 156-157 shopping mall kiosk application. 151 unified messaging. 465-466 call forwarding. 57 transmission power. 421 voice connections. Installing Tomcat Web server. HomeRF.323 standards. 346 videophones. 328 transfer( ) function. 131 PANs. GSM. 438-440 audio-video broadcasting application. 138-139 voice dialing. 334 voice call model. 127 topsitelists. 9 URLs (Uniform Resource Locators) WAP. 69-70 text. 239 user agents. 328 traffic analysis (mobile communications design issues). 2. 132 transmit data rate. 466 interactive voice response systems. 140 Tomcat Web server application directory. Cold Fusion (WAP browser).323 standards. 421 PCM. 502-507 VLR (Visitor Location Register) GSM wireless systems. 7. 3G wireless networks and. 508 temporary binding. 466 525 short messaging service.Index TCS (Telephony Control Protocol Specification). application. 60 User Datagram Protocol. 510-511 ACM. 28-29 Internet access. 151 Weather Report WAP page. 510 WAP toolkits and discussion lists Web site. 508 RF standards and products. 508 Ericsson.wml file. 68-83 WAP Forum. 468-470 W WAE (Wireless Application Environment). 509 Universal Wireless Communications Consortium. 510 3G wireless networks. 510 topsitelists. WML Script. 510 lesswire. 9 code output. 51 WAP technology and standards Web site.com. 149-150 protocol bearers. See WTP Wireless Transport Layer Security. 338-339 3G wireless networks. 510 Bluetooth Application Tool Kit (Ericsson).com. 2 Bluetooth. 510 wireless technologies information. 510 WAP toolkits and discussion lists. 510 cstack. 132 while statements. 510 wireless networks.axis. 508-509 CDMA articles and resources. 510 palowireless. 148-154 browser text display (ColdFusion). evolution of. 345 WECA (Wireless Ethernet Compatibility Association). 163 Telelogic. 370-375 Wireless Transaction Protocol. 478-486 Web sites 3G partnership program. 8 Windows NT/2000. 508 SIGs. 2 piconets and. 508 Lucent Technologies. 510 WAP-enabled phones.com. See WTLS . 350 W-CDMA (Wideband Code Division Multiple Access) systems. 508 Bluetooth protocol stack (opensource). 1 wireless communications last inch. 15 listing. evolution of. 14 listing. 511 IMT2000 standards and resources. 3G wireless networks and. 9 code output.com. 148 servlets-based application. 466 voice messaging application. 2 images. 477 PI. Tomcat Web server. 5 WAP (Wireless Application Protocol). 130-134 Voice XML (Voice Extensible Markup Language). 508 developer. See WDP wireless devices 2G wireless networks and. requirements for. 14-15 Web servers overview. 508 IEEE.526 Index voice messaging. 462 last mile. See WSP wireless toolkit. 1 Wireless Session Protocol. Information Master. 510 Infrared Data Association. 13-14 Weather. 511 Teleca Comtec. 508 Mecel. 510 Lacation interoperability forum.com.com. 2 WAP gateway. 343 WDP (Wireless Datagram Protocol). 508 Philips Semiconductors. 1 wireless protocols. 91 client/server setups. 508 Inter-planetary Internet.wmls file. 68-83 kiosks and. 149 low-speed networks. limitations. evolution of. 510 ACTS. 336-337 JSP-based application. 461 Wireless Datagram Protocol. 424-434 voice services (Bluetooth). 3 WBMP (Wireless Bitmap). 508 Motorola. 477 Tomcat. 89 principles of operation. 508 International Validation and Testing Corporation. 508 Nokia. 343-344 Wireless Information Network Laboratory Web site. WTA server and. 508 Web-based learning. 510 Wireless Information Network Laboratory. 510 CDMA development group. 508 Bluetooth resources. 508 NTTDoCoMo. 508 the3gportal. 68 Weather. 1 wireless network. 510 WAP technology and standards. 508 Sigma ComTec AB. 479-482 wireless applications. Information Master. 508 technoline. 7-8 control structures. 5 WMLBrowser library. 56. 90 namespace references. 487 entries. 364-366 deployment descriptor files. 58-59 interface libraries. 7-8 Restaurant. 501-502 WML definition. 60 Event model. 2 3G programming and. 152 X XHTML (eXtensible HyperText Markup Language). 53 event binding. 350 WML Script commands. 364-366 . 2 WSP (Wireless Session Protocol). 67-68 graphics. 351 SQL Server 2000. 350 program structure. 9 Restaurant Application. 50-51 call log model. 8 Information Master. 5 servlets. 51 WTAGSM library. 51 phone book model. 53 WML Script. 351 HTML comparison. 356-358 video files example. 9 WMLScript. 7. 350-351. 349-350 animation example. 8 functions. 68 servlets. 7-9 operators. 358-359 attributes. 54-56 functions. 349-352 location-based services. 58 security. 350 HTML conversion. 151 WTP (Wireless Transaction Protocol) client/server setups. 15-24 syntax. 350 audio. 3 3G programming and. PAP push submission. 51. 51.wmls listing.Index WML (Wireless Markup Language). 56 network message model. 53-54 user agent. 2-3 3G programming and. 152 WTA (Wireless Application Environment). 351 tags. 49 Accessing emergency services through WTAI (WML code). 355-356 audio files example. support. 352-355 animation. 350 commands. 53 Network command WTAI library. 60 voice call model. 52 logical indicator model. 351 nesting tags. 56-59 WTLS (Wireless Transport Layer Security) client/server setups. 57-58 permissions. 351 XML (eXtensible Markup Language). 58 WTAI function calls example. 59 WTA server. 5 XSL 3G programming audio files. 351 quotation marks. 95 syntax. 360-363 animation example. 56-59 scripting interface. 49-50 architecture. 60 storage. 52 527 state management. 351 root element. 61 applications. 60 event management. 2 video. appl. 60-62 function libraries. 367-369 video files. 351 opening/closing tags. WML Script. 5-7 converting from HTML. 351 syntax. 91 client/server setups. 369-370 animation display in XML. 7-8 wml tag. 351 parsing. 351 nested tags. 53 Public WTAI library. WML Script file. 53 network specific WTAI library. 9-15 libraries. 351 opening/closing tags. 3 dynamic content JSP. 5-7 toolkits.
Copyright © 2024 DOKUMEN.SITE Inc.