Open Source Smart Energy Meter

51
1 CHAPTER 1 INTRODUCTION 1.1 SMART METER A smart meter is usually an electrical meter that records consumption of electric energy in intervals of an hour or less and communicates that information at least daily back to the utility for monitoring and billing purpose. Smart meters enable two-way communication between the meter and the central system. Unlike home energy monitors, smart meters can gather data for remote reporting. Such an advanced metering infrastructure (AMI) differs from traditional automatic meter reading (AMR) in that it enables two-way communications with the meter. 1.1.1. SMART METER BLOCK DIAGRAM & WORKING BLOCK DIAGRAM Figure 1.1: Block Diagram

Transcript of Open Source Smart Energy Meter

Page 1: Open Source Smart Energy Meter

1

CHAPTER 1 INTRODUCTION

1.1 SMART METER

A smart meter is usually an electrical meter that records consumption of electric energy in intervals of an hour or less and communicates that information at least daily back to the utility for monitoring and billing purpose. Smart meters enable two-way communication between the meter and the central system. Unlike home energy monitors, smart meters can gather data for remote reporting. Such an advanced metering infrastructure (AMI) differs from traditional automatic meter reading (AMR) in that it enables two-way communications with the meter. 1.1.1. SMART METER BLOCK DIAGRAM & WORKING BLOCK DIAGRAM

Figure 1.1: Block Diagram

Page 2: Open Source Smart Energy Meter

2

1.1.2. SMART METER ADVANTAGES

Advanced Metering Infrastructure (AMI) are systems that measure, collect, and analyze energy usage, an communicate with metering devices such as electricity meters, gas meters, heat meters, and water meters, either on request or on a schedule. These systems include hardware, software, communications, consumer energy displays and controllers, customer associated systems, Meter Data Management (MDM) software, and supplier business systems. The network between the measurement devices and business systems allows collection and distribution of Information to customers, suppliers, utility companies, and service providers. This enables these businesses to participate in demand response services. Consumers can use information provided by the system to change their normal consumption patterns to take advantage of lower prices. Pricing can be used to curb growth of peak consumption

1.1.3. SMART METER PROTOCOL

ANSI C12.18 is an ANSI standard that describes a protocol used for two-way communications with a meter, mostly used in North American markets. The C12.18 standard is written specifically for meter communications via an ANSI Type 2 Optical Port, and specifies lower-level protocol details. ANSI C12.19 specifies the data tables that will be used. ANSI C12.21 is an extension of C12.18 written for modem instead of optical communications, so it is better suited to automatic meter reading. IEC 61107 is a communication protocol for smart meters published by the IEC that is widely used for utility meters in the European Union. It is superseded by IEC 62056, but remains in wide use because it is simple and well-accepted. It sends ASCII data using a serial port. The physical media are either modulated light, sent with an LED and received with a photodiode, or a pair of wires, usually modulated by EIA-485. The protocol is half-duplex. IEC 61107 is related to, and sometimes wrongly confused with, the FLAG protocol. Ferranti and Landis+Gyr were early proponents of an interface standard that eventually became a sub-set of IEC1107. IEC 62056 - is a more modern European meter protocol and superset of IEC 61107. Open smart grid protocol - The Open Smart Grid Protocol (OSGP) is a family of specifications published by the European Telecommunications Standards Institute (ETSI) used in conjunction with the ISO/IEC 14908 control networking standard for smart metering and smart grid applications. Millions of smart meters based on OSGP are deployed work wide. There is a growing trend toward the use of TCP/IP technology as a common communication platform for Smart Meter applications, so that utilities can deploy multiple communication systems, while using IP technology as a common management platform. Other solutions suggest the use of a single,

Page 3: Open Source Smart Energy Meter

3

universal Smart meter connector separating the function of the smart grid device and its communication module. A universal metering interface would allow for development and mass production of smart meters and smart grid devices prior to the communication standards being set, and then for the relevant communication modules to be easily added or switched when they are. This would lower the risk of investing in the wrong standard as well as permit a single product to be used globally even if regional communication standards vary

Next generation HAN standard developed under ITU and promoted by HomeGrid Forum.

• It supports networking over power lines, phone lines and coaxial cables. • Expected data rates up to 1Gbps. • Provides secure connections between devices through 128‐bit AES encryption. Authentication and key exchange is done following ITU‐T Recommendation X.1035. • G.hn natively supports popular protocols like Ethernet, IPv4 and IPv6 and as a result G.hn‐based Energy Management networks can easily be integrated with IP‐based Smart Grids. • Availability of G.hn‐compliant chips is expected during CY2010.

1.2.RASPBERRY PI

Figure 1.2: Raspberry pi Board Figure 1.3: GPIO pin

Page 4: Open Source Smart Energy Meter

4

1.2. a. The RASPBERRY PI

While the RPi can be used without any additional hardware (except perhaps a power supply of some kind), it won't be much use as a general computer. As with any normal PC, it is likely we will need some additional hardware The following are more or less essential

• Raspberry Pi board • Prepared Operating System SD Card • USB keyboard • Display (with HDMI, DVI, Composite or SCART input) • Power Supply • Cables

Highly suggested extras include: USB mouse

Internet connectivity - a USB WiFi adaptor (Model A/B) or a LAN cable (Model B) Powered USB Hub Case

Connecting Together

Figure 1.4: Raspberry pi I/O

Page 5: Open Source Smart Energy Meter

5

use the diagram to connect everything together, or use the following instructions:

• Plug the preloaded SD Card into the Pi. • Plug the USB keyboard and mouse into the Pi, perhaps via a USB Hub.

Connect the Hub to power, if necessary • Plug the video cable into the screen (TV) and into the Pi. • Plug our extras into the Pi (USB Wi-Fi, Ethernet cable, hard drive etc.). This is

where may really need a USB Hub. • Ensure that our USB Hub (if any) and screen are working. • Plug the power source into the main socket. • With our screen on, plug the other end of the power source into the Pi. • The Pi should boot up and display messages on the screen.

It is always recommended to connect the Micro USB Power to the unit last while most connections can be made live, it is best practice to connect items such as displays/h/w pin connections with the power turned off). The RPi may take a long time to boot when powered-on for the first time, so be patient!

1.2.b. PREPARED OPERATING SYSTEM SD CARD:

• As the RPi has no internal storage or built-in operating system it requires an SD-Card that is set up to boot the RPi.

• Can create our own preloaded card using any suitable SD card have. Be

sure to backup any existing data on the card.

• Preloaded SD cards will be available from the RPi Shop. This guide will assume you have a preloaded SD card.

Keyboard & Mouse:

Most standard USB keyboards and mice will work with the RPi. Wireless keyboard/mice should also function, and only require a single USB port for an RF dongle. In order to use a Bluetooth keyboard or mouse would need to use a Bluetooth dongle, which again uses a single port. Remember that the Model A has a single USB port and the Model B only has two (typically a keyboard and mouse will use a USB port each). Display:

There are two main connection options for the RPi display, HDMI (high definition) and Composite (low definition). HD TVs and most LCD Monitors can be connected using a full-size 'male' HDMI cable, and with an inexpensive adaptor if

Page 6: Open Source Smart Energy Meter

6

