Sunteți pe pagina 1din 150

Home Security System with Bluetooth Technology

Home Security System with Bluetooth Technology

by HUNSENG CHUA

Department of Computer Science and Electrical Engineering, The University of Queensland

Submitted for the degree of Bachelor of Engineering (HONOURS) In the division of Electrical Engineering October 2001

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

9/82
Macquarie Street St. Lucia QLD 4067 Tel. (07) 3870 1717

October 19, 2001 The Dean School of Engineering University of Queensland St. Lucia, QLD 4072

Dear Professor Simmons,

In accordance with the requirements of the degree of Bachelor of Engineering (Honours) in the division of Electrical Engineering, I present the following thesis entitled Home Security System with Bluetooth Technology. This work is performed under the supervision of Dr Adam Postula.

I declare that the work submitted in this thesis is my own, except as acknowledged in the text and footnotes, and has not been previously submitted for a degree at the University of Queensland or any other institutions.

Yours Sincerely,

HUNSENG CHUA

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

Acknowledgements
I would like to express my sincere thanks to my thesis supervisor, Dr Adam Postula, for his patience, guidance and advice throughout the year, which proved valuable for the success of this thesis.

Not forgetting also, my friends and family, heartfelt thanks to all of them for their support and encouragement throughout the year.

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

Abstract
In recent years, wireless applications have been rapidly evolving in personal computing and communications devices. By using Radio Frequency (RF), it resulted in new way for people to communicate and gain access to data without the means of cables. The Bluetooth wireless technology was created to solve a simple problem: replace the cables used on mobile devices with radio frequency waves. Bluetooth is an open specification and the technology encompasses a simple low-cost, low power solution for integration into devices. Bluetooth operate at the globally unlicensed 2.4 GHz Industrial Scientific Medical (ISM) band that is available worldwide. Moreover, Bluetooth employs frequency hopping in 79 hops displaced by 1 MHz and has a data rata of up to 1 Mbps for both voice and data. Such devices can form a quick ad-hoc secure "piconet" and communicate among the connected devices. Leading companies in the

telecommunications and computer industries promote Bluetooth.

In this document, the Bluetooth wireless technology will be briefly introduce before stating the aim and motivation of this thesis. The objective for this effort was to implement Bluetooth technology into the motion detector to demonstrate the establishment of connection and the changing of the motion detector settings, such as the sensitivity and range via the Bluetooth wireless communication. The reasons for implementing this thesis will be discuss next. In Chapter 2, a brief review on the relevant literature for the development of this thesis is given. As for Chapter 3, a theory section of the Bluetooth Protocol Stack gain from reading from books and paper discussed in the Literature review.

Chapter 4 discussed the performance required for this project and further explained the hardware and software implementation of the project in Chapter 5.

After a short comment on the future improvement of this thesis, this thesis will conclude after Chapter 6. The Visual C++ code for the implementation of the motion detector will be presented in the appendix of this thesis.

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

Table of Contents
Acknowledgements I

Abstract.. II

List of Figures III

List of Tables. IV

1.

Introduction 1 1.1 1.2 1.3 Aim of Thesis.. 2 Objective of Thesis 2 Motivation of Thesis 4

1.4

Overview of Thesis.. 4

2.

Literature Review 6

3.

Background Theory of Thesis 10

3.1

The Bluetooth Profiles 10

3.2

Serial Port Profile 12

3.2.1 Application Layer.. 15 3.2.2 Establish Link/Setup Virtual Serial Connection..15 3.2.3 Accept Link/Establish Virtual Serial Connection....16 3.2.4 Register Service Record in Local SDP Database... 16 3.3 Power Mode and Link Loss Handling.. 16

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

3.4

RS-232 Control Signal.. 17 3.4.1 Remote Line Status Indication 17

3.4.2 Remote Port Negotiation. 18

3.5

L2CAP Interoperability Requirement18

3.5.1 Channel Types. 18 3.5.2 Signaling.. 18

3.5.3 Configuration Options. 18

3.6

SDP Interoperability.. 19

3.7

Link Manager Interoperability Requirement. 19

3.7.1 LM Error Behaviour 20

3.7.2 Link Policy...20

3.8

Link Controller Interoperability Requirement...20

3.8.1 Inquiry..20 3.8.2 Inquiry Scan.20

3.8.3 Paging.. 21

3.8.4 Error Behaviour... 21

4.

Overview of Bluetooth Motion Detector.22 4.1 4.2 4.3 Home Security System22 Hardware Overview... 23 Design Requirements.. 25
6

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

4.3.1 Power Requirements 25 4.3.2 Processor Requirements.25 4.3.3 Wireless Requirements..26 4.3.4 Security Requirements...27 4.3.5 PIR Motion Detector..28 4.4 The Work Remaining to be Done29

5.

Software Module30 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 The Bluetooth Protocol Stack..32 Implementation of Software33 Use of GUID to Represent UUID34 The Use of Maximum Transmission Unit (MTU)...36 Destructors for SDK CLASSES...36 Derived Function Run on Separate Threads.36 Examples of RFCOMM.. 37 The Application38 5.8.1 Graphical User Interface (GUI)..39

6.

Future Consideration.45 6.1 6.2 Further Improvement Consideration for Thesis Work.45 Future Foreseeable Bluetooth Product.45

7.

Conclusion..48

8.

References..49

9. 10. 11.

Appendix A: The Schematic Diagram of Motion Detector..A-1 Appendix B: List of Classes B-1 Appendix C: Application Source Code for Both Client and ServerC-1

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

List of Figures
Figure 1. Figure 2. Figure 3 Figure 4 Figure 5 Figure 6 Figure 7 Figure 8 Figure 9 Figure 10 Figure 11 Figure 12 Figure 13 Figure 14 Figure 15 Figure 16 Figure 17 Figure 18 Figure 19 Figure 20 Figure 21 Bluetooth Protocol Layers Overview of Bluetooth Motion Detector The Bluetooth Profiles The Serial Port Profiles Serial Port Profile (example with two notebook) Setps taken to Establish Connection Block Diagram for Hardware Block Diagram of the AT90S8515 Typical Configuration of PIR Sensor Top View of LS6501LP Software Architecture Block Diagram/Overview of the Bluetooth for Window SDK The Client GUI Application Display of Client GUI when Connected Display of Server GUI when Connected Got Arm Status Display Display of Client GUI for Configuring Display of Server GUI for Configuring Client Display for Disconnection Server Display for Disconnection Client Display of Closing

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

List of Tables
Table 1 Table 2 Table 3 List of Hardware Components Features of LHi 958 PIR Sensor Classes Offered in the SDK

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

Chapter One Introduction


As the number of computing and communications devices continue to rise, the art for establishing the connectivity between them becomes more and more complex. Furthermore with the increase usage of wireless applications in recent years, we have recognized that the means of data transfer other than cable is necessary. Today the Bluetooth technology is the only specification targeted at this new market of cable replacement. Bluetooth is a new standard developed by a consortium of companies for an open specification for short-range wireless connectivity. The Bluetooth technology offers low-power, low-cost radios that can be interface with existing devices. The Bluetooth open specification defines how devices could communicate with one another.

Bluetooth radio operate at the unlicensed Industrial Scientific Medical (ISM) band of 2.4 GHz, which is available worldwide. Bluetooth data transfer rates of 1 Mbps is achieved with a Time-Division Duplex (TDD) scheme and interference is avoided using Spread Spectrum Frequency Hopping (FH) techniques [1]. Bluetooth devices wireless link has a range of up to 10 meters apart, therefore it provide a perfect solution for replacing cable in a room or office. Such devices can form a quick ad-hoc secure "piconet" and communicate among the connected devices. The technology has many advantages such as it is always on and it does not require line of sight or conscious intervention by the user and it is adaptable to any wireless standard.

Before we go any further, it is important to introduce the Bluetooth Protocol Layers. Firstly, what are Protocols? Protocols are agreed-upon way that devices exchange information [6]. The Bluetooth specification is made up of seven main Protocol Stacks. A brief description of each of their function is shown in Figure 1 below.

Chua Hun Seng s38042580

10

Home Security System with Bluetooth Technology

Application Host Controller Interface HCI firmware L2CAP Link Manager Baseband RF (radio and antenna) Control Audio
be discussed in more detail.

Figure 1: Bluetooth Protocol Layers

These seven Protocol Layers are essential components, for the device to work properly in order for Bluetooth qualification. The Application Protocol, residing above the RFCOMM/SDP layer is part of the Bluetooth Profiles. The Profiles describe how the technology is to be used, i.e. how different parts of the specification can be used to fulfil a desired function for a Bluetooth device [5]. In Chapter 3, the Bluetooth Profiles will

1.1

Aim of Thesis

The aim of this thesis is to incorporate wireless technology into the motion, which uses the Bluetooth technology to enable a Laptop (User) to control the sensitivity and range of the detection area.

1.2

Objective of Thesis

The scope of the thesis has been negotiated and agreed upon with the thesis supervisor, Dr Adam Postula, at the beginning of semester two, year 2001. Therefore, this thesis (Home Security System with Home Security System) does not involve the complete home security system, as the title might suggest otherwise. The focus of this thesis is on the Motion Detector only. Furthermore the Bluetooth Protocol Stack need not be embedded in to the microprocessor of the motion detector. Instead, the prototype

Chua Hun Seng s38042580

11

Home Security System with Bluetooth Technology

Bluetooth communication link will be done by using two laptops with Bluetooth stack resides on the Laptop connected with the Ericsson ROK 101007 Bluetooth module via the Universal Serial Bus (USB). The motion detector will be connected to one of the laptop via the serial link (Serial cable between the motion detector and the laptop).

The Link manager/L2CAP/RFCOMM reside on the laptop. The setting is got from the remote laptop over Bluetooth and then sent over the serial cable to the Motion detector.

In order to achieve the aim of the thesis, the following key objectives were set:

1.

To demonstrate connection establishment between two Bluetooth module and the motion detector.

2.

To demonstrate basic function of the motion detector such as arming and disarming.

3.

To demonstrate the motion detector getting the configuration information via the serial port from the user.

4.

To demonstrate the ATMEL processor in the motion detector able to set the requested configuration from the user.

Thus, this approach completely reduces the cost for this thesis. Furthermore it would be able to demonstrate the entire communication process between two Bluetooth-enable devices from the connection establishment, configuration of the motion detector sensitivity and range, arming of the motion detector, triggering of the alarm and finally the disarming of the motion detector. Moreover the application does not need to know whether it get its configuration from an actual serial port or a serial port emulated over Bluetooth.

Equipment
Below is the list of equipment use in this thesis for this prototype. 1. Two Ericsson Rok101 Bluetooth module. 2. Two Laptop with Bluetooth Protocol Stack 3. Motion detector with alarm to be managed over serial link.

Chua Hun Seng s38042580

12

Home Security System with Bluetooth Technology

1.3

Motivation of Thesis

The motivation of this thesis will be presented in this section. The formation of the SIG itself was aimed at developing an open specification with the backing from leaders in the computing and telecommunications industries []. These SIG members have realized that interoperability is the key attribute to successfully launching their Bluetooth product and gained the acceptance of the consumers. Therefore fear for a market situation with a multitude of non-standard cable solutions, where one cable is designed specifically for a pair of devices, was one of the main motives that made competing companies join the project [2]. Furthermore, with all these companies adopting this technology, consumers would be assured a broader range of compatible products.

Hence, the motivation of this thesis is such: to show that Bluetooth as a cable replacement solution of the current technology trends. This is to be accomplished by successfully demonstration of this thesis, thus proving the capability of Bluetooth technology as a cable replacement solution.

1.4

Overview of Thesis

As mention in the earlier section, the wireless communication of the Bluetooth motion detector will be done using the Ericsson ROK 101007 module with the laptops. The Ericsson ROK 101007 is a short-range module for implementing Bluetooth functionality into various devices. The module also supports all Bluetooth profiles. There will be a Graphic User Interface (GUI) implemented on the User Laptop and protocol written to let the user configure the motion detector sensitivity and range. While the motion detector will be connected to the other Laptop via the serial port using the RS-232 cable. The application running on the microprocessor (ATMEL) in the motion detector gets the data from the Serial Port and then changes the settings on the motion detector. Figure 2 below shows the overview of this thesis.

Chua Hun Seng s38042580

13

Home Security System with Bluetooth Technology

USB

Serial US Ericsso n Bluetoo

Ericsso n Bluetoo

Motion Detector With Alarm

Figure 2: Overview of Bluetooth Motion Detector


This prototype removes the Bluetooth Stack from the microprocessor (ATMEL) and moves it to the Laptop. The configuration is then fed from the Laptop to the motion detector over the serial port. The prototype Bluetooth motion detector will be discuss in more detail in chapter 4 in the implementation of hardware section.

Chua Hun Seng s38042580

14

Home Security System with Bluetooth Technology

Chapter Two Literature Review


Below are some of the reading and research done on this project. They provide an important source of information for this new technology. Furthermore they contains information on the in-depth understanding of the Bluetooth technology and also painstakingly explained how each of various levels of protocols interface with each other. This work would not be possible without adequate research being done on the following material.

The Official Bluetooth SIG Website, Specifications of the Bluetooth System, Core, version 1.1B, 2000. http://www.bluetooth.com/developer/specification/specification.asp (current April. 20, 2001)

This specification is a newer version but is a revision of the previous version (Bluetooth System Core, version 1.0). This de-facto standard describes the core specifications for the Bluetooth system. It covers specific component details of Radio, Baseband, Link Manager Protocol (LMP), Transport Layer, Logical Link Control and Adaptation Protocol (L2CAP), Service Discovery Protocol (SDP), and last but not least the interoperability with different communication protocols. Some of the revisions are the Radio Specification whereby comments are added on power control step size. The Baseband Specification whereby the Link Monitoring chapter is removed and the Link Manager Protocol where there is a major changes since initiator of pairing procedure does not have to be the master etc. This reference is important in providing me with invaluable information on my thesis.

The Official Bluetooth SIG Website, Specifications of the Bluetooth System, Profiles, version 1.1B, 2000. http://www.bluetooth.com/developer/specification/specification.asp (current April. 20, 2001)

Chua Hun Seng s38042580

15

Home Security System with Bluetooth Technology

This specification is a revision of the previous version (Bluetooth System Profiles, version 1.0B). This de-facto standard specifies the protocols and procedures required for the various types of Bluetooth applications. Some of the revisions are the Serial Port Profile whereby details on application are added. Furthermore the Headset Profile is updated and the PSM is removed for the RFCOMM and for the LAN, the security section is removed. There is more revision and they are mention in the Appendix. This document is very useful to me as it contains example of Link establishment. Moreover it also discussed on the LMP which is responsible for authentication of devices.

ZDNet UK, ZDNet UK News Bluetooth Special Report Website, http://www.zdnet.co.uk/news/specials/1999/04/bluetooth/ (current April. 20, 2001)

