08195432 - Introduction - University of Hertfordshire

advertisement
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
M.sc. Modular Masters in Electronics
Final Project Report
School of Engineering and Technology
Faculty of Science, Technology and Creative Arts
University of Hertfordshire
Smart Home Assisted Living
Report By:
S. M. ATIQUE MOSLEHUDDIN
Supervisor
JOHANN SIAU
8TH of September 2010
1
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Declaration statement
I certify that the work submitted is my own and that any material derived or quoted from the
published or unpublished work of other persons has been duly acknowledged (ref. UPR
AS/C/6.1, Section 7 and UPT AS/C/5, Section 3.6)
Student Full Name: S. M. ATIQUE MOSLEHUDDIN
Student Registration Number: 08195432
Signed: …………………………………………………
Date: 09 February 2016
2
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Abstract
This documentation describes the project work which is based on existing project device where
this project will update and extend a existing device and to design a wearable wrist-belt that
will provide more flexibility, efficiency and effectiveness to assisted living residence by sending
their physical data such as heart beat, pulse reading, blood pressure, temperature, body
movement, location etc. In this project data transmission is done using wireless media Zigbee
and Mobile network. Project deals with the construction of mobile embedded device for
continuous monitoring assisted living residence such as disable or elderly people’s health
condition, movement, location and send this data through wireless communication system to
the service provider or emergency service center. In this report it is proposed a wearable wrist
belt for 24 hours patient monitoring service. This report indicates the working stages
undertaken to design, development and implementation of the device. It also provides the
workout on project management including risk assessment and drawbacks of projects. In the
end report highlights the outcomes of project according to real time and future development
for more successful implementation in different areas of assistive living for elderly citizen.
3
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Acknowledgement
I would like to being thankful to all those who supported me throughout this project. First and
foremost, I am deeply indebted to my project supervisor, Mr. Johann Siau for giving me the
chance to work on this project. I express my sincere thanks to him for the support, invaluable
advice, guidance, useful suggestions and encouragement throughout the project work. I would
like to thank Mr. John Wilmot and Mr. Ian Munro for their logistic support. I would like to give a
very special thanks to Md Ibna Zaman whose project work I updated and extended here. I really
appreciate for his help and advice.
Last but not the least; I would like to thank my parents and my fiancé for supporting me
throughout my time of study in the United Kingdom.
4
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Table of Contents
Declaration statement .................................................................................................................... 2
Abstract ........................................................................................................................................... 3
Acknowledgement .......................................................................................................................... 4
List of Figures .................................................................................................................................. 6
Glossary ........................................................................................................................................... 7
1.
2.
3.
4.
Introduction ............................................................................................................................. 8
1.1.
Project Motivation ........................................................................................................... 8
1.2.
Aim ................................................................................................................................... 9
1.3.
Objectives ......................................................................................................................... 9
1.4.
Project Outline ............................................................................................................... 10
1.5.
Report Outline ................................................................................................................ 10
Literature Review .................................................................................................................. 12
2.1.
Related work: ................................................................................................................. 12
2.2.
Home Automation: ......................................................................................................... 14
2.3.
Smart Home: .................................................................................................................. 15
2.4.
I2C Bus:............................................................................................................................ 16
2.5.
.Net Micro Framework: .................................................................................................. 17
2.6.
Telit GM862 GPS Communication Module: ................................................................... 17
2.7.
AT Command: ................................................................................................................. 18
Device Design & Development: ............................................................................................. 19
3.1.
Proposed System Overview: .......................................................................................... 19
3.2.
Proposed System Design: ............................................................................................... 21
3.2.1.
Microcontroller Unit (Meridian/P): ........................................................................ 22
3.2.2.
Sensors Unit: ........................................................................................................... 23
3.2.3.
Communication Unit (Telit GM862 GPS): ............................................................... 25
Project Implementation......................................................................................................... 28
4.1.
Hardware Implementation ............................................................................................. 28
4.2.
Software Implementation .............................................................................................. 30
5
School of Electronic, Communication and Electrical Engineering
5.
6.
4.2.1.
Sensors and Panic Button: ...................................................................................... 30
4.2.2.
Embedded Device: .................................................................................................. 31
4.2.3.
Telit GM862 GPS: .................................................................................................... 33
Testing, Simulation & Analysis of Result: .............................................................................. 36
5.1.
Hardware Testing: .......................................................................................................... 36
5.2.
Software Testing: ........................................................................................................... 36
5.3.
Simulation and Analysis of Result: ................................................................................. 37
Project Management: ............................................................................................................ 43
6.1.
7.
M.sc. Final Project Report
Risk Assessment and Drawbacks of Project: .................................................................. 43
Conclusion ............................................................................................................................. 45
7.1.
Future development: ..................................................................................................... 45
References .................................................................................................................................... 47
Appendix A .................................................................................................................................... 50
List of Figures
Figure 2-1 Smart Home [16].......................................................................................................... 15
Figure 2-2 Device are connected with microcontroller through I2C [25] ..................................... 16
Figure 3-1 Wrist-belt operation system [25] ................................................................................ 20
Figure 3-2 Block diagram of wrist-belt [25] .................................................................................. 21
Figure 3-3 (a) Meridian/p (b) Connection socket (c) Schematic diagram of Meridian/p Exp2
[28],[25]......................................................................................................................................... 22
Figure 3-4 (a) Temperature sensor of DS1624 (b) Schematic diagram of DS1624 (c) DS1624
connection [29],[25] ..................................................................................................................... 23
Figure 3-5 (a) Accelerometer LIS302DL (b) Schematic pin outline of LIS302DL (c) LIS302DL
connection .................................................................................................................................... 24
Figure 3-6 (a) Panic button (b) Schematic diagram of panic button (c) Connection with
microcontroller ............................................................................................................................. 24
Figure 3-7 Telit GM862 GPS view, Schematic diagram of Telit GM862 GPS, connection of Telit
GM862 GPS ................................................................................................................................... 25
Figure 3-8 Telit GM862 GPS connector architecture [45] ............................................................ 26
Figure 3-9 GSM antenna requirement [45] .................................................................................. 26
Figure 3-10 GPS antenna requirement [45].................................................................................. 27
Figure 3-11 Schematic diagram of proposed embedded system ................................................. 27
Figure 4-1 Meridian/p with sensors in breadboard [] .................................................................. 28
6
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 4-2 Telit GM862 GPS with GPS & GSM antenna ................................................................ 29
Figure 4-3 Total proposed device ................................................................................................. 29
Figure 4-4 (a) DS1624 programming code (b) LIS302DL programming code ............................... 30
Figure 4-5 Panic button programming code ................................................................................. 31
Figure 4-6 Telit GM862 GPS programming block in .net micro framework ................................. 34
Figure 5-1 PuTTY configuration window ....................................................................................... 37
Figure 5-2 AT Command in PuTTY screen (part 1) ........................................................................ 38
Figure 5-3 AT Command in PuTTY screen (part 2) ........................................................................ 40
Figure 5-4 AT Command in PuTTY screen (part 3) ........................................................................ 41
Figure 5-5 AT Command PuTTY screen (part 4) ............................................................................ 41
Figure 6-1 Schematic Diagram of present wrist-belt diagram...................................................... 44
Glossary
MEMS- Micro Electro-Mechanical systems
GSM-Global System for Mobile
GPRS- General Packet Radio Service
UMTS- Universal Mobile Telecommunications System
PDA- Personal Digital Assistant.
SPI- Serial Peripheral Interface
IP- Internet Protocol
CPU- Central Processing Unit
SDA- Serial Data Address
SCL- Serial Clock Line
pF/kF- pico farads / kilo farads
LR-WPAN- low-rate wireless personal area networks
DSSS- Direct Sequence Spread Spectrum.
UART- Universal Asynchronous Receive/Transmitters
CTS/ RTS - Clear to Send / Request to Send
GSM- Global System for Mobile Communications
GPIO- General Purpose Input /Output
Li-ion- Lithium-Ion
DIP- Dual In-line Package
MISO - Master Output/Slave Input
MISO- Master Input/ Slave Output
SDO- Serial Data Output.
AC/DC- Access Current /Direct Current
MSOP- Mini Small Outline Package,
USB- Universal Serial Bus
FPGA- field-programmable gate array
PCB- Printed Circuit Board
7
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
1. Introduction
The implementation of a residential network for smart home assisted living healthcare service
is bringing a new scope for continuous long-term monitoring of assisted and independent-living
residents or elderly citizens. The introduction part provides the project motivation, aims &
objectives as well as project guideline and report guideline.
1.1. Project Motivation
Assisted living residences or senior citizens means those people who need supervision or help
with activities of their day to day life living .The residents are getting extra help outside health
care providers from the 3rd party. Coordination and monitoring of elderly people and keep an
eye on their daily activities to help to ensure their health, safety, and well-being. A trained staff
person provides assistance for administration or supervision of medication, or personal care
services which can be a part of assistance. Assisted living as it exists today emerged in the 1990s
as an eldercare alternative on the continuum of care for people, normally seniors, for
whom Independent living is no longer appropriate but who do not need the 24-hour medical
care provided by a nursing home. Assisted living is a philosophy of care and services promoting
independence and dignity. In the 1990's, assisted living emerged as the next step of continuing
care for people who cannot live independently in a private residence, but who also do not
require the 24-hour medical care provided by a nursing home. [2] In 1980, assisted living
technology concept developed, when microelectromechanical systems (MEMS) have been used
in the medical industry for a variety of silicon pressure, accelerometer, and custom
microstructure applications [1], [25]
As the world’s population ages, those suffering from diseases of elderly and disability are
increasing day by day. So the raising healthcare service costs and the increasing elderly
population are placing a too much pressure on current health care service. An adult who are
aged, infirm or disabled, in particular those with chronic conditions, needs long-term health
monitoring. By using modern home automation system which is called smart home provides
those 24 hours monitoring and continuous care in home environment. Different wearable
sensors build a network in the device for measuring various data and send to receiver by using
wire or wireless communication. [25]This system can be used for single patient or a group of
patients from their care home system. So the service providers can monitor a group of patients
at a time even they can monitor individual patient as well. The network system integrates into a
device which can have audio, video, wearable sensors. Some wearable sensors are placed on
the patient body and some placed inside the living space such as bed, wall etc. such kind device
sending information in a 24/7 basis to the healthcare provider system about the health status
of the resident. Data is collected, aggregated, pre-processed, stored, and acted upon using a
8
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
variety of sensors and devices. Data can be sending through main power line, radio frequency
(RF), Wi-Fi, inferred or Bluetooth etc. [25]
1.2. Aim
The aim of this project is:
To update and extend a existing project device and to design a wearable wrist-belt that will
provide more flexibility, efficiency and effectiveness to assisted living residence by sending their
physical data such as heart beat, pulse reading, blood pressure, temperature, body movement,
location etc. through wirelessly data transmitting media named Zigbee and Mobile network.
Design sensors networking and embedded device which have made it feasible to monitor and
provide medical and other living assistance to people in their homes and outside the home as
well.
1.3. Objectives
Objectives are required to achieve the goal of this project are as follow: The main object can be
divided into two parts. One is hardware and other is software.
 Before going to hardware part, comprehensive study and investigation of various
communication modules/devices is very essential to find out proper communication
device that going to work with meridian/p under control. This is the heart part of this
project. As it will decide how the device is communicate with the smart home other
device. There are many ways to transmit the data through device but here prefer wireless
communication. So the project designed with Telit GM862 GPS communication module.
The details of Telit GM862 GPS communication module is given in section 2.6.
 As it is an update work of existing device, here in the breadboard, some device are all
ready connected which are accelerometer, temperature sensor, panic button, power
management unit and Meridian/P. The accelerometer (LIS302DL) for movement
monitoring and temperature sensor (DIS1624) are connected with I2C Bus of Meridian/P
microcontroller are given a brief explanation in section 2.4 and 3.2.1.
 Second part software part where existing project is developed C# for sensors network and
microcontroller. Here, the author synchronizing Telit GM862 GPS communication module
& Meridian/P microcontroller by C# on .Net Micro framework the programming code. In
section 2.5 details of .NET Micro framework is briefly explained as well.
 After completing the whole hardware design and programming, test the whole system.
Sometimes modification requires in hardware design and programming code. The result
analyzed form the output of the system. The detail provides in Chapter 5.
9
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
1.4. Project Outline
This M.Sc. project deals with wireless communication system under control by meridian/p.
There were different stages involved in this project.
 First stage was the comprehensive investigation of existing & available devices that are best
suited for the given project.
 Second stage was the investigation of a specific communication module and here is Telit
GM862 GPS. Telit GM862 GPS implementation according to the requirements of the
project’s microcontroller meridian/p. This module integrated with GSM, GPRS & GPS.
Telit GM862 GPS is getting data from meridian/p and transferring that data to other mobile
phone through GSM network as a text message.
 Next stage was the verification stage and for above purpose, after finishing hardware
part, Telit GM862 GPS is configured with PUTTY configuration and write in AT command.
Once AT command is successful, write code in .net micro framework for synchronizing
and transfer data from meridian/p to other mobile device through GSM. This was the
final stage of project that includes the hardware implementation.
1.5. Report Outline
This report consists of six chapters.
 Chapter 1: Introduces with assisted living technology the project’s background. This
section includes motivation behind the project, its aim and objectives. It also given
direction about project & report outline.
 Chapter 2: Presents literature review, all background information which is related with
this project has been discussed in this section. It covers related work, home automation,
.NET Micro framework, I2 C Bus and Telit GM862 GPS communication module.
 Chapter 3: Highlights on whole system overview and design. As the author working over
on existing project and updating over project, here still is given a recap of existing
project and forwarded to the update development which is also include block diagram
of the project and the schematic diagram of the design. Design of each part has been
explained briefly in this section from the existing device. The connections between
Meridian/P and all other components are shown here as well. Communication unit Telit
GM862 GPS is designed and explained with diagram. It also shows how is connecting
with meridian/p and send data to other devices.[25]
 Chapter 4: Discussed on hardware and software implementation in this section. The
programming code of each component briefly and whole system is explained in
software implementation section specially communication unit Telit GM862 GPS.
10
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
 Chapter 5: The output result is analysed in this chapter. The output from Telit GM862
GPS is discussed, Analysis and the result is explained as well.
 Chapter 6: Project management is very important part in project handling and
scheduling. Risk assessment and drawbacks of project have been briefly discussed in this
chapter.
 Chapter 7: Terminating the report by discussing the future enhancements that can be
