Sei sulla pagina 1di 99

PREPAID ENERGY METER NETWORK

By
SALMA MOHAMMED ELHAJ ELKASHIF
INDEX NO. 064033

Supervisor
Dr: Kamal Ramadan

A REPORT SUBMITTED TO
University of Khartoum
In partial fulfilment of the requirement of the degree of
B.Sc (HONS) Electrical and Electronic Engineering
(POWER SYSTEM ENGINEERING)
Faculty of Engineering
Department of Electrical and Electronic Engineering
July 2011
‫اآليـــــــة‬

‫تسٌ هللا اىشزَِ اىشز‪ٌٞ‬‬

‫قال تعالى‪:‬‬

‫ض ِمن َش َجَرٍة أَقْالَ ٌم َوالْبَ ْحُر ََيُّدهُ ِمن بَ ْع ِد ِه َسْب َعةُ‬ ‫{ َولَ ْو أَّّنَا ِِف ْ‬
‫األر ِ‬
‫يم }‬ ‫أ َْْب ٍر ما نَِف َدت َكلِمات اللّ ِه إِ ّن اللّه ع ِزيز ح ِ‬
‫ك‬
‫ٌََ َ ٌ‬ ‫ْ َ ُ‬ ‫ُ ّ‬

‫سورة لقمان‬
‫اآلية ‪27‬‬

‫‪II‬‬
‫إهـــــــــداء‬

‫إى‪ ٜ‬مو ٍِ أضاء تعئَ عقو غ‪ٞ‬شٓ‬

‫أٗ ٕذ‪ ٙ‬تاىد٘اب اىصس‪ٞ‬ر ز‪ٞ‬شج سائي‪ٔٞ‬‬

‫فأظٖش تسَازرٔ ذ٘اضع اىعيَاء‬

‫ٗتشزاترٔ سَازح اىعاسف‪ِٞ‬‬

‫‪III‬‬
DECLARATION OF ORIGINALITY

I declare that this report entitled “Prepaid Energy Meter Network” is my own work
except as cited in the references. The report has not been accepted for any degree and is not
being submitted concurrently in candidature for any degree or other award.
Signature: _________________________

Name: _________________________

Date: _________________________

IV
ACKNOWLEDGEMENT

I would like to express my deepest sense of gratitude to my supervisor, Dr. Kamal Ramadan &
also a special thanks to Dr. Shareef Babikir for both of their continuous advice, systematic
guidance, encouragement and great efforts through the course of this project.

I am deeply grateful to my project partner, Sahar Nour Eldeen for her hard work, real team spirit,
continuous support, the unforgettable times we have spent and all good things I have learned
from her.

I also would like to give my gratitude to my lovely residence mates in ELZAHRAA for the five
years period with laugher, dreams, mutual encouragement and love we had.

One more personal note I would like to express my love and gratitude from my deep heart to my
parents, my brother and my sisters for teaching me values that are precious, irrespective of time
and place and for their endless love, support and constant encouragement in all my endeavors.

I am deeply grateful for all people who encouraged and supported me during my university
study.

V
ABSTRACT
This Project is based on the technology of data exchange through electrical power lines.
The main point of this project is to connect the entire prepaid energy meters to the electricity
company which represents the centre station by using the same existing power line network. So,
there is no need to install proprietary cables or a wireless network.
The power Line Communication (PLC) technology utilizes the power cables as a communication
channels. The device performs the operation of data transfer through the power lines and
connects all meters to the electricity company; is called the power line modem (PLM).
By this network the electricity company can easily determine the consumed power in each point
(prepaid meter) which is useful in security purposes to prevent any consumer from any illegal
actions, also for full control of the electrical network especially for emergency cases.
By applying this project the user at the electrical company can easily send data to any meter in
the network like electricity amount or just knowing the status of specific meter either ON or
OFF. The project’s implementation and result seems to be sufficient.

VI
‫المستخلص‬
‫ٕزا اىَششٗع ٍثْ‪ ٜ‬عي‪ ٚ‬ذقْ‪ٞ‬ح ذثاده اىث‪ٞ‬اّاخ عثش خط٘ط اىنٖشتاء‪ .‬اىفنشج األساس‪ٞ‬ح ىيَششٗع ٕ‪ ٜ‬ستظ خَ‪ٞ‬ع أخٖضج عذاد اىذفع‬
‫ذ٘ص‪ٝ‬ع اىَقذً ت٘اسطح شثنح ٍع ششمح اىنٖشتاء ٗ اىر‪ ٜ‬ذَثو ٍشمض ذسنٌ اىشثنح‪ٕ .‬زٓ اىشثنح ٕ‪ّ ٜ‬فس اىشثنح اىشئ‪ٞ‬س‪ٞ‬ح ىْقو ٗ‬
‫اىنٖشتاء؛ ز‪ٞ‬س ذٌ ذأس‪ٞ‬س شثنح ذسنٌ عثش خط٘ط اىنٖشتاء ىشتظ اىعذاداخ اىشئ اىز‪ٝ ٛ‬غْ‪ْٞ‬ا عِ ذثث‪ٞ‬د م٘اتو خاصح أٗ شثنح‬
‫ذسنٌ السين‪ٞ‬ح‪.‬‬
‫إُ ذنْ٘ى٘خ‪ٞ‬ا اإلذصاه عثش خط٘ط اىنٖشتاء ذسرخذً م٘اتو اىنٖشتاء مقْاج إذصاه‪ .‬اىدٖاص اىز‪ٝ ٛ‬قً٘ تعَي‪ٞ‬ح ّقو اىث‪ٞ‬اّاخ عثش‬
‫خط٘ط اىنٖشتاء ٗ مزىل تشتظ اىعذاداخ تخظ اىنٖشتاء ‪ٝ‬سَ‪ ٚ‬تَ٘دً اإلذصاه عثش خط٘ط اىنٖشتاء‪.‬‬
‫ترصَرٌ اىَششٗع ‪ٛ‬صثر تاإلٍناُ ٍشاقة خَ‪ٞ‬ع اىعذاداخ اىَرصيح تاىشثنح ٗ رىل ىيَراتعح ٍْعا ىسذٗز أ‪ٍ ٛ‬التساخ ٍِ خٖح‬
‫اىَسرٖيل معَي‪ٞ‬اخ سشقح اىنٖشتاء ٗ غ‪ٞ‬شٕا؛ أ‪ٝ‬ضا ىَعشفح األٍامِ اىَقط٘ع ٍْٖا اإلٍذاد اىنٖشتائ‪ّ ٜ‬ر‪ٞ‬دح ى٘خ٘د عطو فْ‪ ٜ‬أٗ‬
‫غ‪ٞ‬شٓ‪.‬‬
‫ٕزا اىَششٗع ‪ٝ‬سٖو ىَ٘ظف‪ ٜ‬ششمح اىنٖشتاء إٍناّ‪ٞ‬ح اىرسنٌ ف‪ ٜ‬عذاداخ اىشثنح س٘اء ترغز‪ٝ‬رٖا تنَ‪ٞ‬ح ٍع‪ْٞ‬ح ٍِ اىنٖشتاء ٗ رىل‬
‫إٍا ٍثاششج تإسساه أٍش أٗ تإسساه ّص تٔ اىشقٌ اىرسيسي‪ ٚ‬اىز‪ ٛ‬س‪ٞ‬رٌ إدساخح ت٘اسطح اىَسرٖيل إلذَاً اىعَي‪ٞ‬ح‪ .‬مزىل ‪َٝ‬نِ‬
‫اسساه إٍش‪ٝ‬قً٘ تفصو اىنٖشتاء اىذاخوج‪ ،‬تاإلضافح إى‪ ٚ‬اىَراتعح اىَسرَشج ىإلسرٖالك اى‪. ٍٜ٘ٞ‬‬
‫ذٌ ذصَ‪َّ٘ ٌٞ‬صج ذ٘ض‪ٞ‬س‪ ٜ‬ىعشض فنشج اىَششٗع ٗ أمذخ اىْرائح اىرطث‪ٞ‬ق‪ٞ‬ح ىٔ ٍذ‪ّ ٛ‬داذ ٗ مفاءج اىَششٗع‪.‬‬

‫‪VII‬‬
TABLE OF CONTENTS

‫ـــــــح‬ٟٝ‫ا‬................................................................................................................................................... II
‫ إٕـــــــــذاء‬.............................................................................................................................................. III
DECLARATION OF ORIGINALITY .................................................................................................. IV
AKNOWLEDGEMENT ........................................................................................................................ V
ABSTRACT ........................................................................................................................................ VI
‫ اىَسرخيص‬............................................................................................................................................. VII
TABLE OF CONTENT .................................................................................................................... VIII
LIST OF TABLES ............................................................................................................................... XI
LIST OF FIGURES ............................................................................................................................ XII
LIST OF ABBREVIATIONS ............................................................................................................ XIV
CHAPTER 1: INTRODUCTION ..................................................................................................... 1
1.1 Overview ........................................................................................................................................... 1
1.2 Statement of the problem ................................................................................................................ 1
1.3 Project Objectives ............................................................................................................................ 2
1.4 Thesis Layout ................................................................................................................................... 2
CHAPTER 2: LITERATURE REVIEW ......................................................................................... 3
2.1 History of energy meter .................................................................................................................. 3
2.2 Types of meters ................................................................................................................................ 4
2.2.1 Electromechanical energy meters .......................................................................................... 4
2.2.2 Digital Energy Meter ............................................................................................................... 5
2.2.3 Prepaid Energy Meter.............................................................................................................. 7
2.3 Power Line Communication (PLC) ............................................................................................... 8
2.3.1 Definition: ................................................................................................................................. 8
2.3.2 Concept: .................................................................................................................................... 9
2.3.3 Background ............................................................................................................................. 10
2.3.4 Types of PLC frequency bands ............................................................................................ 10
2.3.5 Advantages of PLC ................................................................................................................ 11
2.3.6 Drawbacks of PLC and their solution ................................................................................. 11
2.3.7 Stages of PLC process ........................................................................................................... 12
2.4 Power Line Modem (PLM) .......................................................................................................... 14
2.4.1 Overview ................................................................................................................................. 14
2.4.2 Design guidelines of simple and low data rate PLM ........................................................ 14

VIII
2.5 Microcontrollers ............................................................................................................................. 17
2.5.1 Overview ................................................................................................................................. 17
2.5.2 General feature of microcontroller ...................................................................................... 17
2.5.3 Types of Microcontrollers .................................................................................................... 20
2.5.4 Microcontroller Architecture................................................................................................ 20
2.5.5 Programming of Microcontrollers ....................................................................................... 21
CHAPTER 3: AMR AND PREPAID METER DESIGN ............................................................. 22
3.1 AUTOMATIC METER READING MODEL ........................................................................... 22
3.1.1 Automatic Meter Reading Concept ..................................................................................... 22
3.1.2 AMR System Overview ........................................................................................................ 22
3.1.3 The AMR System .................................................................................................................. 23
3.1.4 Operating Principle ................................................................................................................ 26
3.1.5 Power Consumption Measuring........................................................................................... 27
3.2 Prepaid Electrical Energy Meter .................................................................................................. 29
3.2.1 Energy Measurement Interface Module (EMIF MODULE) ........................................... 30
3.2.2 Relay Interface Circuit (RLIF) ............................................................................................. 31
3.2.3 Microcontroller Reset Interface Circuit (MRIF) ............................................................... 31
3.2.4 Buzzer Interface Circuit (BUIF) .......................................................................................... 32
3.2.5 Mechanical Coupling Interface Circuit (MCIF) ................................................................ 33
3.2.6 Prepaid Card Reset Interface Circuit (PCRIC) .................................................................. 34
CHAPTER 4: METHODOLOGY AND DESIGN ....................................................................... 35
4.1 Design Goals .................................................................................................................................. 35
4.1.1 User convenience and system portability ........................................................................... 35
4.1.2 Hardware independence ........................................................................................................ 35
4.1.3 System integration ................................................................................................................. 35
4.2 System Requirement...................................................................................................................... 36
4.2.1 Establishment of a power line communication network................................................... 36
4.2.2 Monitor the energy meter network system on PC ............................................................. 36
4.2.3 Design of simple illustrative modules ................................................................................. 36
4.3 System Layout ................................................................................................................................ 36
4.4 System Scenario ............................................................................................................................. 37
4.4.1 The TCP/IP Communication Protocol ................................................................................ 38
4.4.2 Server Functions .................................................................................................................... 39
4.4.3 Client Function ....................................................................................................................... 40

IX
4.5 Development Tools ....................................................................................................................... 40
4.5.1 Hardware Tools ...................................................................................................................... 40
4.5.2 Software Tools ....................................................................................................................... 47
4.6 Modbus Communication Protocol Concept ............................................................................... 48
4.7 Modbus TCP/IP Frame Format .................................................................................................... 49
CHAPTER 5: IMPLEMENTATION AND RESULTS ................................................................ 50
5.1 Overview ......................................................................................................................................... 50
5.2 Implementation of interface models ............................................................................................ 50
5.2.1 Server interface models ......................................................................................................... 50
5.2.2 Client interface models ......................................................................................................... 53
5.2.3 PLM interface with the client ............................................................................................... 55
5.3 Results ............................................................................................................................................. 56
5.3.1 Implementation of Results .................................................................................................... 59
5.4 Actual Load Calculation ............................................................................................................... 62
5.5 Discussion ....................................................................................................................................... 63
5.5.1 Design performance............................................................................................................... 63
5.5.2 Response to user request ....................................................................................................... 63
5.5.3 Data accuration....................................................................................................................... 63
5.5.4 Output Result.......................................................................................................................... 63
CHAPTETR 6: CONCULSION AND RECOMMENDATIONS ................................................ 64
6.1 Conclusion ........................................................................................................................... 64
6.2 Problems and solution ......................................................................................................... 64
6.3 Recommendations ............................................................................................................... 65
6.4 Future work.......................................................................................................................... 66
References ......................................................................................................................................... 67
APPENDEX A: PREPAID ENERGY METER CODES............................................................A-1
APPENDIX B: PROJECT MAIN CODE .................................................................................... B-1

