Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
XI
LIST OF FIGURES
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
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.
2
CHAPTER 2 LITERATURE REVIEW
CHAPTER 2
LITERATURE REVIEW
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].
4
CHAPTER 2 LITERATURE REVIEW
5
CHAPTER 2 LITERATURE REVIEW
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
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.
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:
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
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.
12
CHAPTER 2 LITERATURE REVIEW
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
14
CHAPTER 2 LITERATURE REVIEW
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
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].
17
CHAPTER 2 LITERATURE REVIEW
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. 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
21
CHAPTER 3 AMR AND PREPAID METER DESIGN
CHAPTER 3
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.
24
CHAPTER 3 AMR AND PREPAID METER DESIGN
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
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.
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
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
31
CHAPTER 3 AMR AND PREPAID METER DESIGN
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
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.
35
CHAPTER 4 METHODOLOGY AND DESIGN
36
CHAPTER 4 METHODOLOGY AND DESIGN
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.
38
CHAPTER 4 METHODOLOGY AND DESIGN
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].
39
CHAPTER 4 METHODOLOGY AND DESIGN
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].
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.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).
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
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.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.10 CERTIFICATIONS
European Conformity (CE) 45
CHAPTER 4 METHODOLOGY AND DESIGN
Ethernet cables which shown in Figure 4.7 connect network devices such as modems,
routers, and adapters.
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
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.
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.
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.
50
CHAPTER 5 IMPLEMENTATION AND RESULT
51
CHAPTER 5 IMPLEMENTATION AND RESULT
52
CHAPTER 5 IMPLEMENTATION AND RESULT
53
CHAPTER 5 IMPLEMENTATION AND RESULT
54
CHAPTER 5 IMPLEMENTATION AND RESULT
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
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: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
56
CHAPTER 5 IMPLEMENTATION AND RESULT
57
CHAPTER 5 IMPLEMENTATION AND RESULT
58
CHAPTER 5 IMPLEMENTATION AND RESULT
59
CHAPTER 5 IMPLEMENTATION AND RESULT
Figure 5.6 represents the implementation of the three line current versus time:
Figure 5.7 represent the three phase power versus time using data from table
60
CHAPTER 5 IMPLEMENTATION AND RESULT
Figure5.8 represents the import and export energy with the 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
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.
63
CHAPTER 6 CONCULSION AND RECOMMENDATION
CHAPTETR 6
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.
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
66
APPENDIX A ENERGY METER CODES
APPENDEX .A
A-1
APPENDIX A ENERGY METER CODES
A-2
APPENDIX B PROJECT CODE
APPENDIX .B
/************************************************************************
***************** CONSTANTS AND STRUCTURES *****************************
************************************************************************/
/************************************************************************
***************** PUBLIC DATA ITEMS*************************************
************************************************************************/
/* Define the data items that would be requested from the meter
via the MODBUS prtocol */
B-1
APPENDIX B PROJECT CODE
{ 0x1C, 2 , "Reactive Power", "VAR", 1.0, IDC_EDIT12} ,
{ 0x1E, 2 , "Apparent Power", "VA", 1.0, IDC_EDIT13} ,
/************************************************************************
***************** FUNCTIONS ********************************************
************************************************************************/
/************************************************************************
***************** 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
**********************************************************************************/
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
};
/*********************************************************************************
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;
return false ;
}
return false ;
}
if (noOfBytesRead != size)
{
// 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 ;
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};
if (serial == INVALID_HANDLE_VALUE)
{
return false ;
}
B-5
APPENDIX B PROJECT CODE
if(SetCommState(serial, &dcbSerial) == 0)
{
CloseHandle(serial) ;
return false ;
}
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)) ;
if(noOfBytesWritten == sizeof(Query))
{
}
else
{
CloseHandle(serial) ;
return false ;
}
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 ;
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)
}else
{
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 ;
}
dataIndex++ ;
}
}else
{
/* 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;
WSACleanup();
return -1;
}
if (ListenSocket == INVALID_SOCKET) {
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)
{
closesocket(ListenSocket);
return -1;
}
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 ;
if (sClient>0)
{
FD_SET(sClient,&readfds) ;
}
nfds=MAX_VAL(ListenSocket,sClient) ;
B-10
APPENDIX B PROJECT CODE
nfds++ ;
if (result == 0)
{
/*--> this is a time-out event: just output a trace */
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
*/
if (sClient == INVALID_SOCKET)
{
closesocket(ListenSocket);
WSACleanup();
return 1;
}
}
}
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 */
closesocket(sClient) ;
Command_Size = 0 ;
sClient = -1 ;
}else
{
/* Make sure all data has been read, then process this request */
Command_Size+= Data_Read ;
Command_Size = 0 ;
}
/* Send the data back to the client */
p = (char*)&Response ;
if ( send(sClient,p,sizeof(Response), 0) !=sizeof(Response))
{
}else
{
}
}
}
B-12
APPENDIX B PROJECT CODE
};
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 );
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)
{
closesocket (ConnectSocket) ;
ConnectSocket = INVALID_SOCKET ;
continueWaiting = false ;
return -1 ;
}
Client_Command.Command = Command ;
Client_Command.Option = 0 ;
B-14
APPENDIX B PROJECT CODE
}else
{
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) ;
if (result == 0)
{
if (FD_ISSET(ConnectSocket,&readfds) )
{
p = (char*)Response+Response_Size ;
int BytesRead =
recv(ConnectSocket,p,sizeof(SERVER_RESPONSE)-Response_Size,0);
if (BytesRead == 0)
{
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
if (Response->Status == 0)
{
}else
{
}
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, ...)
{
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);
fflush(logFile) ;
}
B-17