DVI is used. HDMI versions 1.3 and 1.4 are supported, and a version 1.4 cable is recommended. The RPi outputs audio and video via HMDI, but does not support HDMI input. Older TVs can be connected using Composite (a yellow-to-yellow cable) or via SCART (using a Composite to SCART adaptor). PAL and NTSC TVs are supported. When using composite video, audio is available from a 3.5mm (1/8 inch) socket, and can be sent to your TV, to headphones, or to an amplifier. To send audio our TV, you will need a cable which adapts from 3.5mm to double (red and white) RCA connectors.

There is no VGA output available, so older VGA monitors will require an expensive adaptor. Using an HDMI to DVI-D (digital) adaptor plus a DVI to VGA adaptor will not work. HDMI does not supply the DVI-A (analogue) needed to convert to VGA - converting an HDMI or DVI-D source to VGA (or component) needs an active converter. (It can work out cheaper to buy a new monitor.) The lack of VGA has been acknowledged as a priority issue.

Power Supply:

The unit uses a Micro USB connection to power itself (only the power pins are connected – so it will not transfer data over this connection). A standard modern phone charger with a micro- USB connector will do, but needs to produce at least 700mA at 5 volts. Check our power supply's ratings carefully. Suitable mains adaptors will be available from the RPi Shop and are recommended if we are unsure what to use. We Can use a range of other power sources (assuming they are able to provide enough current ~700mA):

Computer USB Port or powered USB hub (will depend on power output) Special wall warts with USB ports Mobile Phone Backup Battery (will depend on power output) (in theory – needs confirmation) To use the above, Our need a USB A 'male' to USB micro 'male' cable - these are often shipped as data cables with MP3 players. Cables:

We will probably need a number of cables in order to connect our RPi up. 1. Micro-B USB Power Cable 2. HDMI-A or Composite cable, plus DVI adaptor or SCART adaptor if required, to connect your RPi to the Display/Monitor/TV of your choice. 3. Audio cable, this is not needed if we use a HDMI TV/monitor. 4. Ethernet/LAN Cable

Page 7: Open Source Smart Energy Meter

7

Additional Peripherals:

We may decide we want to use various other devices with our RPi, such as Flash Drives/Portable Hard Drives, Speakers etc. Internet Connectivity

This may be an Ethernet/LAN cable (standard RJ45 connector) or a USB WiFi adaptor. The RPi ethernet port is auto-sensing which means that it may be connected to a router or directly to another computer (without the need for a crossover cable). USB-Hub

In order to connect additional devices to the RPi, we may want to obtain a USB Hub, which will allow multiple devices to be used. It is recommended that a powered hub is used - this will provide any additional power to the devices without affecting the RPi itself. USB version 2.0 is recommended. USB version 1.1 is fine for keyboards and mice, but may not be fast enough for other accessories. Case

Since the RPi is supplied without a case, it will be important to ensure that we do not use it in places where it will come into contact with conductive metal or liquids, unless suitably protected. Expansion & Low Level Peripherals

If we plan on making use of the low level interfaces available on the RPi, then ensure we have suitable header pins for the GPIO (and if required JTAG) suitable for our needs. Also if we have a particular low-level project in mind, then ensure we design in suitable protection circuits to keep our RPi safe. 1.2.1.BROADCOM PROCESSOR BCM2835 contains the following peripherals which may safely be accessed by

the ARM:

• Timers • Interrupt controller • GPIO • USB • PCM / I2S

Page 8: Open Source Smart Energy Meter

8

• DMA controller • I2C master • I2C / SPI slave • SPI0, SPI1, SPI2 • PWM, UART0, UART1

The purpose of this datasheet is to provide documentation for these peripherals in sufficient detail to allow a developer to port an operating system to BCM2835. There are a number of peripherals which are intended to be controlled by the GPU. These are omitted from this datasheet. Accessing these peripherals from the ARM is not recommended. Address map - Diagrammatic overview

In addition to the ARM’s MMU, BCM2835 includes a second coarse-grained MMU for mapping ARM physical addresses onto system bus addresses. This diagram shows the main address spaces of interest:

Figure 1.5: Broadcom Processor

Addresses in ARM Linux are:

• issued as virtual addresses by the ARM core, then • mapped into a physical address by the ARM MMU, then • mapped into a bus address by the ARM mapping MMU, and finally • used to select the appropriate peripheral or location in RAM

Page 9: Open Source Smart Energy Meter

9

ARM virtual addresses (standard Linux kernel only) As is standard practice, the standard BCM2835 Linux kernel provides a contiguous mapping over the whole of available RAM at the top of memory. The kernel is configured for a 1GB/3GB split between kernel and user-space memory. The split between ARM and GPU memory is selected by installing one of the supplied start*.elf files as start.elf in the FAT32 boot partition of the SD card. The minimum amount of memory which can be given to the GPU is 32MB, but that will restrict the multimedia performance; for example, 32MB does not provide enough buffering for the GPU to do 1080p30 video decoding. Virtual addresses in kernel mode will range between 0xC0000000 and 0xEFFFFFFF. Virtual addresses in user mode (i.e. seen by processes running in ARM Linux) will range between 0x00000000 and 0xBFFFFFFF. Peripherals (at physical address 0x20000000 on) are mapped into the kernel virtual address space starting at address 0xF2000000. Thus a peripheral advertised here at bus address 0x7Ennnnnn is available in the ARM kenel at virtual address 0xF2nnnnnn. ARM physical addresses

Physical addresses start at 0x00000000 for RAM. • The ARM section of the RAM starts at 0x00000000. • The VideoCore section of the RAM is mapped in only if the system is configured to support a memory mapped display (this is the common case).

The VideoCore MMU maps the ARM physical address space to the bus address space seen by VideoCore (and VideoCore peripherals). The bus addresses for RAM are set up to map onto the uncached1 bus address range on the VideoCore starting at 0xC0000000. Physical addresses range from 0x20000000 to 0x20FFFFFF for peripherals. The bus addresses for peripherals are set up to map onto the peripheral bus address range starting at 0x7E000000. Thus a peripheral advertised here at bus address 0x7Ennnnnn is available at physical address 0x20nnnnnn. Bus addresses - The peripheral addresses specified in this document are bus addresses. Software directly accessing peripherals must translate these addresses into physical or virtual addresses, as described above. Software accessing peripherals using the DMA engines must use bus addresses. Software accessing RAM directly must use physical addresses (based at 0x00000000). Software accessing RAM using the DMA engines must use bus addresses (based at 0xC0000000).

Page 10: Open Source Smart Energy Meter

10

Peripheral access precautions for correct memory ordering

The BCM2835 system uses an AMBA AXI-compatible interface structure. In order to keep the system complexity low and data throughput high, the BCM2835 AXI system does not always return read data in-order2. The GPU has special logic to cope with data arriving outof- order; however the ARM core does not contain such logic. Therefore some precautions must be taken when using the ARM to access peripherals. Accesses to the same peripheral will always arrive and return in-order. It is only when switching from one peripheral to another that data can arrive out-of-order. The simplest way to make sure that data is processed in-order is to place a memory barrier instruction at critical positions in the code.

• A memory write barrier before the first write to a peripheral. • A memory read barrier after the last read of a peripheral.