This website give the latest up-to-date information regarding the Bluetooth development. It also updates and reviews on the new product release; development kits and is a source for technical papers. It is also a website where a lot of comments were made on the Bluetooth System. This website serve as the central news depository for me as it aids me on keeping track on any ground breaking event regarding the Bluetooth industry. G. Held, Data Over Wireless Networks BluetoothTM, WAP, and Wireless LANS, McGraw-Hill, United States of America, 2001.

This book discussed on both current and emerging wireless technologies such as BluetoothTM. It also covers on the system architecture, Master-Slave relationship, Interface support and Protocol Stack, which is invaluable information to me. It also briefly explained about The Scatternet whereby two piconets with overlapping area of wireless coverage, can communicate with one another via TDM.

N.J. Muller, Bluetooth Demystified, McGraw-Hill, United States of America, 2001.

This book is written to provides information on Bluetooth Operations and also introduce the various application and network configuration of Bluetooth. It also does comparison

Chua Hun Seng s38042580

16

Home Security System with Bluetooth Technology

with the other wireless technologies with Bluetooth. This book also provides details on the operation of the Link Managers, Protocols, Radio, Transport Interfaces, Audio and Low-Power mode. This information is helpful as it provide me with a better understanding of the Bluetooth System.

J.C. Haartsen, "The Bluetooth Radio System", IEEE Personal Communications, Vol.7, No.1, Feb. 2000, pp. 28-36. This journal article compares the BluetoothTM radio system against the existing wireless standards available, such as the IEEE 802.11. It describes the important features of interference immunity, selection of connectivity using Frequency hopping-Code division multiple access (FH-CDMA). This article argues that Frequency Hopping (FH) is the superior option in ah hoc radio network as compare to Direct Sequencing (DS). This article serves as important guides as it discuss on the difficulties in implementation, which prove to be very useful to me.

S. Diehl, Constructing a Bluetooth Solution, Portable-Design, Vol. 6, No. 2, Feb. 2000, pp. 20-27.

This journal article listed the various interested companies involved in the promotion of the Bluetooth technology. It explains how Bluetooth got its name. It also briefly describes all the different modules that make up of the Bluetooth chip. This article gives me a general knowledge of what are the hardware and software involved in producing the Bluetooth chip.

R. Mettala et al., Bluetooth PC Card Transport Layer, version 1.0, Bluetooth White Paper 1.C.123/1.0, Nokia Mobile Phones, 1999. http://www.bluetooth.com/developer/whitepaper/whitepaper.asp (current April. 20, 2001)

This paper gives an excellent introduction of the Bluetooth PC Card Transport Layer and specified the standardized interfaces for the USB, RS232 (serial cable) and UART. It also describes the general functionality of the communication between the PC card and the host. The requirement for the SW component incorporate with the Bluetooth PC
Chua Hun Seng s38042580 17

Home Security System with Bluetooth Technology

card is also mention in this paper. This paper provided me with invaluable information, which I would need on the interfacing of either RS232 or PC card of the transport layer with the Bluetooth SW protocol stack. This will be critical guide for my thesis.

Advanced Detection Systems, Inc http://www.adssecurity.com (current April. 20, 2001)

This website give a good discussion on the limitation of wire and wireless security systems. It argued that throughout the whole industry wired systems are considered to be more reliable than wireless devices. It also gives some of the limitation face in wireless security systems. An example of which is the battery failure whereby the alarm sensor will not work if the batteries are dead and there is the new supervised wireless devices that can warn the owners before the battery gone flat. This website highlight some of the problems with wireless security systems which I need to considered when designing my security system.

Home Automation System,Inc. (800) SMART-HOME.COM http://www.smarthome.com (current April. 20, 2001)

This website provide me with up-to-date information and introduce some of the latest product on home security systems. Much of the home security system product is available in the market and is advertised on this website. Some example of product advertised is wireless transmitter, receiver and keypad. Furthermore this website also provided free online catalog of their product which saves me time and effort. This website serves as important information center and it aids me on which products would be most suitable to be use in my thesis.

Chua Hun Seng s38042580

18

Home Security System with Bluetooth Technology

Chapter Three Background Theory of Thesis


After much reviewing of the literature from the books and papers introduce in the last chapter, large amount of information were gathers on the Bluetooth technology. The Bluetooth Profiles will be discussed in detail in this chapter and special emphasis is given to the Serial Port Profile (SPP), as this profile is essential for implementation in this thesis.

3.1

The Bluetooth Profiles

Bluetooth defines device Profiles to document how specific types of devices should operate. These Profiles are intended to promote interoperability. If devices from different manufacturers conform to the same Bluetooth SIG profile specification, the can expect to interoperate when used for that particular service and usage case [6]. This mechanism allows simpler devices to implement only those features necessary for their intended application

A profiles defines the specific messages and procedures used to implement a feature [6]. It dictates exactly which features and capabilities each type of device will support to ensure interoperability. All defined features are process-mandatory, meaning that if a feature is implemented, it must be implemented in a specified manner [6]. So as to ensure that the device will work the same way regardless where it is manufacture.

There are four different types of general profiles used by each various usage models. They are namely the Generic Access Profiles (GAP), the Serial Port Profiles (SPP), the Service Discovery Application Profiles (SDAP), and the Generic Object Exchange Profiles (GOEP). However do take note that the number of profiles is expected to grow over time, but for this thesis we will just discuss on these profiles. In this chapter, the Serial Port Profiles (SPP) will be emphasis more as this thesis is implemented on this profile. Before proceeding further, brief introductions of the various profiles name earlier.
Chua Hun Seng s38042580 19

Home Security System with Bluetooth Technology

Generic Access Profile


GAP defines how two Bluetooth units discover and establish a connection with each other. GAP handles discovery and establishment between units that are unconnected. The profile defines operations that are generic and can be used by profiles referring to GAP and by devices implementing multiple profiles. GAP ensures that any two Bluetooth units, regardless of manufacturer and application, can exchange information via Bluetooth in order to discover what type of applications the units support. Bluetooth units not conforming to any other Bluetooth profile must conform to GAP to ensure basic interoperability and co-existence. It also handles security. Figure 3 below show the relationship of the GAP with the other Bluetooth profiles.

Figure 3: The Bluetooth Profiles

Serial Port Profile


The Serial Port Profile defines how to set-up virtual serial ports on two devices and connecting these with Bluetooth. Using this profile provides the Bluetooth units with an emulation of a serial cable using RS232 control signaling (RS232 is a common interface standard for data communications equipment; it is the standard used on the serial port of an ordinary PC). This profile ensures that data rates up to 128 kbit/sec. can be used. The Serial Port Profile is dependent on the GAP, i.e. just as SDAP, Serial Port Profile reuses parts of the GAP.

Chua Hun Seng s38042580

20

Home Security System with Bluetooth Technology

Service Discovery Application Profile


SDAP defines the investigation of services available to a Bluetooth unit. This profile handles the search for known and specific services as well as a general service search. SDAP involves an application, the Service Discovery User Application, which is required in a Bluetooth unit for locating services. This application interfaces the Service Discovery Protocol that sends and receives service inquiries to and from other Bluetooth units. Hence, SDAP describes an application that interfaces with a specific Bluetooth protocol to take full advantage of it for the direct benefit of the end-user. The SDAP is dependent on the GAP, i.e. SDAP re-uses parts of the GAP.

Generic Object Exchange Profile


GOEP defines the set of protocols and procedures to be used by applications handling object exchanges. Several usage models are based on this profile, e.g. File Transfer and Synchronization. Typical Bluetooth units using this profile are notebook PCs, PDAs, mobile phones and smart phones. Applications using the GOEP assume that links and channels are established, as defined by the GAP. The GOEP describes the procedure for pushing data from one Bluetooth unit to another. The profile also describes how to pull data between units. The GOEP is dependent on the Serial Port Profile. The OBEX-standard is used.

3.2

Serial Port Profiles

The Serial Port Profile, or SPP, is a transport protocol profile that defines the fundamental operations necessary to established RFCOMM communications between two peer devices [7]. Another explanation is that this profile defines how to setup virtual serial ports on two devices and connecting these with Bluetooth. Figure 4 below shows the protocol model that emulates serial cable connection.

Chua Hun Seng s38042580

21

Home Security System with Bluetooth Technology

Figure 4: The Serial Port Profile Protocol Model

The user data is being transmitted through using the RFCOMM. Application running on either device will use the virtual serial port as if a physical serial cable, with RS-232 control signaling, were connecting the two device [6]. Therefore the application running on both device would expect the communication between them to occur over the SPP, which emulate a serial cable connection. Since both applications is not aware of Bluetooth procedures for setting up the virtual cable link, some assistance is needed from the application to help it to utilize the Bluetooth specification on both side of the link. The Bluetooth specification does not address the requirements of helper applications because the overriding concern of the Bluetooth SIG is with interoperability [6]. Therefore, the application to help the devices to communicate with each other has to be implemented in this thesis.

This profile ensures that data rate up to 128 Kbit/sec can be used. Furthermore the Serial Port Profile is dependent on the Generic Access Profile (GAP) because it is built upon it. Serial Port Profile reuse part of the GAP.

For a typical serial port configuration, two notebook/computers are connected using the emulated serial cable as shown below in Figure 5.

Chua Hun Seng s38042580

22

Home Security System with Bluetooth Technology

Figure 5: Serial Port profile, example with two notebooks.

The SPP does not define a specific role for master or slave between the devices. It does not matter which devices is the master or the slave. In fact one device will take the initiative and initiates with the other device for a serial communication link. The device targeted for the connection is known as the acceptor. The SPP outlines the necessary steps to establish an RFCOMM emulated serial port connection. These steps are illustrated in Figure 6 below.

SDP query for sever channel number SDP response with sever chanel number (Authentication if necessary) Established L2CAP connection. Establish RFCOMM connection on server channel

Figure 6: Steps taken to establish connection

The establishment or setup of the virtual serial connection is examined in more detail in the later section. After the procedure outlined in the SPP is completed, the wireless link connection would be completed instead of a physical cable being used. This connection without the used of a cable is transparent to the application, as the function described by the SPP is what that is needed to replaced a wired connection with a wireless one. Some form of security such as the devices might require some degree of authentication or perhaps some encryption, prior to establishing a connection between them. The SPP
Chua Hun Seng s38042580 23

Home Security System with Bluetooth Technology

specifies that these security considerations are optional, because the SPP is a generic profile upon which others are built [7]. However if the use of security features is implemented, the two devices will be paired together during the connection establishment phase.

3.2.1 Application Layer

The Bluetooth specification described three application-level of procedures that are required for establishing a virtual serial cable connection between two devices.

3.2.2 Establish Link/Setup Virtual Serial Connection

This procedure describes the step taken to setup a connection with an emulated serial port of a remote device. 1. Using the Service Discovery Protocol (SDP) to submit a query to determine the RFCOMM server channel number of the application in the remote device. User can select from the available ports in the peer device, if browsing capability is included in the application. 2. It may be necessary for the remote device to authenticate itself. As an option, it may require encryption be enabled. 3. 4. 5. A request for a new L2CAP channel to the remote RFCOMM entity. Initiates an RFCOMM session on the L2CAP channel. A new data link connection is started on the RFCOMM session using the server channel number given by remote device, mentioned in step 1.

After this procedure is completed, the establishment of the emulated serial cable connection is ready to be use by the applications on both devices. However if an RFCOMM session already exist between the devices when the establishing of a new connection, then the new connection would be connected on the existing RFCOMM session. Therefore step 3 and 4 would not be necessary.

3.2.3 Accept Link/Establish Virtual Serial Connection

For this procedure, the Acceptor would have to be involved in the following steps:
Chua Hun Seng s38042580 24

Home Security System with Bluetooth Technology

1. Authentication must be provided if requested, and upon further request, encryption have to be turn on. 2. It will have to accept a new channel connection indicated by the L2CAP. 3. It will accept an RFCOMM session establishment on that particular channel. 4. It will accept a new data link connection on the RFCOMM session.

When the user requesting the virtual serial port wants security, and the procedures have already been carried out, a local request may be trigger to authenticate the remote device to turn on the encryption at the last step.

3.2.4 Register Service Record in Local SDP Database

All services/applications reachable through RFCOMM must have a SDP service record that includes the parameters necessary to reach the corresponding service/application [6]. Therefore a Service Database is needed with the ability to respond to SDP queries. In order to support the application running on the emulated serial ports, service registration is with the help of a helper application, which are normally provided by vendors. This helper application will assist the user in setting up the port.

3.3

Power Mode and Link Loss Handling

Devices that are connected by the emulated serial port may have different power requirement, therefore there is no requirement under SPP that power saving mode be used. But if requested to use low-power mode, it will not be denied. Therefore if any of the sniff, park, or hold mode is used, both the RFCOMM data-link connection and the L2CAP channel will not be released. When the device detect link loss, the RFCOMM will be considered shut down. The initialization procedure of the RFCOMM session will have to be performed before communication at higher layer can resume.

Chua Hun Seng s38042580

25

Home Security System with Bluetooth Technology

3.4

RS-232 Control Signal

For a wired-based serial port connection, a flow control is needed to be implement between the devices. This can be done either through software control using characters such as Transmitter On/Transmitter Off (XON/XOFF) or signals such as Request to Send /Clear to Send (RTS/CTS) or Data Terminal Ready /Data Set Ready (DTR/DSR) [6]. This method can be use for either side or just a single direction of a wired link. RFCOMM also provides two flow control mechanisms. The first flow control mechanism that is being examined is the Modem Status Command (MSC). The MSC conveys the RS-232 control signals and break signal for all virtual serial ports. Furthermore, this flow control mechanism operates on an individual data link connections. According to the RFCOMM protocol, all devices are required to send information on all changes in RS-232 control signals with the Modem Status Command. Another flow control mechanism is the RFCOMM protocol own Flow Control On/ Flow control Off (FCON/FCOFF). They operate at the aggregate data flow between two devices [6]. For the next section, the two commands that are used for relaying information between devices are discussed.

3.4.1

Remote Line Status Indication

It is required to inform the other device of any changes in RS-232 line status with the Remote Line Status indication command, if the local device relays information from a physical serial port (or equivalent) where overrun-, parity- or framing-errors may occur.

3.4.2

Remote Port Negotiation

The relaying of RS-232 port setting between devices is done with Remote Port Negotiation command directly before data-link connection. There is a requirement to do so if the API to the RFCOMM adaptation layer exposes those settings (e.g. baud rate, parity). Information conveyed in the Remote Port Negotiation procedure is useful for devices with a physical serial port, or when data pacing is done at an emulated serial interface for any reason [6].

Chua Hun Seng s38042580

26

Home Security System with Bluetooth Technology

3.5

L2CAP Interoperability Requirement

The following section will defines the mandatory requirements with regards to this profile.

3.5.1 Channel Types

In this profile, only connection-oriented channels shall be used. This implies that broadcasts will not be used in this profile. Although connectionless channels are not used within the execution of this profile, concurrent use of both channel types by other profiles and applications is allowed [6].

3.5.2 Signaling

Only the Initiator may issue an L2CAP Connection Request within the execution of this profile. Other than that, the Serial Port Profile does not impose any additional restrictions or requirements on L2CAP signaling [6].