used for further research and development in this field and also presents the overall
conclusions for the project and recommendations are provided here for more useful
applications.
11
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
2. Literature Review
2.1. Related work:
Today in this world, there are around 600 million persons aged 60 years. This total number will
double by 2025. [31]With the population is growing older, the demand for healthcare is
growing more fast. To meet the demand for more healthcare service people are starting to look
for new healthcare technology in less expensive way. Due to this high increase the number of
aging population expresses that the automatic home monitoring will represent major challenge
near future. Advances in communication systems, sensors, and embedded devices have made
possible solution to monitor and provide medical and other assistance to assisted people in
their homes. With the help of modern technology make the home more comfortable, reliable
and caring for elder people. Aging populations will be benefitted from reduced costs and
improved healthcare through assisted living based technologies. Healthcare service for elderly
people is a vast area with lots of potentials work. So many institutions and companies are doing
different kind of research within the area. [25]
IMEC’s developed wireless ECG patch device which is a wearable, wire-free system easy to setup device. The device is suited for remote monitoring of patients in their daily environment,
resulting in more natural readings and greatly increasing the patient’s comfort. Imec’s another
technology such as the ECG necklace prototype, which can be used for permanent screening of
people at risk of cardiovascular disorders, heartbeat and beat analysis information for fit &
healthy people, and therapy compliance and follow-up for people under cardiovascular
treatment. Imec’s Ultra-Low-Power Sensors and Actuators used for next generation medical
devices will enable monitoring of human metabolites and the personal environment for realtime risk assessment. [34], [33]
Imperial Collage of London has brought a device named UbiMon. UbiMon is designed to
addressing general issues related to using wearable and implantable sensors for distributed
mobile monitoring service. Ubimon is a Low power sensor consumption device that also
integrated local processing with remote long term trend analysis and Multi-sensory fusion and
data mining with forecast for critical events what can play a significant role in arrhythmic heart
disease called Cardiovascular disease. They also developed two other device regarding assisted
living named are e-AR which is used for capturing the posture, gait and activity of the patient.
They also developed an implantable cardiac monitor that supposedly can detect changes in
cardiac contractility, hence can function as a continuous (and also wireless) heart failure
monitor. [6], [32],[25]
St. Jude Medical has announced new device named Merlin@home transmitter, an RF wireless
technology that remotely monitors patients’ implanted cardiac devices. The transmitter
12
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
supports existing Medical data management system, Merlin.net Patient Care Network (PCN), to
provide complete remote care service for patients and their physicians. [37]
Harvard University developed CodeBlue and Mercury is wireless sensor network for health care
service. The applications of wireless sensor network technology to a range of medical service
including pre-hospital and in-hospital emergency care, disaster response, and stroke patient
rehabilitation. [3]. Mercury is a sensor network platform device includes long sensor node
lifetime, autonomous operation, and the need for the system to automatically tune its behavior
in response to fluctuations in radio bandwidth and energy availability. A Mercury network
consists of a number of wearable sensors and a base station installed in the patient's home.
Each sensor samples multiple channels of accelerometer, gyroscope, and/or physiological data
and stores raw signals to local flash. An earlier version of Mercury (v1.0) is used on the patient
of Parkinson (Motor neuron disease) and Epilepsy (Brain Disease). [4], [25]
MIT worked on wireless blood pressure monitor system. They developed a wearable blood
pressure sensor that can show continuous 24-hour monitoring. [11] This device monitors
patient high blood pressure (BP) and sends data through radio frequency signal. It could help
diagnose hypertension, heart disease. [11], [25]
Microsoft Corporation introduced HealthGear. It is a real-time wearable system for monitoring,
visualizing and analyzing physiological signals. [12] It is set of non-invasive physiological sensors
which wirelessly connected via Bluetooth to a cell phone which stores, transmits and analyzes
the data. [12], [25]
IMIA & EAMA promoting of research and development in the area of smart homes and ambient
assisted living applications, A “smart home” is a residential setting equipped for illness, infirmity
or reduced mobility specially for aged people with a set of advanced electronics, sensors and
automated devices specifically designed for care delivery, remote monitoring, early detection
of problems or emergency cases and promotion of residential safety and quality of life. This
system is patient-centered rather than institution. [35]
British Telecom and Anchor Trust build together a system which is capable of monitoring
people's movements and looking for deviations from a 'normal' pattern of behavior that may
indicate a potential problem. [9],[25]
Mobihealth is a mobile healthcare project is funded by European Commission. They used GPRS
or UMTS services in healthcare. The system allows patients to be fully mobile whilst
undergoing health monitoring. The patients wear a lightweight monitoring system called the
MobiHealth Body Area Network which is customized to their individual health needs. So it can
monitor of patients status and progress as well as quick handling of emergency condition.
[10],[25]
Royal Philips Electronics has developed Lifeline with AutoAlert, a medical alert service which is
able to detect falls and call for help for elder people. The alert system consists of pendant-style
13
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
button. The button is worn around the neck which can be pressed to call for assistance at any
time. [7],[25]
Corventis is developed of wireless CHF (Congestive Heart Failure) monitoring system that
measure heart rate, heart rate variability, respiratory rate, fluid status and activity. [8] Piix
designed to remote wireless monitoring technology in proactively managing heart failure
patients and reducing hospital readmissions. [8],[25]
CardioNet designed a remote heart monitoring system where ECG signals are transmitted to a
PDA (Personal Digital Assistant) and then routed to the central server by using the cellular
network. [5]
ST+D invented a tiny device will enable clinicians to check a patient’s condition irrespective of
where they are. The ground-breaking “no wires” technology will also help to reduce patients’
time in hospital and free up beds more quickly. [33]
2.2. Home Automation:
World gets more and more technologically advanced and innovative where people find new
technology coming in deeper and deeper into their personal lives even at home. Home
automation is becoming more and more popular around the world and is becoming a
common product. [13] The steps of home automation works by making almost everything in
the house automatically controlled using technology to control and do the works that people
would normally do manually. It is much easier to install home automation in a house while it
has the ability to put things inside the walls to save space. Though, people who have houses
already built can still have home automation done in a less intrusive way through wireless
communication systems. It takes care of a lot of different things in the house. Some of these
things are as simple as turning on the sprinklers at a certain time every day and detecting
burglars in the middle of the night. Others are much more advanced like sensing the presence
of the person in a room and adjusting light ambiance, the temperature in the room, the
volume of the music, according to different factors like the day of the week and the time. [13],
[14] Home Automation provides added comfort, convenience, enhances people security and
produces environmental savings in all their home systems which they automate. Home
automation technique can be applied in the control of home entertainment systems,
houseplant watering and kitchen applications. There are four types of home control system
named power line carrier system, wireless system, and hardwired system and IP control. [15],
[25] Power line carrier system is X10 based system. It operates through existing wire lines.
Wireless system is based on the data transmission through radio frequency technology.
Hardwired system introduces systems which can operate over high-grade communications
cable. IP control means that house operates like its own secure Internet via a Web server, or a
computer network. [15] For this project wireless system is used but IP (Internet Protocol)
control system can be applicable in future application. Home automation for the elderly and
14
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
disabled can provide increased quality of life for persons who might otherwise require
caregivers or institutional care.[25]
Here using home automation system to monitor their daily activities. Home automation is
being implemented for assistive living in order to offer more safety and security. This system
provides more options for the assistive people who would prefer to stay in the comfort of
their homes independently rather than move to a healthcare facility.
2.3. Smart Home:
A home that uses the latest smart technology to give people with dementia and other serious
long-term health conditions greater independence will be will be showcased in this section. The
home which is operating through automated system is called Smart Home. Smart Home designs
in the concept of Home Automation. The main concept of home automation is to employ
sensors and control systems to monitor a dwelling, and accordingly adjust the various
mechanisms that provide heat, ventilation, lighting, and other services. [17] , [25]
Figure 2-1 Smart Home [16]
In figure 2-1 shows a house is in the concept of Smart Home where every system is control and
monitoring. By definition, a dwelling incorporating a communications network that connects
the key electrical appliances and services, and allows them to be remotely controlled,
monitored or accessed. [18] This can provide more control and security in different home
applications. It provides services in six different areas environmental, security, home
entertainment, domestic appliances, information and communication and health care. [18] The
assistive people can be monitored 24 hours basis in homely environment. Smart home system
provides medication reminder, health monitoring, indication of any emergency situations like
fallen. [18] Smart home is real time technology and it's becoming increasingly sophisticated.
15
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
[19] The idea of Smart Homes carries a vital role in the planning of future housing-based models
of care.[25]
2.4. I2C Bus:
In this project all the sensors are only connected with microcontroller (Meridian/P) by using I2 C
bus. This bus is designed by the manufactures of the component. It is a multi-master bus. So
more than one device can be connected with this bus shows in Figure 2-2. The I2 C translates
into "Inter IC” can be called as IIC or I2C Bus. [21] The bus I2 C as designed by Philips in the
early '80s to allow easy communication between components which reside on the same circuit
board. Philips Semiconductors migrated to NXP Semiconductor in 2006. I2C is not only used on
single boards, but can also to connect components which are linked via cable. This bus is Simple
and flexible which are key characteristics that make attractive to many applications. [21],[24],
[25]
Figure 2-2 Device are connected with microcontroller through I2C [25]
I2C Bus requires two bus lines. One is serial data line (SDA) and other is serial clock line (SCL).
[22] It is a multi-master bus including collision detection and arbitration to prevent data
corruption if two or more masters simultaneously initiate data transfer. [22] Here the sensors
are connected with meridian/p microcontroller by using I2C bus. The device can operate as
either a transmitter or receiver, depending on the function of the device. In addition to
transmitters and receivers, devices can also be considered as masters or slaves during data
transmission. [23] A master is the device which initiates a data transfer on the bus and
generates the clock signals to permit that transfer. At that time, any device addressed is
considered a slave. [23],[25]
16
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
2.5. .Net Micro Framework:
This project is based on embedded device which is designed by using .NET Micro Framework.
The .NET Micro Framework is .NET for small and resource constrained devices. It offers a
complete and effective development and execution environment that brings the productivity of
modern computing tools to this class of devices. It does not require an operating system due to
have features to operate like a subset of the operating system. [38] The .NET Micro Framework
does not operate like traditional operating system and it was developed by Microsoft Research.
[38] It works as a bootable run time and its platform can also run in 32-bit processor. [38] The
.NET Micro Framework gives user easy develop powerful, interactive, and complex applications
in a flexible way for an embedded device. It is more applicable in small technology. That’s why
it was known as SPOT (Small Personal Objects Technology). [38],[25]
The .NET Micro Framework helps to write code more reusable way. This can also extend and
modify any existing code easily. It has high level of tools and libraries which help to design the
embedded device quickly. The implementation system is very easy and more flexible. It can
securely connect devices over wired or wireless protocols which is one of the reasons to use
this in this project where the Meridian/P is connected with other components. The
programming for this project is written in C# in .NET Micro Framework platform. [36]
2.6. Telit GM862 GPS Communication Module:
The GM862-GPS module is a new product of Telit Communications PLC which is a global vendor
of wireless machine to machine (M2M) technology. [42] It combines better performance in
quad-band GSM/GPRS modem functionality with the latest 20-channel high sensitivity
SiRFstarIII™ single-chip GPS receiver. It have all the features of the GM862-QUAD version like
Voice, Circuit Switched Data transfer, Phonebook, SMS, four bands GSM capability, hot removal
sensing on board SIM Reader, GPRS Class 10 and battery charger circuitry. It has pin-to-pin
compatibility to the previous GM862-GPS module enhances and expends the functionality of
new and existing GPS uses. With its terrific design, extended temperature range, integrated SIM
card holder and industrial-grade connectors, the Telit GM862-GPS is the ideal platform for
mobile applications in areas such as Telemetry and Telecontrol in medical, Security systems,
vending machines, POS terminals, phones and payphones, return channel for digital
broadcasting. The GPS receiver features low power consumption with position resolution
accuracy of less than 2.5m as well as high sensitivity for indoor fixes. [43] These characteristics
combined with the available Python™ application development environment translate into a
very cost effective and feature rich platform quite capable of becoming the total solution for
the complete customer demand application. It also including jamming detection, integrated
TCP/IP protocol stack, and Easy Scan® offer unmatched benefits to the application developer
without any additional cost. All Telit modules have Over-the-Air firmware update by means
17
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
premium FOTA Management facilities. By embedding RedBend’s vCurrent® agent, a proven and
battle-tested technology powering hundreds of millions of cellular handsets world-wide. Telit is
capable to update its products by transmitting only a delta file, which represents the difference
between one firmware version and another. Telit’s all products comply with the RoHS
(Restriction of Hazardous Substances) directive of the European Union. It approved from R&
TTE, ANATEL and lots of other organization. As it is an update work of existing project, where
meridian/p microcontroller was developed with Zigbee communication which is replaced by
Telit GM862 GPS. Zigbee has very low range coverage of wireless transmission (indoor/outdoor
range is 30m to 100m) which is all right if the patient is in home but if the patient is outside of
home & out of Zigbee range total communication may be failed. Telit GM862 GPS is total
solution of this problem because it has GSM, GPRS & GPS facility. It will get all data from
Meridian/p about patient and it will sent it to other GSM device such as mobile phone or PDA
with patient’s actual location. Here Telit GM862 GPS is connected with the UART pin of the
microcontroller (Meridian/P). [43]The details connection between Meridian/P and Telit GM862
GPS in section 3.2.1 and 3.2.3.
2.7. AT Command:
AT command is a set of machine instructions used to control an intelligent modem device.
Hayes Microcomputer introduced AT command and officially known as the Hayes Standard AT
Command Set. The AT is an ATTENTION command and is used as a prefix to other parameters in
a string.[44] The AT command adjust with other parameters can be set up in the
communications package or typed in manually as a command line instruction. It is used entirely
or partially by most every modem manufacturer. Here the Telit wireless module GM862 GPS
can be controlled via the serial interface using the standard AT commands instruction.
The Telit wireless module GM862 GPS is compatible with:
 Hayes standard AT command set, in order to maintain the suitability with existing software
programs.
 3GPP TS 27.007 specific AT command and GPRS specific commands instruction.
 3GPP TS 27.005 specific AT commands for SMS (Short Message Service) and CBS (Cell
Broadcast Service)
However, Telit wireless module family also supports Telit proprietary AT commands for special
purposes. Here AT command is used in PuTTY configuration in section 5.3.[40]
18
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
3. Device Design & Development:
Here this project is based on the exiting Smart home system where designed a device for
assisted living people like elderly/senior citizen or a disable patient who need 24/7 health
monitoring service. In paragraph 3.1 showed the architecture by developing a collection of
applications and executing them in a prototype system. In paragraph 3.2 represents on only
wrist belt which wearied by the patient and monitor from the remote health care center. Here
is also described design of each part of wrist belt like sensor unit, communication unit and
microcontroller unit. All units connect and work together. The schematic diagram of the
designed system is given below in section 3.2.3.
3.1. Proposed System Overview:
As it is update work existing project, the main goal of this project is to design a device for
assistive residences to monitor their health in 24 hours basis from remote health care center
and it is a part of smart home automation system. Here for monitoring patient a wearable wrist
belt is developed which is designed with Telit GM862 GPS and sensors. LIS302DL is using as
accelerometer for patient body movement and DS1624 is a temperature sensor to measure
temperature of patient. Additionally a panic button is added in the design for the client who
has problems in speech or emergency situation; they can call for assistance by pressing that
button. A brief description is given below in section 3.2. All components are connected and
controlled by Meridian/P microcontroller. Telit GM862 GPS is also connected with the wrist belt
which is always sending data through GSM to mobile phone or GPRS to mail server database
which is connected to remote health service center. The whole operation of the system is
shown in Figure 3-1.
19
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 3-1 Wrist-belt operation system [25]
Figure 3-1 shows that an assistive residence wearing the wrist-belt which is build with Telit
GM862 GPS Module. It can communicate through GSM/GPRS network. Here the project is
developed for GSM network only where the wrist-belt sends data as a SMS through the Telit
GM862 GPS to GSM PDA or mobile phone which is situated in assisted living center or
emergency care service. Meridian/p is controlled all devices even Telit GM862 GPS and sending
patient data in a sequence of time to GSM server. The device can send data toward Main Server
and Database by Telit GM862 GPS using GPRS service of it. The main server sends data again to
the assistive living monitoring centre and emergency service. So care centre can monitor the
assisted residence on 24/7 basis. If any problem occurs then they can provide quick feedback or
emergency service. In that case, patient information can be monitor in both ways which will
provide more accurate service for assisted living client. This system is also applicable for care
home service. By using this system care home service providers can monitor multiple patients
at a time.[25]
20
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 3-2 Block diagram of wrist-belt [25]
In Figure 3-2 shows the internal connection of the proposed wrist-belt. The accelerometer
LIS302DL and temperature sensors DS1624 are connected with Meridian/P by using I2C bus.
The explanation of this bus is given above in section 2.4. A panic button is connected with the
GPIO (General Purpose Input /Output) pin of the Meridian/P. The connections between the
sensors and panic button are described briefly under sensor unit in section 3.2.2. The collected
data will send through the Telit GM862 GPS Module which connected with the UART pin of the
Meridian/P. The microcontroller can receive or transmit data through Telit GM862 GPS
Modules. Regarding this project the Meridian/p is using sending option of Telit GM862 GPS.
Making the device wireless here using light weight rechargeable Li-ion battery which is the
wrist-belt powering the device and the person can independent to move.
3.2. Proposed System Design:
The proposed wrist belt which is developed in this project based in three parts. Those are given
below.
 Microcontroller Unit
 Sensors Unit
 Communication Unit