It is not required to put a memory barrier instruction after each read or write access. Only at those places in the code where it is possible that a peripheral read or write may be followed by a read or write of a different peripheral. This is normally at the entry and exit points of the peripheral service code. As interrupts can appear anywhere in the code so we should safeguard those. If an interrupt routine reads from a peripheral the routine should start with a memory read barrier. If an interrupt routine writes to a peripheral the routine should end with a memory write barrier. 2Normally a processor assumes that if it executes two read operations the data will arrive in order. So a read from location X followed by a read from location Y should return the data of location X first, followed by the data of location Y. Data arriving out of order can have disastrous consequences. For example:

a_status = *pointer_to_peripheral_a; b_status = *pointer_to_peripheral_b;

Without precuations the values ending up in the variables a_status and b_status can be swapped around. It is theoretical possible for writes to go ‘wrong’ but that is far more difficult to achieve. The AXI system makes sure the data always arrives in-order at its intended destination. So:

*pointer_to_peripheral_a = value_a; *pointer_to_peripheral_b = value_b;

will always give the expected result. The only time write data can arrive out-

of-order is if two different peripherals are connected to the same external equipment.

Page 11: Open Source Smart Energy Meter

11

1.2.2. BOARD SPECIFICATION

Model A Model B

SoC: Broadcom BCM2835 (CPU, GPU, DSP, SDRAM, and single USB port)

CPU: 700 MHz ARM1176JZF-S core (ARM11 family)

GPU: Broadcom VideoCore IV, OpenGL ES 2.0, MPEG-2 and VC-1 (with

license), 1080p30 h.264/MPEG-4 AVC high-profile decoder and encoder

Memory (SDRAM):

256 MB (shared with GPU)

512 MB (shared with GPU) as of 15 October 2012

USB 2.0 ports: 1 (direct from BCM2835

chip) 2 (via the built in integrated 3-port USB hub)

Video outputs:

Composite RCA (PAL and NTSC), HDMI (rev 1.3 & 1.4), raw LCD Panels via DSI

14 HDMI resolutions from 640×350 to 1920×1200 plus

various PAL and NTSC standards.

Audio outputs: 3.5 mm jack, HDMI, and, as of revision 2 boards, I²S audio (also potentially for

audio input)

Onboard storage: SD / MMC / SDIO card slot (3,3V card power support only)

Onboard network: None 10/100 Ethernet (8P8C) USB adapter on the third port of

the USB hub Low-level

peripherals: 8 × GPIO, UART, I²C bus, SPI bus with two chip selects, I²S audio[81] +3.3 V,

+5 V, ground Power ratings: 300 mA (1.5 W) 700 mA (3.5 W) Power source: 5 volt via MicroUSB or GPIO header

Size: 85.60 mm × 53.98 mm (3.370 in × 2.125 in) Weight: 45 g (1.6 oz)

Operating systems:

Debian GNU/Linux, Raspbian OS, Fedora, Arch Linux ARM, RISC OS FreeBSD, Plan 9

Table 1.1: Raspberry pi Specification

Page 12: Open Source Smart Energy Meter

12

Model A and Model B are cultural references to the original models of the British educational BBC Micro computer, developed by Acorn Computers, originally developed the ARMprocessors (the architecture of the Raspberry Pi) and operating system RISC OS, which will also be able to be run on the Raspberry Pi (version 5.17). On the older beta model B boards, 128 MB was allocated by default to the GPU, leaving 128 MB for the CPU. On the first 256 MB release model B (and Model A), three different splits were possible. The default split was 192 MB (CPU RAM), which should be sufficient for standalone 1080p video decoding, or for simple 3D, but probably not for both together. 224 MB was for Linux only, with just a 1080p framebuffer, and was likely to fail for any video or 3D. 128 MB was for heavy 3D, possibly also with video decoding (e.g. XBMC). Comparatively the Nokia 701 uses 128 MB for the Broadcom VideoCore IV. For the new model B with 512MB RAM initially there were new standard memory split files released( arm256_start.elf, arm384_start.elf, arm496_start.elf) for 256MB, 384MB and 496MB CPU RAM (and 256MB, 128MB and 16MB video RAM). But a week or so later the RPF released a new version of start.elf that could read a new entry in config.txt (gpu_mem=xx) and could dynamically assign an amount of RAM (from 16 to 256MB in 8MB steps) to the GPU, so the older method of memory splits became obsolete, and a single start.elf worked the same for 256 and 512 MB Pis.

Level 2 Cache is 128 kB, used primarily by the GPU, not the CPU. The ARM11 is based on version 6 of the ARM architecture (ARMv6), which due to its age is no longer supported by several popular versions of Linux, including Ubuntu which dropped support for processors below ARMv7 in 2009. The Raspberry Pi (model B) also contains a 15-pin MIPI camera interface (CSI) connector, which at the moment is unsupported, but the foundation is planning to release a camera module for it, sometime in the near future. Support for raw LCD panels is available in hardware through the available DSI connector from the Mobile Industry Processor Interface (MIPI) Alliance. Software support is being planned. Supported digital video resolutions are: 640 × 350 EGA; 640 × 480 VGA; 800 × 600 SVGA; 1024 × 768 XGA; 1280×720 720p HDTV; 1280 × 768 WXGA Variant; 1280 × 800 WXGAVariant; 1280 × 1024 SXGA; 1366 × 768 WXGA Variant; 1400 × 1050 SXGA+; 1600 × 1200 UXGA; 1680 × 1050 WXGA+; 1920 × 1080 1080p HDTV; 1920 × 1200 WUXGA. Also to be supported are the generation of 576i and 480i composite video signals for PAL-BGHID, PAL-M, PAL-N, NTSC and NTSC-J Originally the on-board USB ports were designed for USB devices using one "unit load" (100 mA) of current. Devices using more than 100 mA were

Page 13: Open Source Smart Energy Meter

13

incompatible with the Raspberry Pi, and for them a self-powered USB hub was required. However, due to user feedback, the RPF, at the end of August 2012, decided to remove the USB polyfuses which largely caused this behaviour. However, the maximum current that can be delivered to a USB port on these modified boards is still limited by the capabilities of the power supply used, and the 1.1 A main polyfuse. Also a disadvantage of the current way the modification is done is that its no longer possible to hot-plug USB devices directly into the PI, when hotplugging is necessary it can be done in a hub. Newer versions of the firmware contain the option to choose between five overclock ("turbo") presets that when turned on try to get the most performance out of the SoC without impairing the lifetime of the Pi. This is done by monitoring the core temperature of the chip, and the CPU load, and dynamically adjusting clock speeds and the core voltage. So when there is a low demand on the CPU, or it is getting too hot, the performance is throttled down, but if the CPU has much to do, and the chip's temperature allows it, performance is temporarily increased, with clock speeds up to 1 GHz, depending on the individual board, and on which of the "turbo" settings is used. The five settings are:

1. "None"; 700 MHz ARM, 250 MHz core, 400 MHz SDRAM, 0 overvolt, 2. "Modest"; 800 MHz ARM, 250 MHz core, 400 MHz SDRAM, 0

overvolt, 3. "Medium" 900 MHz ARM, 250 MHz core, 450 MHz SDRAM, 2

overvolt, 4. "High"; 950 MHz ARM, 250 MHz core, 450 MHz SDRAM, 6 overvolt, 5. "Turbo"; 1000 MHz ARM, 500 MHz core, 600 MHz SDRAM, 6

overvolt

1.3. AD7751/AD7755 ENERGY METERING IC FEATURES