3.5.3 Configuration Options

There are three types of configuration options available for the L2CAP in the SPP. They are as follows: Maximum Transmission Unit (MTU): This profile does not impose any restrictions on MTU sizes over the restrictions stated in the L2CAP spec. The L2CAP implementations must support a minimum MTU size of 48 bytes and the default values is 672 bytes. However the MTU is set as large as possible for efficient use of the communication. This is done with respecting to the physical constraints imposed by the devices involved. And also the devices honoring any previously agreed upon Quality of Service (QoS) commitments with other devices and /or applications [6].

Flush Timeout: Serial Port data is carried over a reliable L2CAP channel. The flush timeout value shall be set to its default value 0xffff. This option is use to inform the recipient of the amount of time the originators link controller/ link manager will

Chua Hun Seng s38042580

27

Home Security System with Bluetooth Technology

attempt to successfully transmit an L2CAP segment before giving up and flushing the packet [6].

Quality of Service (QoS): Negotiation of Quality of Service is optional in this profile. If any QoS configuration is implemented, then a QoS configuration request must be sent, specifying such performance parameters as delay variation (microseconds), peak bandwidth (byte /second), and latency (microseconds). Best effort service will be assumed when no QoS option is requested.

3.6

SDP Interoperability Requirement

There are no SDP Service Records related to the Serial Port Profile in local device (Initiator). To retrieve the service records in support of this profile, the SDP client entity in the Initiator connects and interacts with the SDP server entity in the remote device (Acceptor) via the SDP and L2CAP procedures [6].

3.7

Link Manager Interoperability Requirement

In addition to the requirements on supported procedures stated in the Link Manager specification itself, this profile also requires support for Encryption both the local device (Initiator) and the remote device (Acceptor).

3.7.1 LM Error Behaviour

If a unit tries to use a mandatory feature, and the other unit replies that it is not supported, the initiating unit shall send an LMP_detach with detach reason "unsupported LMP feature". A unit shall always be able to handle the rejection of the request for an optional feature [6].

3.7.2 Link Policy

There are no fixed master-slave roles for the execution of this profile. This profile does not state any requirements on which low-power modes to use, or when to use them.

Chua Hun Seng s38042580

28

Home Security System with Bluetooth Technology

That is up to the Link Manager of each device to decide and request as seen appropriate, within the limitations of the latency requirement.

3.8

Link Controller Interoperability Requirement

The Link Control (LC) level defines several capabilities, including inquiry, inquiry scan, paging, and error behavior

3.8.1 Inquiry

When inquiry is invoked in local device (Acceptor) it shall use the General Inquiry procedure, seen in the Generic Access Profile (GAP) profile. Only Acceptor may inquire within the execution of this profile.

3.8.2 Inquiry Scan

For inquiry scan, (at least) the Generic Inquiry Access Code (GIAC) shall be used, according to one of the discoverable modes defines in GAP. That is, it is allowed to only use the limited discoverable mode, if appropriate for the application(s) residing in the remote device (Acceptor). In the Acceptor INQUIRY RESPONSE messages, the Class of Device field will not contain any hint as to whether Acceptor is engaged in the execution of the Serial Port Profile or not. (This is due to the fact the generalized Serial Port service for legacy applications delivered by this profile does not fit within any of the major Service Class bits in the Class Of Device field definition.)

3.8.3 Paging

Only the local device (Initiator) may page within the execution of this profile. The paging step will be skipped in Acceptor when execution of this profile begins when there already is a baseband connection between the Initiator and Acceptor. (In such a case the connection may have been set up as a result of previous paging by the remote device.)
Chua Hun Seng s38042580 29

Home Security System with Bluetooth Technology

3.8.4 Error Behaviour

Since most features on the LC level have to be activated by LMP procedures, errors will mostly be caught at that layer [6]. However, there are some LC procedures that are independent of the LMP layer, e.g. inquiry or paging. Misuse of such features is difficult or sometimes impossible to detect. There is no mechanism defined to detect or prevent such improper use.

Chua Hun Seng s38042580

30

Home Security System with Bluetooth Technology

Chapter Four Overview of Bluetooth Motion Detector


After reviewing through the relevant theory for this thesis, a breakdown of the project specifications is done. The project mainly consists two integral parts. They are the Hardware Module and the Software Module. The overview of this chapter will discuss on the application; assumption and design decisions that were made to fulfill the objective for this thesis.

Let us be reminded that the focus the thesis is on the motion detector, as the title might suggest otherwise. The scope of this project is to produce a microprocessor controlled motion detector connected to a laptop via a serial cable, which enable a remote laptop to control the sensitivity and the range of the motion detector. The mode of communication between the two laptops uses the Bluetooth wireless technology. Let us discourse for a while and explain what is basic capability of a Home Security System motion detector.

4.1

Home Security System

Basically, a home security system is to protect one property from intruders. We can categorize it in to two parts. They are the exterior sensors and the interior sensors. The sensors should perform one of the three functions: (1) Detection of an intruder approaching or penetrating a secured boundary, such as a door, wall, roof, floor, vent or window. (2) Detection of an intruder moving within a secured area, such as a room or hallway. (3) Detection of an intruder moving, lifting, or touching a particular object.

The interior sensors are also susceptible to false and nuisance alarms, however not to the extent of their exterior counterparts. This is due to the more controlled nature of the environment in which the sensors are employed.

Chua Hun Seng s38042580

31

Home Security System with Bluetooth Technology

4.2

Hardware Overview

In order to fulfil the aim of this thesis, it is necessary to derive the hardware architecture design based on the understanding of the Bluetooth technology. To begin, the basic design module of the hardware is shown in Fig 7 below.

In terface F or E xtern al Alarm

RAM

M otio n D etecto r C ircuit

CPU ATM E L T90S

EEPROM/ F lash

P o w er S u p plies

Figure 7: Block Diagram for Hardware

The Principle hardware modules for this thesis are the STK200 Flash MCU Starter Kit and the motion detector circuit. The breakdown of the Hardware components from these two modules is listed in Table 1 below. The motion detector circuit is presented in greater details, as it is critical portion of the thesis.

Hardware Module

Breakdown of Component Listing AT90S8515 Microcontoller 10-way (interface to 25 pins Male serial connector) ISP Ribbon Cable Power Supply: AC (7-12V) or DC (9-15V) Various onboard components

1. STK 200 Evaluation Board

2. Motion Detector Circuit Board

Capacitors are: 1 x 0.1uF

Chua Hun Seng s38042580

32

Home Security System with Bluetooth Technology

1 x 0.01uF 1 x 33uF Resistors are: 1 x 2.4M 1 x 2.7M 1 x 5K 1 x 36K 1 x 3.6K 1 x 1.0M potentiometer 1 x LED 2 x 4 Header 1 x SW SPDT 1 x SW SPST 1 x (74LS04) 1 x HITACHI CMOS Static RAM (62256) 1 x MAX232 Level Shifter 1 x ATMEL 90S8515 Microcontroller 1 x D-Type Transparent Latch (74LS373) 1 x LS6502LP 1 x PIR (LHI-958) 1 x FLASH 1 x 7905 1 x 8Mhz 1 x AD7847 1 x RS-232 Cable

Table 1: List of Hardware Components

Chua Hun Seng s38042580

33

Home Security System with Bluetooth Technology

4.3

Design Requirements

This section describes the design requirements that were made by the author of this thesis.

4.3.1 Power Requirements

A 9 V battery will be used for the motion detector with an estimated life of 9 months to 1 year. Another consideration is that the product has to consume the least power possible to conserve and enhance the battery life.

4.3.2 Processor Requirements

The product will use a low power ATMEL AT90S8515 CMOS 8bit microcontroller. The AT90S8515 microcontroller achieves throughputs approaching 1 MIPS per MHz allowing the system designer to optimize power consumption versus processing speed. Figure 8 below show a block diagram of the AT90S8515.
Some of the features of the AT90S8515 are: 8k Bytes of In-System Programmable Flash 512 Bytes of SRAM and In-System Programmable EEPROM Master/Slave SPI Serial Interface Low-power, High-speed CMOS Process Technology Power Consumption at 4MHZ, 3V Active: 3.0 mA Idle Mode: 1.0 mA Power Down Mode: <1 A

32 Programmable I/O Lines Operating Voltages 4.0 6.0

Chua Hun Seng s38042580

34

Home Security System with Bluetooth Technology

Speed Grades 8 MHz

Figure 8: Block Diagram of the AT90S8515

4.3.3 Wireless Tuning Requirements

The wireless tuning of the motion detector has been discussed and agreed with the thesis supervisor, Dr Adam Postula that the Bluetooth Stack will not be embedded into the microcontroller. Therefore the wireless tuning of the motion detector will be done with the Bluetooth Stack residing on a laptop and communicates with the motion detector via the serial link (RS-232 serial cable between the motion detector and the laptop). The setting is get from the remote laptop over the Bluetooth communication and then send over via the serial cable to the motion detector.

Chua Hun Seng s38042580

35

Home Security System with Bluetooth Technology

4.3.4

Security Requirements

The sensor for the motion detector is the LHi-958 pyroelectri (PIR) sensor. It is an infrared detector for passive infrared intrusion alarms and motion detector. The features of the Lhi-958 are given in the table below.

Lhi-958 Responsivity [Kv/W] Noise [Vpp] Offset [V]

Min 2,7 15 0,2

Typical 3,5 30 0,8

Max

Remark

40 1,5

Room temperature Operation voltage,47k load

Spectral Range

5,5.14um

Similar radiation

to

human

Encapsulation

T-5

Hermetically sealed

Table 2: Features of Lhi-958 PIR Sensor

The pyroelectric materials produce a charge transfer when they undergo a change in thermal energy. This effect is applied for detectors that show an output signal similar to alternating current with a charge in the infrared radiation. The uses of these sensors are in movement detectors, passive infrared alarms and automatic light switches.

Figure 9 shows the typical connection the PIR sensor. The amplifier is a typical bandwidth limited to about 1Hz to reject high frequency noise. The comparator responds to both positive and negative transitions of the sensor output signal.

Chua Hun Seng s38042580

36

Home Security System with Bluetooth Technology

Figure 9: Typical Configuration of PIR Sensor

4.3.5 PIR Motion Detector

The LS6501LP has been chosen as the integrated circuit for the PIR sensor. This LS6501LP is a monolithic CMOS Silicon Gate integrated circuit, which is show in Figure 10. There is a two stage Differential Amplifier that we can set to our own amplification and bandwidth. It also have a single pulse or dual pulse (two pulse occurring within a specific time period) at the digital filter output and can be selected as the trigger for the output duration time. Thus setting the sensitivity of the PIR sensors. Some of the features of the LS6501LP are given below.

Figure 10: Top view of LS6501LP

Features:

Low Quiescent Current


37

Chua Hun Seng s38042580

Home Security System with Bluetooth Technology

Direct Interface with PIR Sensor Two-Stage Differential Amplifier Amplifier Gain and Bandwidth externally controlled Window Comparator and Digital Filter limit Noise Triac or Relay Output Drive Programmable Out Drive Single or Dual Pulse Detection Regulated 5V Output for PIR Sensor.

4.4

The work remaining to be done

As of now, the hardware of the motion detector is almost finalize. This delay is due to much effort been put into the implementation if the Bluetooth software application. Hopefully I am able to send my hardware for PCB fabrication and able to get it backs before the Expo. The pseudo code for the ATMEL AT90S8515 has yet to be working, Due to some error and the need for debugging. The present aim for the hardware module implementation is to be able to fabricate the motion detector PCB and show it on the Expo day.

The schematic of this motion detector circuit module is attached in Appendix A of this document.

Chua Hun Seng s38042580

38

Home Security System with Bluetooth Technology

Chapter Five Software Module


Having Discuss the hardware module required for this thesis in the earlier chapter, we would now be examining the software module implementation of this project. Before going any further, the figure below shows the overall software architecture of the thesis.

Motion Detector tuning application Power Manage ment

Bluetooth stack

Software interfaces for the motion detector

Figure 11: Software Architecture

The application software of the thesis is created using the Widcomm Bluetooth for Windows Software Development Kit. The reason to choose the Widcomm rather than the Ericsson Bluetooth kit is because the Widcomm stack has a better API and also has a tool to trace the events. The Ericsson stack is good in an Embedded Environment but the PC support is not good. Furthermore the tools needed for tracing any issues on the Ericsson stack are non-existent. The application source code for the Widcomm stack and the step-by-step operation of the Configurator is easier to understand.

This chapter describes Widcomm Bluetooth for Windows Software Development Kit (SDK) and the application software created to perform the require activity to fulfill the objective of this thesis. The SDK supports developers of custom Bluetooth applications with protocol-layer direct access to: L2CAP RFCOMM Service Discovery Protocol (SDP) Serial Port Profile (SPP)
Chua Hun Seng s38042580 39

Home Security System with Bluetooth Technology

The SDK consists of: A Dynamic Link Library (DLL) C++ header files. Source files for sample applications. The operational context for the SDK is standard Bluetooth PC platform on which Widcomm Bluetooth for Windows has been installed. Functionally, the SDK presents a C++ interface to the Inquiry and Discovery functions of the SDP layer. SDK functions allow access to the discovery database and to the attribute values contained there. The custom application can add to and delete from the SDP service database. This chapter also describes the C++ classes provided for all detailed functions for the SDP, L2CAP and RFCOMM layers. The Figure below shows an over view of the SDK in the Windows Bluetooth context.

Figure 12: Block Diagram/Overview of the Bluetooth for Windows SDK

Chua Hun Seng s38042580

40

Home Security System with Bluetooth Technology

5.1

The Bluetooth Protocol Stack

The following are the Stack that contains the higher layers of the Bluetooth protocol stack and compliant with the Bluetooth specification:

1. 2. 3. 4.

Radio Frequency Communication (RFCOMM) Service Discovery Protocol (SDP) Logical Link Control and Adaptation Protocol (L2CAP) Host Controller Interface (HCI) Driver

RFCOMM This is a transport protocol, with additional provisions for emulating RS-232 serial ports. The RFCOMM-protocol supports up to 60 simultaneous connections between two BT devices. For the purpose of RFCOMM, a complete communication path involves two applications running on different devices with a communication segment between them. RFCOMM is able to transmit/receive data packets of up to 32KB over such link. The term application means other tings than end-user application, e.g. higher layer protocols or other services acting on behalf of end-user applications.

Service Discovery Protocol SDP Discovery of services is a crucial part of the Bluetooth framework. Service discovery is fundamental for all the usage models. The SDP provides a means for applications to discover which services are available and to determine the characteristics of those available services using an existing L2CAP connection. After that, an appropriate separate connection between two or more Bluetooth device can be established using information obtained via SDP. The service discovery application does not make use of SDP as a means of accessing a service, but rather as a means of informing the user of a Local Device the services that are available to his/her devices by (and possibly via) Remote Devices.

Chua Hun Seng s38042580

41

Home Security System with Bluetooth Technology