X
LIST OF TABLES

Table4.1 Modbus TCP/IP Frame Fprmat ........................................................................................... 49


Table ‎5-1 Results displayed in the Client interface............................................................................ 57
Table ‎5-2 cont. of Results displayed in the Client interface .............................................................. 58
Table ‎5-2 load calculations ................................................................................................................ 62

XI
LIST OF FIGURES

Figure ‎2.1 Electromechanical Energy Meter..................................................................................... 4


Figure ‎2.2 Digital energy meter ....................................................................................................... 6
Figure ‎2.3 Prepaid Energy Meter ...................................................................................................... 7
Figure ‎2.4 Power line channel spectrum ........................................................................................... 9
Figure ‎2.5 Spectrum diagram of modulated signal over PLC channel ........................................... 13
Figure ‎2.6 Typical architecture of the PLM system ........................................................................ 15
Figure ‎2.7 General view of a microcontroller ................................................................................. 18
Figure2.8 Component of the MCU ................................................................................................. 18
Figure 3.1 System using power line carrier..................................................................................... 23
Figure 3.2 Data Concentrators ........................................................................................................ 24
Figure 3.3 AMR system block diagram .......................................................................................... 25
Figure 3.4 AMR operation principle diagram ................................................................................. 27
Figure 3.5 Hardware block diagram ................................................................................................ 29
Figure 3.6 Electrical circuit of RLIF ............................................................................................... 31
Figure 3.7 Electrical circuit of MRIF .............................................................................................. 32
Figure 3.8 Electrical circuit of BUIF .............................................................................................. 32
Figure 3.9 Electrical circuit of PRIF ............................................................................................... 34
Figure ‎4.1 prepaid energy meter network block diagram ............................................................... 37
Figure ‎4.2 Serial number command on meter screen ...................................................................... 38
Figure ‎4.3 LOVATO Digital multi-meter DMK40 ......................................................................... 40
Figure ‎4.4 Converter from RS-485 to RS-232 ............................................................................... 41
Figure ‎4.5 Power line modem-Edimax .......................................................................................... 43
Figure ‎4.6 Application of home plug using power line modem..................................................... 44
Figure ‎4.7 Ethernet cable ................................................................................................................ 46
Figure ‎4.8 Microsoft Visual C++ interface ..................................................................................... 47
Figure 5.1 Snapshot of the Server interface .................................................................................... 51
Figure 5.2 Snapshot of PLM interface ............................................................................................ 52
Figure 5.3 Snapshot of the Client interface ..................................................................................... 53
Figure ‎5.4 Snapshot of PLM interface ............................................................................................ 55
Figure 5.5 Line-to-line voltage Vs. time ......................................................................................... 59
Figure 5.6 Line current Vs. time ..................................................................................................... 60

XII
Figure 5.7 Three phase power Vs. time .......................................................................................... 60
Figure ‎5.8 Import and export energy Vs. time ................................................................................ 61
Figure 5.9 Active power, reactive power and apparent Vs. time .................................................... 61

XIII
LIST OF ABBREVIATIONS

Abbreviation Meaning
IC Integrated Circuit
CT Current Transformer
PT Potential Transformer
EEPROM Electrically Erasable Programmable Read Only Memory
PLC Power Line Communication
PLCR Power Line Carrier
PLM Power Line Modem
CFS Carrier Frequency System
RCS Ripple Carrier Signaling
CENELEC European Committee for Electro -technical Standardization
FSK Frequency Shift Keying
PSK Pulse Shift Keying
OFDM Orthogonal Frequency Division Multiplexing
MCU Microcontroller
RF Radio Frequency
I/O Input/output
AMR Automatic Meter Reading
HCS Host Central Station
DCU Data Concentration Unit
MIU Meter Interfacing Unit
LAN Local Area Network
MIU Meter Interface Units
RTU Remote Transmit Unit
PSTN Public Switched Telephone Network
rms root mean square
PC Personal Computer
MMIU Multi-channel Meter Interface Unit
TX Transmitter
RX Receiver

XIV
CHAPTER 1 INTRODUCTION

CHAPTER 1

INTRODUCTION
1.1 Overview:
A scheme of Electricity billing system called “PREPAID ENERGY METER NETWORK”
can facilitate in improved cash flow management in energy utilities.
The aim of this project is to develop a new version of prepaid energy meter device which
acts as a point in a large network connects all these devices to a centre (every device has IP
address) directed by energy company “ National electricity company” .
By this network the energy company can easily determine the consumed power in each
point (prepaid meter) which is useful in security purposes to prevent any consumer from any
illegal actions, also for full control of the energy network especially for emergency cases.
In this network each device has a unique memory card (which we called it a SMART
CARD) with a unique pass-word. This smart card can work only after recognition by its device
and it can be recharged when the energy amount is over by inserting it in an automatic
recharging machine.
The automatic recharging machine network is necessary for the smart card; because it
makes the recharging operation so comfortable & easy for consumer by making multiple pay-
points distributed in different places which controlled by one server same as ATM system.
In this project a provision has been used to give an alarm sound to consumer before the
whole amount is reduced.
A computer network is used to connect all these devices with one server depending on a
power line communication (the electric transmission lines) to send data (voltage & current) to
the energy company by using special modem.

1.2 Statement of the problem:


The traditional function of the prepaid energy meter device (Which is recently used in
Sudan) is just to monitor the amount of instantaneous energy for the customer to be ware before
amount is over.
On the side of Electricity Company a SCADA system with fiber cable beside the
transmission lines can monitor the instantaneous current, voltage and then the amount of energy

1
CHAPTER 1 INTRODUCTION

at any substation but no further can use (doesn’t have enough capacity to contain secondary
distribution).
If there is illegal process of stealing electricity or fault at any place in the secondary
distribution system, the company will have no idea because there is no indicator to inform them.
The solution of these problems is to construct the prepaid energy meter network by using
power line communication.

1.3 Project Objectives:


The objective of this project can be summarized in three main points:
 Study of the possibility and feasibility of power line communication as a solution of
sending and receiving data.
 Construct network for connect all prepaid energy meter to one server (The energy
company) for security and control (in emergency cases) purposes by using power line
communication (transmission line).
 Modify the prepaid energy meter device by adding smart card reader unit and alarm
device.

1.4 Thesis Layout:


This thesis is organized as follows:
Chapter 2: Introduces the history and developing of energy meters and their types, also the
concept of the power line communication including their requirement are also explained.
Chapter 3: contains The Automatic Meter Reading Concept and the circuit diagram of the
prepaid energy meter design.
Chapter 4: The methodology and design, architecture and implementation of the various parts
of our system are comprehensively explained.
Chapter 5: Describes the procedures and experiments carried out to evaluate system’s
performance then represents the experimental results deduced from these experiments.
Chapter 6: Presents conclusions and recommended future work.
Appendix A: represents the prepaid energy meter codes.
Appendix B: Gives system programming codes.

2
CHAPTER 2 LITERATURE REVIEW

CHAPTER 2

LITERATURE REVIEW

2.1 History of energy meter


As commercial use of electric power spread in the 1880s, it became increasingly
important that an electrical energy meter, similar to the existing gas meters, was required to
properly bill customers for the cost of energy, instead of billing for a fixed number of lamps per
month. Many experimental types of meter were developed. Edison at first worked on a DC
electromechanical meter with a direct reading register, but instead developed an electrochemical
metering system, which was used an electrolytic cell to totalize current consumption. At periodic
intervals the plates were removed, weighed, and the customer billed. The electrochemical meter
was labor-intensive to read and not well received by customers. In 1885 Ferranti offered a
mercury motor meter with a register similar to gas meters; this had the advantage that the
consumer could easily read the meter and verify consumption. The first accurate, recording
electricity consumption meter was a DC meter by Dr Hermann Aron, who patented it in 1883.
Hugo Hirst of the British General Electric Company introduced it commercially into Great
Britain from 1888. Meters had been used prior to this, but they measured the rate of power
consumption at that particular moment. Aron's meter recorded the total energy used over time,
and showed it on a series of clock dials.
The first specimen of the AC kilowatt-hour meter produced on the basis of Hungarian
Ottó Bláthy's patent and named after him was presented by the Ganz Works at the Frankfurt Fair
in the autumn of 1889, and the first induction kilowatt-hour meter was already marketed by the
factory at the end of the same year. These were the first alternating-current watt meters, known
by the name of Bláthy-meters. The AC kilowatt hour meters used at present operate on the same
principle as Bláthy's original invention. Also around 1889, Elihu Thomson of the American
General Electric company developed a recording watt meter (watt-hour meter) based on an
ironless commutator motor. This meter overcame the disadvantages of the electrochemical type
and could operate on either alternating or direct current.
In 1894 Oliver Shallenberger of the Westinghouse Electric Corporation applied the
induction principle previously used only in AC ampere-hour meters to produce a watt-hour meter
of the modern electromechanical form, using an induction disk whose rotational speed was made
proportional to the power in the circuit. Although the induction meter would only work on

3
CHAPTER 2 LITERATURE REVIEW

alternating current, it eliminated the delicate and troublesome commutator of the Thomson
design. Shallenberger fell ill and was unable to refine his initial large and heavy design, although
he did also develop a polyphase version [1].

2.2 Types of meters


Electricity meters operate by continuously measuring the instantaneous voltage (volts) and
current (amperes) and finding the product of these to give instantaneous electrical power (watts)
which is then integrated against time to give energy used (joules, kilowatt-hours etc.). Meters for
smaller services (such as small residential customers) can be connected directly in-line between
source and customer. For larger loads, more than about 200 amps of load, current transformers
are used, so that the meter can be located other than in line with the service conductors. The
meters fall into two basic categories, electromechanical and electronic [2].

2.2.1 Electromechanical energy meters


The most traditional and widely used energy meter is the electromechanical energy
meter. This energy meter works on the principle of electro-mechanical induction as shown in
Figure 2.1.

Figure 2.1 Electromechanical Energy Meter

4
CHAPTER 2 LITERATURE REVIEW

The construction of an electromechanical energy meter consists of three electrical


circuits, magnetically coupled, two of them fixed and one rotating around the mechanical axis of
the system. The two fixed circuits are the voltage and the current coils. The third circuit is the
Aluminum rotating disk which is mounted on a rigid axis. When the aluminum disk rotates, the
disk axis will transmit the disk rotation to a mechanical counter which provides the energy
display [2].
2.2.1.1 Advantages:
The electromechanical energy meter has the following advantages, relative to more advanced
energy meters.
 It is inexpensive.
 It is easy to use.
 It consumes a negligible amount of electricity.
2.2.1.2 Disadvantages:
The electromechanical energy meter also has the following disadvantages, relative to more
advanced energy meters:
 It is less reliable due to the moving parts (aluminium disc).
 It has less accuracy because of electromechanical errors.
 Tampering is much easier than with more advanced meters.
 There is no security for this meter.
 Billing is a labour consuming process because it must be manually read.
 These electromechanical energy meters are not designed for nonlinear loads such as AC
motors.

2.2.2 Digital Energy Meter


Another way to measure electricity is with a digital energy meter, as shown in
Figure 2.2.

5
CHAPTER 2 LITERATURE REVIEW

Figure 2.2 Digital energy meter

In Figure2.2 the alternating current (AC) is supplied through the current transformer (CT)
and the potential transformer (PT) so that any sudden changes in the voltage and currents will
not affect the energy meter. These transformers also step down the voltage and the current to
circuit levels.
The output of the CT and PT is supplied to Energy Meter IC which generates the pulses
according to the energy supplied to it. The pulse output of the Energy Meter IC is supplied to the
microcontroller‟s counter pin so that the microcontroller can count the number of pulses and
calculate the energy supplied to the consumer. Software burned on to the microcontroller
performs the usage calculations. The LCD display is used to display the number of units
consumed by the consumer [2].
2.2.2.1 Advantages:
The digital energy meter has solved many of the problems with Electro-Mechanical
Energy Meter.
2.2.2.2 Disadvantages:
The major disadvantage of the digital energy meter is that it does not address the billing
which is a labour consuming process.

6
CHAPTER 2 LITERATURE REVIEW

2.2.3 Prepaid Energy Meter


The next enhancement of the energy meter is to make it prepaid. This is done by using a
removable part which can be loaded (and later reloaded) with a specified amount of energy by
the utility. The prepaid energy meter is the upgraded version of the digital energy meter with an
extra feature, i.e. a prepaid system using an Electrically Erasable Programmable Read Only
Memory (EEPROM) chip. In this meter the EEPROM chip is used for recharging the units to
enable that the power usage.
Figure 2.3 shows the block diagram for a prepaid energy meter

Figure 2.3 Prepaid Energy Meter

The AC supply is supplied through CT and PT so that any sudden changes in the
voltage and current will not affect the energy meter. As in a basic digital energy meter, the
voltage and the current are stepped down to circuit levels. The output of the CT and PT is
supplied to the energy meter IC which generates pulses according to the amount of energy
supplied to it. The pulse output of the energy meter IC is supplied to the microcontroller‟s
counter pin so that the microcontroller can count the number of pulses and calculate the energy
supplied to the consumer. The microcontroller will calibrate with each unit in the EEPROM
according to the software burned on to the microcontroller.

7
CHAPTER 2 LITERATURE REVIEW

When the number of units in the EEPROM reaches zero, the timer pin of the
microcontroller will activate the relay to disconnect the supply to the consumer. The LCD
displays the number of units used by the consumer and the number of units left for use [2].
2.2.3.1 Advantages:
 Improved operational efficiencies:
The prepaid meters are likely to cut the cost of meter reading as no meter readers are
required. In addition, they eliminate administrative hassles associated with disconnection
and reconnection. Besides, going by South Africa‟s experience, prepaid meters could
help control appropriation of electricity in a better way than conventional meters.
 Reduced financial risks:
Since the payment is up-front, it reduces the financial risk by improving the cash flows
and necessitates an improved revenue management system.
 Better customer service:
The system eliminates billing delay, removes cost involved in
disconnection/reconnection, enables controlled use of energy, and helps customers to
save money through better energy management.
2.2.3.2 Disadvantages:
The major disadvantage of the prepaid energy meter is the method of recharging the
number of units in the EEPROM chip. To recharge the EEPROM chip, it must be taken to the
distribution.

2.3 Power Line Communication (PLC)


2.3.1 Definition:
Power line communication is “the technology which provides a way to send and receive
voice and data signals through the existing power line network” [3]. Therefore it is a system for
carrying data on a conductor that is also used for electric power transmission.
PLC also goes by a few other names and acronyms: Broadband over Power Lines (BPL),
Power Line Telecommunications (PLT), Power-line Digital Subscriber Line (PDSL), Power
Line Networking (PLN), and Power Line Broadband (PLB) are terms also used [4]. There are a
number of types of PLC systems, using different approaches and architecture. All are "carrier-
current" systems, a term used to describe systems that intentionally conduct signals over
electrical wiring or power lines.

8
CHAPTER 2 LITERATURE REVIEW

2.3.2 Concept:
Power line communication system operates by impressing a modulated carrier signal into
the power line wiring and extracting such a signal from the same power line.
Different types of power line communication use different frequency bands, depending
on the digital transmission characteristics of the power wiring used. Since the power wiring
system was originally intended for transmission of AC power, the power line wire has limitation
for carrying high frequencies. The propagation problem is a limiting factor for each type of
power line communications.
Most of world systems use 50Hz or 60Hz AC power (50Hz in Sudan). The power line
channel spectrum is shown below:

Figure 2.4 Power line channel spectrum


Ac power lines are used as a medium to send and receive discrete frequency-based
control, monitoring and communication messages to run building devices, exchange data and
share information among multiple PCs and other devices. Basically a radio signal is modulated
with that has to be sent. This radio signal is then send down the copper medium (selected power
line) in a band of frequencies not used for the purpose of supplying electricity. The frequencies
and encoding schemes used greatly influence both the efficiency and the speed of the PLC
service.
Data rates over a power line communication system vary widely. Low frequency (about
100-200 KHZ) carriers impressed on high voltage transmission lines with an equivalent data rate
of a few hundred of dedicated network cabling.

9
CHAPTER 2 LITERATURE REVIEW

2.3.3 Background
Power Line Communications is the usage of electrical power supply networks for
communications purposes. In this case, electrical distribution grids are additionally used as a
transmission medium for the transfer of various telecommunications services. The main idea
behind PLC is the reduction of cost and expenditure in the realization of new
telecommunications networks. Around the year 1922 the first Carrier Frequency Systems (CFS)
had been operated in high-voltage electrical networks that were able to span distances over
500km using 10 W signal transmission power. Such systems have been used for internal
communications of electrical utilities and realization of remote measuring and control tasks.
Also, the communications over medium and low-voltage electrical networks has been realized.
In 1950, Ripple Carrier Signalling (RCS) systems have been applied to medium and low-voltage
networks for the realization of load management in electrical supply systems. Then the first
European Committee for Electro -technical Standardization band (CENELEC) PLC systems
appeared, extending from 3 to 148.5kHz, and allowing bidirectional communications over the
low voltage electrical network, for a great number of applications related to the home automation
field (intruder alarm, fire detection, gas leak detection, and so on) [5].
2.3.4 Types of PLC frequency bands
 High Frequency band PLC (f ≥ 1MHz):
High frequency communication may use large portions of the ratio spectrum for
communication, depending on the technology. This type is applied for law-voltage power
lines, so it dedicated to household usage [6].
High frequency PLC can be used to interconnect home computers, peripherals or
other networked consumer peripherals, and internet access broadband over power lines.
 Medium frequency band PLC (1KHz <f<1MHz):
This is the most famous application which uses the electrical power wiring as a
transmission medium. It suited the low/medium voltage power line, which is a suitable
technique for building automation that provides remote control of lighting and
application without installation of additional control wiring [6].
 Low frequency band PLC (f<1KHz):
This types suites the high voltage transmission lines, so it can be used in power
metering and transmission of supervisory data at law data rate (up to hundreds of bps)
[6].

10
CHAPTER 2 LITERATURE REVIEW

2.3.5 Advantages of PLC


In this section some of the PLC advantages are discussed to show the advantages of PLC
over other techniques used in energy metering process:
 Usage of existing power line wiring leads to save money and efforts of a new
communication infrastructure installation.
 High flexibility; any power line socket/node can be used to plug and play.
 Easy to install and modify; doesn‟t need high experience.
 Economically feasible; it saves the additional costs of network installation.
 Has acceptable range, up to 800m in some types and can be extended to be infinite by
using repeaters.
 Fast data transmission rate up to 10Mbps.

2.3.6 Drawbacks of PLC and their solution


 Noisy environment:
The electrical wires are not originally dedicated for communication, so it is a
noisy medium. In addition of noisy medium, some of building appliances generate noise
signals, such as: brush motors, bulbs and lamps, switching power supplies, power tools,
etc.
Therefore it is very important to take in mind this drawback and attempt to reduce
the effect of noise as less as possible.
 Impossibility of direct connection:
It is impossible to exchange messages directly through the power line medium,
because of existence of the live power (e.g. 220V/50Hz) which is impossible to be
interfaced to the digital/DC systems; this problem has been solved by development of
such device which is called Power Line Modem (PLM). PLM is a digital transceiver
which enables transmission and receiving of digital data through power line.
 Range limitation:
The PLC data rate depends mainly on the range to be used for, so the data rate
could be higher in small ranges rather than large ones. But improved encoding techniques
can help to rectify it.
 Sharing of bandwidth:
Each terminal in the network require significant data rate. However the amount of
bandwidth available through the network must be shared fairly and consistently. This
problem can be rectified using suitable high performance modulation techniques like:

11
CHAPTER 2 LITERATURE REVIEW

FSK (Frequency Shift Keying), PSK (Pulse Shift Keying), OFDM (Orthogonal
Frequency Division Multiplexing).
 Security of data:
PLC network, as any other network, needs to be secured and protected from
unauthorized access; therefore encryption must be used to prevent the interception of
sensitive data by unauthorized personnel.
 Interference:
Electrical wires can pick up the Radio Frequency (RF), thus other types of RF
signals may interfere with PLC signal of the same frequency. So it is necessary to use
unused bandwidths.

2.3.7 Stages of PLC process


 Interfacing to the power lines
Due to incompatibility between the AC power (220V/50Hz or more) and the digital
components of controllers; the interfacing process is a critical issue.
The power line coupler helps to connect the low voltage digital devices to the power line without
damping them. It also acts as a high-pass filter to stop power signal. It allows injection and
acquisition of communication signals from and to the power line. Therefore the converted signal
could be manipulated using Digital Signal Processing techniques.
 Filtering
The required signal and power are transmitted together through the same medium, but
they are different in shape, bandwidth and frequency. Obviously it is not true to manipulate the
mixed signals, so an important stage of signals separation must be done. Band Pass Filter is the
suitable choice to do this function [7]. The acquired signal is filtered to remove any high
frequency noises because it can pass only the bandwidth of control signal and eliminate power
signal.
 Modulation
Modulation is needed to use the uncovered bandwidths of power line channel spectrum as
shown in Figure 2.5

12
CHAPTER 2 LITERATURE REVIEW

Figure 2.5 Spectrum diagram of modulated signal over PLC channel

Generally, there are many techniques for modulation. All practical modulation techniques
use the sinusoidal signal as a carrier:
carrier = A sin(2πf + φ) (2.1)
Where:
A: amplitude of the sinusoidal signal
F: frequency of the signal
Φ: Phase angle
The sinusoidal signal has three attributes that could be changed to represent the message:
 Amplitude (amplitude modulation).
 Frequency (frequency modulation).
 Phase (phase modulation).
 Demodulation
Demodulation is the opposite process of modulation, while the digital modulation is used
in PLC, therefore the corresponding digital demodulation techniques are:
 Coherent demodulation: a technique needs phase information.
 Non coherent: doesn‟t need phase information.
Generally, there is no difference between performance of coherent and non-coherent
demodulators and both of them are used in the PLC.

13
CHAPTER 2 LITERATURE REVIEW

2.4 Power Line Modem (PLM)


2.4.1 Overview
PLM is a device that accomplishes the data transfer through the power line, impresses
transmitted signal into power line and extracts received signal from it. The main function of
power line modem is to interface digital devices (computers, Microcontrollers, etc.) to the power
line [8].

2.4.2 Design guidelines of simple and low data rate PLM


Figure2.6 illustrates the architecture of the PLM used to achieve low rate digital data
transmission and reception, displays the functional hierarchy of different modules. Broadly, the
modules can be categorized into the following:
 Power Line Coupler.
 Analog and Digital Signal Processor.
 Modulator and Demodulator.
 Line Driver.
 Interface.

14
CHAPTER 2 LITERATURE REVIEW

Figure 2.6 Typical architecture of the PLM system

The coupler allows injection and acquisition of communication signal from and to the power
line. The acquired signal is filtered to remove any high frequency noises and is amplified; the
operation is performed by the analog signal processing unit. After the analog signal processor,
the signal is passed through demodulator to extract the information. The output of the
demodulator is passed through digital signal processing unit module for the reconstruction of the
information signal. Similarly, at the transmitting part, the information is modulated, passed
through the line driver and then injected to the power line.

15
CHAPTER 2 LITERATURE REVIEW

 Power Line Coupler:


To be able to design a complete PLC system, a proper interface unit between relatively
high voltage power line (HV) and low voltage (LV) communication system, isolation of LV
communication system from HV power line with appropriate frequency response to allow
message signal injection and acquisition are needed to be considered. High voltage rating
coupling capacitors and isolation transformer were used for constructing the power line
coupler.

 Analog Signal Processing Unit:


The received signal from coupler was first sent through active band pass filter. Stage of
amplification, bi-quad filter was used to provide adequate attenuation of power signal and
other high frequency noises.
The band-pass filters were designed to have center frequencies of carrier signals.

 Digital Signal Processing Unit:


The main purpose of the digital signal processing is „Signal Reconstruction‟ using special
DSP chips to extract the acquisitioned data and reconstruct the original wave form.

 Modulation and demodulation:


As mentioned previously, the suitable digital modulation/demodulation techniques are
used in PLC. The signal is passed through demodulator to extract the raw data to be used by
the DSP unit. On the other hand the information signal are modulated to match the noisy
electric grid environment, passed through the line driver and to then it is injected to power
line.

16
CHAPTER 2 LITERATURE REVIEW

2.5 Microcontrollers

2.5.1 Overview:
A microcontroller (sometimes abbreviated µC, uC or MCU) is a small computer on a
single integrated circuit containing a processor core, memory, and programmable input/output
peripherals. Microcontrollers are designed for embedded applications, in contrast to the
microprocessors used in personal computers or other general purpose applications.
Microcontrollers are used in automatically controlled products and devices, such as
automobile engine control systems, implantable medical devices, remote controls, office
machines, appliances, power tools, and toys. By reducing the size and cost compared to a design
that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it
economical to digitally control even more devices and processes. Mixed signal microcontrollers
are common, integrating analog components needed to control non-digital electronic systems [9].

2.5.2 General feature of microcontroller:


In addition to CPU, RAM, and ROM, a single chip microcontroller includes additional
built-in hardware that makes it easier to implement variety of imbedded system requirements.
Like any electronic circuit the microcontroller needs to be powered, and needs a clock signal to
drive the internal logic circuit. A typical microcontroller may include the following feature as
illustrated in Fig 2.7, and Fig 2.8.
 Processor reset.
 Device clocking.
 Central processor.
 Program and Variable Memory (RAM).
 I/O pins.
 Instruction cycle timers.
 More Sophisticated Features:
 Built-in monitor/debugger program.
 Interrupt capability.
 Analog I/O (PWM and variable dc I/O).
 Serial I/O (synchronous, a synchronous).
 Parallel I/O (including direct interface to a master processor.
 External memory interface.

17
CHAPTER 2 LITERATURE REVIEW

Figure 2.7 General view of a microcontroller

Figure2.8 Component of the MCU

18
CHAPTER 2 LITERATURE REVIEW

The various components of the MCU shown in Figure 2.8 above are explained below:
 Random Access Memory (RAM):
RAM is used for temporary storage of data during runtime.
 ROM:
ROM is the memory which stores the program to be executed.
 SFR Registers:
Special Function Registers are special elements.
 Program Counter:
This is the "engine" which starts the program and points to the memory address of the
instruction to be executed. Immediately upon its execution, value of counter increments by 1.
 Control Logic:
As the name implies, it which supervises and controls every aspect of operations within
MCU, and it cannot be manipulated. It comprises several parts, the most important ones
including: instructions decoder, Arithmetical Logic Unit (ALU) and Accumulator.
 A/D Converter:
A/D stands for analog to digital. They convert analog signals to digital signals.
 I/O Ports:
To be of any practical use, microcontrollers have ports which are connected to the pins on its
case. Every pin can be designated as either input or output to suit user's needs.
 Oscillator:
This is the rhythm section of the MCU. The stable pace provided by this instrument allows
harmonious and synchronous functioning of all other parts of MCU.
 Timers:
Timers can be used for measuring time between two occurrences and can also behave like a
counter. The Watchdog Timer resets the MCU every time it overflows, and the program
execution starts anew (much as if the power had just been turned on).

19
CHAPTER 2 LITERATURE REVIEW

2.5.3 Types of Microcontrollers:


 Embedded (Self-contained) 8 bit.
 16-32 bit.
 Digital Signal Processors.

2.5.4 Microcontroller Architecture:


1. von-Neumann architecture:
The von Neumann architecture is a computer design model that uses a
processing unit and a single separate storage structure to hold both instruction and data. It
is named after mathematician and early computer scientist John von Neumann. Such a
computer implements a universal Turing machine, and the common “referential model”
of specifying sequential architecture, in contrast to parallel architectures [10].

2. Harvard architecture:
Harvard architecture is a newer concept than von-Neumann. It is a computer with
physically separate storage signal pathways for instruction and data. The term originated
from the Harvard Mark 1 relay based computer, which stored instructions on punched
tape (24 bits wide) and data in electro-mechanical counters (23 digits wide).
These early machines had limited data storage, entirely contained within the data
processing unit, and provided no access to the instruction storage as data, making loading
and modifying programs as entirely offline process [10].

20
CHAPTER 2 LITERATURE REVIEW

2.5.5 Programming of Microcontrollers:


A microcontroller continuously executes the program stored in its memory. Assembly
language is usually used to write microcontrollers codes. For more complicated programs, C
compilers are available to program, a variety of microcontrollers language offers more options to
the programmers since it contains many function and more complex data types. C codes also
provide header files for many chips and libraries for common hardware used; this hides much of
the hardware complexity from the programmer. Assemblers are used to convert the C code into a
HEX file. The HEX file is the file that is transmitted from PC to the memory of the
microcontroller.
The means by which the HEX file is transmitted from PC to the microcontroller is called
a programmer. The programmer generally consists of PC software that manages the HEX file to
be transferred. A cable between the PC and microcontroller must exist, whether serial cable or
parallel port or USB. Most of the manufacturers of microcontrollers provide Programmers and
compilers.

21
CHAPTER 3 AMR AND PREPAID METER DESIGN

CHAPTER 3

AMR AND PREPAID METER DESIGN

3.1 AUTOMATIC METER READING MODEL


3.1.1 Automatic Meter Reading Concept
Current trend of energy management is changing toward real-time monitoring and
control. There is an emerging trend to use PLC technology to send and receive data over existing
power lines, which is a very low cost solution for automatic meter reading (AMR) and advanced
metering.
AMR is the remote collection of consumption data from customer’s utility meters over
telecommunications, radio, power line and other links. AMR provides water, electric and gas
utility−service companies the opportunities to streamline metering, billing and collection
activities, increase operational efficiency and improve customer service. Utility company uses
technologies that were developed several decades ago with the majority of the meters being read
visually. With manual readings, considerable time is used to physically check out each unit.
AMR becomes a viable option to overcome this problem of time wastage to obtain the meter
readings. There are many different forms of communication links that can be utilized as the
communication medium in an AMR system. One such link is the power line carrier or PLCR.
The advantages of using the PLCR as the communication medium are readily apparent since the
power line network is the property of the utility company and its infrastructure is already there.
However, power lines are never meant for communication and creates much noise and therefore,
various modifications has to be made to make the PLC suitable to be the AMR communication
channel. The AMR system consists of three major components: the meter interface module,
communications system, and data concentrator [11].
3.1.2 AMR System Overview
The remote AMR System is a host driven, multi-level network system consisting of a
Host Central Station (HCS), Data Concentrator Units (DCU) and Meter Interfacing Units (MIU),
with built-in flexibility and expandability. Each HCS, while working independently, can also be
integrated with an existing corporate information management system through software
interface. With additional hardware and software support, the HCS can function as a workstation
in an existing Local Area Network (LAN) and becomes a member of the entire system, or
22
CHAPTER 3 AMR AND PREPAID METER DESIGN

several HCS can be connected together to form a network of their own.


AMR system can be connected to any Electricity, Gas, Water and flow Meters with pulse
output for Meter Readings [12].
3.1.3 The AMR System:
The AMR system consists of three primary components, namely, the meter interface
module, communication system as well as the central control unit or data concentrator, which is
used to store the transmitted meter readings data. Figure 3.1 shows AMR system using PLC.

Figure 3.1 System using power line carrier


An AMR system is also able to combat meter tampering and electricity theft. Real−time
reporting can help the utility identify the location and scope of problems before sending crews to
the field. Also, the utility is able to connect or disconnect the delivery of power without having
an on−site visit. Other tools that AMR data can provide are aggregate billing and consumption
comparisons.

3.1.3.1 Meter Interface Module:


For the meter interface unit (MIU), the functional building block is an electromechanical
meter with an electro-optical interface that must be incorporated into or attached to the meter.
This modification converts information conveyed by the meter's mechanical register indexes, or
dial readings, into electronic signals, which may be processed, manipulated, stored and
transmitted. This meter interface is also known as the Remote Transmit Unit or RTU and is
termed as the end-units for a central control unit. As most of the system's intelligence is placed
upstream at the customers’ meters, there exists a controller unit consisting of a low-voltage
power supply, signal processing electronics, microcomputer, random access memory and
program memory used to store the real-time run or operating system program. The controller unit
is used to press the signals originating from the meter's electromechanical or electro-optical

23
CHAPTER 3 AMR AND PREPAID METER DESIGN

interface device. In effect, the controller unit converts the meter's electromechanical interface
device signals into computer type electronic digital representations of the meter's exact index or
dial readings. The controller's RAM memory maintains an up-to-the-minute mirror image of the
meter's dials and as the dials increment, so do the numerical representations stored in RAM.
3.1.3.2 Communication System:
The second functional building block is the communication scheme and its associated
transmits and receive electronics. In this project, the PLC is chosen as the communication
scheme.
3.1.3.3 Data Concentrator:
DCU as shown in Figure 3.2, of which there are, relatively few, communicate with a
central controller that functions as the overall system manager, based at the utility company’s
headquarters or data processing centre. The communication links for transfer of data to the
central controller can use any convenient medium, such as, ISDN, PSTN, radio, dedicated wires,
optics-optics and microwave.

Figure 3.2 Data Concentrators

24
CHAPTER 3 AMR AND PREPAID METER DESIGN

Figure 3.3 AMR system block diagram

The DCU and all the MIUs and meters connected to it can be considered as a sub-system
of the HCS as shown in Figure 3.3. The sub-system is set up with a DCU monitoring the low
voltage power zone downstream of a Distribution Transformer. The DCU can be viewed as the
front end of the sub-system, collecting meter readings from all the MIUs connected to it through
the low voltage PLC Rand communicating with the HCS through the communication channel.
There are two types of MIUs, a single-channel type connected to a single meter only, and a
multi-channel type, which can be connected up to 16 meters. In projects where meters are
scattered around in an open area, single-channel MIUs are usually used for individual meters.
But for projects where meters are grouped together in a meter room or cabinet, Multi-channel
25
CHAPTER 3 AMR AND PREPAID METER DESIGN

Meter Interface Units (MMIU) are more cost effective.


There are basically two stages of communication in the system, namely, that between the
MIUs and the DCU, and that between the DCUs and the HCS. The communication channel or
medium used between MIU and DCU is the Power Line; and the channel used between DCU
and HCS can be the Public Switched Telephone Network (PSTN), GSM network, radio network,
or directly with handheld terminals and notebook computers with a standard RS-232 interface or
through a modem.

3.1.4 Operating Principle:


The communication device for the PLC communication system is a built-in Power Line
Modem (PLM), which transmits and receives data over the power line. Both the MIU and the
DCU contain the PLM device. The binary data stream is keyed onto a carrier signal by means of
the OFDM (Orthogonal frequency Division multiplexing technique). This signal is then coupled
onto the power line by the PLM. At the receiving end, an identical PLM will detect the signal
and convert it back to a binary data stream. The PLMs operate in a Half Duplex, two-way, Time
Division Multi-plex communication mode. Two-way communication between DCU and MIU is
essential in establishing a proper communication channel, for system synchronization and status
reporting.
In AMRs, transmission speed is not a great concern but reliability is important. Every
MIU is equipped with repeater function. If required, the DCU can designate any MIU in the sub-
system as a repeater to enhance communication with a particular MIU. With the sensitive signal
detection and sophisticated digital filtering technique, this PLC communication is highly
immune to electrical noise and interference.
The MIU is an intelligent device, which can collect, process, and record power
consumption data from the electric meter. It picks up the pulse output of the meter and converts
the measurement of the meter into a digital format suitable for data processing. Thus it is
possible to monitor the electrical load in real time. The MIU saves the data collected in non-
volatile memory, and all data and settings are protected against power failure. It will
automatically resume normal operation when power returns after a power failure. After receiving
a multi-rate tariff command and loading the time-of-use table from the DCU, the MIU will
process energy consumption data according to pre-set time intervals. It will update the peak
values and their time of occurrence at each tariff rate providing real time information of
electrical consumption for the information management system.
Data stored in the MIU are transmitted to the DCU via the power line through the built-in
PLM. Communication is initiated by the DCU, which polls the MIU by calling its address. Data
26
CHAPTER 3 AMR AND PREPAID METER DESIGN

received from different MIUs are stored in the corresponding Load Data Records in the Flash
memory of the DCU. The DCU supports communication with any upward equipment in
conformity with RS-232 standard, e.g. a handheld computer. The HCS is the control centre of the
system, where all the functions of the system are controlled and monitored. The HCS passes
instructions and information requests onto the DCU by calling their addresses, and the DCU will
respond accordingly. The address codes of the DCUs are stored in the HCS. With sufficient mass
storage, theoretically all DCUs can be covered by the HCS, in actual fact the maximum number
of DCUs can be connected to a HCS it will be limited by the required response time and
efficiency of data management.

Figure 3.4 AMR operation principle diagram

3.1.5 Power Consumption Measuring:


In order to calculate the instantaneous power consumption of the load, it is necessary
to determine the voltage and current at any given time. In general, for sinusoidally varing voltage
and current waveforms, this can be determined by calculating the root mean square (RMS)
values, using one of two approaches:
1- Calculate the maximum signal deviation from the zero‐crossing level of the waveform
(i.e. Ipeak or Vpeak) .
2- Calculate the maximum variation in signal (i.e. Ip‐p or Vp‐p).

27
CHAPTER 3 AMR AND PREPAID METER DESIGN
Vp − p
Vrms = (3.1)
2
Ip − p
Irms = 3.2
2
𝑃𝑟𝑚𝑠 = 𝑉𝑟𝑚𝑠 × 𝐼𝑟𝑚𝑠 (3.3)

The Smart Meter shall be able to measure power consumption at a minimum resolution of 5w.

28
CHAPTER 3 AMR AND PREPAID METER DESIGN

3.2 Prepaid Electrical Energy Meter


Fig 3.5 shows the internal design of the prepaid energy meter [13].

Figure 3.5 Hardware block diagram

29
CHAPTER 3 AMR AND PREPAID METER DESIGN

Where:
1. SHNT : Shunt
2. EMIF : Energy Measure Interface
3. RLIF : Relay Interface
4. PFIF : Power Fail Interface
5. PWRS: DC Power Supply
6. MRIF : MCU Reset Interface
7. BUIF: Buzzer Interface
8. MCU : Microcontroller
9. BLCF: Balance Filed
10. PVIF : Prepaid Card Vcc Interface
11. FPCP : Four Pin Connector for Prepaid card
12. PRIF : Prepaid Card Reset Interface
13. MCIF : Mechanical Coupling Interface
3.2.1 Energy Measurement Interface Module (EMIF MODULE):
It is a prefabricated electronics module based on ADE7755 which is a high accuracy
electrical energy measurement IC. The chip contains both ‘Analog Signal Processing’ and
‘Digital Signal Processing’ circuits for precise and accurate noise free measurement of electrical
power consumed by a load.
The chip is factory calibrated to generate 1000 cef (calibrated energy frequency) pulses at
the end of consumption of 1 kWh of electrical energy. This electrical energy meter that uses this
chip is called ‘1000 Impulse Meter’. Thus the resolution of the EMIF chip is 1 cef or 0.001 Wh.
The EMIF produces 10 cef pulses after the consumption of 0.01 kWh energy. The explanation is:
0.01 KWh = 0.01 x 1000 Wh
= 10 Wh
If a 10 Watt lamp remains ON for 1 hour, the EMIF module will generate 10 cef pulses.

30
CHAPTER 3 AMR AND PREPAID METER DESIGN

3.2.2 Relay Interface Circuit (RLIF):


This relay circuit is shown in figure 3.6.
The Load will get electricity if the switch K1 gets closed. The K1 will be closed under the
following conditions:
1. The balance is not zero.
2. The balance has not arrived at lower cut-off value which equal to 25.5 KW and depend
according to the tariff used (say SD 2.00).

Figure 3.6 Electrical circuit of RLIF

3.2.2.1 Working Principle of Electrical Circuit of RLIF:


The relay ON/OFF control signal is supplied by the MCU over P3.3-pin. The signal is not
directly applied to the base of transistor Q1. The P3.3 signal is synchronized with the zero-
crossing 50Hz signal of the 220V line frequency. This arrangement allows the contact K1 to be
open/close at minimum load current. The diode D1 works as a flywheel diode and provides a
closed circuit for the relay-coil energy to dissipate. Without the presence of the diode, there
would appear very high voltage across the CE-junction of Q1. As a result, the Q1 will break
down.
3.2.3 Microcontroller Reset Interface Circuit (MRIF):
The reset pin (RST-pin) of the 8051 is marked as active high, which means that the MCU
will remain at Reset-state (inactive) state as long as the RST-pin remains at LH-state. The MCU
will begin program execution from location 0000H whenever the RST-pin is brought to LL-state.
This job is done by the circuit shown in figure 3.7.

31
CHAPTER 3 AMR AND PREPAID METER DESIGN

Figure 3.7 Electrical circuit of MRIF

3.2.4 Buzzer Interface Circuit (BUIF):


The Buzzer will produce a musical note whenever the balance falls below SD 2.00. This
is to draw the attention of the meter user to insert Prepaid Card into the meter. The meter will
read the money from the Prepaid Card and will recharge the meter. The electrical interface
circuit is shown in figure 3.8.

Figure 3.8 Electrical circuit of BUIF

32
CHAPTER 3 AMR AND PREPAID METER DESIGN

The Music IC goes about 8 stages of musical notes. It is a free running chip. The music
drives the Buzzer whenever the bit P3.3 assumes Logic-H state. +V refers to an unregulated DC
voltage of about +15V.
3.2.5 Mechanical Coupling Interface Circuit (MCIF):
When the meter balance falls below SD 2.00, a musical alarm is initiated to tell the user
to insert the Prepaid Card. The Prepaid Card has mechanical contacts (FPCP = Four Point
Connector Port), which must be properly engaged to allow the Master MCU to read money from
it. Because these are mechanical contacts, they will certainly make a ‘lot of bounces’ before
making the final contacts. These bouncing may create ‘Electrical Noise’, which may be picked
up by the master MCU as false money. Therefore, the possible solution to prevent the generation
of the electrical noise due to mechanical bouncing is to allow the Prepaid Card get engaged first
and then apply +5V (Vcc1) power to the Prepaid Card.
The Prepaid Card goes all the way inside the meter. The Prepaid Card activates a micro-
switch K2. One end of K2 is connected to P1.3-pin and the other end is connected at 0V. As a
result, the P1.3-pin gets shorted to 0V. When the Prepaid Card is removed, the K2 comes back to
normally open condition and the P1.3-pin assumes LH-state through the internal pull-up resistor.
The Vcc1 for the Prepaid Card has been derived from the Vcc (+5V for the master
MCU) through a control mechanism and is described later as PVIF (Prepaid Card Vcc1
Interface). The MCU continuously monitors the logic value of P1.3-bit and whenever it is found
at Logic-L state, the MCU enables the Vcc1 supply by activating the P1.2-bit.

33
CHAPTER 3 AMR AND PREPAID METER DESIGN

3.2.6 Prepaid Card Reset Interface Circuit (PCRIC):


The Microcontroller used for the Prepaid Card is of the type AT90S2313 – a 20-pin RISC
version. The MCU requires a LL-state at its RST/-pin to remain at reset state. The circuit shown
in figure 3.9 may well furnish the RST/ signal for the 2313 RMCU (RISC Microcontroller).

Figure 3.9 Electrical circuit of PRIF

34
CHAPTER 4 METHODOLOGY AND DESIGN

CHAPTER 4
METHODOLOGY AND DESIGN

This chapter presents the design and architecture to come up with our final prepaid
energy meter network system.
First the main goals which the system was designed to achieve are introduced. Then a
general description of the system requirements followed by the system scenario to produce the
final output is given.
Then depending on that scenario; the modular design of the system is deduced and
generally described. Then all modules that constitute the system are presented in details.

4.1 Design Goals


4.1.1 User convenience and system portability
The main goal about Prepaid Energy Meter Network system is to ease the interaction
between the consumer (server) and the electricity company (client). In metering network over
power lines, the unprofessional user can interact directly with the power line (plug in/out
modems to the socket, install/remove component) and the PC (log in/out to the system interface,
set/change parameters, observe system status). So, it must be necessary to take in mind selecting
user friendly components.
4.1.2 Hardware independence
One key factor in designing such a practical system is its ability to perform this network
using the existing power line network with the availability of Personal Computers (PCs) and the
suitable cost of modems.
4.1.3 System integration
The integration of any system is an important requirement. When system integration is not
full, the system will fall down and cannot perform its function in proper manner. One way to
verify the system integration is the modular design technique which divides the entire system
into individual modules. Every module could be designed and implemented individually, thus
the whole system can be represented as individual blocks. Integration of each block could be
easily verified; the integration of whole system also could be easily verified.

35
CHAPTER 4 METHODOLOGY AND DESIGN

4.2 System Requirement


4.2.1 Establishment of a power line communication network
 Existing power line network.
 Power line modems (PLM).
4.2.2 Monitor the energy meter network system on PC
 Microsoft Visual C++.
4.2.3 Design of simple illustrative modules
Design simple system modules based on local distribution system:
 One server PC.
 One client PC.

4.3 System Layout


As mentioned in section 4.2, the designed system is consisted of:
 Power line network.
 Digital multi-meter device.
 Power line modems (PLM).
 Human Machine program Interface (HMI) “Microsoft Visual C++ and software
configuration of PLM in PC”.

36
CHAPTER 4 METHODOLOGY AND DESIGN

4.4 System Scenario


From figure 4.1, the prepaid energy meter network design consist of four main parts,
the energy meter device, the two PC one act as a server and the other as a client, and the power
line modems (PLM1 & PLM2).

Figure 4.1 prepaid energy meter network block diagram

In this project the digital multi-meter device is connected to a bus-bar cable, which
measurements of many parameters such as power, energy, power factor, etc. are taken.
One of the PCs which represent the client (electricity company) is connected to the other
PC which represent a server(energy meter) to perform a small network through the existing
power line by using two power line modems one for each PC. IN this design the server is
connected to the digital multi-meter by using special type of converter to act as interface between
them.
Assume there is a user at the client terminal need to know the status or to get some data
from particular server (here we have one server for simplicity of the work); he/she should enter
the IP of the chosen server to access to it through the network. After entering the IP a signal is
arrived to the server which then act as a client when it requesting the meter to give it the data
required (at this step the meter is a server),after the specified data is given, the server transmit it
back to the user (client).Finally the data is displayed at the client terminal.
37
CHAPTER 4 METHODOLOGY AND DESIGN

Before that the same design was performed by using a switch (hub) instead of PLM and the
same data was retrieved.
In the case of extending the function of the constructed network to be working in two ways
the client (energy company) can send commands and texts to the various meters which
connected to the network. These commands may be a serial number for recharging the energy as
shown in figure 4.2 or may be to alarm the consumer before the whole amount of electricity
totally consumed.

Figure 4.2 Serial number command on meter screen

4.4.1 The TCP/IP Communication Protocol:


This connection between the two computers is established using TCP/IP protocol.
TCP/IP is the communication protocol for communication between computers on the network.
TCP/IP stands for Transmission Control Protocol / Internet Protocol.
TCP/IP defines how electronic devices (like computers) should be connected to the network, and
how data should be transmitted between them.

38
CHAPTER 4 METHODOLOGY AND DESIGN

4.4.1.1 Inside TCP/IP


Inside the TCP/IP standard there are several protocols for handling data communication:
 TCP (Transmission Control Protocol) communication between applications.
 UDP (User Datagram Protocol) simple communication between applications.
 IP (Internet Protocol) communication between computers.
 ICMP (Internet Control Message Protocol) for errors and statistics.
 DHCP (Dynamic Host Configuration Protocol) for dynamic addressing TCP is for
communication between applications.

If one application wants to communicate with another via TCP, it sends a communication
request. This request must be sent to an exact address. After a "handshake" between the two
applications, TCP will set up a "full-duplex" communication between the two applications.
The "full-duplex" communication will occupy the communication line between the two
computers until it is closed by one of the two applications [14].

4.4.2 Server Functions:


Functions of the server towards the client:
(1) Listens for connection from client.
(2) Accepts connection.
(3) Listens for incoming commands.
(4) Reads commands (either GET or SET).

Functions of the server towards the digital multi-meter:


(1) Connects to meter.
(2) Sends request for data to meter.
(3) Reads response.
(4) Constructs a response message back to client.
(5) Sends a response back to client.
(6) Waits for client connection to be closed.
(7) Finally, closes the connection.

39
CHAPTER 4 METHODOLOGY AND DESIGN

4.4.3 Client Function:


The client normally does the following activities:
(1) Gets the IP address of a server.
(2) Waits for user selection to be taken (GET or SET).
(3) Establishes connection to server.
(4) Sends request to server.
(5) Waits for response.
(6) Displays the data items given.
(7) Closes connection to server.

4.5 Development Tools


4.5.1 Hardware Tools:
4.5.1.1 The Supply cable (three phase) from the secondary distribution network which
represents as an input to the energy meter.
4.5.1.2 LOVATO Digital Multi-meter DMK40 type (Three phase energy meter) see Figure 4.2.
The model DMK40 has a built-in isolated Half duplex RS-485 serial interface.

Figure 4.3 LOVATO Digital multi-meter DMK40

40
CHAPTER 4 METHODOLOGY AND DESIGN

There are two different methods to connect a PC with a multi-meter with a serial port using
Ethernet convertor:
1. Using the suitable driver supplied with the Ethernet/serial port converter drive, one can
generate a virtual serial port on the drive itself, positioned at a great distance from the PC.
With this mode and selecting the virtual COM instead of the PC serial port, with the DMK
Supervision software (e.g. COM1 will be the PC port while COM3 the virtual driver
generated port), all of the multi-meters connected will refer to the virtual port only.
2. The second method consists of a direct communication between the PC and the converter
drives, without the use of drivers for the virtual COMs.
This solution requires a specific IP address and port number for each multi-meter, to be
programmed and identified using the DMK Supervision software. This consents to use
more than one converter simultaneously obtaining major flexibility for the multi-meter
locations [15].

4.5.1.3 Convertor from RS-485 to RS-232:


The RS232/RS485 converter allows interfacing any device using an RS232 serial link to
an RS485 link. This convertor is shown in figure 4.3.

Figure 4.4 Converter from RS-485 to RS-232

The RS485 link was conceived for long haul data acquisition and control applications.
The original specifications (which have been surpassed by present hardware), allowed to
network up to 32 stations on the same lines, at speeds up to 10 Mega bits per second to distances
of 4,000 feet (1200 m). The link is balanced so that any electrical noise getting into one of the
lines also gets into the other line thus allowing the receiver to cancel both noise signals.

41
CHAPTER 4 METHODOLOGY AND DESIGN

RS485 links are much used in industrial process control where reliability is important.
Also, the ability to communicate over a long distance at a high speed is important when it comes
to industrial plants where the stations might be spread over a large area.
It is very common to have a PC in charge of controlling a given process. PC's in general
have an RS232 serial port (COM port) and therefore there are two solutions to link the computer
to an RS485 network: One is to plug an RS485 interface in a computer slot and the other is to
convert the RS232 level signal coming out the computer serial port into an RS485 signal. This is
what the RS232/RS485 converter does.

4.5.1.3.1 POWER REQUIREMENTS:


The RS232/RS485 converter can be powered from any DC voltage between 7.5 and 15
volts and it consumes 75 mA. From the converter, a 6-wire line carries the data to and for the
remote stations. Two wires send data, two wires receive data, one additional line is connected to
the computer's ground and one wire is connected to the power supply input (before the
converter's voltage regulator). This way, unregulated power can be carried to the remote stations.

4.5.1.3.2 CONNECTION TO THE COMPUTER:


The converter has a 9 pin DB9 connector of which only 3 lines are used: TX, RX and
Ground. Some commercial cables have "straight" data lines whereas others are "crossed" (null
modern).
In order to accommodate both types, H1 and H2 allow to get a straight or a cross
connection to the TX and RX lines.

4.5.1.4 Server:
One of the computers (PC1) is used as a server which is connected to the multi-meter
through Ethernet convertor (the multi-meter with PC1 represent the consumer side).

4.5.1.5 Power line Modems:


Two power line modems are used each PC have one connected to it to make a network
through the power line.
In this project Edimax HP-2001AV Power Line 200Mbps Ethernet Adapter device was
chosen [16] .see Figure 4.5.
42
CHAPTER 4 METHODOLOGY AND DESIGN

Figure 4.5 Power line modem-Edimax

4.5.1.5.1 Device Description:


Manufacturer: Edimax
Price Range: $101.02 to $121.50 at 16 stores.

HP-2001AV turns the existing electric wires in your home or office into a high-speed
network. You do not have to install the network cables and be annoyed with the cables planning
just use the wires that already run through the building! HP-2001AV enables you to create a
network easily and cost-effectively. Figure 4.6 shows the application of home plug using power
line modem.

43
CHAPTER 4 METHODOLOGY AND DESIGN

Figure 4.6 Application of home plug using power line modem

 Complies with 200Mbps HomePlug AV and IEEE 802.3 / 802.3u Standards.


 Uses the electrical wire to transmit data like an Ethernet network.
 Supports 128-bit AES (Advanced Encryption Standard) link encryption to secure Power
line data transmission.
 Easy Installation and transmission ranges up to 300 meters.
 COEXISTENCE WITH HOMEPLUG 1.0 & 1.0 TURBO
 SUPPORT GROUP BUTTON & RESET BUTTON

4.5.1.5.2 HARDWARE INTERFACE


 1 Power jack + 1 LAN 10/100Mbps Ethernet Ports.
 LED Indicators: Power, Ethernet and Power line.
 Reset button.
 Group button.

44
CHAPTER 4 METHODOLOGY AND DESIGN

4.5.1.5.3 MODULATION
 OFDM (Orthogonal Frequency Division Multiplexing).
 QAM (Quadrature Amplitude Modulation).
 QPSK (Quadrature phase-shift keying).
 BPSK (binary phase shift keying).

4.5.1.5.4 VOLTAGE AND CURRENT RATES


 100~240VAC, 50~60Hz.

4.5.1.5.5 SECURITY & SUPPORT operating system:


 128-bit AES link Encryption.
 Support Windows 98SE/ME/2000/XP/Vista.

4.5.1.5.6 FREQUENCY BAND


 2~30 MHz

4.5.1.5.7 HUMIDITY
 10-90% (Non-condensing)

4.5.1.5.8 FUNCTIONS
 Power line Coverage Range up to 300 meters.
 Support 64 adapters to communicate on a single network
Plug and Play.
 IGMP (Internet Group Management Protocol) managed multicast IP transmission.
 Integrated Quality of Service (QoS): Prioritized random access Contention-free access.

4.5.1.5.9 DIMENSION & TEMPERATURE


 97 x 65 x 54 mm
 0~45 Degree Celsius

4.5.1.5.10 CERTIFICATIONS
 European Conformity (CE) 45
CHAPTER 4 METHODOLOGY AND DESIGN

4.5.1.6 Ethernet cable:

Ethernet cables which shown in Figure 4.7 connect network devices such as modems,
routers, and adapters.

Figure 4.7 Ethernet cable

They transmit data using the Ethernet protocol. NETGEAR Ethernet cables have RJ-45 jacks
on both ends, each with 8 pins. (They look similar to telephone jacks, which use 4 pins or 6
pins).Equipments using Ethernet cables are referred to as wired.

4.5.1.7 Client:
Here the other computer (PC2) is used as a client (the electricity company side).

46
CHAPTER 4 METHODOLOGY AND DESIGN

4.5.2 Software Tools:


 Microsoft Visual C++
Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It
can be used to develop console and graphical user interface applications along with Windows
Forms applications, web sites, web applications, and web services in both native code together
with managed code for all platforms supported by Microsoft Windows, Windows Mobile,
Windows CE, .NET Framework, .NET Compact Framework and Microsoft Silver-light.
Figure 4.8 shows Microsoft Visual C++ interface.

Figure 4.8 Microsoft Visual C++ interface

Visual Studio includes a code editor supporting IntelliSense as well as code refactoring. The
integrated debugger works both as a source-level debugger and a machine-level debugger. Other
built-in tools include a forms designer for building GUI applications, web designer, class
designer, and database schema designer. It accepts plug-ins that enhance the functionality at
47
CHAPTER 4 METHODOLOGY AND DESIGN

almost every level—including adding support for source-control systems (like Subversion and
Visual SourceSafe) and adding new toolsets like editors and visual designers for domain-specific
languages or toolsets for other aspects of the software development lifecycle (like the Team
Foundation Server client: Team Explorer).

 Windows XP for the configuration needs of the PLM (any other version of Microsoft
widows can be used except windows 7).

 The software Configuration Utility for Windows 98SE/Me/2000/ XP/Vista for installing
Edimax HP-2001AV PowerLine 200Mbps Ethernet Adapter.

4.6 Modbus Communication Protocol Concept:


Modbus is a serial communications protocol for use with its programmable logic
controllers (PLCs). Simple and robust, it has since become one of the de facto standard
communications protocols in the industry, Modbus allows for communication between many
(approximately 240) devices connected to the same network, for example a system that
measures temperature and humidity and communicates the results to a computer. Modbus is
often used to connect a supervisory computer with a remote terminal unit (RTU) in
supervisory control and data acquisition (SCADA) systems. Many of the data types are named
from its use in driving relays: a single-bit physical output is called a coil, and a single-bit
physical input is called a discrete input or a contact [17].
Versions of the Modbus protocol exist for serial port and for Ethernet and other networks
that support the Internet protocol suite. Most Modbus devices communicate over a serial EIA-
485 physical layer. There are many variants of Modbus protocols some of them are:
 Modbus RTU: This is used in serial communication and makes use of a compact, binary
representation of the data for protocol communication. The RTU format follows the
commands/data with a cyclic redundancy check checksum as an error check mechanism
to ensure the reliability of data. Modbus RTU is the most common implementation
available for Modbus. A Modbus RTU message must be transmitted continuously
without inter-character hesitations. Modbus messages are framed (separated) by idle
(silent) periods.

48
CHAPTER 4 METHODOLOGY AND DESIGN

 Modbus ASCII : This is used in serial communication and makes use of ASCII
characters for protocol communication.

 Modbus TCP/IP or Modbus TCP: This is a Modbus variant used for communications
over TCP/IP networks, connecting over port 502. It does not require a checksum
calculation as lower layers already provide checksum protection.

 Modbus over TCP/IP or Modbus over TCP or Modbus RTU/IP: This is a Modbus
variant that differs from Modbus TCP in that a checksum is included in the payload as
with Modbus RTU.

 Modbus over UDP: Some have experimented with using Modbus over UDP on IP
networks, which removes the overheads required for TCP.

4.7 Modbus TCP/IP Frame Format:


Table 4-1 show the Modbus TCP/IP frame format

Table4.1 Modbus TCP/IP Frame Fprmat

Modbus TCP Frame Format

Name Length Function

For synchronization between messages of server


Transaction Identifier 2 bytes
& client
Protocol Identifier 2 bytes Zero for MODBUS/TCP
Length Field 2 bytes Number of remaining bytes in this frame
Unit Identifier 1 byte Slave Address (255 if not used)
Function code 1 byte Function codes as in other variants
Data bytes n bytes Data as response or commands

Unit identifier is used with MODBUS/TCP devices that are composites of several
MODBUS devices, e.g. on MODBUS/TCP to MODBUS RTU gateways. In such case, the unit
identifier tells the Slave Address of the device behind the gateway. Natively MODBUS/TCP-
capable devices usually ignore the Unit Identifier.
49
CHAPTER 5 IMPLEMENTATION AND RESULT

CHAPTER 5
IMPLEMENTATION AND RESULTS
5.1 Overview
This chapter is continuity to the methodology and design chapter, which describes the
implementation steps, testing, measuring and results.
The obtained result has been implemented using figures to simplify comparison between different
parameters, finally according to the actual load (Air conditioner, lamp) the total power consumption
from the supply cable connected to the Multimeter device was calculated and the energy during a
specific time can be deduced using the developed power network.

5.2 Implementation of interface models


The software programs tools Microsoft visual C++ and PLM software Configuration Utility
for EDmax offer a nonprofessional user interface model at the server side and client side.

5.2.1 Server interface models


5.2.1.1 Server model:
5.2.1.1.1 Server layout
This was built using Microsoft visual C++ 6.0 to achieve all tasks which were
stated in chapter 4. A snapshot of server interface is shown in figure 5.1.

50
CHAPTER 5 IMPLEMENTATION AND RESULT

Figure 5.1 Snapshot of the Server interface

5.2.1.1.2 Description of C++ interfaces at server:


As shown in figure5.1; this interface represent the server side which is directly
connected to the energy meter.When there is a command from the client side requesting for special
data then, it immediately connect to meter after its running.
So, to get data the SERVER IS RUNNING button at the server interface must been selected.

51
CHAPTER 5 IMPLEMENTATION AND RESULT

5.2.1.2 PLM Model:


5.2.1.2.1 PLM Layout
Figure 5.2 illustrate the PLM interface appears on the server screen for the PLM device
connected to it, after software Configuration Utility for installing EDmax was setup.

Figure 5.2 Snapshot of PLM interface

5.2.1.2.2 Description of PLM interface at a server:


Figure 5.2 shows the PLM software interface for the modem connected to the server, each
PLM device has its unique physical IP address (MAC address) found in the back of the device, this
MAC address is used as an identification name of its device when it has been connected to the
network (LOACL DEVICE ON YOUR COMPUTER), the other PLM devices connected to this
network are appeared automatically after an auto-scan is finished.

52
CHAPTER 5 IMPLEMENTATION AND RESULT

5.2.2 Client interface models


5.2.2.1 Client model:
5.2.2.1.1 Client Layout
Using the same feature of Microsoft visual C++, a client interface model was created to enable
the user to deal with the server in effectively way. A snapshot of the client layout is shown in figure
5.3.
This interface is very flexible; it gives the user many options, then according to the user’s
needs the settings can be done by modifiying in the main code.

Figure 5.3 Snapshot of the Client interface

53
CHAPTER 5 IMPLEMENTATION AND RESULT

5.2.2.1.2 Descriptions of C++ interface at server:


As illustrated in figure 5.3, this interface appears in the the client side. The user must firstly
enter the IP address of the server, so the network can identify to which server the connection must
be established.
If the data need to be read once then the GET DATA ONCE icon could be pressed after IP
address is given.
Then the option of displaying the data after specifid period of time can be set as the user
required by typing the duration of a period in PERIOD(SECs) icon, following by pressing the icon
GET PERIDIC DATA.
Also there is an option if the user needs to record the appeared data after a duration specified
before,this option can be done by checking the LOG RESULTs icon. Then data is saved in a file
called log result.Which is very useful in implementing figures for comparing or observation
parameters ( data )over a time.
In this project the results were taken for some parameter (data) which are line to line
voltages (RY,YB,BR) in Volt, current for the three lines in Amper, phase active power
(RN,YN,BN) in watt, Power factor, and the total average active (W), reactive (VAR) and apperent
power(VA).Also the energy in specific duration time and frequency are displayed.
The icon STOP is used to stop or pause reading, and the icon CLOSE is used for terminate the client
interface.

54
CHAPTER 5 IMPLEMENTATION AND RESULT

5.2.3 PLM interface with the client


The interface in Figure5.4 is same as the server PLM interface; this device can see the
server PLM device automatically when it has been connected to the network also some necessary
information is displayed in the interface such as the RATE (Mbps) with the quality of
communication.

Figure 5.4 Snapshot of PLM interface

55
CHAPTER 5 IMPLEMENTATION AND RESULT

5.3 Results:
Table 5.1 shows the result which displayed at the client interface after the requesting the
labeled data was given. For getting many measurements in regulated periods of time the setting of
GET PERIDIC DATA must be applied.So the data can be taken from the log result file which saves
result from the beginning.
Table 5.1 Result displayed in the client interface

Voltage Voltage Voltage Current Current Current Import Export Active


Time RY(V) YB(V) BR(V) RY(A) YB(A) BR(A) Energy(WH) Energy(WH) Power(W)

17:19:18 421 426 419 12.8 27.3 11.8 173.63 94.79 3140

17:19:49 421 426 419 12.8 27.4 11.7 173.63 94.79 2930

17:20:19 421 426 419 12.8 27.4 11.8 173.64 94.8 3100

17:20:50 421 426 419 12.8 27.4 11.9 173.64 94.8 2940

17:21:21 421 427 420 12.9 27.7 11.9 173.64 94.81 2890

17:21:51 421 426 420 12.9 27.7 11.9 173.64 94.81 3180

17:22:22 420 426 419 12.9 27.6 11.8 173.64 94.82 3030

17:22:53 421 426 419 12.9 27.7 11.9 173.65 94.82 3030

17:23:23 421 426 420 12.9 27.5 11.9 173.65 94.83 3030

17:23:54 422 427 420 12.9 27.7 11.9 173.65 94.83 3060

17:24:24 422 427 420 13 27.6 11.9 173.65 94.84 3080

17:24:55 422 428 421 12.9 27.6 11.8 173.66 94.84 2980

17:25:26 422 428 420 12.9 27.6 11.9 173.66 94.85 3120

17:25:56 422 428 420 12.9 27.6 11.9 173.66 94.85 3170

17:26:27 423 428 420 12.9 27.8 11.9 173.66 94.86 2900

17:26:57 423 429 421 12.9 27.7 12 173.67 94.86 3090

17:27:28 424 429 421 13 27.9 12 173.67 94.87 3040

56
CHAPTER 5 IMPLEMENTATION AND RESULT

17:27:59 424 428 421 12.9 28 11.9 173.67 94.87 2910

17:28:29 423 429 421 13 27.9 12 173.67 94.88 3140

17:29:00 423 428 421 13 28 12 173.68 94.88 3070

17:29:30 423 427 421 13 27.6 12.1 173.68 94.89 2920

17:30:01 423 427 421 12.9 27.6 12 173.68 94.89 3120

Table 5.2 cont. of Result displayed in the Client interface

Phase Phase Phase Power Power Power


Power- Power- Power- Factor- Factor- Factor- Reactive Apparent
Time RN(W) YN(W) BN(W) RN() YN() BN() Power(VAR) Power(VA) Frequency(Hz)

17:19:18 110 5700 2660 0.01 0.84 0.93 1630 3530 50

17:19:49 20 5710 2580 0.03 0.84 0.91 1360 3410 50

17:20:19 120 5780 2720 0.01 0.84 0.92 1600 3450 50

17:20:50 80 5770 2700 0.04 0.84 0.93 1610 3530 50

17:21:21 110 5870 2660 0.03 0.84 0.93 1560 3400 50

17:21:51 90 5830 2700 0.04 0.84 0.94 1620 3650 50

17:22:22 150 5840 2590 0.05 0.85 0.9 1340 3370 50

17:22:53 140 5870 2600 0.02 0.85 0.92 1380 3370 50

17:23:23 70 5800 2630 0.02 0.84 0.89 1380 3240 50

17:23:54 0 5780 2660 0.01 0.84 0.93 1720 3510 50

17:24:24 30 5720 2740 0.01 0.84 0.93 1780 3510 50

17:24:55 130 5730 2620 0.02 0.84 0.91 1610 3450 50

17:25:26 0 5770 2740 0.02 0.84 0.9 1550 3380 50

57
CHAPTER 5 IMPLEMENTATION AND RESULT

17:25:56 40 5780 2740 0.01 0.85 0.91 1810 3620 50

17:26:27 0 5840 2650 0.01 0.84 0.92 1550 3290 50

17:26:57 20 5750 2740 0.01 0.83 0.94 1700 3670 50

17:27:28 80 5910 2710 0 0.83 0.94 1710 3490 50

17:27:59 30 5880 2650 0.01 0.84 0.91 1560 3310 50

17:28:29 130 5890 2710 0.03 0.83 0.94 1760 3710 50

17:29:00 30 5890 2720 0.04 0.85 0.89 1690 3390 50

17:29:30 10 5850 2680 0.03 0.85 0.92 1400 3400 50

58
CHAPTER 5 IMPLEMENTATION AND RESULT

5.3.1 Implementation of Results:


From table 5.1, the three Line-to-line voltages versus time at which data was saved in the log
result file is implemented as in figure 5.5.

Figure 5.5 Line-to-line voltage Vs. time

59
CHAPTER 5 IMPLEMENTATION AND RESULT

Figure 5.6 represents the implementation of the three line current versus time:

Figure 5.6 Line current Vs. time

Figure 5.7 represent the three phase power versus time using data from table

Figure 5.7 Three phase power Vs. time

60
CHAPTER 5 IMPLEMENTATION AND RESULT

Figure5.8 represents the import and export energy with the time:

Figure 5.8 Import and export energy Vs. time

The implementation of active power, reactive power, and the apparent power versus time is shown
in figure 5.9:

Figure 5.9 Active power, reactive power and apparent Vs. time

61
CHAPTER 5 IMPLEMENTATION AND RESULT

5.4 Actual Load Calculation:


By calculating the load which is feeding with the supply cable to which digital multi-
meter device is set, this represents the server and there is a remote PC which represents the utility
centre. The two devices connected through power line by PLM. The calculated results as shown in
table 5.3

Table 5.3 load calculations

Section Type of Number of units Power per unit Total power


component
(W) (W)

Office Lamp 4×4 20 320

Air 1 1800 1800


Conditioner

Refrigerator 1 250 250

Laboratory Lamp 11 × 4 20 880

Air 2 1800 3600


Conditioner

Classroom Lamp 7×4 20 560

Air 2 1800 3600


Conditioner

Total Power Consumption 11,010

62
CHAPTER 5 IMPLEMENTATION AND RESULT

5.5 Discussion
5.5.1 Design performance:
After many tests and observations, a high quality communication between the server and
the client through the PLC network is obtained at a high rate in Mega bit per second (Mbps).
Also the interaction between the server PC and the digital multimeter device was done with high
output efficiency using the MODBUS protocols.

5.5.2 Response to user request:


Generally, few milliseconds are spent between sending a request and receiving the
required data. If the user (client) requests for data then the server (meter) sends it vastly.

5.5.3 Data accuration:


When a comparison is made between the data at the client interface (which is transmitted
over the PLC connection) with the data displayed at the meter’s screen, the result is identical.

5.5.4 Output Result:


From the implementation figures of results versus time, some feature can be noticed:
1) The variation of voltages during day cycle as shown in Figure5.5 which describes the
relationship between the line to line voltages and times is seems to be typical to the standard
and theoretical form as follow:
At early hours in the morning the load is light means a high value of voltage then
with the time, the load increases with decreasing in voltages (peak load at 12:00 PM), then
the voltage increasing slightly during evening hours. Finally at approximate range of 9:00PM
to 2:00AM which has a heavy load the voltage values is decreasing.
2) By comparing the other curves of parameters versus time with the theoretical curves, the
result was acceptable.