• Single +5 V Power Supply • Easy Connection of External Transducers via Screw Terminals • Easy Modification of Signal Conditioning Components • Using PCB Sockets Trim Pot for Analog Calibration of Meter Constant • LED Indicators on Logic Outputs for Fault (AD7751 Only)REVP and

CF • Optically Isolated Output for Calibration/Test Purposes

Page 14: Open Source Smart Energy Meter

14

• External Reference Option Available for Reference Evaluation

GENERAL DESCRIPTION

The AD7751 and AD7755 are high accuracy energy measurement ICs. The part specifications surpass the accuracy requirements as quoted in the IEC1036 standard. The AD7751 incorporates a novel fault detection scheme that both warns of fault conditions with the logic output FAULT but allows the AD7751 to continue accurate billing during a fault event. The AD7751 does this by continuously monitoring both the phase and neutral (return) currents. A fault is indicated when these currents differ by more than 12.5%. Billing is continued using the larger of the two currents. The FAULT output is connected to an LED on the evaluation board.

The AD7751 supplies average real power information on the low frequency outputs F1 and F2. These logic outputs may be used to directly drive an electromechanical counter or interface to an MCU. The evaluation board provides screw connectors for easy connection to an external counter. The CF logic output gives instantaneous real power information. This output is intended to be used for calibration purposes. The evaluation board allows this logic output to be connected to an LED or optoisolator. The REVP logic output goes high when negative real power is detected. This causes an LED on the evaluation board to switch on.

Figure 1.6: AD7751 Pin Diagram

Page 15: Open Source Smart Energy Meter

15

Figure 1.7: Meter terminal Section

Figure 1.8: Meter counter section

Page 16: Open Source Smart Energy Meter

16

1.4. CIRCUIT DIAGRAM

Figure 1.9: Meter circuit Diagram

Page 17: Open Source Smart Energy Meter

17

CHAPTER 2

PROGRAMMING

2.1. PYTHON INTRODUCTION

Python is a dynamic, interpreted language. Source code does not declare the types of variables or parameters or methods. This makes the code short and flexible, and we lose the compile-time type checking in the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs. (todo: link here to the companion video segment for this section)

An excellent way to see how Python code works is to run the Python interpreter and type code right into it. If we ever have a question like "what happens if I add an int to a list?" ... just typing it into the Python interpreter is fast way to see what happens. Python code does not declare the types of variables -- just assign to them and go. Python raises a runtime error if the code tries to read from a variable that has not been given a value. Like C++ and Java, Python is case sensitive so "a" and "A" are different variables. The end of a line marks the end of a statement, so unlike C++ and Java, Python does not require a semicolon at the end of each statement. We can include semicolons at the end of Python statements (perhaps just out of habit), but it's not the best style. Comments begin with a '#' and extend to the end of the line. (See Python Set Up for how to install and Python on various operating systems.)

$ python ## Run the Python interpreter >>> a = 6 ## set a variable in this interpreter session >>> a ## entering an expression prints its value 6 >>> a + 2 8 >>> a = 'hi' ## a can hold a string just as well >>> a 'hi' >>> len(a) ## call the len() function on a string 2

Page 18: Open Source Smart Energy Meter

18

>>> foo(a) ## try something that doesn't work Traceback (most recent call last): File "", line 1, in ? NameError: name 'foo' is not defined >>> ^D ## type CTRL-d to exit (CTRL-z in Windows/DOS terminal )

Python Program

Python source files use the ".py" extension. With a Python program in file hello.py, the easiest way to run it is with the shell command "python hello.py Alice" -- loading and running the code in hello.py, passing it the command line argument "Alice".

Here's a very simple Python hello.py program (notice that blocks of code are delimited strictly using indentation rather than curly braces -- more on this later!):

#!/usr/bin/python # import modules used here -- sys is a very standar d one import sys # Gather our code in a main() function def main(): print 'Hello there', sys.argv[1] # Command line args are in sys.argv[1], sys.arg v[2] ... # sys.argv[0] is the script name itself and can be ignored # Standard boilerplate to call the main() function to begin # the program. if __name__ == '__main__': main()

Running this program from the command line looks like:

$ python hello.py Guido Hello there Guido

$ ./hello.py Alice # without needing 'python' first (Unix) Hello there Alice

Page 19: Open Source Smart Energy Meter

19

Python Module

The outermost statements in a Python file, or "module", do its one-time setup -- those statements run from top to bottom the first time the module is imported somewhere, setting up its variables and functions. A Python module can be run directly -- as above "python hello.py Bob" -- or it can be imported and used by some other module. When a Python file is run directly, the special variable "__name__" is set to "__main__". Therefore, it's common to have the boilerplate if __name__ ==... shown above to call a main() function when the module is run directly, but not when the module is imported by some other module.

In a standard Python program, the list sys.argv contains the command line arguments in the standard way with sys.argv[0] being the program itself, sys.argv[1] the first argument, and so on.

Functions

Functions in Python are defined like this:

# Defines a "repeat" function that takes 2 argument s. def repeat(s, exclaim): """Returns the string s repeated 3 times. If exclaim is true, add exclamation marks. """ result = s + s + s # can also use "s * 3" which is faster (Why?) if exclaim: result = result + '!!!' return result

Notice also how the lines that make up the function or if-statement are grouped by all having the same level of indentation. We also presented 2 different ways to repeat strings, using the + operator which is more user-friendly, but * also works because it's Python's "repeat" operator, meaning that '-' * 10 gives '----------', a neat way to create an onscreen "line." In the code comment, we hinted that * works faster than +, the reason being that * calculates the size of the resulting object once whereas with +, that calculation is made each time + is called. Both + and * are called "overloaded" operators because they mean different things for numbers vs. for strings (and other data types).

The "def" defines the function with its parameters within parentheses and its code indented. The first line of a function can be a documentation string

Page 20: Open Source Smart Energy Meter

20

("docstring") that describes what the function does. The docstring can be a single line, or a multi-line description as in the example above. Variables defined in the function are local to that function, so the "result" in the above function is separate from a "result" variable in another function. The return statement can take an argument, in which case that is the value returned to the caller.

Here is code that calls the above repeat() function, printing what it returns:

def main(): print repeat('Yay', False) ## YayYayYay print repeat('Woo Hoo', True) ## Woo HooWoo H ooWoo Hoo!!!

At run time, functions must be defined by the execution of a "def" before they are called. It's typical to def a main() function towards the bottom of the file with the functions it calls above it.

Indentation

One unusual Python feature is that the whitespace indentation of a piece of code affects its meaning. A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or "if" or whatever. If one of the lines in a group has a different indentation, it is flagged as a syntax error.

Python's use of whitespace feels a little strange at first, but it's logical and I found I got used to it very quickly. Avoid using TABs as they greatly complicate the indentation scheme (not to mention TABs may mean different things on different platforms). Set your editor to insert spaces instead of TABs for Python code.