L2CAP Logical Link Control and Adaptation Protocol provides connectionoriented and connectionless data services to upper layer protocols with protocol multiplexing capability, segmentation and reassemble operation, and group abstractions. L2CAP permits higher level protocols and applications to transmit and receive L2CAP data packets up to 64K KB in length.

Host Controller Interface (HCI) The HCI interface establishes the communication between the Stack and the HCI Firmware in the Bluetooth hardware connected to the equipment running the Stack. The HCI Interface ensures that the Stack can run over a generic hardware. The BLUETOOTH SIG standardizes the HCI interface. The HCI driver is split into a Generic Component (GC) and an Environment Dependent Component (EDC).

5.2

Implementation of Software

The SDK consists of a DLL, a library file and two header files. The library file WidcommSdk.dll should be place in a directory that is in the DLL search path, typically the working directory for the executable or the Windows system directory, while the applications should be linked with the library file name WidcommSdk.lib. Lastly, the two header files are:

BtIfDefinitions.h that defines constants and structures used by the SDK and applications BtIfClasses.h that define the classes offered by the SDK.

Table 3 below shows the Classes offered in the SDK. Note that some of the classes is not being used in the implementation of the application software. Those classes such as CoppClient, ClapClient and Cftpclient is not needed in the interface of the software.

Chua Hun Seng s38042580

42

Home Security System with Bluetooth Technology

Table 3: Classes Offered in the SDK

The SDK classes provide virtual functions, where appropriate, for applications to react to Bluetooth protocol events. For example, an application requiring an RFCOMM connection defines an application class that is derived from the CrfcommPort base class. The derived class defines derived functions that substitute for the virtual functions in CrfcommPort. The OnDataReceived() function is called to passed an incoming data packet to the application while the OnEventReceived() function is called when a significant event is detected, such as a connect or disconnect.

5.3

Use of GUID to Represent UUID

The Bluetooth specification defines the UUID values for service attributes, service classes, and protocols. These are all 16-byte fields, for which the last 12 bytes have the same value, the Bluetooth base UUID, represented in hex bytes as 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0XFB. In order to save storage space and transmission bandwidth, abbreviated versions (2-byte or 4-byte format) are used, where possible, at the lower stack layers and for over-the-air transmissions.

Chua Hun Seng s38042580

43

Home Security System with Bluetooth Technology

However, at the application level, the full 16-byte version is used. The SDK provides 16-byte definitions for the supported standard UUIDs. If an application defines a new service, a new 16-byte UUID have to be generated outside the SDK. The new value may then be passed to the SDK functions on the new applications server and client sides to establish a connection based on the new service. In the Microsoft Visual Studio systems, it provided a utility program, guidgen.exe, to generate unique GUID values. The program can be executed form the Windows Explorer. It offers a choice of formats for the generated GUID, which can then be cut and pasted into the application. An example is shown below.

//{CE37CA6E-288A-409a-9796-191882EE44FC} static GUID <<name>>= {0xce37ca6e, 0x288a, 0x409a, {0x97, 0x96, 0x19, 0x18, 0x82, 0xee, 0x44, 0xfc } }; This can be cut and pasted from the guidgen.exe output window. Just substitute the variable name for <<name>> The SDK implements 16-byte UUIDs as the Microsoft GUID data type. These two definitions are compatible because the Bluetooth base UUID was defined as a form of GUID value. The definition for class CbtIf, in the file CbtIfClasses.h, contains a list of standard GUID, with names guid_SERVCLASS_*>

As for non-Microsoft contexts, the GUID may be defined as a C or C++ structure. An example is given below: typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID;

Chua Hun Seng s38042580

44

Home Security System with Bluetooth Technology

5.4

The Use of Maximum Transmission Unit (MTU)

Bluetooth protocol layers such as L2CAP, RFCOMM, or OBEX have a default MTU value. The MUU sets an upper limit for a single packet at the Bluetooth protocol layer being used. When side A, say, sets an MTU value to side B, side A is saying it has an input buffer MTU bytes long. Therefore, side B must react by segmenting its transmissions if necessary so that a single packet is no longer larger than MTU bytes. The receiving side reconstructs the segmented packets into the original message size. This segmentation and reconstruction occurs below the application level. Applications can take the default or set a non-default value at connections setup time, or for L2CAP, also by supporting a Reconfigure command that can be sent after connection. One of the reason for setting a non-default MTU might be that the hardware platform has very limited memory.

5.5

Destructors for SDK CLASSES

The SDK classes have non-trivial destructors. This is to prevent the application from leaking memory when the application instantiate SDK classes or application classes derived from SDK classes.

5.6

Derived Function Run on Separate Threads

Operations performed in the Derived functions must be made thread-safe for the application. The term thread is short hand for a thread of execution, and it represents the most fundamental information a running program needs while it is executing: a usermode stack to hold temporary variables and return addresses for subroutines, a kernelmode stack to hold addresses for interrupt service returns, and a set of processor registers [8].

5.7

Examples of RFCOMM

The common steps for a typical client application:

Chua Hun Seng s38042580

45

Home Security System with Bluetooth Technology

1. Instantiate an object derived from CBtIf and provide CBtIf functions for the virtual functions. The derived class may be a simple extension of CBtIf or a dialog class derived from both CDialogg and CBtIf. 2. Use method CBtIf::StartInquiry() to obtain a list of devices in the Bluetooth neighborhood. 3. Use the derived method CBtIf::OnDeviceResponded() to build a list of responding devices. A derived method, CBtIf::OnInquiryComplete(), may optionally be used to determine when the inquiry process is complete. 4. Use CBtIf::StartDiscovery() to determine the services each device offers. 5. Call derived method CBtIf::OnDiscoveryComplete() when the discovery process is complete and then call CBtIf::ReadDiscoveryRecords() to obtain a list of the services. 6. Using application dependent criteria, select a server that provides the desired service. 7. Processing now depends on the protocol used by the service.

For RFCOMM: An object of class CRFCommIf is needed to establish a service channel number (SCN) and security settings. The SCN is obtained from the discovery record for the selected server. A connection is established with the server, using an application object derived from class CRfcommPort. CRfCommPort::OpenClient() begins the connection process. The derived OnEventReceived function informs the application that the connection is established. Processing is application dependent; data is sent using the CRfcommPort::Write() functions and the derived function CRfcommPort::OnDataReceived() is called when data is received. The connection remains open until the client calls CRfcommPort::Close(). The close can be initiated by the client or can be called in response to a CONNECT_ERR event from the server.

Chua Hun Seng s38042580

46

Home Security System with Bluetooth Technology

The common steps for a typical Server application:

1. Instantiate an object of class CRfCommIf and call function CRfCommIF:: AssignScnValue() to get an SCN assigned. 2. Instantiate an object of class CsdpService and call the functions

AddServiceClassIdList, AddServiceName, AddRFCommProtocolDescriptor, and MakePublicBrowseable to setup the service in the local Bluetooth device. 3. Call CRfCommIf::SetSecurityLevel(). 4. CRfCommIf::OpenServer starts the server, which then waits for a client to attempt a connection. The derived function CRfCommIf::OnEventReceived() is called when a connection is established. 5. Processing now depends on application logic. For RFCOMM: Data is sent using the CRfCommPort::Write() functions. The derived function CRfCommPort::OnDataReceived() is called to receive incoming data. The connection remains open until the server calls CRfCommPort::Close(). The close can be initiated by the server or can be called in response to a CONNECT_ERR event from the client.

The full listing of the Classes with attached descriptions, operation parameters and error message is provided at Appendix B of this document.

5.8

The Application

The application for the user is written in Microsoft Visual C++, which utilize the Microsoft Foundation Class (MFC) library. Visual C++ provides several AppWizards. This Microsofts Wizard technology allows us to create a project, including a project file, source code files, a resource script and a module definition file [8]. The AppWizard that was chosen for the project is the MFC AppWizard (exe). The reason for choosing this AppWizard is because, the Visual C++ s built-in AppWizard produces predefined code and makes it easier to begin writing an applications. When an application is generated with AppWizard, it produces code that implements an application around the options that have been requested.

Chua Hun Seng s38042580

47

Home Security System with Bluetooth Technology

5.8.1 Graphic User Interface (GUI)


When the client executed the program, it will display a GUI shown in the Figure below.

Figure 13: The Client GUI Application

The Client will have to click on the Connect to Motion Detector button and send an inquiry for the motion detector Server. When the motion detector device is found, the Client GUI will receive the address of the motion detector. The address of the motion detector device will appear in the text box as shown in Figure 13. The Client will then highlight the address and click on the ok button. This will allows the Client L2CAP to request a connection to the motion detector. If the request is successful, the RFCOMM will then create a wireless link between the two laptops. When the two laptops are connected, what will be shown on the Client and Server GUI is shown in Figure 14 and Figure 15.

Chua Hun Seng s38042580

48

Home Security System with Bluetooth Technology

Figure 14: Display of Client GUI when Connected

Figure 15: Display of Server GUI When Connected

Now that both the laptops (Client and Server) have been connected, the Client will receive the motion detector arm status with a textbox displaying Got Data from Mt Dt as shown in Figure 16.

Chua Hun Seng s38042580

49

Home Security System with Bluetooth Technology

Figure 16: Got Arm Status Display

Now that the Client has and got the initial data from the connected motion detector device, the Client is ready to armed or disarm the motion detector. If the Client choose to arm the motion detector, the client just have to click on the Armed button and click the set button. Both the Server and the Client will get a response, which is shown in Figure 17 and Figure 18. The Client GUI will display a text box configuring the Motion Detector.

Chua Hun Seng s38042580

50

Home Security System with Bluetooth Technology

Figure 17: Display of Client GUI Configuring

Figure 18: Display of Server GUI Configuring

As for disarming the motion detector, the disarming response of both Client and Server is the same. When the Client want to disconnect from the motion detector, the Client just have to click on the Disconnect from Motion Detector button. The display will show a textbox showing closed as shown in the figure below.
Chua Hun Seng s38042580 51

Home Security System with Bluetooth Technology

Figure 19 Client Display for Disconnection

Figure 20: Server Display for Disconnection

After the Client click on the ok button of the textbox, the Client GUI status bar will display that the motion detector has been disconnected as shown in Figure 21.

Chua Hun Seng s38042580

52

Home Security System with Bluetooth Technology

Figure 21: Client Display for Disconnection

The full listing of the Source codes for the implementation of this thesis project are provided in Appendix C.

Chua Hun Seng s38042580

53

Home Security System with Bluetooth Technology

Chapter Six Future Considerations


After examined through the pervious chapters on this thesis in detail, we now turn our attention to the future consideration of this thesis work. For this chapter, the further improvement of this thesis would be discussed. Furthermore we also explore the future Bluetooth products that will be marketed in the foreseeable future.

6.1

Further Improvement Consideration for Thesis Work

The future improvement on the Bluetooth motion detector should attempt to expand on what have already achieved. The basic communication aspects of the Bluetooth have been implemented. The future improvement should consider implementing a fully embedded Bluetooth motion detector so as to do away with the laptop which the motion detector is connected to by a serial cable. Another consideration may include the interfacing of the motion detector with the Handspring Visor. This will definitely improve the flexibility of the user using the motion detector.

6.2

Future Foreseeable Bluetooth Products

This section discusses on the ongoing development of Bluetooth technology and the kinds of products expected to appear in time. As of this instance, the work of the Special Interest Group (SIG), which consist of leading company (Ericsson, Intel, IBM, Nokia, Microsoft, Toshiba and Motorola) has not really stop. After the publishing of the initial specification, these SIG members have been busy developing new profiles for Bluetooth uses. One of the important investigations, which are currently done by Ericsson and Nokia, is the increasing of Bluetooth communication data rate. Many knowledgeable engineers believe that Bluetooth wireless communication can occur at higher speed [7]. One of the their consideration is the harmony of Bluetooth devices working with other devices operating at the 2.4 GHz spectrum. Issues such as interference and performance impact when multiple RF technologies are used in the same time and space has to be investigate [7].
Chua Hun Seng s38042580 54

Home Security System with Bluetooth Technology

As mention earlier, new profiles have been extensively been discussed between the members of the SIG. Although new profiles such as the Car Profile and Richer Audio/Video (AV) Profile have been created. But it has to be said that these new profiles are still in the discussion phase and no specific work is done to enable them.

As for this section, some of the Bluetooth products which is in the market and products expected to appear in time will be discuss. A quick way to introduce Bluetooth

technology into the market is to produce add-on components (e.g. PCMCIA cards) to existing products to enable them for Bluetooth wireless communication. The first PC or PCMCIA cards with the associated protocol stack software and drivers for popular PC platforms were announced in 2000, with some being demonstrated at the developers conferences [7]. Therefore it is possible for a customer to purchase this PC cards off the shelves and plug it into their PC an enable his/her PC to communicate with other Bluetooth devices. The advantage of this add-on component is that the user does not have to purchase a new computer.

Mobile phones and personal computers are the next significant end-user products to have Bluetooth technology integrated into them. As of now, customers are able to purchase mobile phones and headsets with Bluetooth technology to allowed them to link these devices with the used of physical cables. Due to the popularity of mobile phones, which resulted in high volume of manufacturing, the significant hardware cost can be decrease. Thus achieving a lower-cost of Bluetooth products.

Although the initial market of Bluetooth products is populated by mobile phones and computers, below are some of the product that are expected to seen in the market with Bluetooth technology incorporated into them. These products include the printers, digital cameras and automobiles. Furthermore with the active participation of the leading industries, devices with Bluetooth technology may expand to include televisions, stereos and other audiovisual devices, which are foreseeable in the near future.

It can be seen that Bluetooth technology definitely have the potential to expand. But first of all, it must be successful in introducing their products to the customer to enable positive perception and user experience for the users. Any rush development or
Chua Hun Seng s38042580 55

Home Security System with Bluetooth Technology

implementation of Bluetooth may result in bad solution for the consumers. Thus it could even destroy public opinion of its capabilities.

Chua Hun Seng s38042580

56

Home Security System with Bluetooth Technology

Chapter Seven Conclusion


As the society move towards the importance of the ease of connectivity of devices and the convenience of information access is highly prized. Despite its initial teething problems, there is a great potential in Bluetooth. Interoperatebility as well as producing low cost, low power cable replacement solution came as a result of the co-operative effort of the various consortiums of companies. It will be only a matter of time where Bluetooth products will be available anywhere in the market.

This thesis had also presented the relevant theory behind the technology and from whence, hardware and software modules that are requirement for implementation within the scope of the stated objectives are identified. However there is still some work to be done and hopefully the hardware module can be finalize and fabricated into PCB before the Expo.

Finally, consideration for further development on the Bluetooth motion detector as well as a forecast on the future of Bluetooth is provided. Thus this thesis concludes that the basic aim and objectives in the implementation of the Bluetooth communication link is fulfilled.

Chua Hun Seng s38042580

57

Home Security System with Bluetooth Technology

References
[1] J.C. Haartsen, "The Bluetooth Radio System", IEEE Personal Communications, Vol.7, No.1, Feb. 2000, pp. 28-36.

[2] S. Diehl, Constructing a Bluetooth Solution, Portable-Design, Vol. 6, No. 2, Feb. 2000, pp. 20-27.