63
CHAPTER 6 CONCULSION AND RECOMMENDATION

CHAPTETR 6

CONCULSION AND RECOMMENDATIONS

6.1 Conclusion
This project of prepaid energy meter network over power line communication was
successfully designed and implemented; also the project objectives introduced in chapter 1 meet
the achieved design goals.
This project is cost less because of the availability of equipments and there is no need to
establish a new network since it’s already exists for electrical power distribution purposes. This
make the electrical network has the ability of data transmission and receiving in addition to the
main distribution function.
This project is a proof of possibility of using the existing power line as a communication
line giving high satisfied result.
In the design of the project both software and hardware tools are used together each with
its specific function to accomplished the entire job in a flexible manner.
One of the benefits of the network through power line communication is the ability to
connect to the network just by plug in the PLM to one of the available sockets, so it easy to make
a small network in a house or any building using this effective feature.
IN this project a TCP/IP protocol and MODBUS protocols were used for managing the
network traffic perfectly since they Simple and robust.

6.2 Problems and solution


 Problem 1:
Unfortunately; there are no energy meters that are permitted to be used outside the
electricity company control, this make a huge failure in the design implementation since
the meter is considered one of the necessary components required.
Solution:
The LOVATO digital multimeter device, which is found in the Power Electronics
Laboratory, has been used.