A common question beginners ask is, "How many spaces should I indent?" According to the official Python style guidelines (PEP 8), you should indent with 4 spaces. (Fun fact: Google's internal style guideline dictates indenting by 2 spaces!)

Code Is Checked At Runtime

Python does very little checking at compile time, deferring almost all type, name, etc. checks on each line until that line runs. Suppose the above main() calls repeat() like this:

def main(): if name == 'Guido': print repeeeet(name) + '!!!'

Page 21: Open Source Smart Energy Meter

21

else: print repeat(name)

The if-statement contains an obvious error, where the repeat() function is accidentally typed in as repeeeet(). The funny thing in Python ... this code compiles and runs fine so long as the name at runtime is not 'Guido'. Only when a run actually tries to execute the repeeeet() will it notice that there is no such function and raise an error. This just means that when we first run a Python program, some of the first errors you see will be simple typos like this. This is one area where languages with a more verbose type system, like Java, have an advantage ... they can catch such errors at compile time (but of course you have to maintain all that type information ... it's a tradeoff).

Variable Names

Since Python variables don't have any type spelled out in the source code, it's extra helpful to give meaningful names to our variables to remind yourself of what's going on. So use "name" if it's a single name, and "names" if it's a list of names, and "tuples" if it's a list of tuples. Many basic Python errors result from forgetting what type of value is in each variable.

Modules and Imports

One file of Python code is called a *module*. The file "binky.py" is also known as the module "binky". A module essentially contains variable definitions like, "x = 6" and "def foo()". Suppose the file "binky.py" contains a "def foo()". The fully qualified name of that foo function is "binky.foo". In this way, various Python modules can name their functions and variables whatever they want, and the variable names won't conflict -- module1.foo is different from module2.foo.

For example, we have the standard "sys" module that contains some standard system facilities, like the argv list, and exit() function. With the statement "import sys" we can can then access the definitions in the sys module and makes them available by their fully-qualified name, e.g. sys.exit(). import sys # Now can refer to sys.xxx facilities sys.exit(0)

There is another import form that looks like this: "from sys import argv, exit". That makes argv and exit() available by their short names; however, we recommend the original form with the fully-qualified names because it's a lot easier to determine where a function or attribute came from.

Page 22: Open Source Smart Energy Meter

22

There are many modules and packages which are bundled with a standard installation of the Python interpreter, so we don't have do anything extra to use them. These are collectively known as the "Python Standard Library." Commonly used modules/packages include:

• sys -- access to exit(), argv, stdin, stdout, ... • re -- regular expressions • os -- operating system interface, file system

2.2. EXAMBLE OBSERVED This is the first of two articles showing basic GPIO on the Raspberry-Pi using the prototype area of the Slice of Pi. This covers basic details on the GPIO pins, setting up a Python library to allow access to the GPIO. There is an example circuit to build on the Slice and some code to get the outputs working.

GPIO Basics:

Figure 1.10: GPIO Basic

The R-Pi has 17 GPIO pins brought out onto the header, most have alternated functions other than just I/O, there are two pins for UART, two for I2C and six for SPI. All the pins can be use for GPIO with either INPUT or OUTPUT, there also internal pull-up & pull-downs for each pin but the I2C pins have and onboard pull-up so using them for GPIO may not work in some cases.

Using any of the pins will require extra care, than most Arduino users maybe be used to. These pins are 3V3 not 5V like the AVR chips, and they a directly connected to the Broadcom chip at the heart of the R-Pi. This means there is not

Page 23: Open Source Smart Energy Meter

23

protection, if you send 5V down a pin there is a good chance of killing the Pi. There will also be an issue with trying to draw to much power form the pins, according to the data-sheet each pin programmed to current drive between 2mA and 16mA, and it has been warned that trying to draw 16mA from several pins at once could also lead to a damaged Pi. Also from the wiki the "maximum permitted current draw from the 3v3 pin is 50mA" and the "maximum permitted current draw from the 5v pin is the USB input current (usually 1A) minus any current draw from the rest of the board." The current draw for Model B is stated as 700mA so with a 1A power supply this leaves about 300mA to play. Installing Rpi.GPIO

RPi.GPIO is a small python lib

rary that take some of the complexity out of driving the GPIO pins, once install a single LED can be lit with 3 lines of python. Installing the library is almost, either at a text console or using LX Terminal enter the following

$ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz

$ tar zxf RPi.GPIO-0.1.0.tar.gz

$ cd RPi.GPIO-0.1.0

$ sudo python setup.py install

It should look something like the above just before we hit enter on the last command. That's it we now have RPi.GPIO python library installed.

LED and Pushbutton Slice

So now I need and LED or two to Flash. So using a Slice of Pi from Ciseco I have wired up four LED's with resistors and two Push button's. First to be soldered up were the LED's and push buttons then I add the resistors and connecting wires. To keep the GPIO pins nice and safe I'm using 470R resistors for the RED,YELLOW and GREEN LED's and a 330R for the BLUE, this will keep the current of each led to around 6-7mA. Here's the schematic and the board

Page 24: Open Source Smart Energy Meter

24

Figure 1.11: Python setup install

Figure 1.12: LED and Push button

Page 25: Open Source Smart Energy Meter

25

Figure 1.13: Raspberry pi Terminal GPIO Pin Setup

If we look at the LED's I'm using the 3.3v rail to power the led and have the cathode going to the GPIO's this mean that to turn the LED on we set the output to LOW or False (in python's case) but to turn the off we set the output to HIGH or True. This means we a sinking the current through the Raspberry Pi rather that trying to source it from the pin's. For the push button we are using a 10K pull-down resistor, this makes sure the button read a solid LOW or False when not pressed, when pressed the 3.3v is connected and we get a solid HIGH or True reading. Some Code

I said turning LED's on was easy well try this in a terminal:

$ sudo python

>>> import RPi.GPIO as GPIO

>>> GPIO.setup(18, GPIO.OUT)

>>> GPIO.output(18, False)

Again it should look a little some thing like this Anyone trying this themselves may notice that the RED LED actual turned on after the GPIO.setup line and that GPIO.output did nothing. This is because we have the cathode of the LED's wired to the GPIO, and are using the Raspberry Pi to switch the GND. The default state for a

Page 26: Open Source Smart Energy Meter

26

output pin is LOW and so this also power to flow throughout the LED. So how about turning that yellow LED on:- >>> GPIO.setup(16, GPIO.OUT)

Figure 1.14: Terminal I/O Pin Setup

Figure 1.15: LED and push button output

Simple, now to turn both LED's off we set the inputs HIGH or True like so:

>>> GPIO.output(18, True)

>>> GPIO.output(16, True)

Page 27: Open Source Smart Energy Meter

27

Figure 1.16: GPIO Pin

Now why if we wired the red LED to GPIO5 on the Slice of Pi, why am I using 18 to control it? Well theres a bit of fun with the pin numbering on Raspberry Pi, and some how i don't expect it to go anyway and time soon, it like that odd gap on the Arduino headers. It comes from this post originally Pinout for GPIO connectors, better shown in the left pic bellow, anyway it turns out the original numbering of GPIO0-GPOI7 relates to nothing logical once inside linux, as they pins are accessed via there BCM2835(the chip on the Pi) GPIO numbers. Anyway RPi.GPIO python library has used yet another form of reference which is to us the pin number on the header, This give three names for each pin :( When referred to by pin number (officially P1_18) we are talking about pin 18 as counted out on the header, GPIO5 by name and GPIO24 internally by the BCM2835. Now if we ever work with the IO using the Shell file access or C memory mapped registers our going to use the BCM2835 numbering. Confused yet, I was till did a little table to help. There more on this on the Raspberry Pi wiki page Low Level Peripherals For now I will leave we with the diagrams and table bellow, and just know you

Page 28: Open Source Smart Energy Meter

28

need to use the RPi.GPIO numbers in python. This is all ready getting far to long so ill cover the inputs and making something interactive in anotherpost.

Pin Numbers

RPi.GPIO

Raspberry Pi Name

BCM2835

P1_01 1 3V3 P1_02 2 5V0 P1_03 3 SDA0 GPIO0 P1_04 4 DNC P1_05 5 SCL0 GPIO1 P1_06 6 GND P1_07 7 GPIO7 GPIO4 P1_08 8 TXD GPIO14 P1_09 9 DNC P1_10 10 RXD GPIO15 P1_11 11 GPIO0 GPIO17 P1_12 12 GPIO1 GPIO18 P1_13 13 GPIO2 GPIO21 P1_14 14 DNC P1_15 15 GPIO3 GPIO22 P1_16 16 GPIO4 GPIO23 P1_17 17 DNC P1_18 18 GPIO5 GPIO24 P1_19 19 SPI_MOSI GPIO10 P1_20 20 DNC P1_21 21 SPI_MISO GPIO9 P1_22 22 GPIO6 GPIO25 P1_23 23 SPI_SCLK GPIO11 P1_24 24 SPI_CE0_N GPIO8 P1_25 25 DNC P1_26 26 SPI_CE1_N GPIO7

Table 1.2: GPIO Pin and Details

Page 29: Open Source Smart Energy Meter

29

2.3.EMBEDDED LINUX CODE

To create a standalone and bootable Embedded Linux System, three main pieces of software must be flashed on the EVM:

· A bootloader, u-Boot in this case · A Linux kernel with built-in drivers for DaVinci DM644x devices · An ARM-target Linux file system containing the shell, application and run

time support utilities and stacks This section quickly reviews the DVEVM, including required hardware and software components. The DM644x EVM Kit is a collection of hardware and software packages for the embedded Linux developer community. The hardware components include:

· TMS320DM6446 device-based development board · NTSC/PAL video camera (region dependent) · NTSC/PAL LCD display (region dependent) · Microphone · IR remote control · 40GB, 2.5-inch IDE hard disk drive

The development board has multiple accessories and I/O interfaces such as USB, 10/100 Mbps Ethernet, video-in (composite), video-out (analog or digital), audio-in (line or microphone), audio-out (S.PDIF, analog), and UART. The board also includes 4 MB of SRAM memory, 16 MB of NOR memory, 64 MB of NAND memory, a 40 GB HDD, and 256 MB of DDR2 memory. For a more detailed list of all the available features of the DVEVM, consult the Technical Reference.

Table 1.3: Required DVEVM Hardware Features

Page 30: Open Source Smart Energy Meter

30

Type Device Description Various software components come with the DVEVM package, including multimedia demos such as audio, speech and video encode and decode using various codec formats. However, in this project only the ARM Linux tool chain, the bootloader, and Linux Support Package (LSP) are needed to complete the goal of building the smallest possible flash-based Linux kernel with an HTTP server for the DM644x DVEVM. DevRocket is a trademark of MontaVista Software, Inc. MontaVista is a registered trademark of MontaVista Software, Inc. All other trademarks are the property of their respective owners. Feature Selection and Kernel Build Steps - Kernel Configuration list of the components that are assumed to be available for use with this project. Although package versions are included in the list, later versions may be available.

Table 1.4: Required DVEVM Software Packages

Item Version Building an embedded Linux kernel can be complex if starting from bare silicon. Drivers must be ported or developed, tested, and compatible cross-development tool chain and upper protocol stacks updated or retargeted for the ARM926EJS processor on the DM644x device. The DVEVM package already includes most of the available tools, such as an ARM GNU tool suite, a Linux Support Package with the ARM Linux kernel v2.6, and all the drivers needed for our project. This section assumes that we have installed the DVEVM software as described in Section 4 of the DVEVM Getting Started Guide (SPRUE66). Section 4 of the DVEVM Getting Started Guide also documents the general commands for building a Linux kernel. Thus, building an embedded Linux kernel comprises two simple steps:

· Configure the kernel to select the needed drivers and features

Page 31: Open Source Smart Energy Meter

31

· Compile the kernel to create an appropriate image, uImage, that u-boot can load on DVEVM Linux kernel features are collected in the .config file at the top level of the kernel directory. This file is used by the GNU make utility in the build process. Although we can edit the .config file directly to turn the features on or off, several menu driven methods are available to make this step easier. The oldest one is make menuconfig, although graphical methods such as make xconfig, which uses the X-windows environment, or make gconfig, which uses GTK+ environment, are preferred. The following sections describe examples of performing the configuration using xconfig. If you are already familiar with the configuration step, use to determine the features that must be selected or deselected from the default LSP of the DVEVM.

Table 1.5: Configuration Summary

Enable Disable

• ARM System Type (TI-Davinci) Loadable module support • TI DM644x Based system Built-in firmware loadable support • TI Davinci EVM MTD support • TI Davinci I2C Expander Loop back device support • ARM EABI Support ATA/ATAPI support • High-Resolution Timer SCSI support • Networking Support Input device support • Initial RAM disk Support Video for Linux support • Kernel .config File Support

Ext3/XFS/Minix/Automounter/MSDOS/VFAT/CRAMFS/NFS support • Configure Kernel for Small Devices Frame buffer device support • POSIX Message Queues USB Support • System V IPC Sound card support

Page 32: Open Source Smart Energy Meter

32

• SPRAAH2A–May 2008 Building a Small Embedded Linux Kernel Example 3 Configuration Steps

Configuration Summary (continued) Enable Disable The following steps assume that the default installed kernel tree has been copied to a private location at /home/user/workdir/lsp before compiling. Also note that the directory names of the kernel tree can change from one version of the package to another. The DVEVM and DVSDK-L or -3L software packages may have slightly different kernel config and build commands. Always check the documentation that comes with the package such as the DVEVM Release Notes, the DVEVM Quick Start Guide or DVEVM Getting Started Guide (SPRUE66) for updated information regarding the exact commands for the build steps. The following steps are for the kernel tree from the DVEVM software package. 1. On the host Linux workstation, go to the base directory of the kernel tree: host $ cd /home/user/working/lsp/ti-davinci 2. Launch the Linux kernel configuration utility: host $ make ARCH=arm CROSS_COMPILE=arm_v5t_le- xconfig

3. Under Loadable module support, uncheck the Enable loadable modulesupport

4. Under Device Drivers ® Generic Driver Options, uncheck the Select only drivers that don’t need compile-time external firmware and Prevent firmware from being built boxes to disable firmware loading features. Building a Small Embedded Linux Kernel Example SPRAAH2A–May 2008

Page 33: Open Source Smart Energy Meter

33

Figure 1.17: Loadable Module Support

5. Under Device Drivers ® Memory Technology Devices (MTD), uncheck the Memory Technology Devices (MTD) support box to disable the memory technology driver support. 6. Under Device Drivers ® Block devices, uncheck the Loopback device support box to disable the loopback device support used to mount an ISO image. 7. Under Device Drivers ® ATA/ATPI/MFM/RRL support, uncheck the ATA/ATPI/MFM/RRL support box to disable the ATA support used to access the EVM hard drive. 8. Under Device Drivers ® SCSI device support, uncheck the legacy /proc/scsi/ support and SCSI disk support boxes to disable SCSI disk support on the EVM.

Page 34: Open Source Smart Energy Meter

34

9. Under Device Drivers ® Input device support, uncheck the Mouse interface, Event interface, and Keyboards boxes to disable the input device support. 10. Under Device Drivers ® Multimedia devices, uncheck the Video For Linux box to disable the v4l2 driver support used to capture video image from the camera. 11. Under Device Drivers ® File systems, uncheck the Ext3 journalling file system support, XFS file system support, Minix fs support, Dnotify support, and Kernel automounter version 4 support boxes to disable file system supports. Do not uncheck ext2 file system support, as the ext2 file system is used in the initial RAM disk. 12. Under Device Drivers ® File systems ® DOS/FAT/NT Filesystems, uncheck the MSDOS fs support and VFAT (Windows 95) fs support boxes to disable Windows file system support. 13. Under Device Drivers ® File systems®Miscellaneous filesystems, uncheck the Compressed ROM file system support (cramfs) box to disable cramfs file system support. 14. Under Device Drivers ® File systems ® Network File Systems, uncheck the NFS file system support, NFS server support, and SMB file system support boxes to disable network file systems support. 15. Under Device Drivers ® File systems®Partition Types, uncheck the Advanced Partition Selection box to disable partition support on the hard disk. 16. Under Device Drivers ® Graphics Support, uncheck the Support for frame buffer devices box to disable Linux frame buffer support.

Page 35: Open Source Smart Energy Meter

35

Figure 1.18: Disable File Systems

17. Under Device Drivers ® Sound, uncheck the Sound card support box to disable Linux sound support. 18. Under Device Drivers ® USB Support, uncheck the Support for Host-side USB and Inventra USB Highspeed Dual Role Controller Support boxes to disable USB driver support.

Kernel Compilation - Building an Initial RAM Disk File System 19. Under Device Drivers ® MMC/SD Card Support, uncheck the MMC Support box to disable Multimedia Card support. This section describes the kernel compilation steps. The DVEVM and DVSDK-L or -3L software packages may have different kernel configurations and build commands. Always check the documentation that comes with the package such as the DVEVM Release Notes, the DVEVM Quick Start Guide or DVEVM Getting Started Guide (SPRUE66) for the exact commands for the build steps. The following steps are for the kernel tree from the DVEVM software package.

Page 36: Open Source Smart Energy Meter

36

1. If not already logged in as user, then log in as user prior to building the kernel.

2. Build the Linux kernel with this command: host$ make ARCH=arm CROSS_COMPILE=arm_v5t_le- uImage Creating the index.html File Edit a file called index.html and add the following lines to it: <HTML> <HEAD> <TITLE>DaVinci DVEVM</TITLE> <STYLE TYPE="text/css"> BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { font-family: Geneva, Arial, Helvetica, sans-serif; } H1 { text-align: center; } CAPTION { font-weight: bold } </STYLE> </HEAD> <BODY> <table width=100%> <tr> <td bgcolor="black" width="1"><a href="http://www.ti.com"><img border=0 src="tilogo.gif"></a></td> <td bgcolor="red"><img src="titagline.gif"></td> </tr> </table> <H1>Welcome!</H1> <P> DaVinci Technology from TI makes the next generation of digital video and audio end-equipment applications possible. Learn more at The DaVinci Effect <A HREF="http://www.thedavincieffect.com">website</A>. </P> <P> This web page is being served from an HTTP server running on the ARM926 processor of the DM6446 SoC on the DaVinci DVEVM board. For the latest news and software updates on the DVEVM, see the DVEVM

Page 37: Open Source Smart Energy Meter

37

<A HREF="http://www.ti.com/dvevmupdates">website</A >. </P> <H1> Kernel Configuration and Statistic</H1> <P> The demo is configured to run minimal kernel image. The kernel only supports TI EMAC and serial driver. Click below to check <UL> <LI> <A HREF="/cgi-bin/memory">Memory usage</A> </L I> <LI> <A HREF="/cgi-bin/log">Kernel boot log</A> </L I> <LI> <A HREF="/cgi-bin/config">Kernel Config option s</A> </LI> </UL> </BODY> </HTML>

1. Edit a file called memory and add the following script lines to create the memory usage script: #!/bin/sh cat << EOF Content-type: text/plain Cache-control: no-cache

Creating the index.html File EOF echo "#cat /proc/meminfo" cat /proc/meminfo echo echo "# free -b" free -b echo echo "# ps -el" ps -el Edit a file called memory and add the following script lines to create the kernel boot log script : #!/bin/sh cat << EOF Content-type: text/plain Cache-control: no-cache EOF echo

Page 38: Open Source Smart Energy Meter

38

echo "#dmesg" dmesg Edit a file called memory and add the following script lines to create the kernel config options script : #!/bin/sh cat << EOF Content-type: text/plain Cache-control: no-cache EOF rm -rf /tmp/config* cp /proc/config.gz /tmp gzip -d /tmp/config.gz cat /tmp/config Make the scripts executable: chmod +x memory chmod +x log chmod +x config 2.4.CODING

On Raspberry Pi, will need to ensure that certain Python related files installed. To make sure, type the following commands...

sudo apt-get install python-dev python-pip

sudo pip install apscheduler

The above installs the advanced python scheduler used by the code. Now we will want to download the files from this github repository. To do so, type the following commands...

sudo apt-get install git

git clone https://github.com/kieranc/power.git &&cd power

The file named power-monitor is used to automatically start the data logging process on boot and stop on shutdown. For testing purposes, we do not need this script. However, we should make use of it if we are setting up a more permanent solution.

Page 39: Open Source Smart Energy Meter

39

sudocp power-monitor /etc/init.d/

sudochmoda+x /etc/init.d/power-monitor

sudo update-rc.d power-monitor defaults

Note: Be sure to check the power-monitor file to make sure that the path to the Python application, monitor.py, matches with the path on our system. For example, /home/pi/power/power.py

Due to Python's inability to respond to an interrupt, I've used a very simple C

app to listen for an interrupt triggered when the LDR detects a pulse. Monitor.py counts these pulses and each minute, creates a power reading in watts which it sends to EmonCMS' API. I'm not much of a coder so a lot of the code is borrowed from other people, I've included all sources as far as I'm aware. The C app came from Radek "Mrkva" Pilar on the raspberrypi. This app will need compiling like so:

gccgpio-irq-demo.c -o gpio-irq

Put it somewhere accessible - I used /usr/local/bin, this will need modifying at the bottom of monitor.py if you put it somewhere else.

Once all this is done we can start the data logging process...

sudo /etc/init.d/power-monitor start

This script is configure only to submit its output to the EmonCMS API. For this we need EmonCMS API.

Install Emoncms on Ubuntu / Debian This guide should work on most debian systems including Ubuntu. For

installation guide on installing emoncms on a raspberrypi

1) Install mysql