[3] R. Mettala et al., Bluetooth Protocol Architecture, version 1.0, Bluetooth White Paper 1.C.120/1.0, Nokia Mobile Phones, 1999. http://www.bluetooth.com/developer/whitepaper/whitepaper.asp (current Aug. 02, 2001)

[4] R. Mettala et al., Bluetooth PC Card Transport Layer, version 1.0, Bluetooth White Paper 1.C.123/1.0, Nokia Mobile Phones, 1999. http://www.bluetooth.com/developer/whitepaper/whitepaper.asp (current Aug. 02, 2001) [5] G. Held, Data Over Wireless Networks BluetoothTM, WAP, and Wireless LANS, McGraw-Hill, United States of America, 2001.

[6] N.J. Muller, Bluetooth Demystified: Understandable Guide to Bluetooth Technology, McGraw-Hill, United States of America, 2001.

[7] B.A. Miller, C. Bisdikian, Bluetooth Revealed: The Insiders Guide To An Open Specification For Global Wireless Communications, Prentice Hall, Upper Saddle River, New Jersey, 2001.

[8] M.Blaszczak, Professional MFC with Visual C++ 6, Wrox Press Ltd, Birmingham, United Kingdom, 1999

[9] Telefonaktiebolaget LM Ericsson et al., Specification of the Bluetooth System, Core, version 1.1B, 2000
Chua Hun Seng s38042580 58

Home Security System with Bluetooth Technology

http://www.bluetooth.com/developer/specification/specification.asp (current April. 20, 2001)

[10]

Telefonaktiebolaget LM Ericsson et al., Specification of the Bluetooth System, Profiles, version 1.1B, 2000 http://www.bluetooth.com/developer/specification/specification.asp (current April. 20, 2001)

Chua Hun Seng s38042580

59

Home Security System with Bluetooth Technology

Appendix A: The Schematic Diagram of Motion Detector

Chua Hun Seng s38042580

60

Home Security System with Bluetooth Technology

Appendix B: List of Class Descriptions and Usage


This section contains the entire listing of the Classes Descriptions and their Usage.

Chua Hun Seng s38042580

61

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

62

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

63

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

64

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

65

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

66

Home Security System with Bluetooth Technology

Class Description and Usage of L2CAP

Chua Hun Seng s38042580

67

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

68

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

69

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

70

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

71

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

72

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

73

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

74

Home Security System with Bluetooth Technology

Class Description and Usage of SDP

Chua Hun Seng s38042580

75

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

76

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

77

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

78

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

79

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

80

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

81

Home Security System with Bluetooth Technology

Class Descriptions and Usage of RFCOMM

Chua Hun Seng s38042580

82

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

83

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

84

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

85

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

86

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

87

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

88

Home Security System with Bluetooth Technology

Class Descriptions and Usage of SPP

Chua Hun Seng s38042580

89

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

90

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

91

Home Security System with Bluetooth Technology

Chua Hun Seng s38042580

92

Home Security System with Bluetooth Technology

Appendix C: Application Source Code for both Client and Server


// Configurator Source Code #if !defined(AFX_BTDISCINPROG_H__2BE58262_AB5C_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_BTDISCINPROG_H__2BE58262_AB5C_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BtDiscInProg.h : header file // ///////////////////////////////////////////////////////////////////////////// // BtDiscInProg dialog class BtDiscInProg : public CDialog { // Construction public: BOOL OnInitDialog(); BtDiscInProg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(BtDiscInProg) enum { IDD = IDD_DIALOG1 }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA

// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(BtDiscInProg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(BtDiscInProg) afx_msg void OnButton1(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };

// DDX/DDV support

//{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTDISCINPROG_H__2BE58262_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

// BtDiscInProg.cpp : implementation file

Chua Hun Seng s38042580

93

Home Security System with Bluetooth Technology


// #include "stdafx.h" #include "MotionConfigurator.h" #include "BtDiscInProg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // BtDiscInProg dialog

BtDiscInProg::BtDiscInProg(CWnd* pParent /*=NULL*/) : CDialog(BtDiscInProg::IDD, pParent) { //{{AFX_DATA_INIT(BtDiscInProg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT }

void BtDiscInProg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(BtDiscInProg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP }

BEGIN_MESSAGE_MAP(BtDiscInProg, CDialog) //{{AFX_MSG_MAP(BtDiscInProg) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // BtDiscInProg message handlers void BtDiscInProg::OnButton1() { // TODO: Add your control notification handler code here CDialog::EndDialog(1); } BOOL BtDiscInProg::OnInitDialog() { return TRUE; }

// MotionConfiguratorDlg.cpp : implementation file

Chua Hun Seng s38042580

94

Home Security System with Bluetooth Technology


// #include "stdafx.h" #include "MotionConfigurator.h" #include "MotionConfiguratorDlg.h" #include "BtdiscInProg.h" #include "BtServicesFnd.h" #include "BtConnecting.h" #include "BtConnected.h" #include "MtStatus.h" #include "BtMtProtocol.h" BOOL gSetPressed = FALSE; //extern CMyBtIf *myBtIf; CBtServicesFnd* ptrSrvdlg; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) 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()

// DDX/DDV support

Chua Hun Seng s38042580

95

Home Security System with Bluetooth Technology

///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorDlg dialog CMotionConfiguratorDlg::CMotionConfiguratorDlg(CWnd* pParent /*=NULL*/) : CDialog(CMotionConfiguratorDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMotionConfiguratorDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); nextstate = GET_MT_DT_INITIAL_STATUS; } void CMotionConfiguratorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMotionConfiguratorDlg) DDX_Control(pDX, IDC_LIST1, m_ctrlstatus); DDX_Control(pDX, IDC_RADIO3, m_ctrlnotarmed); DDX_Control(pDX, IDC_RADIO2, m_ctrlarmed); DDX_Control(pDX, IDOK, m_ok); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMotionConfiguratorDlg, CDialog) //{{AFX_MSG_MAP(CMotionConfiguratorDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_RADIO2, OnRadio2) ON_BN_CLICKED(IDC_RADIO3, OnRadio3) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorDlg message handlers BOOL CMotionConfiguratorDlg::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()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon

Chua Hun Seng s38042580

96

Home Security System with Bluetooth Technology

// TODO: Add extra initialization here m_ctrlstatus.AddString("Status"); return TRUE; // return TRUE unless you set the focus to a control } void CMotionConfiguratorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMotionConfiguratorDlg::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(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMotionConfiguratorDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CMotionConfiguratorDlg::OnButton1() { // TODO: Add your control notification handler code here // Start the Bluetooth Inquiry Process // After the Inquiry Process is complete, do a // service discovery process to get the service // details of all Bluetooth devices around the client //myBtIf->StartInquiry();

Chua Hun Seng s38042580

97

Home Security System with Bluetooth Technology


//CListBox * pclistbox = (CListBox *)CDialog::GetDlgItem(IDC_LIST1); //ASSERT( pclistbox != NULL); //BtDiscInProg dlg; //int nResponse = dlg.DoModal(); m_ok.EnableWindow(FALSE); nextstate = GET_MT_DT_INITIAL_STATUS; CBtServicesFnd btsrvdlg; ptrSrvdlg = &btsrvdlg; int nServResponse = btsrvdlg.DoModal(); if (nServResponse == IDCANCEL) { // Do nothing return to the parent dialog m_ok.EnableWindow(TRUE); } else if (nServResponse == IDOK) { // Get the selection in the list box // and start the RFCOMM connection

} else { AfxMessageBox("Error Creating Dialog. Exitting !"); exit(-1); }

} void CMotionConfiguratorDlg::OnRadio2() { // TODO: Add your control notification handler code here CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL); pcradio3->SetCheck(FALSE); } void CMotionConfiguratorDlg::OnRadio3() { // TODO: Add your control notification handler code here CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); pcradio2->SetCheck(FALSE); }

void CMotionConfiguratorDlg::OnButton2() { // TODO: Add your control notification handler code here CWnd * pctxtcfg = (CWnd *)CDialog::GetDlgItem(IDC_STATICCFG); ASSERT( pctxtcfg != NULL);

Chua Hun Seng s38042580

98

Home Security System with Bluetooth Technology


CWnd * pctxtarm = (CWnd *)CDialog::GetDlgItem(IDC_STATICARM); ASSERT( pctxtarm != NULL); CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL); CButton * pcbuttonset = (CButton *)CDialog::GetDlgItem(IDC_BUTTON3); ASSERT( pcbuttonset != NULL);

pctxtcfg->EnableWindow(FALSE); pctxtarm->EnableWindow(FALSE); pcradio2->SetCheck(FALSE); pcradio3->SetCheck(FALSE); pcradio2->EnableWindow(FALSE); pcradio3->EnableWindow(FALSE); pcbuttonset->EnableWindow(FALSE); CButton * pcbuttonconn = (CButton *)CDialog::GetDlgItem(IDC_BUTTON1); ASSERT( pcbuttonconn != NULL); CButton * pcbuttondisc = (CButton *)CDialog::GetDlgItem(IDC_BUTTON2); ASSERT( pcbuttondisc != NULL); pcbuttonconn->EnableWindow(TRUE); pcbuttondisc->EnableWindow(FALSE); m_ok.EnableWindow(TRUE); if (Close() != SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to disconnect from Motion Detector"); } else { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Disconnected from Motion Detector"); } UINT16 actualwrite; PORT_RETURN_CODE retval; retval = Write("DataToClose", sizeof("DataToClose"), &actualwrite); if (retval != SUCCESS) { AfxMessageBox("Closed"); } } void CMotionConfiguratorDlg::OnButton3() { // TODO: Add your control notification handler code here gSetPressed = TRUE; mtdt_data getmtdtstatus; getmtdtstatus.type = TYPE_SET; getmtdtstatus.status_of = ARM_STATUS; if (m_ctrlarmed.GetCheck() == TRUE) { getmtdtstatus.value = DETECTOR_ARMED; } else {

Chua Hun Seng s38042580

99

Home Security System with Bluetooth Technology


getmtdtstatus.value = DETECTOR_NOT_ARMED; } UINT16 actualwrite = 0; PORT_RETURN_CODE retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); if ((retval!=SUCCESS)||(actualwrite!=sizeof(mtdt_data))) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } CMtStatus cmtstat; cmtstat.DoModal(); gSetPressed = FALSE; }

void CMotionConfiguratorDlg::OnDataReceived(void *data, UINT16 len) { // UINT16 actualwrite; mtdt_data getmtdtstatus; PORT_RETURN_CODE retval = SUCCESS; AfxMessageBox("Got Data from Mt Dt"); if (len == sizeof(mtdt_data)) { memcpy(&getmtdtstatus, data, len); } else { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Motion Detector Configurator protocol error"); return; } switch(getmtdtstatus.type) { case TYPE_RESPONSE: { switch(getmtdtstatus.status_of) { case ARM_STATUS: m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Got Motion Detector Arm status"); AfxMessageBox("Got Arm Status"); ChangeArmUI(getmtdtstatus.value); break; } } break; case TYPE_ACK: switch(getmtdtstatus.status_of) { case ARM_STATUS: if (getmtdtstatus.value == MTDT_SET_SUCCESS) { // Value set successfully m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Motion Detector set successfully.");

Chua Hun Seng s38042580

100

Home Security System with Bluetooth Technology


} } break; } //UINT16 actualwrite; //retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); //if ((retval != SUCCESS) || (actualwrite != sizeof(mtdt_data))) //{ // m_ctrlstatus.DeleteString(0); // m_ctrlstatus.AddString("Unable to configure Motion Detector."); //} } void CMotionConfiguratorDlg::OnEventReceived(UINT32 event_code) { PORT_RETURN_CODE retval = SUCCESS; if (event_code & PORT_EV_CONNECTED) { BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { CButton * pcbuttonconn = (CButton *)CDialog::GetDlgItem(IDC_BUTTON1); ASSERT( pcbuttonconn != NULL); CButton * pcbuttondisc = (CButton *)CDialog::GetDlgItem(IDC_BUTTON2); ASSERT( pcbuttondisc != NULL); CButton * pcbuttonset = (CButton *)CDialog::GetDlgItem(IDC_BUTTON3); ASSERT( pcbuttonset != NULL); pcbuttonconn->EnableWindow(FALSE); pcbuttondisc->EnableWindow(TRUE); CWnd * pctxtcfg = (CWnd *)CDialog::GetDlgItem(IDC_STATICCFG); ASSERT( pctxtcfg != NULL); CWnd * pctxtarm = (CWnd *)CDialog::GetDlgItem(IDC_STATICARM); ASSERT( pctxtarm != NULL); CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL);

pctxtcfg->EnableWindow(TRUE); pctxtarm->EnableWindow(TRUE); pcradio2->EnableWindow(TRUE); pcradio3->EnableWindow(TRUE); pcradio3->SetCheck(FALSE); pcbuttonset->EnableWindow(TRUE); UINT16 actualwrite; m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Connected to Motion Detector"); mtdt_data getmtdtstatus; getmtdtstatus.type = TYPE_QUERY; getmtdtstatus.status_of = ARM_STATUS; getmtdtstatus.value = NULL; if (nextstate == GET_MT_DT_INITIAL_STATUS) {

Chua Hun Seng s38042580

101

Home Security System with Bluetooth Technology


retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); if (retval!=SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } else { nextstate = SET_MT_DT; char lenwrite[10]; _itoa(actualwrite, lenwrite, sizeof(lenwrite)); m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } } } // IsConnected } if (event_code & PORT_EV_CONNECT_ERR) { CString logStr; BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { logStr = "Error: Unable to connect to Motion Detector."; } else { logStr = "Disconnected from Motion Detector"; } Close(); m_ok.EnableWindow(TRUE); m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString(logStr); } if (event_code & PORT_EV_ERR) { if (Close() == SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Disconnected from Motion Detector"); } } //default } void CMotionConfiguratorDlg::OnDestroy() { Close(); } void CMotionConfiguratorDlg::OnOK() { // TODO: Add extra validation here BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { Close(); // Close the RFCOMM connection if it is open return; // Do not allow a close

Chua Hun Seng s38042580

102

Home Security System with Bluetooth Technology


} CDialog::OnOK(); } void CMotionConfiguratorDlg::ChangeArmUI(UINT16 value) { if (value == DETECTOR_ARMED) { m_ctrlarmed.SetCheck(TRUE); m_ctrlnotarmed.SetCheck(FALSE); } else { m_ctrlarmed.SetCheck(FALSE); m_ctrlnotarmed.SetCheck(TRUE); } }

#if !defined(AFX_BTCONNECTED_H__2BE58273_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

Chua Hun Seng s38042580

103

Home Security System with Bluetooth Technology


#define AFX_BTCONNECTED_H__2BE58273_AB5C_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BtConnected.h : header file // ///////////////////////////////////////////////////////////////////////////// // CBtConnected dialog class CBtConnected : public CDialog { // Construction public: CBtConnected(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CBtConnected) enum { IDD = IDD_DIALOG4 }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA

// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBtConnected) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected:

// DDX/DDV support