64
CHAPTER 6 CONCULSION AND RECOMMENDATION

 Problem 2:
Unavailability of PLM modems at markets in Sudan, giving no chance for
projects using these modems to set up; this stop experiments and study cases
improvement of the PLC network.
Solution:
The PLM modems used in this project was borrowed from students of the
University of Sudan. This facilitates the operation rather than getting them from outside
country.

 Problem 3:
The PLM software Configuration Utility for these modems didn’t give any
response when the modems are connected to a computer using other any version of
windows except window XP. This means it just deal with windows XP
Solution:
This was discovered by trying and observation when a connection of PLM device
was done to a number of PCs with different version of windows.

 Problem 4:
After all components for the design were obtained, the problem of getting the IP
addresses of the computers to set the PLC network was encountered; this due to improper
installation of the network card or may be found but not identified.
Solution:
Because of the difficulty of getting the identification of the IP address of a PC,
then a number of PCs were tested and Choices of the required number of PCs with the
identified IP address was done.

6.3 Recommendations
 I recommend the Electricity Company to apply this project.
 I suggest to the dean of the faculty to support laboratories with a number of PLM devices.

65
CHAPTER 6 CONCULSION AND RECOMMENDATION

6.4 Future work


In this project, the design of the PLC network was implemented to get data (measurements and
status) and display it at the client interface (monitoring system of the electricity company), but the client
can only gives a text command or sends a serial number for recharging when the amount of electricity is
over.
Many Options at the client side need to be implemented such as sending a command to cut-off the
supply or detect any illegal activities; thus system improvement (full two way communication).