$ sudo apt-get install mysql-server mysql-client

When the blue dialog appears enter a password for root user, note the password down as you will need it later.

Page 40: Open Source Smart Energy Meter

40

2) Install apache2

$ sudo apt-get install apache2

3) Install php

$ sudo apt-get install php5 libapache2-mod-php5

$ sudo apt-get install php5-mysql

4) Enable mod rewrite

$ sudo a2enmod rewrite

$ sudonano /etc/apache2/sites-enabled/000-default

Change (line 7 and line 11), "AllowOverride None" to "AllowOverride All". [Ctrl + X ] then [Y] then [Enter] to Save and exit.

5) That completes the server installation, restart the server to make everything above operational:

$ sudo /etc/init.d/apache2 restart

Installing emoncms:

6) Install git (recommended but optional)

$ sudo apt-get install git-core

7) Download Emoncms

First cd into the var directory:

$ cd /var/

Set the permissions of the www directory to be owned by our username (on the raspberrypi its pi):

$ sudochown pi www

Cd into www directory

$ cd www

Page 41: Open Source Smart Energy Meter

41

Download emoncms using git:

$ git clone https://github.com/emoncms/emoncms.git

Alternatively download emoncms and unzip to our server:

8) Create a MYSQL database

$ mysql -u root -p