// Generated message map functions //{{AFX_MSG(CBtConnected) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTCONNECTED_H__2BE58273_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

// BtConnected.cpp : implementation file //

Chua Hun Seng s38042580

104

Home Security System with Bluetooth Technology

#include "stdafx.h" #include "MotionConfigurator.h" #include "BtConnected.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CBtConnected dialog

CBtConnected::CBtConnected(CWnd* pParent /*=NULL*/) : CDialog(CBtConnected::IDD, pParent) { //{{AFX_DATA_INIT(CBtConnected) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT }

void CBtConnected::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBtConnected) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP }

BEGIN_MESSAGE_MAP(CBtConnected, CDialog) //{{AFX_MSG_MAP(CBtConnected) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtConnected message handlers

#if !defined(AFX_BTCONNECTING_H__2BE58272_AB5C_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_BTCONNECTING_H__2BE58272_AB5C_11D5_9DAF_0080BD080808__INCLUDED_

Chua Hun Seng s38042580

105

Home Security System with Bluetooth Technology

#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BtConnecting.h : header file // ///////////////////////////////////////////////////////////////////////////// // CBtConnecting dialog class CBtConnecting : public CDialog { // Construction public: CBtConnecting(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CBtConnecting) enum { IDD = IDD_DIALOG3 }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA

// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBtConnecting) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected:

// DDX/DDV support

// Generated message map functions //{{AFX_MSG(CBtConnecting) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTCONNECTING_H__2BE58272_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

// BtConnecting.cpp : implementation file //

Chua Hun Seng s38042580

106

Home Security System with Bluetooth Technology


#include "stdafx.h" #include "MotionConfigurator.h" #include "BtConnecting.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CBtConnecting dialog

CBtConnecting::CBtConnecting(CWnd* pParent /*=NULL*/) : CDialog(CBtConnecting::IDD, pParent) { //{{AFX_DATA_INIT(CBtConnecting) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT }

void CBtConnecting::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBtConnecting) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP }

BEGIN_MESSAGE_MAP(CBtConnecting, CDialog) //{{AFX_MSG_MAP(CBtConnecting) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtConnecting message handlers

#if !defined(AFX_BTSERVICESFND_H__2BE5826D_AB5C_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_BTSERVICESFND_H__2BE5826D_AB5C_11D5_9DAF_0080BD080808__INCLUDED_

Chua Hun Seng s38042580

107

Home Security System with Bluetooth Technology


#if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // BtServicesFnd.h : header file // #include "MyBtIf.h" ///////////////////////////////////////////////////////////////////////////// // CBtServicesFnd dialog class CBtServicesFnd : public CDialog, public CMyBtIf { // Construction public: void OnOK(); void OnCancel(); BOOL OnInitDialog(); CBtServicesFnd(CWnd* pParent = NULL); // standard constructor void RfCommStartSession(UINT8 scn, BD_ADDR bda); // Dialog Data //{{AFX_DATA(CBtServicesFnd) enum { IDD = IDD_DIALOG2 }; CString m_label1; //}}AFX_DATA

// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBtServicesFnd) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CBtServicesFnd) afx_msg void OnSelchangeList1(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };

// DDX/DDV support

//{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTSERVICESFND_H__2BE5826D_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

// BtServicesFnd.cpp : implementation file // #include "stdafx.h"

Chua Hun Seng s38042580

108

Home Security System with Bluetooth Technology


#include "MotionConfigurator.h" #include "MotionConfiguratorDlg.h" #include "BtServicesFnd.h" #include "BtMtProtocol.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CMotionConfiguratorDlg* ptrdlg; //Global CListBox * pclistbox; ///////////////////////////////////////////////////////////////////////////// // CBtServicesFnd dialog

CBtServicesFnd::CBtServicesFnd(CWnd* pParent /*=NULL*/) : CDialog(CBtServicesFnd::IDD, pParent) { //{{AFX_DATA_INIT(CBtServicesFnd) m_label1 = _T(""); //}}AFX_DATA_INIT }

void CBtServicesFnd::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBtServicesFnd) DDX_Text(pDX, IDC_STATIC1, m_label1); //}}AFX_DATA_MAP }

BEGIN_MESSAGE_MAP(CBtServicesFnd, CDialog) //{{AFX_MSG_MAP(CBtServicesFnd) ON_LBN_SELCHANGE(IDC_LIST1, OnSelchangeList1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtServicesFnd message handlers void CBtServicesFnd::OnSelchangeList1() { // TODO: Add your control notification handler code here CButton * pcbuttonok = (CButton *)CDialog::GetDlgItem(IDOK); ASSERT( pcbuttonok != NULL); pcbuttonok->EnableWindow(TRUE); } BOOL CBtServicesFnd::OnInitDialog() { pclistbox = (CListBox *)CDialog::GetDlgItem(IDC_LIST1); ASSERT( pclistbox != NULL); pclistbox->EnableWindow(FALSE); //pclistbox->ShowWindow(FALSE);

Chua Hun Seng s38042580

109

Home Security System with Bluetooth Technology


//CString btdisc1 = "0x6063356AB8\tMotion Detector Serial Port"; //pclistbox->AddString(btdisc1); //btdisc1 = "0x6063356AE9\tHotSync Serial Port"; //pclistbox->AddString(btdisc1); if (StartInquiry() != TRUE) { AfxMessageBox("Unable to connect to Motion Detector"); } return TRUE; }

void CBtServicesFnd::OnCancel() { StopInquiry(); //StopDiscovery(); EndDialog(IDCANCEL); } void CBtServicesFnd::OnOK() { RfCommStartSession(rfcommscn, bd_inq_res); EndDialog(IDOK); } void CBtServicesFnd::RfCommStartSession(UINT8 scn, BD_ADDR bda) { //AfxMessageBox("Starting Rfcomm connection"); if (ptrdlg->OpenClient(scn, bda) != CRfCommPort::SUCCESS) { AfxMessageBox("Rfcomm client Open Failed"); } }

// MotionConfigurator.h : main header file for the MOTIONCONFIGURATOR application //

Chua Hun Seng s38042580

110

Home Security System with Bluetooth Technology


#if !defined(AFX_MOTIONCONFIGURATOR_H__ABC25A05_A862_11D5_9DAF_0080BD080808__INCLUDED_ ) #define AFX_MOTIONCONFIGURATOR_H__ABC25A05_A862_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols

///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorApp: // See MotionConfigurator.cpp for the implementation of this class // class CMotionConfiguratorApp : public CWinApp { public: CMotionConfiguratorApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMotionConfiguratorApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CMotionConfiguratorApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() };

///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MOTIONCONFIGURATOR_H__ABC25A05_A862_11D5_9DAF_0080BD080808__INCLUDED_ )

// MotionConfigurator.cpp : Defines the class behaviors for the application. // #include "stdafx.h"

Chua Hun Seng s38042580

111

Home Security System with Bluetooth Technology


#include "MotionConfigurator.h" #include "MotionConfiguratorDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Global Bluetooth Object //CMyBtIf *myBtIf; CMotionConfiguratorDlg* ptrdlg; ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorApp BEGIN_MESSAGE_MAP(CMotionConfiguratorApp, CWinApp) //{{AFX_MSG_MAP(CMotionConfiguratorApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorApp construction CMotionConfiguratorApp::CMotionConfiguratorApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CMotionConfiguratorApp object CMotionConfiguratorApp theApp; ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorApp initialization BOOL CMotionConfiguratorApp::InitInstance() { if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); #else Enable3dControlsStatic(); #endif

// Call this when using MFC in a shared DLL // Call this when linking to MFC statically

CMotionConfiguratorDlg dlg; m_pMainWnd = &dlg; ptrdlg = &dlg;

Chua Hun Seng s38042580

112

Home Security System with Bluetooth Technology


//myBtIf = new CMyBtIf; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // delete the Bluetooth object delete(myBtIf); // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }

//

// MotionConfiguratorDlg.h : header file //

Chua Hun Seng s38042580

113

Home Security System with Bluetooth Technology


#if !defined(AFX_MOTIONCONFIGURATORDLG_H__ABC25A07_A862_11D5_9DAF_0080BD080808__INCLUD ED_) #define AFX_MOTIONCONFIGURATORDLG_H__ABC25A07_A862_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BtIfDefinitions.h" #include "MyBtIf.h" ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorDlg dialog class CMotionConfiguratorDlg : public CDialog, public CRfCommPort { // Construction public: UINT8 nextstate; void ChangeArmUI(UINT16); void OnDestroy(); void OnEventReceived (UINT32 event_code); void OnDataReceived (void *data, UINT16 len); CMotionConfiguratorDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CMotionConfiguratorDlg) enum { IDD = IDD_MOTIONCONFIGURATOR_DIALOG }; CListBox m_ctrlstatus; CButton m_ctrlnotarmed; CButton m_ctrlarmed; CButton m_ok; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMotionConfiguratorDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CMotionConfiguratorDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnButton1(); afx_msg void OnRadio2(); afx_msg void OnRadio3(); afx_msg void OnButton2(); afx_msg void OnButton3(); virtual void OnOK(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line.

// DDX/DDV support

Chua Hun Seng s38042580

114

Home Security System with Bluetooth Technology


#endif // !defined(AFX_MOTIONCONFIGURATORDLG_H__ABC25A07_A862_11D5_9DAF_0080BD080808__INCLUD ED_)

// MotionConfiguratorDlg.cpp : implementation file

Chua Hun Seng s38042580

115

Home Security System with Bluetooth Technology


// #include "stdafx.h" #include "MotionConfigurator.h" #include "MotionConfiguratorDlg.h" #include "BtdiscInProg.h" #include "BtServicesFnd.h" #include "BtConnecting.h" #include "BtConnected.h" #include "MtStatus.h" #include "BtMtProtocol.h" BOOL gSetPressed = FALSE; //extern CMyBtIf *myBtIf; CBtServicesFnd* ptrSrvdlg; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) 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()

// DDX/DDV support

Chua Hun Seng s38042580

116

Home Security System with Bluetooth Technology

///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorDlg dialog CMotionConfiguratorDlg::CMotionConfiguratorDlg(CWnd* pParent /*=NULL*/) : CDialog(CMotionConfiguratorDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMotionConfiguratorDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); nextstate = GET_MT_DT_INITIAL_STATUS; } void CMotionConfiguratorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMotionConfiguratorDlg) DDX_Control(pDX, IDC_LIST1, m_ctrlstatus); DDX_Control(pDX, IDC_RADIO3, m_ctrlnotarmed); DDX_Control(pDX, IDC_RADIO2, m_ctrlarmed); DDX_Control(pDX, IDOK, m_ok); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMotionConfiguratorDlg, CDialog) //{{AFX_MSG_MAP(CMotionConfiguratorDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_RADIO2, OnRadio2) ON_BN_CLICKED(IDC_RADIO3, OnRadio3) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMotionConfiguratorDlg message handlers BOOL CMotionConfiguratorDlg::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()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon

Chua Hun Seng s38042580

117

Home Security System with Bluetooth Technology

// TODO: Add extra initialization here m_ctrlstatus.AddString("Status"); return TRUE; // return TRUE unless you set the focus to a control } void CMotionConfiguratorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMotionConfiguratorDlg::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(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMotionConfiguratorDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CMotionConfiguratorDlg::OnButton1() { // TODO: Add your control notification handler code here // Start the Bluetooth Inquiry Process // After the Inquiry Process is complete, do a // service discovery process to get the service // details of all Bluetooth devices around the client //myBtIf->StartInquiry();

Chua Hun Seng s38042580

118

Home Security System with Bluetooth Technology


//CListBox * pclistbox = (CListBox *)CDialog::GetDlgItem(IDC_LIST1); //ASSERT( pclistbox != NULL); //BtDiscInProg dlg; //int nResponse = dlg.DoModal(); m_ok.EnableWindow(FALSE); nextstate = GET_MT_DT_INITIAL_STATUS; CBtServicesFnd btsrvdlg; ptrSrvdlg = &btsrvdlg; int nServResponse = btsrvdlg.DoModal(); if (nServResponse == IDCANCEL) { // Do nothing return to the parent dialog m_ok.EnableWindow(TRUE); } else if (nServResponse == IDOK) { // Get the selection in the list box // and start the RFCOMM connection

} else { AfxMessageBox("Error Creating Dialog. Exitting !"); exit(-1); }

} void CMotionConfiguratorDlg::OnRadio2() { // TODO: Add your control notification handler code here CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL); pcradio3->SetCheck(FALSE); } void CMotionConfiguratorDlg::OnRadio3() { // TODO: Add your control notification handler code here CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); pcradio2->SetCheck(FALSE); }

void CMotionConfiguratorDlg::OnButton2() { // TODO: Add your control notification handler code here CWnd * pctxtcfg = (CWnd *)CDialog::GetDlgItem(IDC_STATICCFG); ASSERT( pctxtcfg != NULL);

Chua Hun Seng s38042580

119

Home Security System with Bluetooth Technology


CWnd * pctxtarm = (CWnd *)CDialog::GetDlgItem(IDC_STATICARM); ASSERT( pctxtarm != NULL); CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL); CButton * pcbuttonset = (CButton *)CDialog::GetDlgItem(IDC_BUTTON3); ASSERT( pcbuttonset != NULL);

pctxtcfg->EnableWindow(FALSE); pctxtarm->EnableWindow(FALSE); pcradio2->SetCheck(FALSE); pcradio3->SetCheck(FALSE); pcradio2->EnableWindow(FALSE); pcradio3->EnableWindow(FALSE); pcbuttonset->EnableWindow(FALSE); CButton * pcbuttonconn = (CButton *)CDialog::GetDlgItem(IDC_BUTTON1); ASSERT( pcbuttonconn != NULL); CButton * pcbuttondisc = (CButton *)CDialog::GetDlgItem(IDC_BUTTON2); ASSERT( pcbuttondisc != NULL); pcbuttonconn->EnableWindow(TRUE); pcbuttondisc->EnableWindow(FALSE); m_ok.EnableWindow(TRUE); if (Close() != SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to disconnect from Motion Detector"); } else { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Disconnected from Motion Detector"); } UINT16 actualwrite; PORT_RETURN_CODE retval; retval = Write("DataToClose", sizeof("DataToClose"), &actualwrite); if (retval != SUCCESS) { AfxMessageBox("Closed"); } } void CMotionConfiguratorDlg::OnButton3() { // TODO: Add your control notification handler code here gSetPressed = TRUE; mtdt_data getmtdtstatus; getmtdtstatus.type = TYPE_SET; getmtdtstatus.status_of = ARM_STATUS; if (m_ctrlarmed.GetCheck() == TRUE) { getmtdtstatus.value = DETECTOR_ARMED; } else {

Chua Hun Seng s38042580

120

Home Security System with Bluetooth Technology


getmtdtstatus.value = DETECTOR_NOT_ARMED; } UINT16 actualwrite = 0; PORT_RETURN_CODE retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); if ((retval!=SUCCESS)||(actualwrite!=sizeof(mtdt_data))) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } CMtStatus cmtstat; cmtstat.DoModal(); gSetPressed = FALSE; }