66
APPENDIX A ENERGY METER CODES

APPENDEX .A

PREPAID ENERGY METER CODES

Relay Interface Circuit:


1.1 Control Structure to ON/OFF Relay:
L1: if (Balance > = SD 2.00)
LH → P3.3
L2: LL → P3.3

1.2 8051 Assembly Codes for Control Structures of section:


L1: MOV A, #Balance
CJNE A, #Tk2.00, L1B
L1A: SETB P3.3 ; Blanace = SD2.00
………………
L1B: JNC L1A ; Balance > SD 2.00
L2: CLR P3.3 ; Blanace < SD 2.00
………………

2 Buzzer Interface Circuit:


2.1 Control Structure to activate P3.5
L1: if (Balance < SD 2.00)
LL → P3.5
L2: …………………

A-1
APPENDIX A ENERGY METER CODES

3 Mechanical Coupling Interface Circuit


3.1 Control Structure
L1: if (P1.3 !=LL)
Goto L1
L2: Send LH to P1.2
…………………….

3.2 Assembly Codes for Control Structure of section 3.1


L1: JNB P1.3, L1
L2: SETB P1.2
…………………….

A-2
APPENDIX B PROJECT CODE

APPENDIX .B

PROJECT MAIN CODE

 The Microsoft visual C++ code:


/************************************************************************
Client/Server Application
PLUS
A Simple version of a MODBUS Client

University of Khartoum, Sudan

Authors: Sahar & Selma


March 2011
***********************************************************************/
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <winsock.h>
#include "Main.h"

/************************************************************************
***************** CONSTANTS AND STRUCTURES *****************************
************************************************************************/

/************************************************************************
***************** PUBLIC DATA ITEMS*************************************
************************************************************************/

/* Define the data items that would be requested from the meter
via the MODBUS prtocol */

MODBUS_DEVICE_DATA Devices [NUMBER_OF_REQUESTED_DATA_ITEMS+1 ] =


{
{ 0x0A, 2 , "Voltage RY", "V", 1.0 , IDC_EDIT1} ,
{ 0x0C, 2 , "Voltage YB", "V", 1.0 , IDC_EDIT2} ,
{ 0x0E, 2 , "Voltage BR", "V", 1.0 , IDC_EDIT3} ,

{ 0x12, 2 , "Current RY", "A", 100.0 , IDC_EDIT4} ,


{ 0x14, 2 , "Current YB", "A", 100.0, IDC_EDIT5} ,
{ 0x16, 2 , "Current BR", "A", 100.0 ,IDC_EDIT6} ,

{ 0x1A, 2 , "Active Power", "W", 1.0 , IDC_EDIT11} ,

B-1
APPENDIX B PROJECT CODE
{ 0x1C, 2 , "Reactive Power", "VAR", 1.0, IDC_EDIT12} ,
{ 0x1E, 2 , "Apparent Power", "VA", 1.0, IDC_EDIT13} ,

{ 0x22, 2 , "Import Energy", "WH", 100.0 , IDC_EDIT7} ,


{ 0x24, 2 , "Export Energy", "WH", 100.0 , IDC_EDIT8} ,

{ 0x24, 2 , "Frequency", "Hz", 1.0 , IDC_EDIT14},

{ 0x2A, 2 , "Phase Power-RN", "W", 1.0 , IDC_EDIT10},


{ 0x2C, 2 , "Phase Power-YN", "W", 1.0 , IDC_EDIT15},
{ 0x2E, 2 , "Phase Power-BN", "W", 1.0 , IDC_EDIT16},

{ 0x3C, 2 , "Power Factor-RN", "", 100.0 , IDC_EDIT17},


{ 0x3E, 2 , "Power Factor-YN", "", 100.0 , IDC_EDIT18},
{ 0x40, 2 , "Power Factor-BN", "", 100.0 , IDC_EDIT19},

{ 0xFF, 0xFF,NULL , "", 1.0 , 0} /*Terminating record */


};

FILE* logFile = NULL ;

/************************************************************************
***************** FUNCTIONS ********************************************
************************************************************************/

bool getMeterData(SERVER_RESPONSE* meterData) ;


unsigned short getCRC16(unsigned char *puchMsg, unsigned short usDataLen) ;
bool readSerial (HANDLE h, void* buf,
unsigned long size, char* txt) ;

/************************************************************************
***************** IMPLEMENTATIONS **************************************
************************************************************************/

/*********************************************************************************
Name: getCRC16
Purpose: Calculates and returns the CRC-16 value (Cyclic Redundancy Check) for the
data provide
Inputs: - message to calculate CRC upon
- Length of the data stream
Outpts: None
Returns: The CRC
**********************************************************************************/

unsigned short getCRC16(unsigned char *puchMsg, unsigned short usDataLen )


{
static unsigned char auchCRCHi[] = {
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,

B-2
APPENDIX B PROJECT CODE
0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
0x40
};

static unsigned char auchCRCLo[] = {


0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
0x40
};

unsigned char uchCRCHi = 0xFF ; /* high byte of CRC initialized */


unsigned char uchCRCLo = 0xFF ; /* low byte of CRC initialized */
unsigned uIndex ; /* will index into CRC lookup table */

while (usDataLen--) /* pass through message buffer */


{
uIndex = uchCRCHi ^ *puchMsg++ ; /* calculate the CRC */
uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex] ;
uchCRCLo = auchCRCLo[uIndex] ;
}

return (uchCRCHi << 8 | uchCRCLo) ;


}

/*********************************************************************************
Name: readSerial
Purpose: Reads data from the serial port
Inputs: - The id of the serial port
- The buffer for the data
- Length of the data to be read
- Text describing the data item

B-3
APPENDIX B PROJECT CODE
Outpts: - The buffer containg the data
Returns: true/false --> success/failure
**********************************************************************************/
bool readSerial (HANDLE h, void* buf, unsigned long size, char* txt)
{
unsigned long noOfBytesRead ;
COMMTIMEOUTS timeouts={0};

timeouts.ReadIntervalTimeout= 50;
timeouts.ReadTotalTimeoutConstant= 50;
timeouts.ReadTotalTimeoutMultiplier= 10;
timeouts.WriteTotalTimeoutConstant= 50;
timeouts.WriteTotalTimeoutMultiplier= 10;

if( SetCommTimeouts(h, &timeouts) == 0)


{
/* error occureed. */

LogMyMessage("ReadSerial: unable to set timeouts %s", txt);

return false ;
}

if (ReadFile(h, buf, size, &noOfBytesRead, NULL) == 0)


{

LogMyMessage("ReadSerial: unable to read %s", txt);

return false ;
}

if (noOfBytesRead != size)
{

LogMyMessage("ReadSerial: read %d expected %d: [%s]",


noOfBytesRead,size, txt);

// return false ;
}

#if 0
LogMyMessage ("Data Size = %d", noOfBytesRead) ;
unsigned char* p =(unsigned char*) buf ;
for (int i=0; i<noOfBytesRead; i++)
LogMyMessage (" %02X", p[i]) ;

#endif

return true ;
}