Enter the mysql password that we set above. Then enter the sql to create a database:

mysql> CREATE DATABASE emoncms;

Exit mysql by:

mysql> exit

9) Set emoncms database settings.

cd into the emoncms directory where the settings file is located

$ cd /var/www/emoncms/

Make a copy of default.settings.php and call it settings.php

$ cpdefault.settings.phpsettings.php

Open settings.php in an editor:

$ nanosettings.php

Enter in our database settings.

$username = "USERNAME";

$password = "PASSWORD";

$server = "localhost";

$database = "emoncms";

Enter in our database settings.

Save (Ctrl-X), type Y and exit

Page 42: Open Source Smart Energy Meter

42

10) In an internet browser, load emoncms:

Chrome Ubuntu 23.0.1271.97 - developed with, works great.

Chrome Windows 25.0.1364.172 - quick check revealed no browser specific bugs.

Firefox Ubuntu 15.0.1 - no critical browser specific bugs, but movement in the dashboard editor is much less smooth than chrome.

Internet explorer 9 - works well with compatibility mode turned off. F12 Development tools -> browser mode: IE9. Some widgets such as the hot water cylinder do load later than the dial.

IE 8, 7 - not recommended, widgets and dashboard editor do not work due to no html5 canvas fix implemented but visualisations do work as these have a fix applied.