void CMotionConfiguratorDlg::OnDataReceived(void *data, UINT16 len) { // UINT16 actualwrite; mtdt_data getmtdtstatus; PORT_RETURN_CODE retval = SUCCESS; AfxMessageBox("Got Data from Mt Dt"); if (len == sizeof(mtdt_data)) { memcpy(&getmtdtstatus, data, len); } else { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Motion Detector Configurator protocol error"); return; } switch(getmtdtstatus.type) { case TYPE_RESPONSE: { switch(getmtdtstatus.status_of) { case ARM_STATUS: m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Got Motion Detector Arm status"); AfxMessageBox("Got Arm Status"); ChangeArmUI(getmtdtstatus.value); break; } } break; case TYPE_ACK: switch(getmtdtstatus.status_of) { case ARM_STATUS: if (getmtdtstatus.value == MTDT_SET_SUCCESS) { // Value set successfully m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Motion Detector set successfully.");

Chua Hun Seng s38042580

121

Home Security System with Bluetooth Technology


} } break; } //UINT16 actualwrite; //retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); //if ((retval != SUCCESS) || (actualwrite != sizeof(mtdt_data))) //{ // m_ctrlstatus.DeleteString(0); // m_ctrlstatus.AddString("Unable to configure Motion Detector."); //} } void CMotionConfiguratorDlg::OnEventReceived(UINT32 event_code) { PORT_RETURN_CODE retval = SUCCESS; if (event_code & PORT_EV_CONNECTED) { BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { CButton * pcbuttonconn = (CButton *)CDialog::GetDlgItem(IDC_BUTTON1); ASSERT( pcbuttonconn != NULL); CButton * pcbuttondisc = (CButton *)CDialog::GetDlgItem(IDC_BUTTON2); ASSERT( pcbuttondisc != NULL); CButton * pcbuttonset = (CButton *)CDialog::GetDlgItem(IDC_BUTTON3); ASSERT( pcbuttonset != NULL); pcbuttonconn->EnableWindow(FALSE); pcbuttondisc->EnableWindow(TRUE); CWnd * pctxtcfg = (CWnd *)CDialog::GetDlgItem(IDC_STATICCFG); ASSERT( pctxtcfg != NULL); CWnd * pctxtarm = (CWnd *)CDialog::GetDlgItem(IDC_STATICARM); ASSERT( pctxtarm != NULL); CButton * pcradio2 = (CButton *)CDialog::GetDlgItem(IDC_RADIO2); ASSERT( pcradio2 != NULL); CButton * pcradio3 = (CButton *)CDialog::GetDlgItem(IDC_RADIO3); ASSERT( pcradio3 != NULL);

pctxtcfg->EnableWindow(TRUE); pctxtarm->EnableWindow(TRUE); pcradio2->EnableWindow(TRUE); pcradio3->EnableWindow(TRUE); pcradio3->SetCheck(FALSE); pcbuttonset->EnableWindow(TRUE); UINT16 actualwrite; m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Connected to Motion Detector"); mtdt_data getmtdtstatus; getmtdtstatus.type = TYPE_QUERY; getmtdtstatus.status_of = ARM_STATUS; getmtdtstatus.value = NULL; if (nextstate == GET_MT_DT_INITIAL_STATUS) {

Chua Hun Seng s38042580

122

Home Security System with Bluetooth Technology


retval = Write(&getmtdtstatus, sizeof(mtdt_data), &actualwrite); if (retval!=SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } else { nextstate = SET_MT_DT; char lenwrite[10]; _itoa(actualwrite, lenwrite, sizeof(lenwrite)); m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Unable to write on the Bluetooth link"); } } } // IsConnected } if (event_code & PORT_EV_CONNECT_ERR) { CString logStr; BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { logStr = "Error: Unable to connect to Motion Detector."; } else { logStr = "Disconnected from Motion Detector"; } Close(); m_ok.EnableWindow(TRUE); m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString(logStr); } if (event_code & PORT_EV_ERR) { if (Close() == SUCCESS) { m_ctrlstatus.DeleteString(0); m_ctrlstatus.AddString("Disconnected from Motion Detector"); } } //default } void CMotionConfiguratorDlg::OnDestroy() { Close(); } void CMotionConfiguratorDlg::OnOK() { // TODO: Add extra validation here BD_ADDR bd_connect; if (IsConnected(&bd_connect) == TRUE) { Close(); // Close the RFCOMM connection if it is open return; // Do not allow a close

Chua Hun Seng s38042580

123

Home Security System with Bluetooth Technology


} CDialog::OnOK(); } void CMotionConfiguratorDlg::ChangeArmUI(UINT16 value) { if (value == DETECTOR_ARMED) { m_ctrlarmed.SetCheck(TRUE); m_ctrlnotarmed.SetCheck(FALSE); } else { m_ctrlarmed.SetCheck(FALSE); m_ctrlnotarmed.SetCheck(TRUE); } }

#if !defined(AFX_MTSTATUS_H__2BE5827E_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

Chua Hun Seng s38042580

124

Home Security System with Bluetooth Technology


#define AFX_MTSTATUS_H__2BE5827E_AB5C_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // MtStatus.h : header file // ///////////////////////////////////////////////////////////////////////////// // CMtStatus dialog class CMtStatus : public CDialog { // Construction public: BOOL OnInitDialog(); CMtStatus(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CMtStatus) enum { IDD = IDD_DIALOG5 }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA

// Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMtStatus) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected:

// DDX/DDV support

// Generated message map functions //{{AFX_MSG(CMtStatus) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MTSTATUS_H__2BE5827E_AB5C_11D5_9DAF_0080BD080808__INCLUDED_)

// MtStatus.cpp : implementation file

Chua Hun Seng s38042580

125

Home Security System with Bluetooth Technology


// #include "stdafx.h" #include "MotionConfigurator.h" #include "MtStatus.h" extern BOOL gSetPressed; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMtStatus dialog

CMtStatus::CMtStatus(CWnd* pParent /*=NULL*/) : CDialog(CMtStatus::IDD, pParent) { //{{AFX_DATA_INIT(CMtStatus) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT }

void CMtStatus::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMtStatus) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP }

BEGIN_MESSAGE_MAP(CMtStatus, CDialog) //{{AFX_MSG_MAP(CMtStatus) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMtStatus message handlers BOOL CMtStatus::OnInitDialog() { if (gSetPressed == TRUE) { CWnd * pctxtget = (CWnd *)CDialog::GetDlgItem(IDC_STATICGET); ASSERT( pctxtget != NULL); pctxtget->ShowWindow(FALSE); CWnd * pctxtapply = (CWnd *)CDialog::GetDlgItem(IDC_STATICAPPLY); ASSERT( pctxtapply != NULL); pctxtapply->ShowWindow(TRUE); } else { CWnd * pctxtapply = (CWnd *)CDialog::GetDlgItem(IDC_STATICAPPLY); ASSERT( pctxtapply != NULL); pctxtapply->ShowWindow(FALSE); CWnd * pctxtget = (CWnd *)CDialog::GetDlgItem(IDC_STATICGET); ASSERT( pctxtget != NULL); pctxtget->ShowWindow(TRUE);

Chua Hun Seng s38042580

126

Home Security System with Bluetooth Technology


} return TRUE; }

// MyBtIf.h: interface for the CMyBtIf class.

Chua Hun Seng s38042580

127

Home Security System with Bluetooth Technology


// ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MYBTIF_H__0EA9EC02_B4F2_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_MYBTIF_H__0EA9EC02_B4F2_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BtIfDefinitions.h" #include "BtIfClasses.h" #include "BtConnecting.h" class CMyBtIf : public CBtIf { public: UINT8 rfcommscn; CRfCommIf mtdtRfIf; BOOL isBdAddrEqual(BD_ADDR bd_addr); BD_ADDR bd_inq_res; CString DeviceAsString(); void OnInquiryComplete(BOOL success, short num_responses); void OnDiscoveryComplete(); void OnDeviceResponded(BD_ADDR bda, DEV_CLASS dev_class, BD_NAME bd_name,BOOL b_connected); CMyBtIf(); virtual ~CMyBtIf(); }; #endif // !defined(AFX_MYBTIF_H__0EA9EC02_B4F2_11D5_9DAF_0080BD080808__INCLUDED_)

// MyBtIf.cpp: implementation of the CMyBtIf class.

Chua Hun Seng s38042580

128

Home Security System with Bluetooth Technology


// ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MotionConfigurator.h" #include "MotionConfiguratorDlg.h" #include "Btconnecting.h" #include "BtDiscInProg.h" #include "BtServicesFnd.h" #include "MyBtIf.h"

#ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif

extern CBtServicesFnd* ptrSrvdlg; extern CListBox * pclistbox; // {B82FB441-B438-11d5-9DAF-0080BD080808} static GUID service_guid = { 0xb82fb441, 0xb438, 0x11d5, { 0x9d, 0xaf, 0x0, 0x80, 0xbd, 0x8, 0x8, 0x8 } }; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMyBtIf::CMyBtIf() { for(int i=0; i<BD_ADDR_LEN; bd_inq_res[i]=0x00,i++); rfcommscn = 0; } CMyBtIf::~CMyBtIf() { } void CMyBtIf::OnDeviceResponded(BD_ADDR bda, DEV_CLASS dev_class, BD_NAME bd_name, BOOL b_connected) { if (isBdAddrEqual(bda)!= TRUE) { bd_inq_res[0] = bda[0]; bd_inq_res[1] = bda[1]; bd_inq_res[2] = bda[2]; bd_inq_res[3] = bda[3]; bd_inq_res[4] = bda[4]; bd_inq_res[5] = bda[5]; //AfxMessageBox("Device Has Responded"); } //myBtIf->StartInquiry(); } void CMyBtIf::OnDiscoveryComplete() { // ADD the SDP record extracction here //GUID mtdtSerPortGuid = CBtIf::guid_SERVCLASS_SERIAL_PORT; CSdpDiscoveryRec mtdtsdprec; int nNumRec = ReadDiscoveryRecords(bd_inq_res, 1, /* CSdpDiscoveryRec*/&mtdtsdprec, &service_guid);

Chua Hun Seng s38042580

129

Home Security System with Bluetooth Technology


if (nNumRec < 1) { AfxMessageBox("No Motion detectors found to configure!"); return; }

if ((mtdtsdprec.FindRFCommScn(&rfcommscn)) == TRUE) { // Connect to the RFCOMM channel if (mtdtRfIf.AssignScnValue(&service_guid, rfcommscn)!= TRUE) { AfxMessageBox("Error in AssignScnValue"); exit(-1); } if (mtdtRfIf.SetSecurityLevel("MotionDetectorConfigClient",BTM_SEC_NONE,FALSE)!=TRUE) { AfxMessageBox("Error in SetSecurityLevel"); exit(-1); } //pclistbox->ShowWindow(TRUE); pclistbox->EnableWindow(TRUE); pclistbox->AddString(DeviceAsString()+" <- Motion Detector"); } else { AfxMessageBox("No Motion detectors found to configure!"); return; } } void CMyBtIf::OnInquiryComplete(BOOL success, short num_responses) { //AfxMessageBox("Inquiry Complete"); StopInquiry(); if (num_responses < 1) { AfxMessageBox("No Motion Detectors found to configure.", MB_OK|MB_ICONSTOP); return; } if (StartDiscovery(bd_inq_res, &service_guid)!=TRUE) { AfxMessageBox("Error in starting discovery"); } } BOOL CMyBtIf::isBdAddrEqual(BD_ADDR bd_addr) { return (0 == memcmp(bd_inq_res, bd_addr, sizeof(BD_ADDR))); } CString CMyBtIf::DeviceAsString() { CString s; // Default the string to the BD Address only. // s.Format("[%x:%x:%x:%x:%x:%x]", bd_inq_res[0], bd_inq_res[1], bd_inq_res[2], bd_inq_res[3], bd_inq_res[4], bd_inq_res[5]);

Chua Hun Seng s38042580

130

Home Security System with Bluetooth Technology


return s; }

#ifndef _BTMTPROTOCOL_H_

Chua Hun Seng s38042580

131

Home Security System with Bluetooth Technology


#define _BTMTPROTOCOL_H_ #define TYPE_QUERY #define TYPE_RESPONSE #define TYPE_SET #define TYPE_ACK #define ARM_STATUS #define SENSITIVITY_STATUS #define BATTERY_STATUS 0x01 0x02 0x03 0x04 // Acks the last set 0x10 0x20 0x30

// Values #define DETECTOR_ARMED #define DETECTOR_NOT_ARMED 0x0002 #define BATTERY_OK #define BATTERY_REPLACE #define MTDT_SET_SUCCESS #define MTDT_SET_FAILURE 0x0000 0xFFFF

0x0001

0x0004 0x0008

// <Type 1 byte><Status of 1 byte><value 2 bytes> typedef struct { UINT8 type; UINT8 status_of; UINT16 value; } mtdt_data; // States #define GET_MT_DT_INITIAL_STATUS 0x01 #define SET_MT_DT 0x02 #endif

Chua Hun Seng s38042580

132

Home Security System with Bluetooth Technology

// Server Source Code // BtWidcommServDlg.cpp : implementation file // #include "stdafx.h" #include "BtWidcommServ.h" #include "BtWidcommServDlg.h" #include "BtIfDefinitions.h" #include "BtIfClasses.h" #include "BtMtProtocol.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // {B82FB441-B438-11d5-9DAF-0080BD080808} static GUID mtdtSerPortGuid = { 0xb82fb441, 0xb438, 0x11d5, { 0x9d, 0xaf, 0x0, 0x80, 0xbd, 0x8, 0x8, 0x8 } }; ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) 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()

// DDX/DDV support

Chua Hun Seng s38042580

133

Home Security System with Bluetooth Technology

///////////////////////////////////////////////////////////////////////////// // CBtWidcommServDlg dialog CBtWidcommServDlg::CBtWidcommServDlg(CWnd* pParent /*=NULL*/) : CDialog(CBtWidcommServDlg::IDD, pParent) { //{{AFX_DATA_INIT(CBtWidcommServDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); listindex = -1; lprfcommServ = NULL; lpsdpmtdt = NULL; dt_armstatus = DETECTOR_NOT_ARMED; m_scn = 0; } void CBtWidcommServDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBtWidcommServDlg) DDX_Control(pDX, IDC_LIST1, m_ctrlList); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CBtWidcommServDlg, CDialog) //{{AFX_MSG_MAP(CBtWidcommServDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnClearLog) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServDlg message handlers BOOL CBtWidcommServDlg::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()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here

Chua Hun Seng s38042580

134

Home Security System with Bluetooth Technology


StartRfCommServer(); return TRUE; // return TRUE unless you set the focus to a control } void CBtWidcommServDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CBtWidcommServDlg::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(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CBtWidcommServDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; }