/*********************************************************************************
Name: getMeterData

B-4
APPENDIX B PROJECT CODE
Purpose: Establihes the conection with the meter, sends the request to the
meter, collects the data
Inputs: - Buffer to held the values of data items
Outpts: - The buffer containg the data
Returns: true/false --> success/failure
**********************************************************************************/
bool getMeterData(SERVER_RESPONSE* meterData)
{

HANDLE serial ;
MODBUS_QUERY_MSG Query ;

unsigned char deviceAddr ;


unsigned char functionCode ;
unsigned char exceptionCode ;
unsigned char byteCount ;
DCB dcbSerial = {0};
int i, k, dataIndex;
unsigned char* p;
unsigned long noOfBytesWritten = 0;
short registerValues [256];
unsigned short Crc ;
static int vTest = 0 ;

if (meterData != NULL)
{
memset (meterData, 0 , sizeof(SERVER_RESPONSE)) ;
}

unsigned char modBusMsg[] = {0x01, 0x04, 0x00, 0x01, 0x00, 0x0A, 0x21, 0xCD};
unsigned char mbMsg[] = {01, 04, 00, 01, 00, 0x14, 0xA1, 0xC5};

/* Open connection with the serial device */


serial= CreateFile(/*(LPCWSTR)*/ "COM1",GENERIC_READ | GENERIC_WRITE,
0,0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) ;

if (serial == INVALID_HANDLE_VALUE)
{

LogMyMessage ("getMeterData: unable to open conection to meter") ;

return false ;
}

LogMyMessage ("serial = %d", serial) ;

/* Set the parameters for the serla connection */


memset (&dcbSerial,0,sizeof(dcbSerial)) ;
dcbSerial.BaudRate = CBR_9600;
dcbSerial.Parity = NOPARITY;
dcbSerial.ByteSize= 8;
dcbSerial.StopBits= ONESTOPBIT;

B-5
APPENDIX B PROJECT CODE

if(SetCommState(serial, &dcbSerial) == 0)
{

LogMyMessage("getMeterData: SetCommState Failed");

CloseHandle(serial) ;
return false ;
}

LogMyMessage("Set CommState Succeeded");

i=0;
dataIndex=0;

/* Send the request to the Meter for each item defined in Devices[] data */
while (Devices[i].Name != NULL)
{
Query.Function_Code = READ_INPUT_REGISTERS ;
Query.Device_Address = 1;
/* The data field must contain the information telling the slave
which register to start at and how many registers to read*/
Query.Starting_Address = htons(Devices[i].Start_Address-1);
Query.Nr_Of_Registers = htons(Devices[i].Nr_Registers);
p = (unsigned char*) &Query ;

Query.Crc = htons(getCRC16(p,6)) ;

for(k =0;k < sizeof(Query) ;k++)


{
LogMyMessage("0x%02X ", (unsigned char)p[k]);
}

LogMyMessage ("CRC = %X",Query.Crc) ;

WriteFile(serial, p, sizeof(Query), &noOfBytesWritten, NULL);

if(noOfBytesWritten == sizeof(Query))
{

LogMyMessage("All Bytes Sent");

}
else
{

LogMyMessage("getMeterData: Sending failed %d", noOfBytesWritten);

CloseHandle(serial) ;
return false ;
}

/* START READING DATA: */

B-6
APPENDIX B PROJECT CODE

char dummyChar = 0 ;
while (dummyChar!= 0x01)
{
if (readSerial (serial, &dummyChar, 1, "dummyChar") == false)
{
CloseHandle(serial) ;
return false ;
}
}

deviceAddr = dummyChar ;

LogMyMessage ("deviceAddr= 0x%02X", deviceAddr) ;

/* Read the Function Code */


if (readSerial (serial, &functionCode, 1, "Function Code") == false)
{
CloseHandle(serial) ;
return false ;
}

LogMyMessage ("getMeterData: functionCode = 0x%02X",


functionCode) ;

/* Check whether this indicates an error: */

if ( (functionCode&0x80) != 0)
{
/* Exception: In an exception response, the server sets the MSB
of the function code to 1 i.e 0x80*/
if (readSerial (serial, &exceptionCode, 1, "Exception Code") == false)

LogMyMessage("getMeterData: unable to read Exception Code field");

}else
{

LogMyMessage("getMeterData:Exception Code= 0x%02X (%d)",


exceptionCode,exceptionCode);

CloseHandle(serial) ;
return false ;
}

/*--> NO ERROR: */

B-7
APPENDIX B PROJECT CODE
/* read the number of data bytes in the message */
if (readSerial (serial, &byteCount, 1, "Byte Code") == false)
{
CloseHandle(serial) ;
return false ;
}

LogMyMessage ("getMeterData: Byte Count = %d [Items=%d]",


byteCount,byteCount/2) ;

/* Read the Register values returned by the meter */


if (readSerial (serial, &registerValues, byteCount, "Values") == false)
{
CloseHandle(serial) ;
return false ;
}

for (k=0; k<byteCount/2;k++)


{
if (meterData != NULL)
meterData->Status = 1 ;

if (dataIndex < OUR_NUMBER_OF_METER_ITEMS)


{
if ( (k%2) != 0)
{
if (meterData != NULL)
meterData->Data[dataIndex] = ntohs(registerValues
[k]);

dataIndex++ ;

LogMyMessage("--> Data%d\t= %d",


dataIndex, meterData->Data[dataIndex-1] );

}
}else
{

LogMyMessage ("Too many data items received. Not sent back to


client") ;

/* Also, read the CRC: we are not checking the CRC here */
if (readSerial (serial, &Crc, 2, "Crc") == false)
{

B-8
APPENDIX B PROJECT CODE
LogMyMessage ("Failed to read CRC") ;
}

i++ ;

CloseHandle(serial) ;

return true ;

/*********************************************************************************
Name: runServer
Purpose: Main engine for the server. Waits for connections from the client,
accepts the connections, contacts the meter and sends the data
back to the client.
Inputs: None
Outpts: None
Returns: None
**********************************************************************************/
DWORD WINAPI runServer ( LPVOID param )
{
int ListenSocket ;
sockaddr_in service;
int result ;
fd_set readfds ;
int nfds ;
int Command_Size = 0 ;
CLIENT_COMMAND Client_Command ;
SERVER_RESPONSE Response ;
char* p;

struct timeval timeout ;


int sClient = -1 ;

/* Initialize Winsock: starts the sockets capabilities*/


WSADATA wsaData;

int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);


if (iResult != NO_ERROR)
{

LogMyMessage("runServer: Error at WSAStartup()");

WSACleanup();
return -1;
}

/* Create the manin listening socket:*/


ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (ListenSocket == INVALID_SOCKET) {

LogMyMessage("runServer: Error at socket(): %ld", WSAGetLastError());

B-9
APPENDIX B PROJECT CODE
WSACleanup();
return -1;
}

//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY; /* Listen on ANY interface*/
service.sin_port = htons(PORT_NR);

//----------------------
/* Bind the socket to the above interfaces */
if (bind( ListenSocket, (SOCKADDR*) &service,
sizeof(service)) == SOCKET_ERROR)
{

LogMyMessage("runServer: bind() failed.");

closesocket(ListenSocket);
return -1;
}

/* Make this socket a listening socket */


result = listen(ListenSocket, 3) ;
if (result < 0)
{

LogMyMessage("runServer: listen() failed.");

closesocket(ListenSocket);
return -1;
}

Command_Size = 0 ;
sClient = -1 ;
/* Define the time-out for the 'select' function */
timeout.tv_sec = 60 ;
timeout.tv_usec = 0 ;

LogMyMessage ("Server Started successfully...") ;

while (true) /* Do forever*/


{
/* Define the list of multiplexed sockets */
FD_ZERO(&readfds) ;
FD_SET(ListenSocket,&readfds) ;

if (sClient>0)
{
FD_SET(sClient,&readfds) ;
}

nfds=MAX_VAL(ListenSocket,sClient) ;

B-10
APPENDIX B PROJECT CODE
nfds++ ;

/* Now, wait for an event on any socket */


result = select (nfds, &readfds, NULL, NULL, &timeout ) ;

if (result == 0)
{
/*--> this is a time-out event: just output a trace */

LogMyMessage ("runServer: Server waiting ....") ;

if (FD_ISSET(ListenSocket,&readfds) )
{
/* This is an event on the listeing socket: must be a client
trying to connect:
Note, in this code, we will allow only one client to connect,
hence the check below
*/

/* CHECK WHTHER ALREADY CONNCTED? */


if (sClient >0)
{

LogMyMessage ("runServer: Can not serve multiple clients. Rejected") ;

/* just silently ignore this request */


}else
{
/* Accept this connection ..*/
sClient = accept(ListenSocket, NULL, NULL);

if (sClient == INVALID_SOCKET)
{

LogMyMessage ("runServer: accept failed with error: %ld",


WSAGetLastError());

closesocket(ListenSocket);
WSACleanup();
return 1;
}

LogMyMessage ("runServer: Client connection accepted") ;

}
}

if (FD_ISSET(sClient,&readfds) )
{
/* this is an event on the client connection.
--> Must be data been sent by the client
--> Go and read this data
*/

B-11
APPENDIX B PROJECT CODE

p = (char*) &Client_Command+Command_Size ;
/* Read Command data: */
int Data_Read = recv(sClient, p, sizeof(Client_Command)-Command_Size, 0) ;

if (Data_Read <= 0)
{
/* Socket has been closed by client */

LogMyMessage ("Socket closed by client") ;

closesocket(sClient) ;
Command_Size = 0 ;
sClient = -1 ;
}else
{
/* Make sure all data has been read, then process this request */
Command_Size+= Data_Read ;

LogMyMessage ("%d bytes read", Data_Read) ;

if (Command_Size == sizeof (Client_Command))


{

LogMyMessage ("runServer: Processing Command: %d",


Client_Command.Command) ;

Command_Size = 0 ;

/* Obtain the data from the meter */


if ( getMeterData(&Response) == false)
{

LogMyMessage ("Failed to get meter data") ;

}
/* Send the data back to the client */
p = (char*)&Response ;
if ( send(sClient,p,sizeof(Response), 0) !=sizeof(Response))
{

LogMyMessage ("runServer: Failed to send data to


client ") ;

}else
{

LogMyMessage ("runServer: Data successfully sent to


client ") ;

}
}
}

B-12
APPENDIX B PROJECT CODE
};

LogMyMessage("No errors ");

SOCKET ConnectSocket = INVALID_SOCKET;


/*********************************************************************************
Name: runClient
Purpose: Main engine for the Client. Waits for user requests, establishes a link
with the Server, sends the request to the server, waits for the response
and outputs the data returned by the server.
Inputs: IP Address
Outpts: The response data
Returns: 0 if successful
**********************************************************************************/
int runClient ( const char* IP_Addr, SERVER_RESPONSE* Response,
CT1Dlg* me )
{
//----------------------
// Initialize Winsock
extern CT1App theApp;
static bool InitialisedOnce = false ;

WSADATA wsaData;
int nfds ;
int i;
int Response_Size ;
char* p;
struct timeval timeout ;
int sClient ;
bool continueWaiting ;
fd_set readfds ;
int Command ;
CLIENT_COMMAND Client_Command ;
int iResult ;

if (ConnectSocket != INVALID_SOCKET)
{
return 0 ;
}

if (InitialisedOnce == false)
{
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != NO_ERROR)
{

LogMyMessage("Error at WSAStartup()");
me->MessageBox("Failed to initialise sockets");

return -1 ;
}
InitialisedOnce = true ;
}

B-13
APPENDIX B PROJECT CODE

//----------------------
// Create a SOCKET for connecting to server
//----------------------
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.

sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( IP_Addr );
clientService.sin_port = htons( PORT_NR );

ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);


if (ConnectSocket == INVALID_SOCKET) {

LogMyMessage("Error at socket(): %ld", WSAGetLastError());


me->MessageBox("Failed to initialise sockets");
return -1;
}

Command= GET_DATA_COMMAND ;
if ( (Command == SET_DATA_COMMAND) || (Command == GET_DATA_COMMAND))
{

//----------------------
// Connect to server.
if ( connect( ConnectSocket, (SOCKADDR*) &clientService,
sizeof(clientService) ) == SOCKET_ERROR)
{

me->MessageBox( (LPCTSTR) "Failed to connect to server..." );

closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
continueWaiting = false ;
return -1 ;
}

LogMyMessage( "Connected ok" );

Client_Command.Command = Command ;
Client_Command.Option = 0 ;

/* Send request to server */


if ( send(ConnectSocket,(char*)&Client_Command,sizeof(Client_Command), 0)
!=sizeof(Client_Command))
{

LogMyMessage ("Failed to send command to server ") ;


me->MessageBox( (LPCTSTR) "Failed to send command to server" );
closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
return -1 ;

B-14
APPENDIX B PROJECT CODE
}else
{

LogMyMessage ("Data successfully sent to server ") ;


LogMyMessage ("Waiting for response") ;

nfds =ConnectSocket+1 ;
Response_Size = 0 ;
sClient = -1 ;
timeout.tv_sec = 60 ;
timeout.tv_usec = 0 ;
continueWaiting = true ;
while (continueWaiting == true)
{
FD_ZERO(&readfds) ;
FD_SET(ConnectSocket,&readfds) ;

int result = select (nfds, &readfds, NULL, NULL, &timeout ) ;

if (result == 0)
{

LogMyMessage ("Timed out: Server did not respond") ;


me->MessageBox( (LPCTSTR) "Timed out: Server did not
respon" );
closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
return -1 ;

if (FD_ISSET(ConnectSocket,&readfds) )
{
p = (char*)Response+Response_Size ;
int BytesRead =
recv(ConnectSocket,p,sizeof(SERVER_RESPONSE)-Response_Size,0);
if (BytesRead == 0)
{

LogMyMessage ("Connection closed by server ..") ;


me->MessageBox( (LPCTSTR) "Connection closed by
server .." );
closesocket (ConnectSocket) ;

ConnectSocket = INVALID_SOCKET ;
continueWaiting = false ;
return -1 ;
}else
{
Response_Size+=BytesRead ;
LogMyMessage ("Bytes received= %d/%d ",
BytesRead, sizeof(SERVER_RESPONSE)) ;

if (Response_Size == sizeof(SERVER_RESPONSE))
{

B-15
APPENDIX B PROJECT CODE

LogMyMessage ("Response received") ;

if (Response->Status == 0)
{

LogMyMessage ("\tINVALID data


returned by server") ;

}else
{

LogMyMessage ("VALID data returned


by server") ;

/* Valid Data items */


for
(i=0;i<OUR_NUMBER_OF_METER_ITEMS; i++)
{

LogMyMessage ("\t%s\t= %7.2f


%s",
Devices[i].Name ,
1.0* Response-
>Data[i]/Devices[i].Factor ,
Devices[i].Unit) ;

}
continueWaiting = false ;
}
}
}
}

closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
continueWaiting = false ;
}
}

if ( ConnectSocket != INVALID_SOCKET)
{
closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
}

return 0;
}

/*********************************************************************************
Name: LogMyMessage
Purpose: Construcst the text message to be logged and logs the message
to the file

B-16
APPENDIX B PROJECT CODE
Inputs: Message description
Outpts: None
Returns: None
**********************************************************************************/
void LogMyMessage (char* descriptor, ...)
{

extern bool ServerRunning ;


char outBuffer [1028] ;
char *cp = outBuffer ;
va_list args;

if (logFile == NULL)
{
logFile = fopen (ServerRunning? "LogServer.txt":"LogClient.txt","w") ;
if (logFile == NULL)
{
return ;
}
}

va_start(args, descriptor);
vsprintf(cp, descriptor, args);
va_end(args);

fprintf (logFile, "%s\n", outBuffer) ;

fflush(logFile) ;
}

B-17

Potrebbero piacerti anche