In this section all units are explained with schematic diagram and finally attached all units
altogether to design the whole embedded device.
21
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
3.2.1. Microcontroller Unit (Meridian/P):
Here Meridian/P Micro Development Board is used as microcontroller in this project. This is the
core of this project and sensors, Telit GM862 GPS are connected with this. The wrist belt is
designed on the base of Meridian/P. Meridian/P Micro Development Board is a compact device
where meridian/p is combined with a 100MHz Freescale i.MXS ARM920T based processor,
8MByte of SDRAM (running at 96MHz), LCD controller, USB function, GPIO, SPI and I2C bus and
serial port. The device operating voltage is 5V or 3.3v. It runs on .NET Micro Framework
platform. [28] So for programming use C# in .NET Micro Framework. Meridian/P has total 27
pins available for use as general purpose input/output pins but 19 of those pins are labeled as
GPIO pins, remaining pin are not supported by .NET Micro Framework. [28] ,[25]
Figure 3-3 (a) Meridian/p (b) Connection socket (c) Schematic diagram of Meridian/p Exp2 [28],[25]
For this project, design the device by using only expansion 2 (EXP2). Other connections like LCD
Expansion are not used. The pin identification of EXP2 is shown in above Figure 3-3. The pins
are notified with blue color those are used for designing. Rest of the pins is in black color those
are not used. Powered 4.3V to 5V DC input voltage through USB port (J1) to run Meridian/P.
The typical power consumption of Meridian/P is only 80mA and operating temperature ratio is
0°C to 70°C. [28] Maximum voltage of Input/ Output pin is 3.3V. Pin-3 gives +3.3V of output. So
this pin works as supply voltage for all devices including panic button as well. Pin 4 is 0V
designed to make it universal ground for all connections. Meridian/P supports interfacing to
device through the internal I2C bus master or SPI (Serial Peripheral Interface). [28] But here
choose I2C bus to connect with devices. The sensors LIS302DL and DS1624 are connected
through I2C bus. To connect with this bus the device has to configurable with this bus by
manufacture. The base input frequency to the I2C bus is 96MHz.[25], [28] In EXP2, Pin-20 and
Pin-22 are signaled as I2C-SDA and I2C-SCL. Serial Clock line (SCL) is used to clock data to the
bus and Serial Data line for controller send or receive data on this line. [28] If any of I2C or SPI
bus does not use then that pins can be worked as input/output pin. In this design SDA and SCL
both are pulled up with 47KΩ resistors. Telit GM862 GPS is connected with UART (Universal
Asynchronous Receive/Transmitters) pins of meridian/p for data communication. Meridian/P
22
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
has two UART pins. Here using UART1 of EXP2. Both UART 1 and UART2 are available serial
ports (COM1 and COM2) under the .NET Micro Framework. [28] In this design using all the
UART pins of EXP2. The connections between UART pins and Telit GM862 GPS are given in
details in Section 3.2.3. There are four UART pins are available in Meridian/P EXP2 where Telit
GM862 GPS is using only 2 pins which are UART1-TXD Pin-24 and UART1-RXD Pin-28 .one for
receive and another for transmit.[25]
3.2.2. Sensors Unit:
This part carried from old project for better understanding the project.Sensor Unit is designed for
two devices which are DS1624 temperature sensor and LIS302DL accelerometer and a panic
button. LIS302DL is three-axis accelerometer and DS1624 is digital temperature sensor are
connect with I2C serial interface. In this section has briefly explained the connections of both
sensors as well as the panic button. Both are using supply voltage and I2C bus from Meridian/P.
This area is focuses on the Dallas 1624 Digital Thermometer. The DS1624 provides a direct 13 bit
reading (0.03125 degrees C) and also includes a 256 byte EEPROM. The DS1624 might be a part
of a data logger where some 120 temperatures are stored over time and the client transports the
data from the remote data logger by easily recovering this device and reading it to a PC for
analysis. This device uses the I2C protocol developed by Philips. [29],[25]
Figure 3-4 (a) Temperature sensor of DS1624 (b) Schematic diagram of DS1624 (c) DS1624
connection [29],[25]
Figure 3-4 shows that Pin-1and Pin-2 is called as SDA and SCL are used for I2C bus. So Pin-1 &
Pin-1 are connected with Pin-20 and Pin-20 of Meridian/P. Those are pulled up with 47KΩ
resistor. Pin-8 is used for supply voltage of 3.3v connected Pin-3 of Meridian/P. DS1624
operates voltage is 2.8V to 5.5V. [29] Pin-3 of this sensor is not connected and Pin-4 to Pin-7
those three pins are connected to ground. [25]
23
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 3-5 (a) Accelerometer LIS302DL (b) Schematic pin outline of LIS302DL (c) LIS302DL
connection [25]
In figure 3-5 shows LIS302DL accelerometer pins outline and connection which is carried from
existing project. It is an ultra compact low-power three axis linear accelerometer. [30] It is
designed with sensing element which is capable of detecting the acceleration and an IC
interface able to provide the measured acceleration through I2C/SPI serial interface. [30]
LIS302DL has dynamically user selectable full scales of ± 2g/± 8g and it is capable of measuring
accelerations with an output data rate of 100 Hz or 400 Hz as well as the operating voltage
range is 2.16V to 3.6V and temperature range is -40°C to 85°C. [30],[25]
Pin-1 is connected with 3.3V of supply voltage of Meridian/P. Pin-2 is connected with ground.
Pin-3 is SCL. Pin-4 and Pin-5 are notified is as MOSI and MISO. MISO (Master Output/Slave
Input) and MISO (Master Input/ Slave Output) is used as SDA (Serial Data Address) and SDO
(Serial Data Output). [30] [31] Pin-4 is connected with SCL and SDA. Pin-5 is CS and leaves open.
[30] Pin-7 and Pin-8 is interrupt pin. So Pin-7 and Pin-8 are connected with Pin-17 (GPIO6) and
Pin-13 (GPIO2) of Meridian/P. The wrist belt is consisting of Panic Button. [25]
18
Figure 3-6 (a) Panic button (b) Schematic diagram of panic button (c) Connection with
microcontroller [25]
24
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
In this above figure 3-6, Panic button works here as a switch. When panic button is pressed then
it makes interruption in the whole system and giving command to the system by sending data
that assistance is need. It has two pins. One pin is connected with ground and another pin is
connected with Pin13 of Meridian/P pull up with 47KΩ resistor. The programming code of this
panic button is given in Section 4.2.1. [25]
3.2.3. Communication Unit (Telit GM862 GPS):
Telit GM862 GPS module works as data transmission unit in this whole projects. The wrist-belt
is designed with Telit GM862 GPS for communicating with other GSM mobile device. It is
connected directly with Meridian/P microcontroller. All electrical devices are controlled by
meridian/p and send data to it .Meridian/P sends those data through Telit GM862 GPS to the
GSM network.
Figure 3-7 Telit GM862 GPS view, Schematic diagram of Telit GM862 GPS, connection of Telit
GM862 GPS
In figure 3-7 shows, The Telit GM862 GPS board to board connector is a CSTP 50 pin vertical
SMD Molex 52991–0508 (male). As Telit GM862 GPS have 50 pin molex connector which is
really hard plug in to other device, a PCB board was developed with the existing project for
takeout the connection. This project is concern about 8 pins of telit out of 50 pins which are
pin-1 to pin-5, pin-7, pin-20 and pin-37. Odd number of pin like pin-1, pin-3, pin-5, and pin-7 are
used for power supply. An external power supply is given in this module. A main line socket of
220v -240v and 50/60 Hz is used which is converted by adapter into a DC voltage of 5V with
1.5A. Here Telit is operated in 3.3V. For that’s why here is using a voltage regulator LT1528.
LT1528 takes DC 5V as input and given the module 3.3V of output.pin-2 & pin-4 are using as
ground for creating the circuit. Pin-20 is called C103/TXD of Telit connected with pin-24 of
25
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
meridian/p which is called UART1-RXD. Pin-37 is called C104/RXD of Telit connected with pin-28
of meridian/p which is called UART1-TXD. By default Telit GM862 GPS is on for operation.
Figure 3-8 Telit GM862 GPS connector architecture [45]
According to the figure 3-8 shows, Telit GM862 GPS is provided have four types of interfaces
which are GSM antenna connector, Board to Board Interface connector, SIM Card Reader, GPS
antenna connector. A GSM SIM is inserted to SIM Card Reader which is provides connection
with network through GSM or GPRS. Through this SIM can send patient information from the
device to remote care center. To get GSM reception here is needed a GSM antenna which will
fulfill figure 3-8 requirement. [45]
Figure 3-9 GSM antenna requirement [45]
Here is using Compact PCB Antennas (GSMQB Antenna) for GSM Cellular applications where
high performance is required from a small size of device. It have several features like
26
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
850/900/1800/1900MHz of GSM band, very linear polarization, available with SMA/ufl or
MMCX fixing and it also operates from 2.7—5.5V.[26]
Figure 3-10 GPS antenna requirement [45]
This is using Lowrance Airmap external GPS antenna with superb performance and excellent
quality. It can catch more satellites and get stronger signal. It is ready to plug in and use. This
antenna rapidly picks up position. The base of the antenna is magnetic so it will adjust to any
metal surface. It has several features like Ultra high signal gain: 32 dB to 55 dB Gain, low power
consumption: 6 to 11 mA, output Impedance: 50 ohms, power input: 2.5V DC to 12V DC input
and waterproof.[27]
Figure 3-11 Schematic diagram of proposed embedded system
In figure 3-11, shows the proposed schematic diagram of the wrist-belt with power
management unit and this is total mobile device. All components will be powered by power
management unit which have a battery inside.
27
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
4. Project Implementation
In this chapter, the proposed design that is discussed in chapter 3 is needed hardware and
software implementation for testing and analysis. Here design is build in breadboard then the
programming code is implemented. So this section explains hardware and software
implementation of the proposed design.
4.1. Hardware Implementation
In this section provides hardware implementation of the design. At first the design is tested by
using breadboard design. After hardware testing, the Microsoft .net micro framework
programming code is applied. Breadboard is a prototype for the proposed wrist-belt device.
Final product will be carried out by PCB (Printed Circuit Board) when the breadboard design is
finished. PCB provides the pattern for industrial manufacturing. [25]
Figure 4-1 Meridian/p with sensors in breadboard [25]
28
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 4-2 Telit GM862 GPS with GPS & GSM antenna
Figure 4-3 Total proposed device
In Figure 4-1 shows the scenario of previous project work where all components are connected
with Meridian/p. It shows sensors are connected with I2C bus and panic button is connected
with GPIO pin of Meridian/P. here is also shows a power management unit which have a
rechargeable battery. Figure 4-2 shows the scenario of Telit GM862 GPS development board
with GSM and GPRS antenna. The proposed model of project shows in figure where Xbee
29
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
communication is replaced by Telit GM862 GPS. In Figure 4-1 shows the total scenario of
proposed device.
4.2. Software Implementation
This chapter will talk about the programming code that is written for this device in C# on .NET
Micro Framework platform. The .NET Micro Framework is all ready been discussed in section
2.5. The code is written by using Microsoft Visual Studio 2008 service pack1. Meridian/P runs in
.NET Micro Framework platform. It needs to download Device Solution SDK Version 3 to work
on this microcontroller. As well as download .NET Micro Framework 3.5 from Microsoft
Website.[25]
4.2.1. Sensors and Panic Button:
As it mentioned this is update and extend work of existing project, here it is given a very brief
explanation of temperature sensor DS1624 and accelerometer LIS302DL that carried from
previous project. The sensors written in RoomBoard.cs shows in Figure 4-8.
Figure 4-4 (a) DS1624 programming code (b) LIS302DL programming code
Here in figure 4-5, the code is divided under the class in different block such as Fields, Constants,
Constructors etc. To create the block writes down #region region_name. Every block differs in
function. [25]
, This block shows I2C bus configuration. This provides option for time for I2C bus.
, Here is for declaring the registers. The default address is associated on Slave
Address (SDA) for both sensors. The address is 8-bet length. [25]
30
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
, It defines as class methods that executed when an object is created [39] Here
the objects are defined in Constant block. The constructor is called I2C bus time out, bus speed
and default address for DS1624 and addressed clock rate and default address for LIS302DL. [25]
, It is located the resister mapping except default register. It defines the register
address operation mode. Both sensors are worked as a slave device. After START the slave
address is sent. I2C Slave Address can operate in Read/Write Mode. In this block the operation
mode is defined. [25]
, This requires for dispose any objects. It performs to release any
allocated resources. This method is not applied in this project.
Here define the panic button as ipPanic by using interrupt port in main function. The port
resistor mode is disabled and indicated GPIO 11. If panic button is pressed then the system is
interrupted by defining time of 500ms.[25]
Figure 4-5 Panic button programming code
Figure 4-6 shows that by pressing button the system interrupts for 500ms and sends the data
through serial port to Telit GM862 GPS. Here use debug.print so it prints the text by string. So
the receiver prints the same statement “Need Assistant”. [25]
4.2.2. Embedded Device:
Over this entire project is based on an embedded system. This section represents how the code
addressed all components together. The code for embedded device is written in Program.cs.
The components are defined under the class library. Then each component is defined individual
as well. Here Telit GM862 GPS using COM1 serial port and declares RoomBoard. It prints
“initialising...” when the device starts debugging. When compiling completes then a message
appears on screen “initialising complete”. [25]
31
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
public static void Main()
{
Debug.Print("Initialising...");
room1 = new RoomBoard(0);
gm862 = new GM862GPS("COM1");
gm862.OnRecievedSMS += new GM862GPS.RecievedSMS(gm862_OnRecievedSMS);
gm862.OnRecievingCall += new GM862GPS.RecievingCallEvent(gm862_OnRecievingCall);
gm862.OnUnsolicitedResponse
+=
new
GM862GPS.UnsolicitedResponseEvent(gm862_OnUnsolicitedResponse);
ipPanic = new InterruptPort(MeridianP.Pins.GPIO11, true, Port.ResistorMode.Disabled,
Port.InterruptMode.InterruptEdgeHigh);
ipPanic.OnInterrupt += new NativeEventHandler(ipPanic_OnInterrupt);
StartTimer();
Debug.Print("Initialisation complete");
}
static void gm862_OnUnsolicitedResponse(string Response)
{
Debug.Print("UnsolicitedResponse: " + Response);
}
static void gm862_OnRecievingCall()
{
lock (gm862)
{
Debug.Print("Receiving call");
Debug.Print("Hanging Up");
gm862.ExecuteCommand("AT+CHUP", 500);
Debug.Print("Disconnected call");
}
}
static void gm862_OnRecievedSMS(string Storage, int Number)
{
Debug.Print("SMS Received");
Debug.Print("Number: " + Number.ToString() + " | Storage: " + Storage);
}
static void ipPanic_OnInterrupt(uint data1, uint data2, TimeSpan time)
{
bool GPIO_Pin11 = true;
// while (false)
// {
if (ipPanic.Read() == true)
{
32
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
GPIO_Pin11 = !GPIO_Pin11;
Thread.Sleep(500); //Thrad used for time. So it will stop for 500ms.
Debug.Print(DateTime.Now.ToString() + "|" + ipPanic.Read().ToString());
text += DateTime.Now.ToString();
Debug.Print("Need Assistance");
//xbee.WriteData("Need Assistance");
//gm862.SendSMSMessage("Destination", "Message");
}
//
}
}
static void xbee_DataReceived(object sender, XBeeDataReceivedEventArgs e)
{
Debug.Print("Received something");
}
private static void UpdateTick()
{
Thread.Sleep(200);
text
=
room1.Temperature.ToString()
+
"|"
+
room1.GetAccelerometerValue()[0].ToString() + "|"
+
room1.GetAccelerometerValue()[1].ToString()
+
"|"
+
room1.GetAccelerometerValue()[2].ToString() + "|";
text += DateTime.Now.ToString();
Debug.Print(text);
//xbee.WriteData(text);
}
Here in above code, Second loop shows the output of Receiving Call. For receive, hang up or
disconnect call it showed different output. The output comes out in text. Last loop shows the
body temperature, then the value of x-axis, y-axis and z-axis of the accelerometer. It prints on
during debugging as well as it shows in text on the receiver.
4.2.3. Telit GM862 GPS:
Telit GM862 GPS module supports AT command. Here in .net micro framework platform can
works with AT command. GM862.cs is programming code file for Telit GM862 GPS. GM862.cs
file defined a public class named ‘GM862GPS : IDisposable’ which have 11 different blocks of
function for different operation.
33
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 4-6 Telit GM862 GPS programming block in .net micro framework
Here in figure 4-7 shows programming block in .net micro framework of Telit GM862 GPS which
have 11 blocks and all blocks have different work to do.
, 1st blocks allow serial port communication with GM862 and
declare variables of function for all other blocks.
, 2nd blocks represents mode of Telit GM86,is it Idle or active. Triggered
GM862 is in Command mode. An AT command has been send and wait data is parsed until a
valid response code is returned.
, 3rd blocks represent handling the event of the program. Unsolicited
response received and allow code to handle response. Check when there is a PIN request.
, here this bolck create new serial port Object. Create thread also
that handles unsolicited responses. Additionally,check for incomming SMS and Call.
, this block initialize the function of the block. Initializes basic
GSM functions and settings and it also initialize basic SMS settings. It define GPRS and activate
GPRS context as well.
34
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
, Request HTML page from web server. Work for GPRS communication. Get
GPS location and dimensions of Fix data (0 = No fix, 2 = 2D fix, 3 = 3D fix). Tracked number of
tracked satelites. Locate latitude and longitude in degrees.
, this block is concern about AT command that is need for
send or receive message. It also works with message storage memory.
, its main function check the network registration. Checks if
connected to a GPRS network or not. Check if there is an outstanding PIN request.if yes then try
to receive the request.
, this blocks deal with unsolicited response of
thread and events. Check there is any FIFO. It also concern about SMS response.
, it executes basic command .it also handle send
command and wait until command is send. Wait for last unsolicited response text is
received.once text is received.program back to command mode and execute another
command. Save command response body and return response
, it deals with internal function to convert a numeric string to an
integer.Internal function used to convert DD.MM.SSSS string of Latitude/Longitude to degrees.
35
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
5. Testing, Simulation & Analysis of Result:
After hardware and software implementation, here is coming test, simulation & result part.
This chapter describes shows the output after hardware and software implementations. Here
first it will be discussed about testing and after that simulation, result etc.
5.1. Hardware Testing:
This chapter focused on the hardware testing. This testing is basically based on the breadboard
design where meridian/p and Telit GM862 GPS module connected with other existing device
that carried from previous project. Testing has to parts. One is hardware and other is software.
Software testing is on the programming code and analyzed on the outputs that got from the
designed device will be discussed in Section 5.2. In this project, total circuit design is done on
the breadboard. Multi-meter measures the output voltage of different points. The whole device
is powered by the mobile power management unit. Pin-3 of Meridian/P is used here as source
for 3.3V for the sensors and panic button. The system requires approximately 305mA current
that is measured by multi-meter. [25]
5.2. Software Testing:
The programming code is written in C# language on .NET Micro Framework in PC. It is written
in Microsoft Visual Studio 2008 service pack 1. The written code is applied according to the
hardware design through Meridian/P. So the designed device is connected with a PC. The code
is implemented on the device through that PC. The code has already discussed in Section 4.2.
By pressing F5 in Microsoft Visual Studio debugs the whole programming code. The window
shows the output of the system. All data come out together. Then the designed device moves in
different directions. Result shows in output window according to data of temperature sensor,
then x-axis, y-axis and z-axis direction of accelerometer. Here date and time defined after those
values. Initially, temperature sensor shows room temperature but after touching the sensor for
few second, it was changed. From these observations, it is identified temperature, falling and
movement of the user of this proposed wrist-belt. Panic button is used for asking help. When
the button is pressed then the system is interrupted. [25]The system sends data for this
interruption through Telit to GSM device. For asking assistance, the button needs to hold for
few second. In Appendix B will provide more information about the sensors & panic button that
got from previous report.
36
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
5.3. Simulation and Analysis of Result:
The wrist-belt monitors the patients for 24 hours a day. So wrist-belt has a continuous flow of
data transmissions. To observe the data transmission through Telit GM862 GPS use PuTTY in
the PC. PuTTY is using here for simulation purpose. Here is given AT commands that are
supported by Telit GM862 GPS. PuTTY acts as an open source terminal emulator application for
SSH, Telnet and Rlogin network protocol. [41] The given protocols are used for operating a
remote session on the PC through a network. [41] It shows the display of the running session.
[25]
Figure 5-1 PuTTY configuration window
PuTTy runs in all operating system because of its Dos mode operation. The PuTTY comes out
with the window shows in Figure 5-1. Serial port is used as connection mode for this project.
Here is using a cable which has USB adapter in one side and other side a 4 pin connector. The 4
pin connector goes on Telit development board of P5 section and USB adapter goes in PC USB
socket. After installation small software, it informs about the connection of serial line. PC serial
port is used “COM1” in .net micro framework platform but “COM3” is used here as serial line
with interface speed of 9600 bps in PuTTY configuration. All are selected in Figure 5-9. [25]
37
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
PuTTy runs after selecting Open. Though Telit GM862 GPS data are sending or receiving from
GSM network. The data is sending through wireless network continuously. Here for data
communication through Telit is used AT command. AT command is all ready discussed in
section 2.7.
Figure 5-2 AT Command in PuTTY screen (part 1)
In this figure 5-2, 1st command is AT. If AT is ok that means the device is working fine. Here in
below explaining the command that are in figure 1.
ATD (dial) = ATD <number> [;], execution command starts a call to the phone number given as
parameter.
If semicolon is not omitted, a VOICE call to the given number is performed, regardless of the
current value of the connection mode set by AT+FCLASS command.
ATH (disconnect call) = ATH, execution command is used to stop the current conversation
(voice, data or fax). [20],[40]
38
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
When call came outside to Telit module then it showed “Ring” message on the screen.
AT+CLIP (calling line identification presentation) = AT+CLIP [=<n>], shows the GSM
supplementary service CLIP (Calling Line Identification Presentation) that enables a called
subscriber to get the CLI (Calling Line Identity) of the calling party when receiving a mobile
call.[20],[40]
Parameters:
<n>
0 - disables CLI indication (default)
1 - Enables CLI indication
<Type>: type of address octet in integer format
145 - International numbering scheme (contains the character "+")
129 - National numbering scheme
ATA (accept call) = ATA, execution command is used to answer to an incoming call if automatic
answer is disabled. [20],[40]
AT+CSQ (signal quality) = AT+ CSQ, execution command refers received signal quality. Here in
figure 1 showing signal level is 16 which mean signal quality is extremely bad.
AT+CMGF (message format) = AT+CMGF [=<mode>], set command selects the SMS format to
be used in reading and writing messages in telit.[20],[40]
Parameter:
<Mode>
0 - PDU (default)
1 – Text, Here is using text format. Because PDU is showed message as HEX numeric format.
AT+CMGR (location of SMS) = AT+CMGR=<index>, execution command reports the message
with location value.
(Text Mode)
For the received messages:
+CMGR: <stat>,<oa>,,<scts> [,<tooa>,<fo>,<pid>,<dcs>,<sca>,
<tosca>,<length>]<CR><LF><text>
For the sent messages:
+CMGR: <stat>,<da>[,,<toda>,<fo>,<pid>,<dcs>,,
<sca>,<tosca>,<length>]<CR><LF><testo>
Where:
<stat> - status of the message
"REC UNREAD" - new received message unread
"REC READ" - received message read
"STO UNSENT" - message stored not yet sent
"STO SENT" - message stored already sent
<fo> - first octet of the message PDU
39
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
<mr> - message reference number
<scts> - arrival time of the message to the SC
<dt> - sending time of the message
<st> - message status as coded in the PDU
<pid> - Protocol Identifier
<dcs> - Data Coding Scheme
<oa> - Originator address number
<da> - Destination address number
<sca> - Service Centre number
< tooa>,<toda >,<tosca> - type of number <oa>,<da>,<sca>
145 - number in international format (contains the "+")
129 - number in national format
<length> - text length
<text> - message text[20],[40]
Figure 5-3 AT Command in PuTTY screen (part 2)
40
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Here in figure 5-3 shows, AT+CMGL (list of message) =AT+CMGL [=<stat>], execution command
reports the list of all the messages stored into memory storage. [20],[40]
Parameter (Text Mode):
<stat>
"REC UNREAD" - new message
"REC READ" - read message
"STO UNSENT" - stored message not yet sent
"STO SENT" - store message already sent
"ALL" - all messages (applies only to +CMGL command)[20],[40]
Rest of the parameter is as same as AT+CMGR
Figure 5-4 AT Command in PuTTY screen (part 3)
Here in figure 5-4 represents, AT+CMGD (delete message) = AT+CMGD <index> [,<delflag>],
execution command deletes the message from memory. Here second message is deleted. After
that calling second message from memory it is given “ERROR” because if the location to be
deleted is empty, an error message is reported. [20],[40]
Figure 5-5 AT Command PuTTY screen (part 4)
In this figure 5-5 show, AT$GPSSW (GPS Software version) = AT$GPSSW, execution command
provides GPS Module software version in the format:
41
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
$GPSSW: <sw version>
Where <sw version> depends on the GPS chipset used. [20],[40]
AT$GPSACP (GPS Actual position information) = AT$GPSACP, execution command returns
information about the last GPS position in the format:
$GPSACP:<UTC>,<latitude>,<longitude>,<hdop>,<altitude>,<fix>,<c
og>, <spkm>,<spkn>,<date>,<nsat>
<UTC> - UTC time (hhmmss) referred to GGA sentence
<latitude>: ddmm.mmmm N/S (referred to GGA sentence) [20],[40]
Values:
dd (degrees) 00 to 90
mm.mmmm (minutes) 00,0000 to 59.9999
N/S: North / South
<longitude>: dddmm.mmmm E/W (referred to GGA sentence)
Values:
ddd (degrees) 00 to 180
mm.mmmm (minutes) 00,0000 to 59.9999
E/W: East / West
<hdop>: x.x - Horizontal Diluition of Precision (referred to GGA
sentence)
<altitude>: xxxx.x Altitude – mean-sea-level (geoid) in meters
(referred to GGA sentence)
<fix>: 1 Invalid Fix
2 2D fix
3 3D fix
(referred to GSA sentence)
<cog>: ddd.mm - Course over Ground (degrees, True) (referred to
VTG sentence)
Values:
ddd: 000 to 360 degrees
mm 00 to 59 minutes
<spkm>: xxxx.x Speed over ground (Km/hr) (referred to VTG
sentence)
<spkn>: xxxx.x- Speed over ground (knots) (referred to VTG
sentence)
<date>: ddmmyy Date of Fix (referred to RMC sentence)
Values:
dd (day) 01 to 31
mm (month) 01 to 12. [20],[40]
42
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
6. Project Management:
A project needs a proper management for a smooth progress. A few steps have to be followed
in a successful project. 1st step, a proper effective and efficient plan is need for a project. 2 nd
step is Literature review that was done at the beginning of the project. Literature review based
search and understand what the requirement for a successful project is. Literature review
includes web based search, books, journals, IEEE, IET & other electrical organization research
paper regarding the topic. 3rd step is research on the require components based. 4 th step a
paper based design was made for total diagram and circuit. 5 th step is proposed design
implemented on the breadboard. So the hardware design can be modified. Some
modifications have done in this project. Last and final step, the programming code applied on
hardware design. Then whole designed device was tested and verified.
6.1. Risk Assessment and Drawbacks of Project:
This is a wearable embedded device. So the human body considered over here very carefully.
Any kind of danger was considered as well. This device is powered by DC voltage. The
microcontroller meridian/p, Telit GM862 GPS needs 5V DC and 80mA current. [28] The entire
device need approximate 300mA-350 mA of current.[25] It works at very low voltage and
current. So there is no risk of electric shock. As it is a mobile wearable device weight is also
considered.
It is mentioned several times this is an update and extend work of existing project. When the
developer got the project the device was developed meridian/p and Zigbee with the
breadboard. The breadboard included a temperature sensor, accelerometer, power
management unit and a panic button. But power management unit was not completed and
power IC was broken as well. After finishing all most all the work, when it was time to test the
entire device by programming code .net micro frame work. Meridian/p microcontroller was not
working and it was broken. As it was very time consuming to get a new one by online and it was
not available in local market. The project was tested and simulated by PuTTY configuration
which was given as same result as in real time. Here in figure 6-1 shows diagram of present
diagram of the wrist-belt below.
43
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Figure 6-1 Schematic Diagram of present wrist-belt diagram
44
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
7. Conclusion
Now around the globe, there are around 600 million people aged 60 years. This total figure will
be double by 2025. [31] With the population is growing older, need for healthcare is growing
fast. To meet the demand for more healthcare service people are starting to look for new
healthcare technology in less expensive way. Keep in mind such kind healthcare technology,
this M.Sc. project goal is to update and extend a existing project device and to design a mobile
wearable wrist-belt that will give more flexibility, efficiency and effectiveness to assisted living
residence by sending their physical data such as heart beat, pulse reading, blood pressure,
temperature, body movement, location etc. Here in this M.sc project deals with the
investigation wireless data transmission media like Zigbee and GSM network. The key role of
this project is regarding wireless data transmission (Telit GM862 GPS) and giving customer a
total flexible and mobile compact embedded system device that will send their data to existing
GSM/GPRS network architecture without any kinds of manual interruption. This device is
capable to monitor patient home and abroad anywhere in the world. Additionally, with the
power management unit, this device can work as wireless as well as portable device.
7.1. Future development:
Research described in this report about a wrist-belt which can monitors movement and
temperature and location only. The designed device has successfully sends data to the GSM
network. In the market there are lots of healthcare technology service products that can only
do one task at a time. But here this is a compact device that is able to do multi-tasks together.
The device is using I2C bus which is multi-master bus. In future more sensors can be added with
this I2C bus. Such as blood pressure sensor, pulse-oximeter, heart-beat monitor sensor etc. [25]
By doing this, one device can measure different health related data at the same time. Many
heart disease patient use pacemaker that need batteries. The device itself will need
replacement as the batteries lose power. Now at the moment for changing batteries of
pacemaker need another operation in patient body. In the future it would be examined for
heart pacemaker that uses batteries and with this embedded device power management unit
can able to give power to pacemaker. This device can also be used in home automation service
in future. So the same device will be used is to deploy sensors and control systems to monitor a
home, and accordingly adjust the various mechanisms that provide heat, ventilation, lighting,
and other services. [25] It will allow assisted living residence or remote care center to be
remotely controlled, monitored or accessed in different home applications. Even this device can
control safety and security of the house as well. [18] Telit GM862 GPS have GSM as well as
GPRS. Here this project is used GSM facilities only. But nearby future, this project device will
45
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
capable to send data transmission through GPRS as well which will provide bulk of information
about patient to web server. Then it will come easier for doctors to keep patient’s history and
give them medication according to that information. If GPRS is implemented then a huge range
of services and products will be possible to add in this project device and customize the device
according to customer need.
46
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
References
1. Joseph Harold, Swafford, Bob & Terry, Stephen. (April 1997). MEMS in the Medical
World. Website: http://archives.sensorsmag.com/articles/0497/medical/main.shtml.
last viewed : august 2010
2. P. M. Jones (2009, January 19). Assisted Living - A Brief History and Definition. Website:
http://ezinearticles.com/?Assisted-Living---A-Brief-History-and-Definition&id=1898892.
Last viewed : august 2010
3. CodeBlue:Wireless
Sensors
for
Medical
Care.Website:
http://fiji.eecs.harvard.edu/CodeBlue. Last viewed : august 2010
4. Mercury: A Wearable Sensor Network Platform for High-Fidelity Motion Analysis.
Website: http://fiji.eecs.harvard.edu/Mercury. last viewed : august 2010
5. Ross, P.E. (December 2008). Managing Care through the Air. Website:
http://www.cs.indiana.edu/surg/pervasive/class_materials/ManagingCareThroughtheAi
r.pdf. data assessed: September 2010
6. Ubiquitous Monitoring Environment for Wearable and Implantable Sensors, website:
http://www.doc.ic.ac.uk/vip/ubimon/home/index.html. Data assessed: September 2010
7. Telemedicine Archive. website: http://www.medgadget.com/archives/telemedicine/
8. Piix Wireless Home Cardiac Monitoring to Undergo Randomized Trial. (2009, June
25).website:http://medgadget.com/archives/2009/06/wireless_home_cardiac_monitori
ng_to_undergo_randomized_trials.html. data Retrieved: September 2010
9. Porteus, J. & Brownsell, S. (2000). Exploring Technologies for Independent Living for
Older People. Website: http://www.housingcare.org/downloads/kbase/2334.pdf. Last
viewed: august 2010.
10. Innovative GPRS/UMTS mobile services for applications in healthcare. Website:
http://www.mobihealth.org. Last viewed: July 2010.
11. Asada, Harry. (2009, April 8), Wearable blood pressure sensor offers 24/7 continuous.
monitoring.Website:http://web.mit.edu/newsoffice/2009/techtalk53-21.pdf.last
viewed: august 2010.
12. Oliver, N. & Fernando, Flores-Mangas. HealthGear: A Real-time Wearable System for
Monitoring
and
Analyzing
Physiological
Signals.website:ftp://ftp.research.microsoft.com/pub/tr/TR-2005-182.pdf. Last viewed :
august 2010.
13. Home
Automation.
Website:
http://home-automation.org/.
Last
viewed:
September2010.
14. Home
Automation,
In
Wikipedia.
Website
http://en.wikipedia.org/wiki/Home_automation#Architecture//.
Last
viewed:
September 2010.
15. Home Automation. Website: http://www.esl-usa.com/home_automation.html. Last
viewed: September2010.
16. Figure2-1 Smart Home. Website: http://www.ciseco.co.uk/images/house.jpg. Last
viewed: September2010
47
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
17. Gross, Mark D. Smart House and Home Automation Technologies.
Website:http://depts.washington.edu/dmgftp/publications/pdfs/smarthouse98mdg.pdf. Last viewed: September2010
18. King, N. (September 2003). SMART HOME-A DEFINATION. Website:
http://www.housingcare.org/downloads/kbase/2545.pdf. Last viewed: September2010
19. Craven,J.
What
Is
a
“Smart
House”?
Website:
http://architecture.about.com/od/buildyourhous1/g/smarthouse.htm. Last viewed:
September2010
20. Telit technical reference manual “AT commands description”. Website:
http://www.roundsolutions.com/techdocs/gsm_modules/GM862_TRIZIUM_Family_AT_
Commands_r1.pdf. Last viewed: September2010
21. I2C Bus. Website: http://www.i2c-bus.org/. Last viewed: September2010
22. The I2C-Bus and how to use it (including specification). Website:
http://www.datsi.fi.upm.es/docencia/Micro_C/i2c.pdf. Last viewed: September2010
23. UM1024
I2C-bus
specification
and
user
manual.
Website:
http://www.nxp.com/documents/user_manual/UM10204.pdf. Last viewed: July 2010
24. History of I2C interface. Website: http://www.lammertbies.nl/comm/info/I2C-bus.html.
Last viewed: September2010
25. Final Year Project Report “Interhome: Extension on assisted living”, MD Ibne Zaman,
School of electrical, electronic & communication engineering, University of
Hertfordshire, 14th April 2010.
26. Technical
report”
GSM
Mini
Quad
Band
Antennas”.
Website:
http://www.rfsolutions.co.uk/acatalog/DS038-GSMQB-2.pdf.
Last
viewed:
September2010
27. Lowrance airmap external GPS antenna .website: http://www.lowrance.com/Products/.
Last viewed: June 2010
28. Meridian/P
Technical
Reference
Manual.
Website:
http://devicesolutions.net/Portals/0/Download/Documents/MeridianP%20Technical%20Reference%20Manual.pdf. Last viewed: September2010
29. DS1624 Digital Thermometer and Memory Product Manual. Website:
http://datasheets.maxim-ic.com/en/ds/DS1624.pdf. Last viewed: September2010
30. LIS302DL
MEMS
Motion
Sensor
Product
Manual.
Website:
http://www.st.com/stonline/books/pdf/docs/12726.pdf. Last viewed: September2010
31. World
health
organization”ageing
and
life
course”.
Website:
http://www.who.int/ageing/events/idop_rationale/en/index.html.Last
viewed:
September2010
32. Body sensor networks. website: http://ubimon.doc.ic.ac.uk/bsn/m192.html.last
viewed: September2010
33. Ultra-low-power radio wireless communication for healthcare. Website:
http://www2.imec.be/content/user/File/Leaflets/HPP2010_leaflet_ulp_radio.pdf. last
viewed: august 2010
34. Body
area
networks.
Website:
http://www2.imec.be/content/user/File/Leaflets/HPP2010_leaflet_ban.pdf.
last
viewed: august 2010
48
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
35. Smart homes. Website: http://www.health-smarthomes.org/index.html. last viewed:
august 2010
36. Microsoft
.net
micro
framework.
Website:
http://www.microsoft.com/netmf/default.mspx. data Accessed: June 2010
37. Body sensor networks. Website: http://ubimon.doc.ic.ac.uk/bsn/a1759.html. last
viewed : September 2010
38. Thompson, D. Miles, Rob.S. (2007). Embedded programming with the Microsoft .NET
Micro Framewor. Microsoft Press. Chapter1.Using Constructors (C# Programming
Guide). Website: http://msdn.microsoft.com/en-us/library/ms173115(VS.80).aspx. data
Accessed: June 2010
39. Using Constructors (C# Programming Guide). Website: http://msdn.microsoft.com/enus/library/ms173115(VS.80).aspx. last viewed : September 2010
40. Telit
technical
report
“AT
Commands
Reference
Guide”,
website:
http://www.telit.com/en/products.php?p_id=3&p_ac=show&p=7. last viewed :
September 2010
41. PuTTY FAQ. Website: http://www.chiark.greenend.org.uk/~sgtatham/putty/faq.html.
data Accessed: June 2010
42. Wikipedia of Wikimedia Foundation, Inc, “http://en.wikipedia.org/wiki/Telit”.last
viewed : September 2010
43. Telit
GM862
GPS
Website:
http://www.telit.com/en/products.php?p_id=3&p_ac=show&p=7. last viewed :
September 2010
44. Introduction
to
AT
command.
Website:
http://www.developershome.com/sms/atCommandsIntro.asp. last viewed : September
2010
45. Telit
technical
report
“GM862
Family
Hardware
User
Guide”.
http://www.telit.com/en/products.php?p_id=3&p_ac=show&p=7. last viewed :
September 2010
49
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Appendix A
EzSerials.cs
namespace InterHomeMeriP
{
public class EzSerial : SerialPort
{
public EzSerial(string port, int baudRate, Handshake handShake)
: base(port, baudRate)
{
this.Handshake = handShake;
this.Open();
}
public void Write(string message)
{
byte[] outputBuffer = Encoding.UTF8.GetBytes(message);
this.Write(outputBuffer, 0, outputBuffer.Length);
}
public string Read()
{
Thread.Sleep(100);
byte[] inputBuffer = new byte[this.BytesToRead];
this.Read(inputBuffer, 0, inputBuffer.Length);
string ret = string.Empty;
foreach (char ch in Encoding.UTF8.GetChars(inputBuffer))
ret += ch.ToString();
return ret;
}
}
}
I2CSlaves.cs
namespace InterHomeMeriP
{
public static class I2CSlave
{
private static I2CDevice _slaveDevice = new I2CDevice(new I2CDevice.Configuration(0, 0));
private static byte[] _registerBuffer = new byte[1] { 0x00 };
private static byte[] _writeBuffer = new byte[2] { 0x00, 0x00 };
/// <summary>
/// Generic write operation from I2C slave
/// </summary>
/// <param name="writeBuffer">Buffer for input</param>
public static void Write(I2CDevice.Configuration config, byte[] writeBuffer, int timeOut)
{
lock (_slaveDevice)
{
_slaveDevice.Config = config;
I2CDevice.I2CTransaction[] xact = new I2CDevice.I2CTransaction[] {
_slaveDevice.CreateWriteTransaction(writeBuffer)
};
50
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
int bytesCount = _slaveDevice.Execute(xact, timeOut);
if (bytesCount < writeBuffer.Length)
{
Thread.Sleep(2000);
throw new IOException("I2C Error");
}
}
}
/// <summary>
/// Generic read operation from I2C slave
/// </summary>
/// <param name="readBuffer">Buffer for output</param>
public static void Read(I2CDevice.Configuration config, byte[] readBuffer, int timeOut)
{
lock (_slaveDevice)
{
_slaveDevice.Config = config;
I2CDevice.I2CTransaction[] xact = new I2CDevice.I2CTransaction[] {
_slaveDevice.CreateReadTransaction(readBuffer)
};
int bytesCount = _slaveDevice.Execute(xact, timeOut);
if (bytesCount < readBuffer.Length)
{
Thread.Sleep(2000);
throw new IOException("I2C Error");
}
}
}
public static void ReadRegister(I2CDevice.Configuration config, byte register, byte[] readBuffer, int timeOut)
{
_registerBuffer[0] = register;
I2CSlave.Write(config, _registerBuffer, timeOut);
I2CSlave.Read(config, readBuffer, timeOut);
}
public static void WriteRegister(I2CDevice.Configuration config, byte register, byte[] writeBuffer, int timeOut)
{
byte[] data = new byte[writeBuffer.Length + 1];
Array.Copy(writeBuffer, 0, data, 1, writeBuffer.Length);
data[0] = register;
I2CSlave.Write(config, data, timeOut);
}
public static void WriteRegister(I2CDevice.Configuration config, byte register, byte value, int timeOut)
{
_writeBuffer[0] = register;
_writeBuffer[1] = value;
I2CSlave.Write(config, _writeBuffer, timeOut);
}
}
}
Program.cs
namespace InterHomeMeriP
{
51
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
public class Program
{
private static RoomBoard room1;
//private static XBee xbee;
private static GM862GPS gm862;
private static string text;
private static InterruptPort ipPanic;
public static void Main()
{
Debug.Print("Initialising...");
room1 = new RoomBoard(0);
//xbee = new XBee("COM1");
//xbee.DataReceived += new XBee.DataReceivedHandler(xbee_DataReceived);
gm862 = new GM862GPS("COM1");
gm862.OnRecievedSMS += new GM862GPS.RecievedSMS(gm862_OnRecievedSMS);
gm862.OnRecievingCall += new GM862GPS.RecievingCallEvent(gm862_OnRecievingCall);
gm862.OnUnsolicitedResponse
+=
new
GM862GPS.UnsolicitedResponseEvent(gm862_OnUnsolicitedResponse);
ipPanic
=
new
InterruptPort(MeridianP.Pins.GPIO11,
true,
Port.ResistorMode.Disabled,
Port.InterruptMode.InterruptEdgeHigh);
ipPanic.OnInterrupt += new NativeEventHandler(ipPanic_OnInterrupt);
StartTimer();
Debug.Print("Initialisation complete");
}
static void gm862_OnUnsolicitedResponse(string Response)
{
Debug.Print("UnsolicitedResponse: " + Response);
}
static void gm862_OnRecievingCall()
{
lock (gm862)
{
Debug.Print("Receiving call");
Debug.Print("Hanging Up");
gm862.ExecuteCommand("AT+CHUP", 500);
Debug.Print("Disconnected call");
}
}
static void gm862_OnRecievedSMS(string Storage, int Number)
{
Debug.Print("SMS Received");
Debug.Print("Number: " + Number.ToString() + " | Storage: " + Storage);
}
static void ipPanic_OnInterrupt(uint data1, uint data2, TimeSpan time)
{
bool GPIO_Pin11 = true
// while (false)
// {
if (ipPanic.Read() == true)
{
GPIO_Pin11 = !GPIO_Pin11;
Thread.Sleep(500); //Thrad used for time. So it will stop for 500ms.
52
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
Debug.Print(DateTime.Now.ToString() + "|" + ipPanic.Read().ToString());
text += DateTime.Now.ToString();
Debug.Print("Need Assistance");
//xbee.WriteData("Need Assistance");
//gm862.SendSMSMessage("Destination", "Message");
}
// }
}
static void xbee_DataReceived(object sender, XBeeDataReceivedEventArgs e)
{
Debug.Print("Received something");
}
private static void UpdateTick()
{
Thread.Sleep(200);
text = room1.Temperature.ToString() + "|" + room1.GetAccelerometerValue()[0].ToString() + "|"
+ room1.GetAccelerometerValue()[1].ToString() + "|" + room1.GetAccelerometerValue()[2].ToString() +
"|";
text += DateTime.Now.ToString();
Debug.Print(text);
//xbee.WriteData(text);
}
#region Main thread
// Delegate type for the callback
private delegate void VoidProcDelegate();
private static Thread TimerThread;
/// <summary>Starts the timer thread for the animation</summary>
static void StartTimer()
{
TimerThread = new Thread(new ThreadStart(TimerThreadProc));
TimerThread.Start();
}
static void TimerThreadProc()
{
while (TimerThread.ThreadState == ThreadState.Running)
{
DispatcherOperation
op
=
Dispatcher.CurrentDispatcher.BeginInvoke(new
VoidProcDelegate(UpdateTick));
op.Wait();
Thread.Sleep(100);
}
}
#endregion
}
}
Roomboard.cs
namespace InterHomeMeriP
{
public class RoomBoard
{
#region Drivers for on-board devices
53
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
internal sealed class DS1624
{
#region Fields
private I2CDevice.Configuration config;
//private I2CSlave _slave;
//private byte _deviceAddress;
private byte[] _dataBuffer = new byte[2] { 0x00, 0x00 };
#endregion
#region Constants
const int TIMEOUT = InterHomeConfig.I2C_TIMEOUT;
const int BUS_SPEED = InterHomeConfig.I2C_BUS_SPEED;
const byte DEFAULT_Address = 0x48;
const byte REG_IO = 0x00;
const byte REG_MEMORY = 0x17;
const byte REG_CONFIG = 0xAC;
const byte REG_TEMP = 0xAA;
const byte REG_START = 0xEE;
const byte REG_STOP = 0x22;
#endregion
#region Constructors
/// <summary>
/// DS1624 default address
/// </summary>
public DS1624()
: this(DS1624.DEFAULT_Address)
{
}
public DS1624(int deviceAddress)
{
config = new I2CDevice.Configuration((byte)(DEFAULT_Address + deviceAddress), BUS_SPEED);
}
/// <summary>
/// DS1624 Temperature Monitoring
/// </summary>
/// <param name="deviceAddress"></param>
public DS1624(byte deviceAddress)
{
config = new I2CDevice.Configuration(deviceAddress, BUS_SPEED);
//_deviceAddress = deviceAddress;
//this._slave = new I2CSlave(deviceAddress);
}
#endregion
54
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
#region Members
public byte StartConversion
{
set
{
try
{
/*
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
_slave.WriteRegister(DS1624.REG_START, _dataBuffer);
}
*/
I2CSlave.WriteRegister(config, REG_START, _dataBuffer, TIMEOUT);
}
catch (System.IO.IOException e)
{
Debug.Print(e.Message);
}
}
}
public byte StopConversion
{
set
{
try
{
/*
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
_slave.WriteRegister(DS1624.REG_STOP, _dataBuffer);
}
*/
I2CSlave.WriteRegister(config, REG_STOP, _dataBuffer, TIMEOUT);
}
catch (System.IO.IOException e)
{
Debug.Print(e.Message);
}
}
}
/// <summary>
/// Temperature Reading
/// </summary>
public byte Temp
{
get
{
try
{
/*
55
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
_slave.ReadRegister(DS1624.REG_TEMP, _dataBuffer);
}
*/
I2CSlave.ReadRegister(config, REG_TEMP, _dataBuffer, TIMEOUT);
}
catch (System.IO.IOException e)
{
Debug.Print(e.Message);
}
return _dataBuffer[0];
}
}
/// <summary>
/// Memory
/// </summary>
public byte Memory
{
get
{
try
{
/*
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
_slave.ReadRegister(DS1624.REG_MEMORY, _dataBuffer);
}
*/
I2CSlave.ReadRegister(config, REG_MEMORY, _dataBuffer, TIMEOUT);
}
catch (System.IO.IOException e)
{
Debug.Print(e.Message);
}
return _dataBuffer[0];
}
}
#endregion
/// <summary>
/// Config
/// </summary>
public byte Config
{
get
{
try
{
/*
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
56
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
_slave.ReadRegister(DS1624.REG_CONFIG, _dataBuffer);
}
*/
I2CSlave.ReadRegister(config, REG_CONFIG, _dataBuffer, TIMEOUT);
}
catch (System.IO.IOException e)
{
Debug.Print(e.Message);
}
return _dataBuffer[0];
}
}
#region IDisposable Members
/// <summary>
/// Dispose object
/// </summary>
public void Dispose()
{
/*
using (I2CSlave _slave = new I2CSlave(_deviceAddress))
{
_slave.Dispose();
}
*/
}
#endregion
}
#endregion
internal sealed class LIS302DL
{
#region Fields
private I2CDevice.Configuration _deviceConfig;
private int _timeOut = 50;
private byte[] _dataBuffer = new byte[2] { 0x00, 0x00 };
#endregion
#region Constants
const int CLOCK_Rate = 100;
const byte DEFAULT_Address = 0x1C;
const byte REG_WHO_AM_I = 0x0F;
const byte REG_CTRL_REG1 = 0x20;
const byte REG_CTRL_REG2 = 0x21;
const byte REG_CTRL_REG3 = 0x22;
const byte REG_HP_FILTER_RESET = 0x23;
const byte REG_STATUS_REG = 0x27;
const byte REG_OUTX = 0x29;
const byte REG_OUTY = 0x2B;
const byte REG_OUTZ = 0x2D;
57
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
const byte REG_FF_WU_CFG_1 = 0x30;
const byte REG_FF_WU_SRC_1 = 0x31;
const byte REG_FF_WU_THS_1 = 0x32;
const byte REG_FF_WU_DURATION_1 = 0x33;
const byte REG_FF_WU_CFG_2 = 0x34;
const byte REG_FF_WU_SRC_2 = 0x35;
const byte REG_FF_WU_THS_2 = 0x36;
const byte REG_FF_WU_DURATION_2 = 0x37;
const byte REG_CLICK_CFG = 0x38;
const byte REG_CLICK_SRC = 0x39;
const byte REG_CLICK_THSY_X = 0x3B;
const byte REG_CLICK_THSZ = 0x3C;
const byte REG_CLICK_TimeLimit = 0x3D;
const byte REG_CLICK_Latency = 0x3E;
const byte REG_CLICK_Window = 0x3F;
#endregion
#region Constructors
/// <summary>
/// LIS302DL default address 0x1c
/// </summary>
public LIS302DL()
: this(LIS302DL.DEFAULT_Address)
{
}
/// <summary>
/// LIS302DL Triple Axis Accelerometer
/// </summary>
/// <param name="deviceAddress"></param>
public LIS302DL(byte deviceAddress)
: this(deviceAddress, CLOCK_Rate)
{
}
/// <summary>
/// LIS302DL Triple Axis Accelerometer
/// </summary>
/// <param name="deviceAddress"></param>
/// <param name="clockRate"></param>
public LIS302DL(byte deviceAddress, int clockRate)
{
_deviceConfig = new I2CDevice.Configuration(deviceAddress, clockRate);
}
#endregion
#region Members
58
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
/// <summary>
/// Device identification register. This register contains the device identifier for LIS302DL (set to 3Bh)
/// </summary>
public byte Who_Am_I
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_WHO_AM_I, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
/// <summary>
/// 8bit Control Register |DR|PD|FS|STP|STM|Zen|Yen|Xen|
/// DR bit allows to select the data rate at which acceleration samples are produced. The default value is 0
which corresponds to a data-rate of 100Hz. By changing the content of DR to “1” the selected data-rate will be set
equal to 400Hz.
/// PD bit allows to turn on the turn the device out of power-down mode. The device is in powerdown mode
when PD= “0” (default value after boot). The device is in normal mode when PD is set to 1.
/// STP, STM bit is used to activate the self test function. When the bit is set to one, an output change will
occur to the device outputs (refer to Table 3 and 4 for specification) thus allowing to check the functionality of the
whole measurement chain.
/// Zen bit enables the generation of Data Ready signal for Z-axis measurement channel when set to 1. The
default value is 1.
/// Yen bit enables the generation of Data Ready signal for Y-axis measurement channel when set to 1. The
default value is 1.
/// Xen bit enables the generation of Data Ready signal for X-axis measurement channel when set to 1. The
default value is 1.
/// </summary>
public byte Ctrl_Reg1
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CTRL_REG1, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CTRL_REG1, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
/// <summary>
/// 8bit Control Register |SIM|BOOT|--|FDS|HP_FF_WU2|HP_FF_WU1|HP_coeff2|HP_coeff1|
/// SIM bit selects the SPI Serial Interface Mode. When SIM is ‘0’ (default value) the 4-wire interface mode is
selected. The data coming from the device are sent to SDO pad. In 3-wire interface mode output data are sent to
SDA_SDI pad.
/// BOOT bit is used to refresh the content of internal registers stored in the flash memory block. At the device
power up the content of the flash memory block is transferred to the internal registers related to trimming
functions to permit a good behavior of the device itself. If for any reason the content of trimming registers was
changed it is sufficient to use this bit to restore correct values. When BOOT bit is set to ‘1’ the content of internal
flash is copied inside corresponding internal registers and it is used to calibrate the device. These values are factory
59
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
trimmed and they are different for every accelerometer. They permit a good behavior of the device and normally
they have not to be changed. At the end of the boot process the BOOT bit is set again to ‘0’.
/// FDS bit enables (FDS=1) or bypass (FDS=0) the high pass filter in the signal chain of the sensor
/// HP_coeff[2:1]. These bits are used to configure high-pass filter cut-off frequency ft.
/// </summary>
public byte Ctrl_Reg2
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CTRL_REG2, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CTRL_REG2, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte Ctrl_Reg3
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CTRL_REG3, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CTRL_REG3, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte HP_Filter_Reset
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_HP_FILTER_RESET, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte Status_Reg
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_STATUS_REG, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte OutX
{
get
{
60
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_OUTX, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte OutY
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_OUTY, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte OutZ
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_OUTZ, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_CFG_1
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_CFG_1, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_CFG_1, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_CFG_2
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_CFG_2, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_CFG_2, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_SRC_1
{
get
{
61
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_SRC_1, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_SRC_2
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_SRC_2, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_THS_1
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_THS_1, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_THS_1, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_THS_2
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_THS_2, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_THS_2, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte FF_WU_DURATION_1
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_DURATION_1, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_DURATION_1, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
62
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
public byte FF_WU_DURATION_2
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_FF_WU_DURATION_2, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_FF_WU_DURATION_2, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_CFG
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_CFG, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_CFG, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_SRC
{
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_SRC, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_THSY_X
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_THSY_X, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_THSY_X, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_THSZ
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_THSZ, value, _timeOut);
63
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_THSZ, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_TimeLimit
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_TimeLimit, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_TimeLimit, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_Latency
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_Latency, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_Latency, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
public byte CLICK_Window
{
set
{
I2CSlave.WriteRegister(_deviceConfig, LIS302DL.REG_CLICK_Window, value, _timeOut);
}
get
{
I2CSlave.ReadRegister(_deviceConfig, LIS302DL.REG_CLICK_Window, _dataBuffer, _timeOut);
return _dataBuffer[0];
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose object
/// </summary>
64
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
public void Dispose()
{
}
#endregion
}
private int _address;
private DS1624 _temp;
private LIS302DL _accelometer;
private bool[] _outputs;
private bool[] _inputs;
public int Address { get { return _address; } }
public int Temperature { get { return (int)_temp.Temp; } }
public bool[] Outputs { get { return _outputs; } }
public RoomBoard(int address)
{
_address = address;
_temp = new DS1624(_address);
_accelometer = new LIS302DL ();
_outputs = new bool[8];
_inputs = new bool[8];
for (int i = 0; i < _outputs.Length; i++)
_outputs[i] = false;
_temp.StartConversion = 0xEE;
_accelometer.Ctrl_Reg1 = 0x67;
}
public int[] GetAccelerometerValue()
{
int[] xyz = new int[3];
xyz[0] = _accelometer.OutX;
xyz[1] = _accelometer.OutY;
xyz[2] = _accelometer.OutZ;
//The output value for x-axis.
//The output value for y-axis.
//The output value for z-axis.
//Debug.Print(_accelometer.ToString());
return xyz;
}
65
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
}
}
Gm862.cs
namespace ElzeKool.Devices
{
/// <summary>
/// Class to interface a GM862GPS Device
/// The GM862 is a GSM module from Telit with build-in GPRS and GPS
///
/// (C)opyright 2009 Elze Kool, http://www.microframework.nl
///
/// This Sourcecode is Public Domain. You are free to use this class Non-Commercialy and Commercialy.
///
/// This sourcecode is provided AS-IS. I take no responsibility for direct or indirect
/// damage coused by this program/class.
/// </summary>
public class GM862GPS : IDisposable
{
#region Private Internal Variables
// Serialport used to communicate with GM862
private SerialPort _ComPort;
// Variable to check if this object is disposed
private bool _Disposed = false;
// Serial FIFO for Command mode responses
private String _SerialFIFO_CommandMode;
// Serial FIFO for Idle mode responses (Unsolicitated Responses)
private String _SerialFIFI_IdleMode;
// Current GM862 State
private GM862GPSStates _CurrentState;
private Object _CurrentStateLock = new Object();
// Auto reset event used to signal data reception
private AutoResetEvent WaitForDataToArrive = new AutoResetEvent(false);
// Thread that monitors Unsolicitated Responses
private Thread _ParseUnsolicitatedResponses;
#endregion
#region Public Classes
/// <summary>
/// States where GM862 can be in
/// </summary>
public enum GM862GPSStates
{
/// <summary>
/// GM862 is Idle. Event is triggered when data arrives
66
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
/// </summary>
Idle,
/// <summary>
/// GM862 is in Command mode. An AT command has been send en
/// data is parsed until a valid response code is returned
/// </summary>
Command,
/// <summary>
/// GM862 is in Data mode, no commands may be fired except '+++' escape sequence
/// </summary>
Data
}
/// <summary>
/// VT25 AT Response Codes
/// </summary>
public enum ResponseCodes
{
OK,
CONNECT,
RING,
NO_CARRIER,
ERROR,
NO_DIALTONE,
BUSY,
NO_ANSWER,
SEND_SMS_DATA
}
/// <summary>
/// Exception used for GM862 related errors
/// </summary>
public class GM862GPSException : Exception
{
public GM862GPSException(String Message) : base(Message) { }
public const String FAILED_TO_CREATE = "Failed to create a new SerialPort object";
public const String NOT_IN_IDLE_STATE = "Not in IDLE State";
public const String NOT_IN_COMMAND_OR_DATA_STATE = "Can't recieve response in IDLE state";
public const String TIMEOUT = "Timed-Out while waiting for response";
public const String MALFORMED_RESPONSE = "Recieved an empty or malformed command response";
}
/// <summary>
/// Class used to return SMS message in it's structure
/// </summary>
public class SMSMessage
{
public readonly String Memory;
public readonly int Location;
public readonly String Status;
public readonly String Orginator;
67
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
public readonly String ArrivalTime;
public readonly String Message;
/// <summary>
/// Instantiate a new SMS
/// </summary>
public SMSMessage(String Memory, int Location, String Status, String Orginator, String ArrivalTime, String
Message)
{
this.Memory = Memory;
this.Location = Location;
this.Status = Status;
this.Orginator = Orginator;
this.ArrivalTime = ArrivalTime;
this.Message = Message;
}
}
#endregion
#region Event Handlers
/// <summary>
/// Unsolicited response recieved. Allow code to handle response
/// </summary>
/// <param name="Response">Recieved response</param>
public delegate void UnsolicitedResponseEvent(String Response);
public event UnsolicitedResponseEvent OnUnsolicitedResponse;
/// <summary>
/// Event triggered when called
/// </summary>
public delegate void RecievingCallEvent();
public event RecievingCallEvent OnRecievingCall;
/// <summary>
/// Event triggered when a SMS is recieved
/// </summary>
/// <param name="Storage">Storage for recieved SMS</param>
/// <param name="Number">Number of recieved SMS</param>
public delegate void RecievedSMS(String Storage, int Number);
public event RecievedSMS OnRecievedSMS;
/// <summary>
/// Called when there is a PIN request (Like SIM PIN/PUK etc.)
/// </summary>
/// <param name="PINType">Type of PIN requested</param>
/// <returns>Required PIN</returns>
public delegate string PINRequestHandler(String PINType);
public PINRequestHandler getRequestedPIN;
#endregion
68
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
#region Constructor/Destructor
/// <summary>
/// Create new GM862GPS instance
/// </summary>
/// <param name="Port">Serial Port to use</param>
public GM862GPS(String Port)
{
// We begin in IDLE state
_CurrentState = GM862GPSStates.Idle;
_SerialFIFO_CommandMode = "";
_SerialFIFI_IdleMode = "";
try
{
// Create new SerialPort Object
_ComPort = new SerialPort(Port, 19200, Parity.None, 8, StopBits.One);
_ComPort.Handshake = Handshake.None;
_ComPort.Open();
}
catch
{
// If failed throw error
throw new GM862GPSException(GM862GPSException.FAILED_TO_CREATE);
}
// DataRecieved Handler
_ComPort.DataReceived += new SerialDataReceivedEventHandler(_ComPort_DataReceived);
// Create thread that handles Unsolicited Responses
_ParseUnsolicitatedResponses = new Thread(new ThreadStart(ParseUnsolicitedResponse));
_ParseUnsolicitatedResponses.Priority = ThreadPriority.AboveNormal;
_ParseUnsolicitatedResponses.Start();
// Add onUnsolicitedResponse Handler to check for incomming SMS and Call
OnUnsolicitedResponse += new UnsolicitedResponseEvent(CheckForNewSMS);
OnUnsolicitedResponse += new UnsolicitedResponseEvent(CheckForCall);
}
/// <summary>
/// Dispose Object
/// </summary>
public void Dispose()
{
try
{
_Disposed = true;
_ComPort.Dispose();
_ParseUnsolicitatedResponses.Abort();
}
catch
{
}
69
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
}
#endregion
#region Initialization functions
/// <summary>
/// Initializes basic GSM Functions and settings
/// </summary>
public void InitializeBasicGSM()
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Select extended instruction set
if (ExecuteCommand("AT#SELINT=2", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to select extended instruction set");
// Reset to factory settings
if (ExecuteCommand("AT&F1", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to reset to factory settings");
// Disable local echo
if (ExecuteCommand("ATE0", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to disable local echo");
// Disable Flowcontrol
if (ExecuteCommand("AT&K0", 500) != ResponseCodes.OK)
throw new GM862GPSException("Failed to disable Flow control");
// Parse all PIN requests
while (CheckPIN() == false) { Thread.Sleep(10); }
}
/// <summary>
/// Initialize basic SMS Settings
/// </summary>
public void InitializeSMS()
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Select standard SMS instruction set
if (ExecuteCommand("AT#SMSMODE=0", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to select standard SMS instruction set");
// Select Unsolicited SMS code to be buffered and in form +CMTI: <mem>, <id>
if (ExecuteCommand("AT+CNMI=2,1,0,0,0", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to select standard SMS instruction set");
// Select Text Message Format
if (ExecuteCommand("AT+CMGF=1", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to select Text SMS format");
70
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
}
/// <summary>
/// Initialze GPRS and Activate GPRS Context
/// </summary>
/// <param name="ContextID">Context to create/activate</param>
/// <param name="APN">Access Point</param>
/// <param name="Username">Username</param>
/// <param name="Password">Password</param>
public void ActivateGPRSContext(int ContextID, String APN, String Username, String Password)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Create new GPRS Context
if (ExecuteCommand("AT+CGDCONT=" + ContextID.ToString() + ",\"IP\", \"" + APN + "\",\"0.0.0.0\",0,0",
500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to create new GPRS Context");
// Set UserID
if (ExecuteCommand("AT#USERID=\"" + Username + "\"", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to set Username");
// Set Password
if (ExecuteCommand("AT#PASSW=\"" + Password + "\"", 500) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to set Password");
// Check if Context is Active
String CheckActiveContext;
if (ExecuteCommand("AT#GPRS?", 500, out CheckActiveContext) != ResponseCodes.OK)
throw new GM862GPSException("Failed to check if context active");
// Check if context isn't active
if (CheckActiveContext.IndexOf("\r\n#GPRS: 1") == -1)
{
if (ExecuteCommand("AT#GPRS=1", 5000) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to activate GPRS context");
}
// Setup Socket Config
if (ExecuteCommand("AT#SCFG=1,1,64,90,600,1", 1000) != GM862GPS.ResponseCodes.OK)
throw new GM862GPSException("Failed to setup Socket config");
}
#endregion
#region Misc functions
/// <summary>
/// Request HTML page from Server
/// !!! UNFINISHED !!!
71
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
/// </summary>
/// <param name="SocketID">Socket ID to use</param>
/// <param name="Host">Host of server</param>
/// <param name="Path">Path to fetch data from</param>
/// <returns>Recieved HTTP Response</returns>
public String RequestHTML(int SocketID, String Host, String Path)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Say we want to connect to Socket
if (ExecuteCommand("AT#SD=" + SocketID.ToString() + ", 0,80,\"" + Host + "\",0,0,0", 50000) !=
ResponseCodes.CONNECT)
{
throw new GM862GPSException("Did not recieve CONNECT response");
}
// Object used for recieving HTML
String RecievedData = "";
// Build request
String Request = "GET " + Path + " HTTP/1.1\r\n";
Request += "Host: " + Host + "\r\n";
Request += "Connection: Close\r\n";
Request += "\r\n";
// Send request
byte[] OutBuffer = System.Text.Encoding.UTF8.GetBytes(Request);
lock (_ComPort) { _ComPort.Write(OutBuffer, 0, OutBuffer.Length); }
// Recieve data
while (true)
{
// Wait for .5 sec for data to arrive
if (!WaitForDataToArrive.WaitOne(500, true))
{
// When exit recieved exit now
if (RecievedData.IndexOf("\r\nNO CARRIER\r\n") != -1)
{
RecievedData = RecievedData.Substring(0, RecievedData.LastIndexOf("\r\nNO CARRIER\r\n"));
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
break;
}
// No exit? Give some more time to get data
if (!WaitForDataToArrive.WaitOne(10000, true))
{
// If still no data Escape data mode
try { Escape(); }
catch { lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; } }
// Close socket
ExecuteCommand("AT#SH=" + SocketID.ToString(), 1000);
72
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
break;
}
}
// Add data to recieve buffer
lock (_SerialFIFO_CommandMode)
{
RecievedData += _SerialFIFO_CommandMode;
_SerialFIFO_CommandMode = "";
}
}
// Return HTTP response
return RecievedData;
}
/// <summary>
/// Get GPS Location and Fix Data
/// </summary>
/// <param name="Fix">Dimensions of Fix (0 = No fix, 2 = 2D fix, 3 = 3D fix)</param>
/// <param name="NoSatelites">Number of tracked satelites (Valid when fix>0)</param>
/// <param name="Latitude">Latitude in degrees (Valid when fix>0)</param>
/// <param name="Longitude">Longitude in degrees (Valid when fix>0)</param>
public void ReadGPS(out byte Fix, out byte NoSatelites, out Double Latitude, out Double Longitude)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Send Command
String GPSResponseBody = "";
if (ExecuteCommand("AT$GPSACP", 1000, out GPSResponseBody) != ResponseCodes.OK)
throw new Exception("Failed to get GPS information");
// Parse response
int GPSResponseStart;
int GPSResponseEnd;
GPSResponseStart = GPSResponseBody.IndexOf("$GPSACP: ");
if (GPSResponseStart == -1)
throw new GM862GPSException("Unkown $GPSACP response!");
GPSResponseStart += "$GPSACP: ".Length;
GPSResponseEnd = GPSResponseBody.IndexOf("\r\n", GPSResponseStart);
if (GPSResponseEnd == -1)
throw new GM862GPSException("Unkown $GPSACP response!");
GPSResponseBody
=
GPSResponseBody.Substring(GPSResponseStart,
GPSResponseStart);
GPSResponseEnd
-
// Split message on comma
String[] SplitResponse = GPSResponseBody.Split(new char[] { ',' });
// Check for Fix
if (SplitResponse.Length > 1)
Fix = (byte)_intval(SplitResponse[5]);
73
M.sc. Final Project Report
School of Electronic, Communication and Electrical Engineering
else
Fix = 0;
if (Fix > 0)
{
// If Fix get Satelites, Lat and Lon
NoSatelites = (byte)_intval(SplitResponse[10]);
Latitude = _decodeDMS(SplitResponse[1]);
Longitude = _decodeDMS(SplitResponse[2]);
}
else
{
// If not return 0
NoSatelites = 0;
Latitude = 0F;
Longitude = 0F;
}
}
#endregion
#region Read/Send SMS Text Messages
/// <summary>
/// Read Message from Memory
/// </summary>
/// <param name="Memory">Memory to read from</param>
/// <param name="Location">Location of message</param>
/// <returns>SMS Message</returns>
public SMSMessage ReadMessage(String Memory, int Location)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
String ResponseBody;
int HeaderStart;
int HeaderEnd;
int MessageStart;
int MessageEnd;
String Status = "";
String Orginator = "";
String ArrivalTime = "";
String Message = "";
// Select Memory location
if (ExecuteCommand("AT+CPMS=" + Memory, 15000) != GM862GPS.ResponseCodes.OK)
throw new Exception("Failed to set SMS Storage");
// Read Message from Location
if (ExecuteCommand("AT+CMGR="
+ Location.ToString(),
GM862GPS.ResponseCodes.OK)
throw new Exception("Failed to read SMS Storage");
15000,
out
ResponseBody)
!=
74
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
// Make sure there is no unsolicitated text in our message
if (ResponseBody.IndexOf("\r\n\r\n") != -1)
ResponseBody = ResponseBody.Substring(0, ResponseBody.IndexOf("\r\n\r\n") + 2);
// Check response
HeaderStart = ResponseBody.IndexOf("+CMGR: ");
if (HeaderStart == -1)
throw new GM862GPSException("Malformed +CMGR response");
HeaderStart += "+CMGR: ".Length;
HeaderEnd = ResponseBody.IndexOf("\r\n", HeaderStart);
if (HeaderEnd == -1)
throw new GM862GPSException("Malformed +CMGR response");
// Skip <cr><lf>
MessageStart = HeaderEnd + 2;
MessageEnd = ResponseBody.Length;
if (MessageEnd == -1)
throw new GM862GPSException("Malformed +CMGR response");
Message = ResponseBody.Substring(MessageStart, (MessageEnd - MessageStart) - 2);
// Break up header
System.Collections.ArrayList Header = new System.Collections.ArrayList();
String HeaderPart = "";
bool WithinQuote = false;
foreach (char c in ResponseBody.Substring(HeaderStart, HeaderEnd + 2 - HeaderStart))
{
if (c == '"') { WithinQuote = !WithinQuote; continue; }
if (WithinQuote) { HeaderPart += c; continue; }
if (c == ' ') { continue; }
if (c == ',') { Header.Add(HeaderPart); HeaderPart = ""; continue; }
if ((c == '\r') | (c == '\n')) { Header.Add(HeaderPart); HeaderPart = ""; break; }
}
// Return message
Status = (String)Header[0];
Orginator = (String)Header[1];
ArrivalTime = (String)Header[3];
return new SMSMessage(Memory, Location, Status, Orginator, ArrivalTime, Message);
}
/// <summary>
/// Send SMS Message
/// </summary>
/// <param name="Destination">Destination for SMS</param>
/// <param name="Message">Message to Send</param>
public void SendSMSMessage(String Destination, String Message)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
75
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
// Add format identification to destination
if (Destination.IndexOf('+') != -1)
Destination = "\"" + Destination + "\",157"; // Internation format
else
Destination = "\"" + Destination + "\",129"; // National format
// Say we want to send message
if (ExecuteCommand("AT+CMGS=" + Destination, 1000) != ResponseCodes.SEND_SMS_DATA)
throw new GM862GPSException("Did not recieve SEND_SMS_DATA response");
// Send Message, End with ^Z
byte[] OutBuffer = System.Text.Encoding.UTF8.GetBytes(Message + "\x1A");
lock (_ComPort) { _ComPort.Write(OutBuffer, 0, OutBuffer.Length); }
// Now we wait for OK response
int ResponseStart;
int ResponseLength;
if (WaitForResponse(out ResponseStart, out ResponseLength, 10000) != ResponseCodes.OK)
throw new GM862GPSException("Failed to send SMS");
}
#endregion
#region Registration/PIN Checks
/// <summary>
/// Checks if connected to a network.
/// </summary>
/// <param name="AllowRoaming">Also return true on roaming networks</param>
/// <returns></returns>
public bool RegisteredOnNetwork(bool AllowRoaming)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
String ResponseBody = "";
int ResponseStart;
int ResponseEnd;
// Do Network Registration request
if (ExecuteCommand("AT+CREG?", 2500, out ResponseBody) != ResponseCodes.OK)
throw new GM862GPSException("Network Registration Check Failed");
// Check response
ResponseStart = ResponseBody.IndexOf("+CREG: ");
if (ResponseStart == -1)
throw new GM862GPSException("Malformed +CREG? response");
ResponseStart += "+CREG: ".Length;
ResponseEnd = ResponseBody.IndexOf("\r\n", ResponseStart);
if (ResponseEnd == -1)
throw new GM862GPSException("Malformed +CREG? response");
76
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
// ResponseBody now holds requested Network Registration
ResponseBody = ResponseBody.Substring(ResponseStart, ResponseEnd - ResponseStart);
// Parse Response
switch (_intval(ResponseBody.Substring(ResponseBody.LastIndexOf(','))))
{
case 1:
return true; // Home network
case 5:
if (AllowRoaming) return true; // Roaming
break;
}
// No network
return false;
}
/// <summary>
/// Checks if connected to a GPRS network.
/// </summary>
/// <param name="AllowRoaming">Also return true on roaming networks</param>
/// <returns></returns>
public bool RegisteredOnGPRS(bool AllowRoaming)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
String ResponseBody = "";
int ResponseStart;
int ResponseEnd;
// Do Network Registration request
if (ExecuteCommand("AT+CGREG?", 2500, out ResponseBody) != ResponseCodes.OK)
throw new GM862GPSException("Network Registration Check Failed");
// Check response
ResponseStart = ResponseBody.IndexOf("+CGREG: ");
if (ResponseStart == -1)
throw new GM862GPSException("Malformed +CGREG? response");
ResponseStart += "+CGREG: ".Length;
ResponseEnd = ResponseBody.IndexOf("\r\n", ResponseStart);
if (ResponseEnd == -1)
throw new GM862GPSException("Malformed +CGREG? response");
// ResponseBody now holds requested Network Registration
ResponseBody = ResponseBody.Substring(ResponseStart, ResponseEnd - ResponseStart);
// Parse Response
switch (_intval(ResponseBody.Substring(ResponseBody.LastIndexOf(','))))
{
case 1:
return true; // Home network
77
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
case 5:
if (AllowRoaming) return true; // Roaming
break;
}
// No network
return false;
}
/// <summary>
/// Check if there is an outstanding PIN request
/// If so try to get PIN from getRequestedPIN() funtion
/// </summary>
/// <returns>True when all codes are entered</returns>
private bool CheckPIN()
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
String ResponseBody = "";
int RequestTypeStart;
int RequestTypeEnd;
// Do PIN request
if (ExecuteCommand("AT+CPIN?", 2500, out ResponseBody) != ResponseCodes.OK)
{
throw new GM862GPSException("PIN Request Check Failed");
}
// Check response
RequestTypeStart = ResponseBody.IndexOf("+CPIN: ");
if (RequestTypeStart == -1)
throw new GM862GPSException("Malformed +CPIN? response");
RequestTypeStart += "+CPIN: ".Length;
RequestTypeEnd = ResponseBody.IndexOf("\r\n", RequestTypeStart);
if (RequestTypeEnd == -1)
throw new GM862GPSException("Malformed +CPIN? response");
// ResponseBody now holds requested PIN type
ResponseBody = ResponseBody.Substring(RequestTypeStart, RequestTypeEnd - RequestTypeStart);
// No more PIN request
if (ResponseBody == "READY")
return true;
// Check for a getRequestedPIN handler
if (getRequestedPIN == null)
throw new GM862GPSException("No PIN Request Handler");
// Send PIN code
if (ExecuteCommand("AT+CPIN=" + getRequestedPIN(ResponseBody), 2500, out ResponseBody) !=
ResponseCodes.OK)
78
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
throw new GM862GPSException("Enter PIN Failed");
// Check for next PIN request
return false;
}
#endregion
#region Unsolicited Response Thread and Events
/// <summary>
/// Tread that parses Unsolicited Responses
/// </summary>
private void ParseUnsolicitedResponse()
{
String UnsolicitedResponse = "";
int UnsolicitedResponseStart = 0;
int UnsolicitedResponseEnd = 0;
// Loop
while (true)
{
// Try to find Unsolicited Response
UnsolicitedResponse = "";
lock (_SerialFIFI_IdleMode)
{
// Check if there is data in FIFO
if (_SerialFIFI_IdleMode.Length > 4)
{
// Find start and end
UnsolicitedResponseStart = 0;
UnsolicitedResponseEnd = _SerialFIFI_IdleMode.IndexOf("\r\n", UnsolicitedResponseStart + 2);
if (UnsolicitedResponseEnd != -1)
{
UnsolicitedResponse
=
_SerialFIFI_IdleMode.Substring(0,
UnsolicitedResponseEnd
UnsolicitedResponseStart + 2);
_SerialFIFI_IdleMode = _SerialFIFI_IdleMode.Substring(UnsolicitedResponseEnd);
}
else
{
Thread.Sleep(250);
continue;
}
}
else
{
Thread.Sleep(250);
continue;
}
}
-
// Trigger event if set
if (OnUnsolicitedResponse != null)
{
79
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
OnUnsolicitedResponse(UnsolicitedResponse);
}
}
}
/// <summary>
/// Check if Unsolicitate response is a New SMS response.
/// If so it fires a OnRecievedSMS event
/// </summary>
/// <param name="Response">Recieve response</param>
private void CheckForNewSMS(string Response)
{
// Check for +CMTI: in string
if (Response.IndexOf("+CMTI: ") == -1)
return;
int ResponseStart;
int ResponseEnd;
// Select only <mem>, <id>
ResponseStart = Response.IndexOf("+CMTI: ");
if (ResponseStart == -1)
return;
ResponseStart += "+CMTI: ".Length;
ResponseEnd = Response.IndexOf("\r\n", ResponseStart);
if (ResponseEnd == -1)
return;
Response = Response.Substring(ResponseStart, ResponseEnd - ResponseStart);
// SMS event
if (OnRecievedSMS != null)
OnRecievedSMS(Response.Substring(0,
_intval(Response.Substring(Response.IndexOf(',') + 1)));
}
Response.IndexOf(',')),
/// <summary>
/// Check if Unsolicitate response is a Recieving Call response.
/// If so it fires a OnRecievingCall event
/// </summary>
/// <param name="Response">Recieve response</param>
private void CheckForCall(string Response)
{
// Check for RING
if (Response.IndexOf("\r\nRING\r\n") == -1)
return;
// Call event
if (OnRecievingCall != null)
OnRecievingCall();
}
80
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
#endregion
#region Basic Command Excecution and Handling
/// <summary>
/// Execute AT Command. Wait until response is recieved.
/// </summary>
/// <param name="Command">Command to execute</param>
/// <param name="Timeout">Timeout for response</param>
/// <returns>Recieved response code</returns>
public ResponseCodes ExecuteCommand(String Command, int Timeout)
{
String DummyResponseBody;
return ExecuteCommand(Command, Timeout, out DummyResponseBody);
}
/// <summary>
/// Execute AT Command. Wait until response is recieved.
/// </summary>
/// <param name="Command">Command to execute</param>
/// <param name="Timeout">Timeout for response in miliseconds</param>
/// <param name="ResponseBody">Returns the Response body</param>
/// <returns>Recieved response code</returns>
public ResponseCodes ExecuteCommand(String Command, int Timeout, out String ResponseBody)
{
/*
* Send Command
* Wait until command is send
* Wait for last unsolicited response text is recieved
* Go to command mode
* Send \r\n to execute command
* Wait until \r\n is send
* Wait for response
* Save command response body
* Return response
*/
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Recieved response code
ResponseCodes RecievedResponse;
// Check if we are ready for Command
lock (_CurrentStateLock)
{
if (_CurrentState != GM862GPSStates.Idle)
throw new GM862GPSException(GM862GPSException.NOT_IN_IDLE_STATE);
}
// Send AT to Serial Port
byte[] OutBuffer = System.Text.Encoding.UTF8.GetBytes(Command);
lock (_ComPort)
81
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
{
_ComPort.Write(OutBuffer, 0, OutBuffer.Length);
// Wait until command is send
while (_ComPort.BytesToWrite > 0)
{
WaitForDataToArrive.WaitOne(10, false);
}
}
// Check if in Idle State and set Command state
lock (_CurrentStateLock)
{
if (_CurrentState != GM862GPSStates.Idle)
throw new GM862GPSException(GM862GPSException.NOT_IN_IDLE_STATE);
// Now where in command state
_CurrentState = GM862GPSStates.Command;
}
// Wait for last data to arrive
// WaitOne returns true when no data recieved in given time
// So this loop exits when for the last 10 mSec no data has arrived
while (WaitForDataToArrive.WaitOne(10, false)) { }
// Clear input buffer
lock (_SerialFIFO_CommandMode)
{
_SerialFIFO_CommandMode = "";
}
// Send \r\n
OutBuffer = System.Text.Encoding.UTF8.GetBytes("\r\n");
lock (_ComPort)
{
_ComPort.Write(OutBuffer, 0, OutBuffer.Length);
// Wait until send
while (_ComPort.BytesToWrite > 0)
{
WaitForDataToArrive.WaitOne(10, false);
}
}
// Now we wait for a response to come in
int ResponseStart;
int ResponseLength;
RecievedResponse = WaitForResponse(out ResponseStart, out ResponseLength, Timeout);
// Now get response body and delete response from FIFO
lock (_SerialFIFO_CommandMode)
{
82
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
if (_SerialFIFO_CommandMode != "")
{
ResponseBody = _SerialFIFO_CommandMode.Substring(0, ResponseStart);
_SerialFIFO_CommandMode
=
_SerialFIFO_CommandMode.Substring(ResponseStart
ResponseLength);
}
else
{
ResponseBody = "";
_SerialFIFO_CommandMode = "";
}
}
+
// Return recieved response
return RecievedResponse;
}
/// <summary>
/// Send Escape Sequence '+++'
/// </summary>
/// <returns>Return code</returns>
public ResponseCodes Escape()
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
ResponseCodes RecievedResponse;
int ResponseStart;
int ResponseLength;
// Set Command state
lock (_CurrentStateLock)
{
// Now where in command state
_CurrentState = GM862GPSStates.Command;
}
Thread.Sleep(2500);
// Send Command to Serial Port
byte[] OutBuffer = System.Text.Encoding.UTF8.GetBytes("+++");
lock (_ComPort) { _ComPort.Write(OutBuffer, 0, OutBuffer.Length); }
Thread.Sleep(2500);
// Now we wait for a response to come in
RecievedResponse = WaitForResponse(out ResponseStart, out ResponseLength, 5000);
// Delete response from FIFO
lock (_SerialFIFO_CommandMode)
{
_SerialFIFO_CommandMode = _SerialFIFO_CommandMode.Substring(ResponseStart + ResponseLength);
83
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
}
// Return recieved response
return RecievedResponse;
}
/// <summary>
/// Waits until it recieves a valid response code.
/// This command automaticly sets the state to IDLE or DATA
/// Throws exception when no response is recieved within timeout time.
/// </summary>
/// <param name="ResponseStart">Returns the position in the FIFO of response</param>
/// <param name="ResponseLength">Returns the length of the response</param>
/// <param name="Timeout">Timeout in miliseconds</param>
/// <returns>Received response code</returns>
private ResponseCodes WaitForResponse(out int ResponseStart, out int ResponseLength, int Timeout)
{
// Check if disposed
if (_Disposed) throw new ObjectDisposedException();
// Set TimeOut
DateTime TimeOutAt = DateTime.Now.AddMilliseconds(Timeout);
// Check if in Command or Data State
lock (_CurrentStateLock)
{
if ((_CurrentState != GM862GPSStates.Command) && (_CurrentState != GM862GPSStates.Data))
throw new GM862GPSException(GM862GPSException.NOT_IN_COMMAND_OR_DATA_STATE);
}
// Search for response until timeout
while (DateTime.Now < TimeOutAt)
{
// TODO:
// Check if it's better to release/aquire lock for each response check
lock (_SerialFIFO_CommandMode)
{
//DebugMessage("Check");
// OK response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nOK\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nOK\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.OK;
}
// ERROR response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nERROR\r\n");
if (ResponseStart != -1)
{
84
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
ResponseLength = "\r\nERROR\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.ERROR;
}
// RING response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nRING\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nRING\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.RING;
}
// BUSY response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nBUSY\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nBUSY\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.BUSY;
}
// NO CARRIER response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nNO CARRIER\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nNO CARRIER\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.NO_CARRIER;
}
// NO DIALTONE response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nNO DIALTONE\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nNO DIALTONE\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.NO_DIALTONE;
}
// NO ANSWER response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\nNO ANSWER\r\n");
if (ResponseStart != -1)
{
ResponseLength = "\r\nNO ANSWER\r\n".Length;
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
return ResponseCodes.NO_ANSWER;
}
// CONNECT response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("CONNECT");
if (ResponseStart != -1)
85
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
{
ResponseLength = _SerialFIFO_CommandMode.IndexOf("\r\n", ResponseStart + 2);
if (ResponseLength != -1)
{
ResponseLength = (ResponseLength - ResponseStart) + 2;
WaitForDataToArrive.Reset();
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Data; }
return ResponseCodes.CONNECT;
}
}
// SEND_SMS_DATA (>) response
ResponseStart = _SerialFIFO_CommandMode.IndexOf("\r\n>");
if (ResponseStart != -1)
{
ResponseLength = "\r\n>".Length;
WaitForDataToArrive.Reset();
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Data; }
return ResponseCodes.SEND_SMS_DATA;
}
}
WaitForDataToArrive.WaitOne(50, false);
}
// Response Timeout
lock (_CurrentStateLock) { _CurrentState = GM862GPSStates.Idle; }
ResponseStart = -1;
ResponseLength = 0;
return ResponseCodes.ERROR;
}
#endregion
#region Internal functions
/// <summary>
/// Serial Data In Event
/// </summary>
private void _ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
String NewText = "";
byte[] inBuffer = null;
if (e.EventType == SerialData.Chars)
{
// Lock ComPort and Recieve data
lock (_ComPort)
{
inBuffer = new byte[_ComPort.BytesToRead];
_ComPort.Read(inBuffer, 0, inBuffer.Length);
}
86
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
try
{
NewText = new String(System.Text.Encoding.UTF8.GetChars(inBuffer));
}
catch { return; }
lock (_CurrentStateLock)
{
if (_CurrentState == GM862GPSStates.Idle)
{
lock (_SerialFIFI_IdleMode)
{
_SerialFIFI_IdleMode += NewText;
}
}
else
{
lock (_SerialFIFO_CommandMode)
{
_SerialFIFO_CommandMode += NewText;
}
WaitForDataToArrive.Set();
}
}
}
}
/// <summary>
/// Internal function to convert a numeric string to an integer
/// </summary>
/// <param name="S">String to convert</param>
/// <returns>Converted integer</returns>
private static int _intval(String S)
{
int r = 0;
foreach (Char c in S)
{
if ("0123456789".IndexOf(c) != -1)
{
r *= 10;
r += (int)(c - '0');
}
}
return r;
}
/// <summary>
/// Internal function used to convert DD.MM.SSSS string to degrees
/// </summary>
/// <param name="S">Latitude/Longitude in DD.MM.SSSS format</param>
87
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
/// <returns>Latitude/Longitude in degrees</returns>
private static double _decodeDMS(String S)
{
// Internal values used to store values
double Result = 0F;
double Degrees = 0F;
double Minutes = 0F;
double Seconds = 0F;
// Internal values used to convert value to double
bool afterDot = false;
bool negativeR = false;
// Go trough String
foreach (Char c in S)
{
// If Number then add it to R
if ("0123456789".IndexOf(c) != -1)
{
if (!afterDot)
{
Degrees *= 10F;
Degrees += (double)(c - '0');
}
else
{
Seconds *= 10F;
Seconds += (double)(c - '0');
}
}
// Check for Dot
else if (c == '.')
{
afterDot = true;
continue;
}
// If West and South Negative number
else if ((c == 'W') || (c == 'S'))
{
negativeR = true;
continue;
}
// If North/East ignore
else if ((c == 'N') || (c == 'E'))
{
continue;
}
// Other character, throw error
else
{
throw new ArgumentException("Unknown character '" + c + "' in DMS String");
}
}
88
School of Electronic, Communication and Electrical Engineering
M.sc. Final Project Report
// Modified NMEA simple equation
//double PosDeg = Math.Floor(Degrees / 100);
//double PosDec = ((Degrees - (PosDeg * 100)) + (Seconds / 1000.0)) / 60.0;
//Microsoft.SPOT.Debug.Print("-----" + S);
//Microsoft.SPOT.Debug.Print("----" + Degrees);
//Microsoft.SPOT.Debug.Print("---" + PosDeg);
//Microsoft.SPOT.Debug.Print("--" + Seconds);
//Microsoft.SPOT.Debug.Print("-" + PosDec);
//Microsoft.SPOT.Debug.Print("-------------------------");
//Result = PosDeg + PosDec;
// Now convert from DD.MMSSSS to Degrees
//Minutes = Degrees % 100F;
//Degrees = System.Math.Floor(Degrees / 100F);
//while (Seconds > 100F)
// Seconds /= 10F;
//Result = Degrees + (Minutes / 60F) + (Seconds / 3600F);
//// Make it negative when in West or South
//if (negativeR)
// Result = -Result;
Minutes = Degrees % 100.0;
Degrees = System.Math.Floor(Degrees / 100.0);
Seconds /= 10000.0;
Result = Degrees + ((Minutes + Seconds) / 60.0);
if (negativeR)
Result = -Result;
return Result;
}
#endregion
}
}
89
Download