Page 43: Open Source Smart Energy Meter

43

CHAPTER 3 WORKING

3.1. BLOCK DIAGRAM

Figure 1.19: Working Block Diagram 3.2. EXPERIMENT SETUP

Figure 1.20: Set of Project

Page 44: Open Source Smart Energy Meter

44

Figure 1.21: Meter pin configuration with CT & PT connection

Figure 1.22: Load connection with proto type

Page 45: Open Source Smart Energy Meter

45

3.3. DIFFUCULTIES OBSERVED

Internet connection

This project main part is Raspberry pi Board . This board include in LAN port. But internet not connected in directly. Solution is change the simple proxy and Host in First time Browsing. So take the long time for internet connection Python Library installs

First time library install completed in 80% not completed in fully installed. Some errors displayed. The library 100% completed in only server LAN connection. So find the problem is very difficult

Page 46: Open Source Smart Energy Meter

46

CHAPTER 4 RESULT

4.1. SCREENSHOTS

Figure 1.23: Data file setting (Live Graph)

Page 47: Open Source Smart Energy Meter

47

Figure 1.24: Live Graph

4.2. DESCRIPTION

Data Writer API

If we are not using Java we will have to take care of creating the data files yourself. This should be very straight forward, as the data file format is very simple. Please refer to the data file format definition for details. If we are using Java we can make use of the LiveGraph data writer API. This simple API handles all data file matters for your application.

The API is distributed in Java

packages org.LiveGraph.dataFile.common andorg.LiveGraph.dataFile.write;

Page 48: Open Source Smart Energy Meter

48

it also includes the package org.LiveGraph.demoDataSource which contains examples .

The package org.LiveGraph.dataFile.common includes helper classes;

the package org.LiveGraph.dataFile.write includes the main writer API. When we are interested in a detailed description of the API, please refer to the appropriate Javadoc reference page. At this stage we want to provide akick-start example.

DataStreamWriterFactory

The first class need to know about is

org.LiveGraph.dataFile.write.DataStreamWriterFactor y .

The most interesting methods in this class are the static createDataWriter (…)-methods. They create new writer objects for a unique files located in a specified directory. The file's name is constructed form a specified basis and the current date and time. This makes creating verbose file names and managing data files very easy.

For instance, the statement

DataStreamWriterFactory.createDataWriter("C:\\Tutor ialDir", "TutorialData", "dat");

creates a writer which writes to the file c:\TutorialDir\TutorialData.07.03.13-19.09.21.dat (assuming it was executed at 19:09:21 on the 13.03.2007).

If that file already exists than the names

c:\TutorialDir\TutorialData.07.03.13-19.09.21(1).dat ,c:\TutorialDir\TutorialData.07.03.13-19.09.21(2).dat and so on will be automatically used instead. This mechanism allows we to do all we data file management in just one line.

DataStreamWriter

The second class you need to know about is

Page 49: Open Source Smart Energy Meter

49

org.LiveGraph.dataFile.write.DataStreamWriter .

DataStreamWriter objects are actually used for writing data to files. DataStreamWriter does not extendjava.io.Writer because the structure of the data being written is different and the making use of the methods published by the standard API class would be counter-intuitive; however, DataStreamWriter objects

should be used in much the same manner as a normal Writer in an application. The class provides methods for setting up the data file separator, adding information lines and comments to the data file, defining the number of and the labels for the data series and, eventually, for writing the data.

Before any data is sent to the writer the data series should be set up with a series of calls toaddDataSeries(String) . Once a dataset is written to the stream, no more data series may be added.

A dataset is written by a series of calls to one of the setDataValue (...) methods. Calls to those methods do not cause any data to be written. Instead, the values are associated with the appropriate data series and cached. In order to actually write the data to the underlying stream the method writeDataSet() must be invoked. It flushes the cache to the data stream and prepares for the processing of the next dataset.

In order to allow for concise code when using this class in applications, no methods of DataStreamWriterthrow any I/O exceptions. If an IOException is thrown by the underlying stream.

it is immediately caught by the writer itself. In order to allow the application to nevertheless access and control the error handling, the methodshadIOException(), getIOException() and resetIOException() are provided.

Page 50: Open Source Smart Energy Meter

50

4.3. CONCLUSION Thus the smart meter with the implementation of open source coding and software has been developed. This project mainly focuses on developing the software (or) RTOS framework for open source energy meter. The future work of this project includes may novel ideas such as wireless networking, deploying secured web server. Thus with this open source hardware and software technology. We can able to monitor energy and power easily. 4.4. FUTURE WORK

The future work includes the following,

• The Energy Meter data can be made to transfer in wireless. • The wireless network can be formed with WIFI or Open Smart Grid

Protocol (OSGP).

Page 51: Open Source Smart Energy Meter

51

4.5.REFERENCE http://openenergymonitor.org/emon/node/2017

https://github.com/kieranc/power

http://en.wikipedia.org/wiki/Smart_meter

http://www.raspberrypi.org/phpBB3/viewtopic.php?f=44&t=7509

http://pypi.python.org

http://pyevolve.sourceforge.net/wordpress/?p=2383

http://www.ti.com