void CBtWidcommServDlg::OnDataReceived(void *p_data, UINT16 len) { UINT16 actlen = 0; listindex++; //m_ctrlList.AddString("Got Data..."); mtdt_data mtdtgotdata, mtdtsenddata; memcpy(&mtdtgotdata, p_data, sizeof(mtdt_data)); if (len != sizeof(mtdt_data)) { void *ptrtemp_mem = (void *) malloc(len);

Chua Hun Seng s38042580

135

Home Security System with Bluetooth Technology


memcpy(&mtdtgotdata, p_data, sizeof(mtdt_data)); m_ctrlList.AddString("Motion Detector Protocol Error."); free(ptrtemp_mem); return; } else { switch(mtdtgotdata.type) { case TYPE_QUERY: if (mtdtgotdata.status_of == ARM_STATUS) { mtdtsenddata.type = TYPE_RESPONSE; mtdtsenddata.status_of = mtdtgotdata.status_of; mtdtsenddata.value = dt_armstatus; } break; case TYPE_SET: if (mtdtgotdata.status_of == ARM_STATUS) { if ((mtdtgotdata.value == DETECTOR_ARMED)|| (mtdtgotdata.value == DETECTOR_NOT_ARMED)) { dt_armstatus = mtdtgotdata.value; m_ctrlList.AddString("Got Motion Detector ARM status request."); } else { m_ctrlList.AddString("Motion Detector Protocol Error"); } mtdtsenddata.type = TYPE_ACK; mtdtsenddata.status_of = mtdtgotdata.status_of; mtdtsenddata.value = MTDT_SET_SUCCESS; } break; } PORT_RETURN_CODE retval = Write(&mtdtsenddata, sizeof(mtdt_data), &actlen); if ((retval != SUCCESS)||(actlen != sizeof(mtdt_data))) { m_ctrlList.AddString("ERROR: Unable to write to Bluetooth link."); return; } else { m_ctrlList.AddString("Responded to configurator."); return; } } } void CBtWidcommServDlg::OnEventReceived(UINT32 event_code) { listindex++; if (event_code & PORT_EV_CONNECTED) { m_ctrlList.AddString("Connected..."); } if (event_code & PORT_EV_CONNECT_ERR) { m_ctrlList.AddString("Disconnected."); //Close();

Chua Hun Seng s38042580

136

Home Security System with Bluetooth Technology


//StartRfCommServer(); } char lpszeventcode[10]; //_itoa(event_code, lpszeventcode, sizeof(lpszeventcode)); //m_ctrlList.AddString(lpszeventcode);

//

void CBtWidcommServDlg::OnClearLog() { // TODO: Add your control notification handler code here int nTotal = m_ctrlList.GetCount(); for (int i=nTotal-1; i>=0; i--) { m_ctrlList.DeleteString(i); } listindex = 0; } void CBtWidcommServDlg::OnDestroy() { Close(); } void CBtWidcommServDlg::StartRfCommServer() { // RFCOMM server on server channel <scn> if (lprfcommServ != NULL) { delete lprfcommServ; } CRfCommIf *rfcommServ = new CRfCommIf; this->lprfcommServ = rfcommServ; rfcommServ->AssignScnValue(&mtdtSerPortGuid); UINT8 scn = rfcommServ->GetScn(); // SDP service for RFCOMM server on SCN <assigned> if (lpsdpmtdt != NULL) { delete lpsdpmtdt; } CSdpService *sdpmtdt = new CSdpService; this->lpsdpmtdt = sdpmtdt; //GUID mtdtprofileGuid = UUID_SERVCLASS_SERIAL_PORT; if ((sdpmtdt->AddServiceClassIdList(1, &mtdtSerPortGuid))!= SDP_OK) { AfxMessageBox("Unable to register SDP record"); exit(-1); } if ((sdpmtdt->AddServiceName("Motion Detector Serial Port"))!= SDP_OK) { AfxMessageBox("Unable to set Service Name"); exit(-1); } if ((sdpmtdt->AddRFCommProtocolDescriptor(scn))!= SDP_OK) { AfxMessageBox("Unable to set SCN in SDP DB"); exit(-1); }

Chua Hun Seng s38042580

137

Home Security System with Bluetooth Technology

if ((sdpmtdt->MakePublicBrowseable())!=SDP_OK) { AfxMessageBox("Unable to set SDP record as browsable"); }

rfcommServ->SetSecurityLevel("Motion Detector Serial Port", BTM_SEC_NONE, TRUE /*Server*/);

if (OpenServer(scn)!= SUCCESS) { AfxMessageBox("Unable to start server"); exit(-1); } else { m_scn = scn; } }

Chua Hun Seng s38042580

138

Home Security System with Bluetooth Technology


// BtWidcommServ.h : main header file for the BTWIDCOMMSERV application // #if !defined(AFX_BTWIDCOMMSERV_H__E6E8D227_B349_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_BTWIDCOMMSERV_H__E6E8D227_B349_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols

///////////////////////////////////////////////////////////////////////////// // CBtWidcommServApp: // See BtWidcommServ.cpp for the implementation of this class // class CBtWidcommServApp : public CWinApp { public: CBtWidcommServApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBtWidcommServApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CBtWidcommServApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() };

///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTWIDCOMMSERV_H__E6E8D227_B349_11D5_9DAF_0080BD080808__INCLUDED_)

Chua Hun Seng s38042580

139

Home Security System with Bluetooth Technology


// BtWidcommServ.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "BtWidcommServ.h" #include "BtWidcommServDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServApp BEGIN_MESSAGE_MAP(CBtWidcommServApp, CWinApp) //{{AFX_MSG_MAP(CBtWidcommServApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServApp construction CBtWidcommServApp::CBtWidcommServApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CBtWidcommServApp object CBtWidcommServApp theApp; ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServApp initialization BOOL CBtWidcommServApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); #else Enable3dControlsStatic(); #endif

// Call this when using MFC in a shared DLL // Call this when linking to MFC statically

CBtWidcommServDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); delete dlg.lprfcommServ; delete dlg.lpsdpmtdt; dlg.Close(); // Close the RFCOMMM Port if (nResponse == IDOK) {

Chua Hun Seng s38042580

140

Home Security System with Bluetooth Technology


// TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }

Chua Hun Seng s38042580

141

Home Security System with Bluetooth Technology


// BtWidcommServDlg.h : header file // #if !defined(AFX_BTWIDCOMMSERVDLG_H__E6E8D229_B349_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_BTWIDCOMMSERVDLG_H__E6E8D229_B349_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000

#include "BtIfDefinitions.h" #include "BtIfClasses.h" #include "MtDtRfcommPort.h" ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServDlg dialog class CBtWidcommServDlg : public CDialog, public CRfCommPort { // Construction public: void StartRfCommServer(); UINT8 m_scn; void OnDestroy(); UINT16 dt_armstatus; int listindex; void OnEventReceived(UINT32 event_code); void OnDataReceived(void *p_data, UINT16 len); CSdpService * lpsdpmtdt; CRfCommIf * lprfcommServ; CBtWidcommServDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CBtWidcommServDlg) enum { IDD = IDD_BTWIDCOMMSERV_DIALOG }; CListBox m_ctrlList; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CBtWidcommServDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CBtWidcommServDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnClearLog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_BTWIDCOMMSERVDLG_H__E6E8D229_B349_11D5_9DAF_0080BD080808__INCLUDED_)

// DDX/DDV support

Chua Hun Seng s38042580

142

Home Security System with Bluetooth Technology


// BtWidcommServDlg.cpp : implementation file // #include "stdafx.h" #include "BtWidcommServ.h" #include "BtWidcommServDlg.h" #include "BtIfDefinitions.h" #include "BtIfClasses.h" #include "BtMtProtocol.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // {B82FB441-B438-11d5-9DAF-0080BD080808} static GUID mtdtSerPortGuid = { 0xb82fb441, 0xb438, 0x11d5, { 0x9d, 0xaf, 0x0, 0x80, 0xbd, 0x8, 0x8, 0x8 } }; ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) 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() /////////////////////////////////////////////////////////////////////////////

// DDX/DDV support

Chua Hun Seng s38042580

143

Home Security System with Bluetooth Technology


// CBtWidcommServDlg dialog CBtWidcommServDlg::CBtWidcommServDlg(CWnd* pParent /*=NULL*/) : CDialog(CBtWidcommServDlg::IDD, pParent) { //{{AFX_DATA_INIT(CBtWidcommServDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); listindex = -1; lprfcommServ = NULL; lpsdpmtdt = NULL; dt_armstatus = DETECTOR_NOT_ARMED; m_scn = 0; } void CBtWidcommServDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBtWidcommServDlg) DDX_Control(pDX, IDC_LIST1, m_ctrlList); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CBtWidcommServDlg, CDialog) //{{AFX_MSG_MAP(CBtWidcommServDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnClearLog) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBtWidcommServDlg message handlers BOOL CBtWidcommServDlg::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()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here StartRfCommServer();

Chua Hun Seng s38042580

144

Home Security System with Bluetooth Technology


return TRUE; // return TRUE unless you set the focus to a control } void CBtWidcommServDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CBtWidcommServDlg::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(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CBtWidcommServDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; }

void CBtWidcommServDlg::OnDataReceived(void *p_data, UINT16 len) { UINT16 actlen = 0; listindex++; //m_ctrlList.AddString("Got Data..."); mtdt_data mtdtgotdata, mtdtsenddata; memcpy(&mtdtgotdata, p_data, sizeof(mtdt_data)); if (len != sizeof(mtdt_data)) { void *ptrtemp_mem = (void *) malloc(len); memcpy(&mtdtgotdata, p_data, sizeof(mtdt_data)); m_ctrlList.AddString("Motion Detector Protocol Error.");

Chua Hun Seng s38042580

145

Home Security System with Bluetooth Technology


free(ptrtemp_mem); return; } else { switch(mtdtgotdata.type) { case TYPE_QUERY: if (mtdtgotdata.status_of == ARM_STATUS) { mtdtsenddata.type = TYPE_RESPONSE; mtdtsenddata.status_of = mtdtgotdata.status_of; mtdtsenddata.value = dt_armstatus; } break; case TYPE_SET: if (mtdtgotdata.status_of == ARM_STATUS) { if ((mtdtgotdata.value == DETECTOR_ARMED)|| (mtdtgotdata.value == DETECTOR_NOT_ARMED)) { dt_armstatus = mtdtgotdata.value; m_ctrlList.AddString("Got Motion Detector ARM status request."); } else { m_ctrlList.AddString("Motion Detector Protocol Error"); } mtdtsenddata.type = TYPE_ACK; mtdtsenddata.status_of = mtdtgotdata.status_of; mtdtsenddata.value = MTDT_SET_SUCCESS; } break; } PORT_RETURN_CODE retval = Write(&mtdtsenddata, sizeof(mtdt_data), &actlen); if ((retval != SUCCESS)||(actlen != sizeof(mtdt_data))) { m_ctrlList.AddString("ERROR: Unable to write to Bluetooth link."); return; } else { m_ctrlList.AddString("Responded to configurator."); return; } } } void CBtWidcommServDlg::OnEventReceived(UINT32 event_code) { listindex++; if (event_code & PORT_EV_CONNECTED) { m_ctrlList.AddString("Connected..."); } if (event_code & PORT_EV_CONNECT_ERR) { m_ctrlList.AddString("Disconnected."); //Close(); //StartRfCommServer(); }

Chua Hun Seng s38042580

146

Home Security System with Bluetooth Technology


// char lpszeventcode[10]; //_itoa(event_code, lpszeventcode, sizeof(lpszeventcode)); //m_ctrlList.AddString(lpszeventcode);

void CBtWidcommServDlg::OnClearLog() { // TODO: Add your control notification handler code here int nTotal = m_ctrlList.GetCount(); for (int i=nTotal-1; i>=0; i--) { m_ctrlList.DeleteString(i); } listindex = 0; } void CBtWidcommServDlg::OnDestroy() { Close(); } void CBtWidcommServDlg::StartRfCommServer() { // RFCOMM server on server channel <scn> if (lprfcommServ != NULL) { delete lprfcommServ; } CRfCommIf *rfcommServ = new CRfCommIf; this->lprfcommServ = rfcommServ; rfcommServ->AssignScnValue(&mtdtSerPortGuid); UINT8 scn = rfcommServ->GetScn(); // SDP service for RFCOMM server on SCN <assigned> if (lpsdpmtdt != NULL) { delete lpsdpmtdt; } CSdpService *sdpmtdt = new CSdpService; this->lpsdpmtdt = sdpmtdt; //GUID mtdtprofileGuid = UUID_SERVCLASS_SERIAL_PORT; if ((sdpmtdt->AddServiceClassIdList(1, &mtdtSerPortGuid))!= SDP_OK) { AfxMessageBox("Unable to register SDP record"); exit(-1); } if ((sdpmtdt->AddServiceName("Motion Detector Serial Port"))!= SDP_OK) { AfxMessageBox("Unable to set Service Name"); exit(-1); } if ((sdpmtdt->AddRFCommProtocolDescriptor(scn))!= SDP_OK) { AfxMessageBox("Unable to set SCN in SDP DB"); exit(-1); } if ((sdpmtdt->MakePublicBrowseable())!=SDP_OK)

Chua Hun Seng s38042580

147

Home Security System with Bluetooth Technology


{ AfxMessageBox("Unable to set SDP record as browsable"); }

rfcommServ->SetSecurityLevel("Motion Detector Serial Port", BTM_SEC_NONE, TRUE /*Server*/);

if (OpenServer(scn)!= SUCCESS) { AfxMessageBox("Unable to start server"); exit(-1); } else { m_scn = scn; } }

// MtDtRfcommPort.h: interface for the CMtDtRfcommPort class.

Chua Hun Seng s38042580

148

Home Security System with Bluetooth Technology


// ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MTDTRFCOMMPORT_H__ABF957C1_B353_11D5_9DAF_0080BD080808__INCLUDED_) #define AFX_MTDTRFCOMMPORT_H__ABF957C1_B353_11D5_9DAF_0080BD080808__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BtIfDefinitions.h" #include "BtIfClasses.h"

class CMtDtRfcommPort : public CRfCommPort { public: void OnEventReceived(UINT32 event_code); void OnDataReceived(UINT16 len, void *data); CMtDtRfcommPort(); virtual ~CMtDtRfcommPort(); }; #endif // !defined(AFX_MTDTRFCOMMPORT_H__ABF957C1_B353_11D5_9DAF_0080BD080808__INCLUDED_)

// MtDtRfcommPort.cpp: implementation of the CMtDtRfcommPort class. //

Chua Hun Seng s38042580

149

Home Security System with Bluetooth Technology


////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "BtWidcommServ.h" #include "MtDtRfcommPort.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMtDtRfcommPort::CMtDtRfcommPort() { } CMtDtRfcommPort::~CMtDtRfcommPort() { } void CMtDtRfcommPort::OnDataReceived(UINT16 len, void *data) { AfxMessageBox("Data"); } void CMtDtRfcommPort::OnEventReceived(UINT32 event_code) { switch (event_code) { case PORT_EV_CONNECTED: AfxMessageBox("Connected"); CRfCommPort::Close(); break; } }

Chua Hun Seng s38042580

150

S-ar putea să vă placă și